context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// 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.Collections.Specialized.OrderedDictionary.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 0067
// Disable the "this event 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.Collections.Specialized
{
public partial class OrderedDictionary : IOrderedDictionary, System.Collections.IDictionary, System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback
{
#region Methods and constructors
public void Add(Object key, Object value)
{
}
public System.Collections.Specialized.OrderedDictionary AsReadOnly()
{
Contract.Ensures(Contract.Result<System.Collections.Specialized.OrderedDictionary>() != null);
return default(System.Collections.Specialized.OrderedDictionary);
}
public void Clear()
{
}
public bool Contains(Object key)
{
return default(bool);
}
public void CopyTo(Array array, int index)
{
}
public virtual new System.Collections.IDictionaryEnumerator GetEnumerator()
{
return default(System.Collections.IDictionaryEnumerator);
}
public virtual new void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
}
public void Insert(int index, Object key, Object value)
{
}
protected virtual new void OnDeserialization(Object sender)
{
}
public OrderedDictionary()
{
}
public OrderedDictionary(System.Collections.IEqualityComparer comparer)
{
}
public OrderedDictionary(int capacity, System.Collections.IEqualityComparer comparer)
{
}
protected OrderedDictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
}
public OrderedDictionary(int capacity)
{
}
public void Remove(Object key)
{
}
public void RemoveAt(int index)
{
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return default(System.Collections.IEnumerator);
}
void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(Object sender)
{
}
#endregion
#region Properties and indexers
public int Count
{
get
{
return default(int);
}
}
public bool IsReadOnly
{
get
{
return default(bool);
}
}
public Object this [int index]
{
get
{
return default(Object);
}
set
{
}
}
public Object this [Object key]
{
get
{
return default(Object);
}
set
{
}
}
public System.Collections.ICollection Keys
{
get
{
return default(System.Collections.ICollection);
}
}
bool System.Collections.ICollection.IsSynchronized
{
get
{
return default(bool);
}
}
Object System.Collections.ICollection.SyncRoot
{
get
{
return default(Object);
}
}
bool System.Collections.IDictionary.IsFixedSize
{
get
{
return default(bool);
}
}
public System.Collections.ICollection Values
{
get
{
return default(System.Collections.ICollection);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Xml;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Individual node-specific silo configuration parameters.
/// </summary>
[Serializable]
public class NodeConfiguration : ITraceConfiguration, IStatisticsConfiguration
{
private readonly DateTime creationTimestamp;
private string siloName;
/// <summary>
/// The name of this silo.
/// </summary>
public string SiloName
{
get { return siloName; }
set
{
siloName = value;
ConfigUtilities.SetTraceFileName(this, siloName, creationTimestamp);
}
}
/// <summary>
/// The DNS host name of this silo.
/// This is a true host name, no IP address. It is NOT settable, equals Dns.GetHostName().
/// </summary>
public string DNSHostName { get; private set; }
/// <summary>
/// The host name or IP address of this silo.
/// This is a configurable IP address or Hostname.
/// </summary>
public string HostNameOrIPAddress { get; set; }
private IPAddress Address { get { return ClusterConfiguration.ResolveIPAddress(HostNameOrIPAddress, Subnet, AddressType).GetResult(); } }
/// <summary>
/// The port this silo uses for silo-to-silo communication.
/// </summary>
public int Port { get; set; }
/// <summary>
/// The epoch generation number for this silo.
/// </summary>
public int Generation { get; set; }
/// <summary>
/// The IPEndPoint this silo uses for silo-to-silo communication.
/// </summary>
public IPEndPoint Endpoint
{
get { return new IPEndPoint(Address, Port); }
}
/// <summary>
/// The AddressFamilyof the IP address of this silo.
/// </summary>
public AddressFamily AddressType { get; set; }
/// <summary>
/// The IPEndPoint this silo uses for (gateway) silo-to-client communication.
/// </summary>
public IPEndPoint ProxyGatewayEndpoint { get; set; }
internal byte[] Subnet { get; set; } // from global
/// <summary>
/// Whether this is a primary silo (applies for dev settings only).
/// </summary>
public bool IsPrimaryNode { get; internal set; }
/// <summary>
/// Whether this is one of the seed silos (applies for dev settings only).
/// </summary>
public bool IsSeedNode { get; internal set; }
/// <summary>
/// Whether this is silo is a proxying gateway silo.
/// </summary>
public bool IsGatewayNode { get { return ProxyGatewayEndpoint != null; } }
/// <summary>
/// The MaxActiveThreads attribute specifies the maximum number of simultaneous active threads the scheduler will allow.
/// Generally this number should be roughly equal to the number of cores on the node.
/// Using a value of 0 will look at System.Environment.ProcessorCount to decide the number instead, which is only valid when set from xml config
/// </summary>
public int MaxActiveThreads { get; set; }
/// <summary>
/// The DelayWarningThreshold attribute specifies the work item queuing delay threshold, at which a warning log message is written.
/// That is, if the delay between enqueuing the work item and executing the work item is greater than DelayWarningThreshold, a warning log is written.
/// The default value is 10 seconds.
/// </summary>
public TimeSpan DelayWarningThreshold { get; set; }
/// <summary>
/// ActivationSchedulingQuantum is a soft time limit on the duration of activation macro-turn (a number of micro-turns).
/// If a activation was running its micro-turns longer than this, we will give up the thread.
/// If this is set to zero or a negative number, then the full work queue is drained (MaxWorkItemsPerTurn allowing).
/// </summary>
public TimeSpan ActivationSchedulingQuantum { get; set; }
/// <summary>
/// TurnWarningLengthThreshold is a soft time limit to generate trace warning when the micro-turn executes longer then this period in CPU.
/// </summary>
public TimeSpan TurnWarningLengthThreshold { get; set; }
internal bool EnableWorkerThreadInjection { get; set; }
/// <summary>
/// The LoadShedding element specifies the gateway load shedding configuration for the node.
/// If it does not appear, gateway load shedding is disabled.
/// </summary>
public bool LoadSheddingEnabled { get; set; }
/// <summary>
/// The LoadLimit attribute specifies the system load, in CPU%, at which load begins to be shed.
/// Note that this value is in %, so valid values range from 1 to 100, and a reasonable value is
/// typically between 80 and 95.
/// This value is ignored if load shedding is disabled, which is the default.
/// If load shedding is enabled and this attribute does not appear, then the default limit is 95%.
/// </summary>
public int LoadSheddingLimit { get; set; }
/// <summary>
/// The values for various silo limits.
/// </summary>
public LimitManager LimitManager { get; private set; }
private string traceFilePattern;
/// <summary>
/// </summary>
public Severity DefaultTraceLevel { get; set; }
/// <summary>
/// </summary>
public IList<Tuple<string, Severity>> TraceLevelOverrides { get; private set; }
/// <summary>
/// </summary>
public bool TraceToConsole { get; set; }
/// <summary>
/// </summary>
public string TraceFilePattern
{
get { return traceFilePattern; }
set
{
traceFilePattern = value;
ConfigUtilities.SetTraceFileName(this, siloName, creationTimestamp);
}
}
/// <summary>
/// </summary>
public string TraceFileName { get; set; }
/// <summary>
/// </summary>
public int LargeMessageWarningThreshold { get; set; }
/// <summary>
/// </summary>
public bool PropagateActivityId { get; set; }
/// <summary>
/// </summary>
public int BulkMessageLimit { get; set; }
/// <summary>
/// Specifies the name of the Startup class in the configuration file.
/// </summary>
public string StartupTypeName { get; set; }
public string StatisticsProviderName { get; set; }
/// <summary>
/// The MetricsTableWriteInterval attribute specifies the frequency of updating the metrics in Azure table.
/// The default is 30 seconds.
/// </summary>
public TimeSpan StatisticsMetricsTableWriteInterval { get; set; }
/// <summary>
/// The PerfCounterWriteInterval attribute specifies the frequency of updating the windows performance counters.
/// The default is 30 seconds.
/// </summary>
public TimeSpan StatisticsPerfCountersWriteInterval { get; set; }
/// <summary>
/// The LogWriteInterval attribute specifies the frequency of updating the statistics in the log file.
/// The default is 5 minutes.
/// </summary>
public TimeSpan StatisticsLogWriteInterval { get; set; }
/// <summary>
/// The WriteLogStatisticsToTable attribute specifies whether log statistics should also be written into a separate, special Azure table.
/// The default is yes.
/// </summary>
public bool StatisticsWriteLogStatisticsToTable { get; set; }
/// <summary>
/// </summary>
public StatisticsLevel StatisticsCollectionLevel { get; set; }
/// <summary>
/// </summary>
public int MinDotNetThreadPoolSize { get; set; }
/// <summary>
/// </summary>
public bool Expect100Continue { get; set; }
/// <summary>
/// </summary>
public int DefaultConnectionLimit { get; set; }
/// <summary>
/// </summary>
public bool UseNagleAlgorithm { get; set; }
public Dictionary<string, SearchOption> AdditionalAssemblyDirectories { get; set; }
public List<string> ExcludedGrainTypes { get; set; }
public string SiloShutdownEventName { get; set; }
internal const string DEFAULT_NODE_NAME = "default";
private static readonly TimeSpan DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD = TimeSpan.FromSeconds(30);
private static readonly TimeSpan DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD = TimeSpan.FromSeconds(30);
private static readonly TimeSpan DEFAULT_STATS_LOG_WRITE_PERIOD = TimeSpan.FromMinutes(5);
internal static readonly StatisticsLevel DEFAULT_STATS_COLLECTION_LEVEL = StatisticsLevel.Info;
private static readonly int DEFAULT_MAX_ACTIVE_THREADS = Math.Max(4, System.Environment.ProcessorCount);
private const int DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE = 200;
private static readonly int DEFAULT_MIN_DOT_NET_CONNECTION_LIMIT = DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE;
private static readonly TimeSpan DEFAULT_ACTIVATION_SCHEDULING_QUANTUM = TimeSpan.FromMilliseconds(100);
internal const bool ENABLE_WORKER_THREAD_INJECTION = false;
public NodeConfiguration()
{
creationTimestamp = DateTime.UtcNow;
SiloName = "";
HostNameOrIPAddress = "";
DNSHostName = Dns.GetHostName();
Port = 0;
Generation = 0;
AddressType = AddressFamily.InterNetwork;
ProxyGatewayEndpoint = null;
MaxActiveThreads = DEFAULT_MAX_ACTIVE_THREADS;
DelayWarningThreshold = TimeSpan.FromMilliseconds(10000); // 10,000 milliseconds
ActivationSchedulingQuantum = DEFAULT_ACTIVATION_SCHEDULING_QUANTUM;
TurnWarningLengthThreshold = TimeSpan.FromMilliseconds(200);
EnableWorkerThreadInjection = ENABLE_WORKER_THREAD_INJECTION;
LoadSheddingEnabled = false;
LoadSheddingLimit = 95;
DefaultTraceLevel = Severity.Info;
TraceLevelOverrides = new List<Tuple<string, Severity>>();
TraceToConsole = ConsoleText.IsConsoleAvailable;
TraceFilePattern = "{0}-{1}.log";
LargeMessageWarningThreshold = Constants.LARGE_OBJECT_HEAP_THRESHOLD;
PropagateActivityId = Constants.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID;
BulkMessageLimit = Constants.DEFAULT_LOGGER_BULK_MESSAGE_LIMIT;
StatisticsMetricsTableWriteInterval = DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD;
StatisticsPerfCountersWriteInterval = DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD;
StatisticsLogWriteInterval = DEFAULT_STATS_LOG_WRITE_PERIOD;
StatisticsWriteLogStatisticsToTable = true;
StatisticsCollectionLevel = DEFAULT_STATS_COLLECTION_LEVEL;
LimitManager = new LimitManager();
MinDotNetThreadPoolSize = DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE;
// .NET ServicePointManager settings / optimizations
Expect100Continue = false;
DefaultConnectionLimit = DEFAULT_MIN_DOT_NET_CONNECTION_LIMIT;
UseNagleAlgorithm = false;
AdditionalAssemblyDirectories = new Dictionary<string, SearchOption>();
ExcludedGrainTypes = new List<string>();
}
public NodeConfiguration(NodeConfiguration other)
{
creationTimestamp = other.creationTimestamp;
SiloName = other.SiloName;
HostNameOrIPAddress = other.HostNameOrIPAddress;
DNSHostName = other.DNSHostName;
Port = other.Port;
Generation = other.Generation;
AddressType = other.AddressType;
ProxyGatewayEndpoint = other.ProxyGatewayEndpoint;
MaxActiveThreads = other.MaxActiveThreads;
DelayWarningThreshold = other.DelayWarningThreshold;
ActivationSchedulingQuantum = other.ActivationSchedulingQuantum;
TurnWarningLengthThreshold = other.TurnWarningLengthThreshold;
EnableWorkerThreadInjection = other.EnableWorkerThreadInjection;
LoadSheddingEnabled = other.LoadSheddingEnabled;
LoadSheddingLimit = other.LoadSheddingLimit;
DefaultTraceLevel = other.DefaultTraceLevel;
TraceLevelOverrides = new List<Tuple<string, Severity>>(other.TraceLevelOverrides);
TraceToConsole = other.TraceToConsole;
TraceFilePattern = other.TraceFilePattern;
TraceFileName = other.TraceFileName;
LargeMessageWarningThreshold = other.LargeMessageWarningThreshold;
PropagateActivityId = other.PropagateActivityId;
BulkMessageLimit = other.BulkMessageLimit;
StatisticsProviderName = other.StatisticsProviderName;
StatisticsMetricsTableWriteInterval = other.StatisticsMetricsTableWriteInterval;
StatisticsPerfCountersWriteInterval = other.StatisticsPerfCountersWriteInterval;
StatisticsLogWriteInterval = other.StatisticsLogWriteInterval;
StatisticsWriteLogStatisticsToTable = other.StatisticsWriteLogStatisticsToTable;
StatisticsCollectionLevel = other.StatisticsCollectionLevel;
LimitManager = new LimitManager(other.LimitManager); // Shallow copy
Subnet = other.Subnet;
MinDotNetThreadPoolSize = other.MinDotNetThreadPoolSize;
Expect100Continue = other.Expect100Continue;
DefaultConnectionLimit = other.DefaultConnectionLimit;
UseNagleAlgorithm = other.UseNagleAlgorithm;
StartupTypeName = other.StartupTypeName;
AdditionalAssemblyDirectories = new Dictionary<string, SearchOption>(other.AdditionalAssemblyDirectories);
ExcludedGrainTypes = other.ExcludedGrainTypes.ToList();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(" Silo Name: ").AppendLine(SiloName);
sb.Append(" Generation: ").Append(Generation).AppendLine();
sb.Append(" Host Name or IP Address: ").AppendLine(HostNameOrIPAddress);
sb.Append(" DNS Host Name: ").AppendLine(DNSHostName);
sb.Append(" Port: ").Append(Port).AppendLine();
sb.Append(" Subnet: ").Append(Subnet == null ? "" : Subnet.ToStrings(x => x.ToString(), ".")).AppendLine();
sb.Append(" Preferred Address Family: ").Append(AddressType).AppendLine();
if (IsGatewayNode)
{
sb.Append(" Proxy Gateway: ").Append(ProxyGatewayEndpoint.ToString()).AppendLine();
}
else
{
sb.Append(" IsGatewayNode: ").Append(IsGatewayNode).AppendLine();
}
sb.Append(" IsPrimaryNode: ").Append(IsPrimaryNode).AppendLine();
sb.Append(" Scheduler: ").AppendLine();
sb.Append(" ").Append(" Max Active Threads: ").Append(MaxActiveThreads).AppendLine();
sb.Append(" ").Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine();
sb.Append(" ").Append(" Delay Warning Threshold: ").Append(DelayWarningThreshold).AppendLine();
sb.Append(" ").Append(" Activation Scheduling Quantum: ").Append(ActivationSchedulingQuantum).AppendLine();
sb.Append(" ").Append(" Turn Warning Length Threshold: ").Append(TurnWarningLengthThreshold).AppendLine();
sb.Append(" ").Append(" Inject More Worker Threads: ").Append(EnableWorkerThreadInjection).AppendLine();
sb.Append(" ").Append(" MinDotNetThreadPoolSize: ").Append(MinDotNetThreadPoolSize).AppendLine();
#if !NETSTANDARD_TODO
int workerThreads;
int completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
sb.Append(" ").AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine();
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
sb.Append(" ").AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine();
#endif
sb.Append(" ").AppendFormat(" .NET ServicePointManager - DefaultConnectionLimit={0} Expect100Continue={1} UseNagleAlgorithm={2}", DefaultConnectionLimit, Expect100Continue, UseNagleAlgorithm).AppendLine();
sb.Append(" Load Shedding Enabled: ").Append(LoadSheddingEnabled).AppendLine();
sb.Append(" Load Shedding Limit: ").Append(LoadSheddingLimit).AppendLine();
sb.Append(" SiloShutdownEventName: ").Append(SiloShutdownEventName).AppendLine();
sb.Append(" Debug: ").AppendLine();
sb.Append(ConfigUtilities.TraceConfigurationToString(this));
sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this));
sb.Append(LimitManager);
return sb.ToString();
}
internal void Load(XmlElement root)
{
SiloName = root.LocalName.Equals("Override") ? root.GetAttribute("Node") : DEFAULT_NODE_NAME;
foreach (XmlNode c in root.ChildNodes)
{
var child = c as XmlElement;
if (child == null) continue; // Skip comment lines
switch (child.LocalName)
{
case "Networking":
if (child.HasAttribute("Address"))
{
HostNameOrIPAddress = child.GetAttribute("Address");
}
if (child.HasAttribute("Port"))
{
Port = ConfigUtilities.ParseInt(child.GetAttribute("Port"),
"Non-numeric Port attribute value on Networking element for " + SiloName);
}
if (child.HasAttribute("PreferredFamily"))
{
AddressType = ConfigUtilities.ParseEnum<AddressFamily>(child.GetAttribute("PreferredFamily"),
"Invalid preferred address family on Networking node. Valid choices are 'InterNetwork' and 'InterNetworkV6'");
}
break;
case "ProxyingGateway":
ProxyGatewayEndpoint = ConfigUtilities.ParseIPEndPoint(child, Subnet).GetResult();
break;
case "Scheduler":
if (child.HasAttribute("MaxActiveThreads"))
{
MaxActiveThreads = ConfigUtilities.ParseInt(child.GetAttribute("MaxActiveThreads"),
"Non-numeric MaxActiveThreads attribute value on Scheduler element for " + SiloName);
if (MaxActiveThreads < 1)
{
MaxActiveThreads = DEFAULT_MAX_ACTIVE_THREADS;
}
}
if (child.HasAttribute("DelayWarningThreshold"))
{
DelayWarningThreshold = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DelayWarningThreshold"),
"Non-numeric DelayWarningThreshold attribute value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("ActivationSchedulingQuantum"))
{
ActivationSchedulingQuantum = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ActivationSchedulingQuantum"),
"Non-numeric ActivationSchedulingQuantum attribute value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("TurnWarningLengthThreshold"))
{
TurnWarningLengthThreshold = ConfigUtilities.ParseTimeSpan(child.GetAttribute("TurnWarningLengthThreshold"),
"Non-numeric TurnWarningLengthThreshold attribute value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("MinDotNetThreadPoolSize"))
{
MinDotNetThreadPoolSize = ConfigUtilities.ParseInt(child.GetAttribute("MinDotNetThreadPoolSize"),
"Invalid ParseInt MinDotNetThreadPoolSize value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("Expect100Continue"))
{
Expect100Continue = ConfigUtilities.ParseBool(child.GetAttribute("Expect100Continue"),
"Invalid ParseBool Expect100Continue value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("DefaultConnectionLimit"))
{
DefaultConnectionLimit = ConfigUtilities.ParseInt(child.GetAttribute("DefaultConnectionLimit"),
"Invalid ParseInt DefaultConnectionLimit value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("UseNagleAlgorithm "))
{
UseNagleAlgorithm = ConfigUtilities.ParseBool(child.GetAttribute("UseNagleAlgorithm "),
"Invalid ParseBool UseNagleAlgorithm value on Scheduler element for " + SiloName);
}
break;
case "LoadShedding":
if (child.HasAttribute("Enabled"))
{
LoadSheddingEnabled = ConfigUtilities.ParseBool(child.GetAttribute("Enabled"),
"Invalid boolean value for Enabled attribute on LoadShedding attribute for " + SiloName);
}
if (child.HasAttribute("LoadLimit"))
{
LoadSheddingLimit = ConfigUtilities.ParseInt(child.GetAttribute("LoadLimit"),
"Invalid integer value for LoadLimit attribute on LoadShedding attribute for " + SiloName);
if (LoadSheddingLimit < 0)
{
LoadSheddingLimit = 0;
}
if (LoadSheddingLimit > 100)
{
LoadSheddingLimit = 100;
}
}
break;
case "Tracing":
ConfigUtilities.ParseTracing(this, child, SiloName);
break;
case "Statistics":
ConfigUtilities.ParseStatistics(this, child, SiloName);
break;
case "Limits":
ConfigUtilities.ParseLimitValues(LimitManager, child, SiloName);
break;
case "Startup":
if (child.HasAttribute("Type"))
{
StartupTypeName = child.GetAttribute("Type");
}
break;
case "Telemetry":
ConfigUtilities.ParseTelemetry(child);
break;
case "AdditionalAssemblyDirectories":
ConfigUtilities.ParseAdditionalAssemblyDirectories(AdditionalAssemblyDirectories, child);
break;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.ExceptionServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Principal;
namespace System.Net.Security
{
/*
An authenticated stream based on NEGO SSP.
The class that can be used by client and server side applications
- to transfer Identities across the stream
- to encrypt data based on NEGO SSP package
In most cases the innerStream will be of type NetworkStream.
On Win9x data encryption is not available and both sides have
to explicitly drop SecurityLevel and MuatualAuth requirements.
This is a simple wrapper class.
All real work is done by internal NegoState class and the other partial implementation files.
*/
public partial class NegotiateStream : AuthenticatedStream
{
private NegoState _negoState;
private string _package;
private IIdentity _remoteIdentity;
public NegotiateStream(Stream innerStream) : this(innerStream, false)
{
}
public NegotiateStream(Stream innerStream, bool leaveInnerStreamOpen) : base(innerStream, leaveInnerStreamOpen)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState = new NegoState(innerStream, leaveInnerStreamOpen);
_package = NegoState.DefaultPackage;
InitializeStreamPart();
#if DEBUG
}
#endif
}
public virtual IAsyncResult BeginAuthenticateAsClient(AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, null, string.Empty,
ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification,
asyncCallback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient(credential, null, targetName,
ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification,
asyncCallback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, string targetName, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient(credential, binding, targetName,
ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification,
asyncCallback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsClient(
NetworkCredential credential,
string targetName,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel,
AsyncCallback asyncCallback,
object asyncState)
{
return BeginAuthenticateAsClient(credential, null, targetName,
requiredProtectionLevel, allowedImpersonationLevel,
asyncCallback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsClient(
NetworkCredential credential,
ChannelBinding binding,
string targetName,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel,
AsyncCallback asyncCallback,
object asyncState)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
_negoState.ValidateCreateContext(_package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);
LazyAsyncResult result = new LazyAsyncResult(_negoState, asyncState, asyncCallback);
_negoState.ProcessAuthentication(result);
return result;
#if DEBUG
}
#endif
}
public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState.EndProcessAuthentication(asyncResult);
#if DEBUG
}
#endif
}
public virtual void AuthenticateAsServer()
{
AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
}
public virtual void AuthenticateAsServer(ExtendedProtectionPolicy policy)
{
AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
}
public virtual void AuthenticateAsServer(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
{
AuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel);
}
public virtual void AuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
_negoState.ValidateCreateContext(_package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
_negoState.ProcessAuthentication(null);
#if DEBUG
}
#endif
}
public virtual IAsyncResult BeginAuthenticateAsServer(AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsServer(ExtendedProtectionPolicy policy, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsServer(
NetworkCredential credential,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel requiredImpersonationLevel,
AsyncCallback asyncCallback,
object asyncState)
{
return BeginAuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel, asyncCallback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsServer(
NetworkCredential credential,
ExtendedProtectionPolicy policy,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel requiredImpersonationLevel,
AsyncCallback asyncCallback,
object asyncState)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
_negoState.ValidateCreateContext(_package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
LazyAsyncResult result = new LazyAsyncResult(_negoState, asyncState, asyncCallback);
_negoState.ProcessAuthentication(result);
return result;
#if DEBUG
}
#endif
}
//
public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState.EndProcessAuthentication(asyncResult);
#if DEBUG
}
#endif
}
public virtual void AuthenticateAsClient()
{
AuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, null, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
}
public virtual void AuthenticateAsClient(NetworkCredential credential, string targetName)
{
AuthenticateAsClient(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
}
public virtual void AuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, string targetName)
{
AuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
}
public virtual void AuthenticateAsClient(
NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
{
AuthenticateAsClient(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel);
}
public virtual void AuthenticateAsClient(
NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
_negoState.ValidateCreateContext(_package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);
_negoState.ProcessAuthentication(null);
#if DEBUG
}
#endif
}
public virtual Task AuthenticateAsClientAsync()
{
return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, null);
}
public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName)
{
return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, credential, targetName, null);
}
public virtual Task AuthenticateAsClientAsync(
NetworkCredential credential, string targetName,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel)
{
return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(credential, targetName, requiredProtectionLevel, allowedImpersonationLevel, callback, state), EndAuthenticateAsClient, null);
}
public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, ChannelBinding binding, string targetName)
{
return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, credential, binding, targetName, null);
}
public virtual Task AuthenticateAsClientAsync(
NetworkCredential credential, ChannelBinding binding,
string targetName, ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel allowedImpersonationLevel)
{
return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(credential, binding, targetName, requiredProtectionLevel, allowedImpersonationLevel, callback, state), EndAuthenticateAsClient, null);
}
public virtual Task AuthenticateAsServerAsync()
{
return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, null);
}
public virtual Task AuthenticateAsServerAsync(ExtendedProtectionPolicy policy)
{
return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, policy, null);
}
public virtual Task AuthenticateAsServerAsync(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
{
return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, credential, requiredProtectionLevel, requiredImpersonationLevel, null);
}
public virtual Task AuthenticateAsServerAsync(
NetworkCredential credential, ExtendedProtectionPolicy policy,
ProtectionLevel requiredProtectionLevel,
TokenImpersonationLevel requiredImpersonationLevel)
{
return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsServer(credential, policy, requiredProtectionLevel, requiredImpersonationLevel, callback, state), EndAuthenticateAsClient, null);
}
public override bool IsAuthenticated
{
get
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsAuthenticated;
#if DEBUG
}
#endif
}
}
public override bool IsMutuallyAuthenticated
{
get
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsMutuallyAuthenticated;
#if DEBUG
}
#endif
}
}
public override bool IsEncrypted
{
get
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsEncrypted;
#if DEBUG
}
#endif
}
}
public override bool IsSigned
{
get
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsSigned;
#if DEBUG
}
#endif
}
}
public override bool IsServer
{
get
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsServer;
#if DEBUG
}
#endif
}
}
public virtual TokenImpersonationLevel ImpersonationLevel
{
get
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.AllowedImpersonation;
#if DEBUG
}
#endif
}
}
public virtual IIdentity RemoteIdentity
{
get
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
if (_remoteIdentity == null)
{
_remoteIdentity = _negoState.GetIdentity();
}
return _remoteIdentity;
#if DEBUG
}
#endif
}
}
//
// Stream contract implementation
//
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanRead
{
get
{
return IsAuthenticated && InnerStream.CanRead;
}
}
public override bool CanTimeout
{
get
{
return InnerStream.CanTimeout;
}
}
public override bool CanWrite
{
get
{
return IsAuthenticated && InnerStream.CanWrite;
}
}
public override int ReadTimeout
{
get
{
return InnerStream.ReadTimeout;
}
set
{
InnerStream.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
return InnerStream.WriteTimeout;
}
set
{
InnerStream.WriteTimeout = value;
}
}
public override long Length
{
get
{
return InnerStream.Length;
}
}
public override long Position
{
get
{
return InnerStream.Position;
}
set
{
throw new NotSupportedException(SR.net_noseek);
}
}
public override void SetLength(long value)
{
InnerStream.SetLength(value);
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.net_noseek);
}
public override void Flush()
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
InnerStream.Flush();
#if DEBUG
}
#endif
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return InnerStream.FlushAsync(cancellationToken);
}
protected override void Dispose(bool disposing)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
try
{
_negoState.Close();
}
finally
{
base.Dispose(disposing);
}
#if DEBUG
}
#endif
}
public override async ValueTask DisposeAsync()
{
try
{
_negoState.Close();
}
finally
{
await base.DisposeAsync().ConfigureAwait(false);
}
}
public override int Read(byte[] buffer, int offset, int count)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
_negoState.CheckThrow(true);
if (!_negoState.CanGetSecureStream)
{
return InnerStream.Read(buffer, offset, count);
}
return ProcessRead(buffer, offset, count, null);
#if DEBUG
}
#endif
}
public override void Write(byte[] buffer, int offset, int count)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
_negoState.CheckThrow(true);
if (!_negoState.CanGetSecureStream)
{
InnerStream.Write(buffer, offset, count);
return;
}
ProcessWrite(buffer, offset, count, null);
#if DEBUG
}
#endif
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
_negoState.CheckThrow(true);
if (!_negoState.CanGetSecureStream)
{
return TaskToApm.Begin(InnerStream.ReadAsync(buffer, offset, count), asyncCallback, asyncState);
}
BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, asyncState, asyncCallback);
AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult);
ProcessRead(buffer, offset, count, asyncRequest);
return bufferResult;
#if DEBUG
}
#endif
}
public override int EndRead(IAsyncResult asyncResult)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState.CheckThrow(true);
if (!_negoState.CanGetSecureStream)
{
return TaskToApm.End<int>(asyncResult);
}
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
if (bufferResult == null)
{
throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult));
}
if (Interlocked.Exchange(ref _NestedRead, 0) == 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndRead"));
}
// No "artificial" timeouts implemented so far, InnerStream controls timeout.
bufferResult.InternalWaitForCompletion();
if (bufferResult.Result is Exception e)
{
if (e is IOException)
{
ExceptionDispatchInfo.Throw(e);
}
throw new IOException(SR.net_io_read, e);
}
return bufferResult.Int32Result;
#if DEBUG
}
#endif
}
//
//
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
_negoState.CheckThrow(true);
if (!_negoState.CanGetSecureStream)
{
return TaskToApm.Begin(InnerStream.WriteAsync(buffer, offset, count), asyncCallback, asyncState);
}
BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, asyncState, asyncCallback);
AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult);
ProcessWrite(buffer, offset, count, asyncRequest);
return bufferResult;
#if DEBUG
}
#endif
}
public override void EndWrite(IAsyncResult asyncResult)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState.CheckThrow(true);
if (!_negoState.CanGetSecureStream)
{
TaskToApm.End(asyncResult);
return;
}
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
if (bufferResult == null)
{
throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult));
}
if (Interlocked.Exchange(ref _NestedWrite, 0) == 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndWrite"));
}
// No "artificial" timeouts implemented so far, InnerStream controls timeout.
bufferResult.InternalWaitForCompletion();
if (bufferResult.Result is Exception e)
{
if (e is IOException)
{
ExceptionDispatchInfo.Throw(e);
}
throw new IOException(SR.net_io_write, e);
}
#if DEBUG
}
#endif
}
}
}
| |
#region License
//L
// 2007 - 2013 Copyright Northwestern University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
//L
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using ClearCanvas.Common;
using ClearCanvas.Common.Utilities;
namespace AIM.Annotation.View.WinForms.Template
{
internal partial class SimpleQuestionControl : UserControl
{
internal event EventHandler<ResponseChangedEventArgs> SelectedResponseChanged;
private readonly Control _questionControl;
private readonly ConfidenceControl _confidenceControl;
private readonly int _questionNumber;
private readonly StandardValidTerm _questionType;
private List<StandardValidTerm> _selectedAnswers;
private readonly int _maxNumberOfAnswers;
private bool _fireChangeEvent = true;
private readonly List<string> _staticDisplayItems;
public SimpleQuestionControl(
string label,
StandardValidTerm questionType,
string description,
List<StandardValidTerm> answers,
List<StandardCodeSequence> nonQuantifableAnswers,
List<StandardValidTerm> initialSelection,
int minCardinality, int maxCardinality,
int questionNumber, bool hasConfidence,
bool addFirstDefaultItem,
bool shouldDisplay) :
this(
label,
questionType,
description,
answers,
nonQuantifableAnswers,
initialSelection,
minCardinality,
maxCardinality,
questionNumber,
hasConfidence,
addFirstDefaultItem,
shouldDisplay,
null) { }
public SimpleQuestionControl(
string label,
StandardValidTerm questionType,
string description,
List<StandardValidTerm> answers,
List<StandardCodeSequence> nonQuantifableAnswers,
List<StandardValidTerm> initialSelection,
int minCardinality, int maxCardinality,
int questionNumber, bool hasConfidence,
bool addFirstDefaultItem,
bool shouldDisplay,
List<string> staticDisplayItems)
{
Platform.CheckForNullReference(answers, "answers");
InitializeComponent();
_questionType = questionType;
_lblEntity.Text = _questionType == null
? label
: CodeUtils.ToStringBuilder(_questionType, new StringBuilder()).ToString();
_lblEntity.ToolTipText = SplitIntoLines(description);
_lblEntity.ShowToolTipChanged += OnLabelShowToolTipChanged;
_lblEntity.TabStop = false;
_questionNumber = questionNumber;
Debug.Assert(maxCardinality - minCardinality >= 0, "MinCardinality must be less or equal to MaxCardinality in a question");
_maxNumberOfAnswers = Math.Max(1, Math.Min(answers.Count, maxCardinality));
var availableAnswers = new List<StandardValidTerm>(answers);
if (nonQuantifableAnswers != null)
{
Debug.Assert(false, "Non-quantifieables should not really be here");
availableAnswers.InsertRange(0, ComponentUtilities.ToStandardValidTermList(nonQuantifableAnswers));
}
_selectedAnswers = initialSelection;
_staticDisplayItems = staticDisplayItems;
if (shouldDisplay)
{
SuspendLayout();
_questionControl = InitializeResponseControl(availableAnswers, initialSelection, addFirstDefaultItem);
Controls.Add(_questionControl);
Height += _questionControl.Height + 3;
if (hasConfidence)
{
_confidenceControl = InitializeConfidenceControl();
Controls.Add(_confidenceControl);
Height += _confidenceControl.Height + 3;
}
ResumeLayout(false);
PerformLayout();
}
else
{
if (initialSelection == null || initialSelection.Count == 0)
Platform.Log(LogLevel.Error,
"Template data error: no default values are provided for questions that are not going to be displayed. Template answers are never going to be valid");
}
}
private Control InitializeResponseControl(List<StandardValidTerm> codeList, List<StandardValidTerm> initialSelection, bool addFirstDefault)
{
var ptX = _lblEntity.Location.X + 3;
var ptY = _lblEntity.Location.Y + _lblEntity.Height;
if (_staticDisplayItems != null)
{
var staticLines = String.Empty;
foreach (var staticDisplayItem in _staticDisplayItems)
staticLines += staticDisplayItem + Environment.NewLine;
var label = new Label
{
Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right,
Margin = new Padding(4),
Location = new System.Drawing.Point(ptX, ptY),
Name = "staticDisplayItemLabel"
};
label.AutoSize = true;
label.Text = staticLines;
return label;
}
if (_maxNumberOfAnswers > 1)
{
var chklistEntity = new CheckedListBox();
chklistEntity.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
chklistEntity.FormattingEnabled = true;
chklistEntity.Margin = new Padding(4);
chklistEntity.Location = new System.Drawing.Point(ptX, ptY);
chklistEntity.IntegralHeight = false;
chklistEntity.Name = "chklistEntity";
var ctrlHeight = (codeList == null ? 1 : Math.Max(1, codeList.Count)) * (chklistEntity.ItemHeight + 2) + chklistEntity.ItemHeight / 2;
chklistEntity.Size = new System.Drawing.Size(Width - ptX, ctrlHeight);
chklistEntity.TabIndex = 1;
chklistEntity.CheckOnClick = true;
foreach (var validTerm in codeList)
{
var idx = chklistEntity.Items.Add(new ValidTermListItem(validTerm));
var sequence = validTerm;
if (initialSelection != null && CollectionUtils.Contains(initialSelection, cs => cs.Equals(sequence)))
chklistEntity.SetItemChecked(idx, true);
}
chklistEntity.ItemCheck += OnItemCheck;
return chklistEntity;
}
var ddlEntity = new ComboBox();
ddlEntity.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ddlEntity.DropDownStyle = ComboBoxStyle.DropDownList;
ddlEntity.FormattingEnabled = true;
ddlEntity.Margin = new Padding(4);
ddlEntity.Location = new System.Drawing.Point(ptX, ptY);
ddlEntity.Name = "ddlEntity";
ddlEntity.Size = new System.Drawing.Size(Width - ptX, ddlEntity.Height);
ddlEntity.TabIndex = 1;
if (addFirstDefault)
ddlEntity.Items.Add(new ValidTermListItem(null));
foreach (var validTerm in codeList)
{
var idx = ddlEntity.Items.Add(new ValidTermListItem(validTerm));
var term = validTerm;
if (initialSelection != null && ddlEntity.SelectedIndex == -1 && CollectionUtils.Contains(initialSelection, cs => cs.Equals(term)))
ddlEntity.SelectedIndex = idx;
}
if (ddlEntity.SelectedIndex == -1 && ddlEntity.Items.Count > 0)
ddlEntity.SelectedIndex = 0;
ddlEntity.DropDown += OnDropDown;
ddlEntity.SelectedIndexChanged += OnSelectedIndexChanged;
return ddlEntity;
}
private ConfidenceControl InitializeConfidenceControl()
{
var previousCtrl = _questionControl ?? _lblEntity;
var ptX = previousCtrl.Location.X;
var ptY = previousCtrl.Location.Y + previousCtrl.Height + 3;
var confidenceControl = new ConfidenceControl();
confidenceControl.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
confidenceControl.Location = new System.Drawing.Point(ptX, ptY);
confidenceControl.TabIndex = previousCtrl.TabIndex + 1;
confidenceControl.Size = new System.Drawing.Size(Width - ptX, confidenceControl.Height);
confidenceControl.ConfidenceChanged += OnConfidenceChanged;
return confidenceControl;
}
public bool HasMoreThanOneAnswer
{
get
{
if (_questionControl is ComboBox)
return ((ComboBox)_questionControl).Items.Count > 1;
if (_questionControl is CheckedListBox)
return ((CheckedListBox)_questionControl).Items.Count > 1;
return false;
}
}
public int QuestionNumber
{
get { return _questionNumber; }
}
public string Label
{
get { return _lblEntity.Text; }
}
public List<StandardValidTerm> SelectedAnswers
{
get { return _selectedAnswers; }
set
{
if (_selectedAnswers == value)
return;
_selectedAnswers = value;
FireSelectedAnswerChanged();
}
}
public void Reset(List<StandardValidTerm> selectedItems)
{
var hasChanges = false;
var itemsToSelect = selectedItems ?? new List<StandardValidTerm>();
_fireChangeEvent = false;
if (_questionControl != null)
{
if (_questionControl is ComboBox)
{
var cmbQuestion = (ComboBox)_questionControl;
if (cmbQuestion.Items.Count > 0)
{
if (itemsToSelect.Count == 0 && cmbQuestion.SelectedIndex != 0)
{
hasChanges = true;
cmbQuestion.SelectedIndex = 0;
}
else
{
var listItem = cmbQuestion.SelectedItem as ValidTermListItem;
if (listItem == null || listItem.Value == null || !CollectionUtils.Contains(itemsToSelect, code => code.Equals(listItem.Value)))
{
for (var idx = 0; idx < cmbQuestion.Items.Count; idx++)
{
var item = cmbQuestion.Items[idx] as ValidTermListItem;
if (item != null && item.Value != null && CollectionUtils.Contains(itemsToSelect, code => code.Equals(item.Value)))
{
hasChanges = true;
cmbQuestion.SelectedIndex = idx;
break;
}
}
}
}
}
}
else if (_questionControl is CheckedListBox)
{
var chkBox = (CheckedListBox)_questionControl;
while (chkBox.CheckedIndices.Count > 0)
{
hasChanges = true;
chkBox.SetItemChecked(chkBox.CheckedIndices[0], false);
}
if (itemsToSelect.Count > 0)
{
for (var idx = 0; idx < chkBox.Items.Count; idx++)
{
var listItem = chkBox.Items[idx] as ValidTermListItem;
if (listItem != null && listItem.Value != null && CollectionUtils.Contains(itemsToSelect, code => code.Equals(listItem.Value)))
{
hasChanges = true;
chkBox.SetItemChecked(idx, true);
}
}
}
}
}
if (_confidenceControl != null && _confidenceControl.Value != 1.0d)
{
hasChanges = true;
_confidenceControl.Value = 1.0d;
}
_fireChangeEvent = true;
if (hasChanges)
FireSelectedAnswerChanged();
}
private void OnDropDown(object sender, EventArgs e)
{
var cmbBox = sender as ComboBox;
if (cmbBox != null)
cmbBox.DropDownWidth = AimWinFormsUtil.CalculateComboBoxDropdownWidth(cmbBox);
}
private void OnSelectedIndexChanged(object sender, EventArgs e)
{
var cmbBox = sender as ComboBox;
if (cmbBox != null)
{
var listItem = cmbBox.SelectedItem as ValidTermListItem;
if (listItem != null && listItem.Value != null)
SelectedAnswers = new List<StandardValidTerm> { listItem.Value };
else
SelectedAnswers = null;
}
}
private void OnItemCheck(object sender, ItemCheckEventArgs e)
{
if (sender is CheckedListBox)
{
var checkedListBox = (CheckedListBox)sender;
if (e.NewValue == CheckState.Checked && checkedListBox.CheckedItems.Count >= _maxNumberOfAnswers)
{
e.NewValue = e.CurrentValue;
}
else
{
SynchronizationContext.Current.Post(
delegate
{ ProcessCheckedItems(checkedListBox); }
, null);
}
}
}
private void ProcessCheckedItems(CheckedListBox checkListBox)
{
Debug.Assert(checkListBox != null);
List<StandardValidTerm> validTerms = null;
if (checkListBox.CheckedItems.Count > 0)
{
validTerms = new List<StandardValidTerm>();
foreach (var checkedItem in checkListBox.CheckedItems)
{
ValidTermListItem validTermListItem = checkedItem as ValidTermListItem;
if (validTermListItem != null && validTermListItem.Value != null)
validTerms.Add(validTermListItem.Value);
}
}
SelectedAnswers = validTerms == null || validTerms.Count == 0 ? null : validTerms;
}
private void OnConfidenceChanged(object sender, EventArgs e)
{
FireSelectedAnswerChanged();
}
private void OnLabelShowToolTipChanged(object sender, EventArgs e)
{
_toolTip.SetToolTip(_lblEntity, _lblEntity.ShowToolTip ? _lblEntity.ToolTipText : null);
}
private void FireSelectedAnswerChanged()
{
if (!_fireChangeEvent)
return;
if (_confidenceControl == null)
EventsHelper.Fire(SelectedResponseChanged, this, new ResponseChangedEventArgs(SelectedAnswers, QuestionNumber));
else
{
var confidence = _confidenceControl.Value;
{
EventsHelper.Fire(SelectedResponseChanged, this, new ResponseChangedEventArgs(SelectedAnswers, QuestionNumber, confidence));
}
}
}
private string SplitIntoLines(string inLine)
{
if (string.IsNullOrEmpty(inLine))
return null;
const int maxLineLength = 90;
var words = inLine.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var sb = new StringBuilder();
var len = 0;
foreach (var word in words)
{
if (len + word.Length > maxLineLength)
{
sb.Append(Environment.NewLine);
len = word.Length;
}
else
{
len += word.Length + 1;
sb.Append(" ");
}
sb.Append(word);
}
return sb.ToString().Trim();
}
}
internal class ResponseChangedEventArgs : EventArgs
{
public List<StandardValidTerm> Responses { get; private set; }
public int QuestionNumber { get; private set; }
public double? Confidence { get; private set; }
public ResponseChangedEventArgs(List<StandardValidTerm> answers, int questionNumber)
{
Responses = answers == null ? null : new List<StandardValidTerm>(answers);
QuestionNumber = questionNumber;
}
public ResponseChangedEventArgs(List<StandardValidTerm> answers, int questionNumber, double confidence)
{
Responses = answers == null ? null : new List<StandardValidTerm>(answers);
QuestionNumber = questionNumber;
Confidence = confidence;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// ----------------------------------------------------------------------------
// This class takes an EXPRMEMGRP and a set of arguments and binds the arguments
// to the best applicable method in the group.
// ----------------------------------------------------------------------------
internal partial class ExpressionBinder
{
internal class GroupToArgsBinder
{
private enum Result
{
Success,
Failure_SearchForExpanded,
Failure_NoSearchForExpanded
}
private ExpressionBinder _pExprBinder;
private bool _fCandidatesUnsupported;
private BindingFlag _fBindFlags;
private EXPRMEMGRP _pGroup;
private ArgInfos _pArguments;
private ArgInfos _pOriginalArguments;
private bool _bHasNamedArguments;
private AggregateType _pDelegate;
private AggregateType _pCurrentType;
private MethodOrPropertySymbol _pCurrentSym;
private TypeArray _pCurrentTypeArgs;
private TypeArray _pCurrentParameters;
private TypeArray _pBestParameters;
private int _nArgBest;
// Keep track of the first 20 or so syms with the wrong arg count.
private SymWithType[] _swtWrongCount = new SymWithType[20];
private int _nWrongCount;
private bool _bIterateToEndOfNsList; // we have found an appliacable extension method only itereate to
// end of current namespaces extension method list
private bool _bBindingCollectionAddArgs; // Report parameter modifiers as error
private GroupToArgsBinderResult _results;
private List<CandidateFunctionMember> _methList;
private MethPropWithInst _mpwiParamTypeConstraints;
private MethPropWithInst _mpwiBogus;
private MethPropWithInst _mpwiCantInferInstArg;
private MethWithType _mwtBadArity;
private Name _pInvalidSpecifiedName;
private Name _pNameUsedInPositionalArgument;
private Name _pDuplicateSpecifiedName;
// When we find a type with an interface, then we want to mark all other interfaces that it
// implements as being hidden. We also want to mark object as being hidden. So stick them
// all in this list, and then for subsequent types, if they're in this list, then we
// ignore them.
private List<CType> _HiddenTypes;
private bool _bArgumentsChangedForNamedOrOptionalArguments;
public GroupToArgsBinder(ExpressionBinder exprBinder, BindingFlag bindFlags, EXPRMEMGRP grp, ArgInfos args, ArgInfos originalArgs, bool bHasNamedArguments, AggregateType atsDelegate)
{
Debug.Assert(grp != null);
Debug.Assert(exprBinder != null);
Debug.Assert(args != null);
_pExprBinder = exprBinder;
_fCandidatesUnsupported = false;
_fBindFlags = bindFlags;
_pGroup = grp;
_pArguments = args;
_pOriginalArguments = originalArgs;
_bHasNamedArguments = bHasNamedArguments;
_pDelegate = atsDelegate;
_pCurrentType = null;
_pCurrentSym = null;
_pCurrentTypeArgs = null;
_pCurrentParameters = null;
_pBestParameters = null;
_nArgBest = -1;
_nWrongCount = 0;
_bIterateToEndOfNsList = false;
_bBindingCollectionAddArgs = false;
_results = new GroupToArgsBinderResult();
_methList = new List<CandidateFunctionMember>();
_mpwiParamTypeConstraints = new MethPropWithInst();
_mpwiBogus = new MethPropWithInst();
_mpwiCantInferInstArg = new MethPropWithInst();
_mwtBadArity = new MethWithType();
_HiddenTypes = new List<CType>();
}
// ----------------------------------------------------------------------------
// This method does the actual binding.
// ----------------------------------------------------------------------------
public bool Bind(bool bReportErrors)
{
Debug.Assert(_pGroup.sk == SYMKIND.SK_MethodSymbol || _pGroup.sk == SYMKIND.SK_PropertySymbol && 0 != (_pGroup.flags & EXPRFLAG.EXF_INDEXER));
// We need the EXPRs for error reporting for non-delegates
Debug.Assert(_pDelegate != null || _pArguments.fHasExprs);
LookForCandidates();
if (!GetResultOfBind(bReportErrors))
{
if (bReportErrors)
{
ReportErrorsOnFailure();
}
return false;
}
return true;
}
public GroupToArgsBinderResult GetResultsOfBind()
{
return _results;
}
public bool BindCollectionAddArgs()
{
_bBindingCollectionAddArgs = true;
return Bind(true /* bReportErrors */);
}
private SymbolLoader GetSymbolLoader()
{
return _pExprBinder.GetSymbolLoader();
}
private CSemanticChecker GetSemanticChecker()
{
return _pExprBinder.GetSemanticChecker();
}
private ErrorHandling GetErrorContext()
{
return _pExprBinder.GetErrorContext();
}
public static CType GetTypeQualifier(EXPRMEMGRP pGroup)
{
Debug.Assert(pGroup != null);
CType rval = null;
if (0 != (pGroup.flags & EXPRFLAG.EXF_BASECALL))
{
rval = null;
}
else if (0 != (pGroup.flags & EXPRFLAG.EXF_CTOR))
{
rval = pGroup.GetParentType();
}
else if (pGroup.GetOptionalObject() != null)
{
rval = pGroup.GetOptionalObject().type;
}
else
{
rval = null;
}
return rval;
}
private void LookForCandidates()
{
bool fExpanded = false;
bool bSearchForExpanded = true;
int cswtMaxWrongCount = _swtWrongCount.Length;
bool allCandidatesUnsupported = true;
bool lookedAtCandidates = false;
// Calculate the mask based on the type of the sym we've found so far. This
// is to ensure that if we found a propsym (or methsym, or whatever) the
// iterator will only return propsyms (or methsyms, or whatever)
symbmask_t mask = (symbmask_t)(1 << (int)_pGroup.sk);
CType pTypeThrough = _pGroup.GetOptionalObject() != null ? _pGroup.GetOptionalObject().type : null;
CMemberLookupResults.CMethodIterator iterator = _pGroup.GetMemberLookupResults().GetMethodIterator(GetSemanticChecker(), GetSymbolLoader(), pTypeThrough, GetTypeQualifier(_pGroup), _pExprBinder.ContextForMemberLookup(), true, // AllowBogusAndInaccessible
false, _pGroup.typeArgs.size, _pGroup.flags, mask);
while (true)
{
bool bFoundExpanded;
Result currentTypeArgsResult;
bFoundExpanded = false;
if (bSearchForExpanded && !fExpanded)
{
bFoundExpanded = fExpanded = ConstructExpandedParameters();
}
// Get the next sym to search for.
if (!bFoundExpanded)
{
fExpanded = false;
if (!GetNextSym(iterator))
{
break;
}
// Get the parameters.
_pCurrentParameters = _pCurrentSym.Params;
bSearchForExpanded = true;
}
if (_bArgumentsChangedForNamedOrOptionalArguments)
{
// If we changed them last time, then we need to reset them.
_bArgumentsChangedForNamedOrOptionalArguments = false;
CopyArgInfos(_pOriginalArguments, _pArguments);
}
// If we have named arguments, reorder them for this method.
if (_pArguments.fHasExprs)
{
// If we dont have EXPRs, its because we're doing a method group conversion.
// In those scenarios, we never want to add named arguments or optional arguments.
if (_bHasNamedArguments)
{
if (!ReOrderArgsForNamedArguments())
{
continue;
}
}
else if (HasOptionalParameters())
{
if (!AddArgumentsForOptionalParameters())
{
continue;
}
}
}
if (!bFoundExpanded)
{
lookedAtCandidates = true;
allCandidatesUnsupported &= _pCurrentSym.getBogus();
// If we have the wrong number of arguments and still have room in our cache of 20,
// then store it in our cache and go to the next sym.
if (_pCurrentParameters.size != _pArguments.carg)
{
if (_nWrongCount < cswtMaxWrongCount &&
(!_pCurrentSym.isParamArray || _pArguments.carg < _pCurrentParameters.size - 1))
{
_swtWrongCount[_nWrongCount++] = new SymWithType(_pCurrentSym, _pCurrentType);
}
bSearchForExpanded = true;
continue;
}
}
// If we cant use the current symbol, then we've filtered it, so get the next one.
if (!iterator.CanUseCurrentSymbol())
{
continue;
}
// Get the current type args.
currentTypeArgsResult = DetermineCurrentTypeArgs();
if (currentTypeArgsResult != Result.Success)
{
bSearchForExpanded = (currentTypeArgsResult == Result.Failure_SearchForExpanded);
continue;
}
// Check access.
bool fCanAccess = !iterator.IsCurrentSymbolInaccessible();
if (!fCanAccess && (!_methList.IsEmpty() || _results.GetInaccessibleResult()))
{
// We'll never use this one for error reporting anyway, so just skip it.
bSearchForExpanded = false;
continue;
}
// Check bogus.
bool fBogus = fCanAccess && iterator.IsCurrentSymbolBogus();
if (fBogus && (!_methList.IsEmpty() || _results.GetInaccessibleResult() || _mpwiBogus))
{
// We'll never use this one for error reporting anyway, so just skip it.
bSearchForExpanded = false;
continue;
}
// Check convertibility of arguments.
if (!ArgumentsAreConvertible())
{
bSearchForExpanded = true;
continue;
}
// We know we have the right number of arguments and they are all convertible.
if (!fCanAccess)
{
// In case we never get an accessible method, this will allow us to give
// a better error...
Debug.Assert(!_results.GetInaccessibleResult());
_results.GetInaccessibleResult().Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
}
else if (fBogus)
{
// In case we never get a good method, this will allow us to give
// a better error...
Debug.Assert(!_mpwiBogus);
_mpwiBogus.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
}
else
{
// This is a plausible method / property to call.
// Link it in at the end of the list.
_methList.Add(new CandidateFunctionMember(
new MethPropWithInst(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs),
_pCurrentParameters,
0,
fExpanded));
// When we find a method, we check if the type has interfaces. If so, mark the other interfaces
// as hidden, and object as well.
if (_pCurrentType.isInterfaceType())
{
TypeArray ifaces = _pCurrentType.GetIfacesAll();
for (int i = 0; i < ifaces.size; i++)
{
AggregateType type = ifaces.Item(i).AsAggregateType();
Debug.Assert(type.isInterfaceType());
_HiddenTypes.Add(type);
}
// Mark object.
AggregateType typeObject = GetSymbolLoader().GetReqPredefType(PredefinedType.PT_OBJECT, true);
_HiddenTypes.Add(typeObject);
}
}
// Don't look at the expanded form.
bSearchForExpanded = false;
}
_fCandidatesUnsupported = allCandidatesUnsupported && lookedAtCandidates;
// Restore the arguments to their original state if we changed them for named/optional arguments.
// ILGen will take care of putting the real arguments in there.
if (_bArgumentsChangedForNamedOrOptionalArguments)
{
// If we changed them last time, then we need to reset them.
CopyArgInfos(_pOriginalArguments, _pArguments);
}
}
private void CopyArgInfos(ArgInfos src, ArgInfos dst)
{
dst.carg = src.carg;
dst.types = src.types;
dst.fHasExprs = src.fHasExprs;
dst.prgexpr.Clear();
for (int i = 0; i < src.prgexpr.Count; i++)
{
dst.prgexpr.Add(src.prgexpr[i]);
}
}
private bool GetResultOfBind(bool bReportErrors)
{
// We looked at all the evidence, and we come to render the verdict:
CandidateFunctionMember pmethBest;
if (!_methList.IsEmpty())
{
if (_methList.Count == 1)
{
// We found the single best method to call.
pmethBest = _methList.Head();
}
else
{
// We have some ambiguities, lets sort them out.
CandidateFunctionMember pAmbig1 = null;
CandidateFunctionMember pAmbig2 = null;
CType pTypeThrough = _pGroup.GetOptionalObject() != null ? _pGroup.GetOptionalObject().type : null;
pmethBest = _pExprBinder.FindBestMethod(_methList, pTypeThrough, _pArguments, out pAmbig1, out pAmbig2);
if (null == pmethBest)
{
// Arbitrarily use the first one, but make sure to report errors or give the ambiguous one
// back to the caller.
pmethBest = pAmbig1;
_results.AmbiguousResult = pAmbig2.mpwi;
if (bReportErrors)
{
if (pAmbig1.@params != pAmbig2.@params ||
pAmbig1.mpwi.MethProp().Params.size != pAmbig2.mpwi.MethProp().Params.size ||
pAmbig1.mpwi.TypeArgs != pAmbig2.mpwi.TypeArgs ||
pAmbig1.mpwi.GetType() != pAmbig2.mpwi.GetType() ||
pAmbig1.mpwi.MethProp().Params == pAmbig2.mpwi.MethProp().Params)
{
GetErrorContext().Error(ErrorCode.ERR_AmbigCall, pAmbig1.mpwi, pAmbig2.mpwi);
}
else
{
// The two signatures are identical so don't use the type args in the error message.
GetErrorContext().Error(ErrorCode.ERR_AmbigCall, pAmbig1.mpwi.MethProp(), pAmbig2.mpwi.MethProp());
}
}
}
}
// This is the "success" exit path.
Debug.Assert(pmethBest != null);
_results.BestResult = pmethBest.mpwi;
// Record our best match in the memgroup as well. This is temporary.
if (bReportErrors)
{
ReportErrorsOnSuccess();
}
return true;
}
return false;
}
/////////////////////////////////////////////////////////////////////////////////
// This method returns true if we're able to match arguments to their names.
// If we either have too many arguments, or we cannot match their names, then
// we return false.
//
// Note that if we have not enough arguments, we still return true as long as
// we can find matching parameters for each named arguments, and all parameters
// that do not have a matching argument are optional parameters.
private bool ReOrderArgsForNamedArguments()
{
// First we need to find the method that we're actually trying to call.
MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.GetOptionalObject());
if (methprop == null)
{
return false;
}
int numParameters = _pCurrentParameters.size;
// If we have no parameters, or fewer parameters than we have arguments, bail.
if (numParameters == 0 || numParameters < _pArguments.carg)
{
return false;
}
// Make sure all the names we specified are in the list and we dont have duplicates.
if (!NamedArgumentNamesAppearInParameterList(methprop))
{
return false;
}
_bArgumentsChangedForNamedOrOptionalArguments = ReOrderArgsForNamedArguments(
methprop,
_pCurrentParameters,
_pCurrentType,
_pGroup,
_pArguments,
_pExprBinder.GetTypes(),
_pExprBinder.GetExprFactory(),
GetSymbolLoader());
return _bArgumentsChangedForNamedOrOptionalArguments;
}
internal static bool ReOrderArgsForNamedArguments(
MethodOrPropertySymbol methprop,
TypeArray pCurrentParameters,
AggregateType pCurrentType,
EXPRMEMGRP pGroup,
ArgInfos pArguments,
TypeManager typeManager,
ExprFactory exprFactory,
SymbolLoader symbolLoader)
{
// We use the param count from pCurrentParameters because they may have been resized
// for param arrays.
int numParameters = pCurrentParameters.size;
EXPR[] pExprArguments = new EXPR[numParameters];
// Now go through the parameters. First set all positional arguments in the new argument
// set, then for the remainder, look for a named argument with a matching name.
int index = 0;
EXPR paramArrayArgument = null;
TypeArray @params = typeManager.SubstTypeArray(
pCurrentParameters,
pCurrentType,
pGroup.typeArgs);
foreach (Name name in methprop.ParameterNames)
{
// This can happen if we had expanded our param array to size 0.
if (index >= pCurrentParameters.size)
{
break;
}
// If:
// (1) we have a param array method
// (2) we're on the last arg
// (3) the thing we have is an array init thats generated for param array
// then let us through.
if (methprop.isParamArray &&
index < pArguments.carg &&
pArguments.prgexpr[index].isARRINIT() && pArguments.prgexpr[index].asARRINIT().GeneratedForParamArray)
{
paramArrayArgument = pArguments.prgexpr[index];
}
// Positional.
if (index < pArguments.carg &&
!pArguments.prgexpr[index].isNamedArgumentSpecification() &&
!(pArguments.prgexpr[index].isARRINIT() && pArguments.prgexpr[index].asARRINIT().GeneratedForParamArray))
{
pExprArguments[index] = pArguments.prgexpr[index++];
continue;
}
// Look for names.
EXPR pNewArg = FindArgumentWithName(pArguments, name);
if (pNewArg == null)
{
if (methprop.IsParameterOptional(index))
{
pNewArg = GenerateOptionalArgument(symbolLoader, exprFactory, methprop, @params.Item(index), index);
}
else if (paramArrayArgument != null && index == methprop.Params.Count - 1)
{
// If we have a param array argument and we're on the last one, then use it.
pNewArg = paramArrayArgument;
}
else
{
// No name and no default value.
return false;
}
}
pExprArguments[index++] = pNewArg;
}
// Here we've found all the arguments, or have default values for them.
CType[] prgTypes = new CType[pCurrentParameters.size];
for (int i = 0; i < numParameters; i++)
{
if (i < pArguments.prgexpr.Count)
{
pArguments.prgexpr[i] = pExprArguments[i];
}
else
{
pArguments.prgexpr.Add(pExprArguments[i]);
}
prgTypes[i] = pArguments.prgexpr[i].type;
}
pArguments.carg = pCurrentParameters.size;
pArguments.types = symbolLoader.getBSymmgr().AllocParams(pCurrentParameters.size, prgTypes);
return true;
}
/////////////////////////////////////////////////////////////////////////////////
private static EXPR GenerateOptionalArgument(
SymbolLoader symbolLoader,
ExprFactory exprFactory,
MethodOrPropertySymbol methprop,
CType type,
int index)
{
CType pParamType = type;
CType pRawParamType = type.IsNullableType() ? type.AsNullableType().GetUnderlyingType() : type;
EXPR optionalArgument = null;
if (methprop.HasDefaultParameterValue(index))
{
CType pConstValType = methprop.GetDefaultParameterValueConstValType(index);
CONSTVAL cv = methprop.GetDefaultParameterValue(index);
if (pConstValType.isPredefType(PredefinedType.PT_DATETIME) &&
(pRawParamType.isPredefType(PredefinedType.PT_DATETIME) || pRawParamType.isPredefType(PredefinedType.PT_OBJECT) || pRawParamType.isPredefType(PredefinedType.PT_VALUE)))
{
// This is the specific case where we want to create a DateTime
// but the constval that stores it is a long.
AggregateType dateTimeType = symbolLoader.GetReqPredefType(PredefinedType.PT_DATETIME);
optionalArgument = exprFactory.CreateConstant(dateTimeType, new CONSTVAL(DateTime.FromBinary(cv.longVal)));
}
else if (pConstValType.isSimpleOrEnumOrString())
{
// In this case, the constval is a simple type (all the numerics, including
// decimal), or an enum or a string. This covers all the substantial values,
// and everything else that can be encoded is just null or default(something).
// For enum parameters, we create a constant of the enum type. For everything
// else, we create the appropriate constant.
if (pRawParamType.isEnumType() && pConstValType == pRawParamType.underlyingType())
{
optionalArgument = exprFactory.CreateConstant(pRawParamType, cv);
}
else
{
optionalArgument = exprFactory.CreateConstant(pConstValType, cv);
}
}
else if ((pParamType.IsRefType() || pParamType.IsNullableType()) && cv.IsNullRef())
{
// We have an "= null" default value with a reference type or a nullable type.
optionalArgument = exprFactory.CreateNull();
}
else
{
// We have a default value that is encoded as a nullref, and that nullref is
// interpreted as default(something). For instance, the pParamType could be
// a type parameter type or a non-simple value type.
optionalArgument = exprFactory.CreateZeroInit(pParamType);
}
}
else
{
// There was no default parameter specified, so generally use default(T),
// except for some cases when the parameter type in metatdata is object.
if (pParamType.isPredefType(PredefinedType.PT_OBJECT))
{
if (methprop.MarshalAsObject(index))
{
// For [opt] parameters of type object, if we have marshal(iunknown),
// marshal(idispatch), or marshal(interface), then we emit a null.
optionalArgument = exprFactory.CreateNull();
}
else
{
// Otherwise, we generate Type.Missing
AggregateSymbol agg = symbolLoader.GetOptPredefAgg(PredefinedType.PT_MISSING);
Name name = symbolLoader.GetNameManager().GetPredefinedName(PredefinedName.PN_CAP_VALUE);
FieldSymbol field = symbolLoader.LookupAggMember(name, agg, symbmask_t.MASK_FieldSymbol).AsFieldSymbol();
FieldWithType fwt = new FieldWithType(field, agg.getThisType());
EXPRFIELD exprField = exprFactory.CreateField(0, agg.getThisType(), null, 0, fwt, null);
if (agg.getThisType() != type)
{
optionalArgument = exprFactory.CreateCast(0, type, exprField);
}
else
{
optionalArgument = exprField;
}
}
}
else
{
// Every type aside from object that doesn't have a default value gets
// its default value.
optionalArgument = exprFactory.CreateZeroInit(pParamType);
}
}
Debug.Assert(optionalArgument != null);
optionalArgument.IsOptionalArgument = true;
return optionalArgument;
}
/////////////////////////////////////////////////////////////////////////////////
private MethodOrPropertySymbol FindMostDerivedMethod(
MethodOrPropertySymbol pMethProp,
EXPR pObject)
{
return FindMostDerivedMethod(GetSymbolLoader(), pMethProp, pObject != null ? pObject.type : null);
}
/////////////////////////////////////////////////////////////////////////////////
public static MethodOrPropertySymbol FindMostDerivedMethod(
SymbolLoader symbolLoader,
MethodOrPropertySymbol pMethProp,
CType pType)
{
MethodSymbol method;
bool bIsIndexer = false;
if (pMethProp.IsMethodSymbol())
{
method = pMethProp.AsMethodSymbol();
}
else
{
PropertySymbol prop = pMethProp.AsPropertySymbol();
method = prop.methGet != null ? prop.methGet : prop.methSet;
if (method == null)
{
return null;
}
bIsIndexer = prop.isIndexer();
}
if (!method.isVirtual)
{
return method;
}
if (pType == null)
{
// This must be a static call.
return method;
}
// Now get the slot method.
if (method.swtSlot != null && method.swtSlot.Meth() != null)
{
method = method.swtSlot.Meth();
}
if (!pType.IsAggregateType())
{
// Not something that can have overrides anyway.
return method;
}
for (AggregateSymbol pAggregate = pType.AsAggregateType().GetOwningAggregate();
pAggregate != null && pAggregate.GetBaseAgg() != null;
pAggregate = pAggregate.GetBaseAgg())
{
for (MethodOrPropertySymbol meth = symbolLoader.LookupAggMember(method.name, pAggregate, symbmask_t.MASK_MethodSymbol | symbmask_t.MASK_PropertySymbol).AsMethodOrPropertySymbol();
meth != null;
meth = symbolLoader.LookupNextSym(meth, pAggregate, symbmask_t.MASK_MethodSymbol | symbmask_t.MASK_PropertySymbol).AsMethodOrPropertySymbol())
{
if (!meth.isOverride)
{
continue;
}
if (meth.swtSlot.Sym != null && meth.swtSlot.Sym == method)
{
if (bIsIndexer)
{
Debug.Assert(meth.IsMethodSymbol());
return meth.AsMethodSymbol().getProperty();
}
else
{
return meth;
}
}
}
}
// If we get here, it means we can have two cases: one is that we have
// a delegate. This is because the delegate invoke method is virtual and is
// an override, but we wont have the slots set up correctly, and will
// not find the base type in the inheritance hierarchy. The second is that
// we're calling off of the base itself.
Debug.Assert(method.parent.IsAggregateSymbol());
return method;
}
/////////////////////////////////////////////////////////////////////////////////
private bool HasOptionalParameters()
{
MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.GetOptionalObject());
return methprop != null ? methprop.HasOptionalParameters() : false;
}
/////////////////////////////////////////////////////////////////////////////////
// Returns true if we can either add enough optional parameters to make the
// argument list match, or if we dont need to at all.
private bool AddArgumentsForOptionalParameters()
{
if (_pCurrentParameters.size <= _pArguments.carg)
{
// If we have enough arguments, or too many, no need to add any optionals here.
return true;
}
// First we need to find the method that we're actually trying to call.
MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.GetOptionalObject());
if (methprop == null)
{
return false;
}
// If we're here, we know we're not in a named argument case. As such, we can
// just generate defaults for every missing argument.
int i = _pArguments.carg;
int index = 0;
TypeArray @params = _pExprBinder.GetTypes().SubstTypeArray(
_pCurrentParameters,
_pCurrentType,
_pGroup.typeArgs);
EXPR[] pArguments = new EXPR[_pCurrentParameters.size - i];
for (; i < @params.size; i++, index++)
{
if (!methprop.IsParameterOptional(i))
{
// We dont have an optional here, but we need to fill it in.
return false;
}
pArguments[index] = GenerateOptionalArgument(GetSymbolLoader(), _pExprBinder.GetExprFactory(), methprop, @params.Item(i), i);
}
// Success. Lets copy them in now.
for (int n = 0; n < index; n++)
{
_pArguments.prgexpr.Add(pArguments[n]);
}
CType[] prgTypes = new CType[@params.size];
for (int n = 0; n < @params.size; n++)
{
prgTypes[n] = _pArguments.prgexpr[n].type;
}
_pArguments.types = GetSymbolLoader().getBSymmgr().AllocParams(@params.size, prgTypes);
_pArguments.carg = @params.size;
_bArgumentsChangedForNamedOrOptionalArguments = true;
return true;
}
/////////////////////////////////////////////////////////////////////////////////
private static EXPR FindArgumentWithName(ArgInfos pArguments, Name pName)
{
for (int i = 0; i < pArguments.carg; i++)
{
if (pArguments.prgexpr[i].isNamedArgumentSpecification() &&
pArguments.prgexpr[i].asNamedArgumentSpecification().Name == pName)
{
return pArguments.prgexpr[i];
}
}
return null;
}
/////////////////////////////////////////////////////////////////////////////////
private bool NamedArgumentNamesAppearInParameterList(
MethodOrPropertySymbol methprop)
{
// Keep track of the current position in the parameter list so that we can check
// containment from this point onwards as well as complete containment. This is
// for error reporting. The user cannot specify a named argument for a parameter
// that has a fixed argument value.
List<Name> currentPosition = methprop.ParameterNames;
HashSet<Name> names = new HashSet<Name>();
for (int i = 0; i < _pArguments.carg; i++)
{
if (!_pArguments.prgexpr[i].isNamedArgumentSpecification())
{
if (!currentPosition.IsEmpty())
{
currentPosition = currentPosition.Tail();
}
continue;
}
Name name = _pArguments.prgexpr[i].asNamedArgumentSpecification().Name;
if (!methprop.ParameterNames.Contains(name))
{
if (_pInvalidSpecifiedName == null)
{
_pInvalidSpecifiedName = name;
}
return false;
}
else if (!currentPosition.Contains(name))
{
if (_pNameUsedInPositionalArgument == null)
{
_pNameUsedInPositionalArgument = name;
}
return false;
}
if (names.Contains(name))
{
if (_pDuplicateSpecifiedName == null)
{
_pDuplicateSpecifiedName = name;
}
return false;
}
names.Add(name);
}
return true;
}
// This method returns true if we have another sym to consider.
// If we've found a match in the current type, and have no more syms to consider in this type, then we
// return false.
private bool GetNextSym(CMemberLookupResults.CMethodIterator iterator)
{
if (!iterator.MoveNext(_methList.IsEmpty(), _bIterateToEndOfNsList))
{
return false;
}
_pCurrentSym = iterator.GetCurrentSymbol();
AggregateType type = iterator.GetCurrentType();
// If our current type is null, this is our first iteration, so set the type.
// If our current type is not null, and we've got a new type now, and we've already matched
// a symbol, then bail out.
if (_pCurrentType != type &&
_pCurrentType != null &&
!_methList.IsEmpty() &&
!_methList.Head().mpwi.GetType().isInterfaceType() &&
(!_methList.Head().mpwi.Sym.IsMethodSymbol() || !_methList.Head().mpwi.Meth().IsExtension()))
{
return false;
}
else if (_pCurrentType != type &&
_pCurrentType != null &&
!_methList.IsEmpty() &&
!_methList.Head().mpwi.GetType().isInterfaceType() &&
_methList.Head().mpwi.Sym.IsMethodSymbol() &&
_methList.Head().mpwi.Meth().IsExtension())
{
// we have found a applicable method that is an extension now we must move to the end of the NS list before quiting
if (_pGroup.GetOptionalObject() != null)
{
// if we find this while looking for static methods we should ignore it
_bIterateToEndOfNsList = true;
}
}
_pCurrentType = type;
// We have a new type. If this type is hidden, we need another type.
while (_HiddenTypes.Contains(_pCurrentType))
{
// Move through this type and get the next one.
for (; iterator.GetCurrentType() == _pCurrentType; iterator.MoveNext(_methList.IsEmpty(), _bIterateToEndOfNsList)) ;
_pCurrentSym = iterator.GetCurrentSymbol();
_pCurrentType = iterator.GetCurrentType();
if (iterator.AtEnd())
{
return false;
}
}
return true;
}
private bool ConstructExpandedParameters()
{
// Deal with params.
if (_pCurrentSym == null || _pArguments == null || _pCurrentParameters == null)
{
return false;
}
if (0 != (_fBindFlags & BindingFlag.BIND_NOPARAMS))
{
return false;
}
if (!_pCurrentSym.isParamArray)
{
return false;
}
// Count the number of optionals in the method. If there are enough optionals
// and actual arguments, then proceed.
{
int numOptionals = 0;
for (int i = _pArguments.carg; i < _pCurrentSym.Params.size; i++)
{
if (_pCurrentSym.IsParameterOptional(i))
{
numOptionals++;
}
}
if (_pArguments.carg + numOptionals < _pCurrentParameters.size - 1)
{
return false;
}
}
Debug.Assert(_methList.IsEmpty() || _methList.Head().mpwi.MethProp() != _pCurrentSym);
// Construct the expanded params.
return _pExprBinder.TryGetExpandedParams(_pCurrentSym.Params, _pArguments.carg, out _pCurrentParameters);
}
private Result DetermineCurrentTypeArgs()
{
TypeArray typeArgs = _pGroup.typeArgs;
// Get the type args.
if (_pCurrentSym.IsMethodSymbol() && _pCurrentSym.AsMethodSymbol().typeVars.size != typeArgs.size)
{
MethodSymbol methSym = _pCurrentSym.AsMethodSymbol();
// Can't infer if some type args are specified.
if (typeArgs.size > 0)
{
if (!_mwtBadArity)
{
_mwtBadArity.Set(methSym, _pCurrentType);
}
return Result.Failure_NoSearchForExpanded;
}
Debug.Assert(methSym.typeVars.size > 0);
// Try to infer. If we have an errorsym in the type arguments, we know we cant infer,
// but we want to attempt it anyway. We'll mark this as "cant infer" so that we can
// report the appropriate error, but we'll continue inferring, since we want
// error sym to go to any type.
bool inferenceSucceeded;
inferenceSucceeded = MethodTypeInferrer.Infer(
_pExprBinder, GetSymbolLoader(),
methSym, _pCurrentType.GetTypeArgsAll(), _pCurrentParameters,
_pArguments, out _pCurrentTypeArgs);
if (!inferenceSucceeded)
{
if (_results.IsBetterUninferrableResult(_pCurrentTypeArgs))
{
TypeArray pTypeVars = methSym.typeVars;
if (pTypeVars != null && _pCurrentTypeArgs != null && pTypeVars.size == _pCurrentTypeArgs.size)
{
_mpwiCantInferInstArg.Set(_pCurrentSym.AsMethodSymbol(), _pCurrentType, _pCurrentTypeArgs);
}
else
{
_mpwiCantInferInstArg.Set(_pCurrentSym.AsMethodSymbol(), _pCurrentType, pTypeVars);
}
}
return Result.Failure_SearchForExpanded;
}
}
else
{
_pCurrentTypeArgs = typeArgs;
}
return Result.Success;
}
private bool ArgumentsAreConvertible()
{
bool containsErrorSym = false;
bool bIsInstanceParameterConvertible = false;
if (_pArguments.carg != 0)
{
UpdateArguments();
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pCurrentParameters.Item(ivar);
bool constraintErrors = !TypeBind.CheckConstraints(GetSemanticChecker(), GetErrorContext(), var, CheckConstraintsFlags.NoErrors);
if (constraintErrors && !DoesTypeArgumentsContainErrorSym(var))
{
_mpwiParamTypeConstraints.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
return false;
}
}
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pCurrentParameters.Item(ivar);
containsErrorSym |= DoesTypeArgumentsContainErrorSym(var);
bool fresult;
if (_pArguments.fHasExprs)
{
EXPR pArgument = _pArguments.prgexpr[ivar];
// If we have a named argument, strip it to do the conversion.
if (pArgument.isNamedArgumentSpecification())
{
pArgument = pArgument.asNamedArgumentSpecification().Value;
}
fresult = _pExprBinder.canConvert(pArgument, var);
}
else
{
fresult = _pExprBinder.canConvert(_pArguments.types.Item(ivar), var);
}
// Mark this as a legitimate error if we didn't have any error syms.
if (!fresult && !containsErrorSym)
{
if (ivar > _nArgBest)
{
_nArgBest = ivar;
// If we already have best method for instance methods don't overwrite with extensions
if (!_results.GetBestResult())
{
_results.GetBestResult().Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
_pBestParameters = _pCurrentParameters;
}
}
else if (ivar == _nArgBest && _pArguments.types.Item(ivar) != var)
{
// this is to eliminate the paranoid case of types that are equal but can't convert
// (think ErrorType != ErrorType)
// See if they just differ in out / ref.
CType argStripped = _pArguments.types.Item(ivar).IsParameterModifierType() ?
_pArguments.types.Item(ivar).AsParameterModifierType().GetParameterType() : _pArguments.types.Item(ivar);
CType varStripped = var.IsParameterModifierType() ? var.AsParameterModifierType().GetParameterType() : var;
if (argStripped == varStripped)
{
// If we already have best method for instance methods don't overwrite with extensions
if (!_results.GetBestResult())
{
_results.GetBestResult().Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
_pBestParameters = _pCurrentParameters;
}
}
}
if (_pCurrentSym.IsMethodSymbol())
{
// Do not store the result if we have an extension method and the instance
// parameter isn't convertible.
if (!_pCurrentSym.AsMethodSymbol().IsExtension() || bIsInstanceParameterConvertible)
{
_results.AddInconvertibleResult(
_pCurrentSym.AsMethodSymbol(),
_pCurrentType,
_pCurrentTypeArgs);
}
}
return false;
}
}
}
if (containsErrorSym)
{
if (_results.IsBetterUninferrableResult(_pCurrentTypeArgs) && _pCurrentSym.IsMethodSymbol())
{
// If we're an instance method or we're an extension that has an inferrable instance argument,
// then mark us down. Note that the extension may not need to infer type args,
// so check if we have any type variables at all to begin with.
if (!_pCurrentSym.AsMethodSymbol().IsExtension() ||
_pCurrentSym.AsMethodSymbol().typeVars.size == 0 ||
MethodTypeInferrer.CanObjectOfExtensionBeInferred(
_pExprBinder,
GetSymbolLoader(),
_pCurrentSym.AsMethodSymbol(),
_pCurrentType.GetTypeArgsAll(),
_pCurrentSym.AsMethodSymbol().Params,
_pArguments))
{
_results.GetUninferrableResult().Set(
_pCurrentSym.AsMethodSymbol(),
_pCurrentType,
_pCurrentTypeArgs);
}
}
}
else
{
if (_pCurrentSym.IsMethodSymbol())
{
// Do not store the result if we have an extension method and the instance
// parameter isn't convertible.
if (!_pCurrentSym.AsMethodSymbol().IsExtension() || bIsInstanceParameterConvertible)
{
_results.AddInconvertibleResult(
_pCurrentSym.AsMethodSymbol(),
_pCurrentType,
_pCurrentTypeArgs);
}
}
}
return !containsErrorSym;
}
private void UpdateArguments()
{
// Parameter types might have changed as a result of
// method type inference.
_pCurrentParameters = _pExprBinder.GetTypes().SubstTypeArray(
_pCurrentParameters, _pCurrentType, _pCurrentTypeArgs);
// It is also possible that an optional argument has changed its value
// as a result of method type inference. For example, when inferring
// from Foo(10) to Foo<T>(T t1, T t2 = default(T)), the fabricated
// argument list starts off as being (10, default(T)). After type
// inference has successfully inferred T as int, it needs to be
// transformed into (10, default(int)) before applicability checking
// notices that default(T) is not assignable to int.
if (_pArguments.prgexpr == null || _pArguments.prgexpr.Count == 0)
{
return;
}
MethodOrPropertySymbol pMethod = null;
for (int iParam = 0; iParam < _pCurrentParameters.size; ++iParam)
{
EXPR pArgument = _pArguments.prgexpr[iParam];
if (!pArgument.IsOptionalArgument)
{
continue;
}
CType pType = _pCurrentParameters.Item(iParam);
if (pType == pArgument.type)
{
continue;
}
// Argument has changed its type because of method type inference. Recompute it.
if (pMethod == null)
{
pMethod = FindMostDerivedMethod(_pCurrentSym, _pGroup.GetOptionalObject());
Debug.Assert(pMethod != null);
}
Debug.Assert(pMethod.IsParameterOptional(iParam));
EXPR pArgumentNew = GenerateOptionalArgument(GetSymbolLoader(), _pExprBinder.GetExprFactory(), pMethod, _pCurrentParameters[iParam], iParam);
_pArguments.prgexpr[iParam] = pArgumentNew;
}
}
private bool DoesTypeArgumentsContainErrorSym(CType var)
{
if (!var.IsAggregateType())
{
return false;
}
TypeArray typeVars = var.AsAggregateType().GetTypeArgsAll();
for (int i = 0; i < typeVars.size; i++)
{
CType type = typeVars.Item(i);
if (type.IsErrorType())
{
return true;
}
else if (type.IsAggregateType())
{
// If we have an agg type sym, check if its type args have errors.
if (DoesTypeArgumentsContainErrorSym(type))
{
return true;
}
}
}
return false;
}
// ----------------------------------------------------------------------------
private void ReportErrorsOnSuccess()
{
// used for Methods and Indexers
Debug.Assert(_pGroup.sk == SYMKIND.SK_MethodSymbol || _pGroup.sk == SYMKIND.SK_PropertySymbol && 0 != (_pGroup.flags & EXPRFLAG.EXF_INDEXER));
Debug.Assert(_pGroup.typeArgs.size == 0 || _pGroup.sk == SYMKIND.SK_MethodSymbol);
// if this is a binding to finalize on object, then complain:
if (_results.GetBestResult().MethProp().name == GetSymbolLoader().GetNameManager().GetPredefName(PredefinedName.PN_DTOR) &&
_results.GetBestResult().MethProp().getClass().isPredefAgg(PredefinedType.PT_OBJECT))
{
if (0 != (_pGroup.flags & EXPRFLAG.EXF_BASECALL))
{
GetErrorContext().Error(ErrorCode.ERR_CallingBaseFinalizeDeprecated);
}
else
{
GetErrorContext().Error(ErrorCode.ERR_CallingFinalizeDepracated);
}
}
Debug.Assert(0 == (_pGroup.flags & EXPRFLAG.EXF_USERCALLABLE) || _results.GetBestResult().MethProp().isUserCallable());
if (_pGroup.sk == SYMKIND.SK_MethodSymbol)
{
Debug.Assert(_results.GetBestResult().MethProp().IsMethodSymbol());
if (_results.GetBestResult().TypeArgs.size > 0)
{
// Check method type variable constraints.
TypeBind.CheckMethConstraints(GetSemanticChecker(), GetErrorContext(), new MethWithInst(_results.GetBestResult()));
}
}
}
private void ReportErrorsOnFailure()
{
// First and foremost, report if the user specified a name more than once.
if (_pDuplicateSpecifiedName != null)
{
GetErrorContext().Error(ErrorCode.ERR_DuplicateNamedArgument, _pDuplicateSpecifiedName);
return;
}
Debug.Assert(_methList.IsEmpty());
// Report inaccessible.
if (_results.GetInaccessibleResult())
{
// We might have called this, but it is inaccesable...
GetSemanticChecker().ReportAccessError(_results.GetInaccessibleResult(), _pExprBinder.ContextForMemberLookup(), GetTypeQualifier(_pGroup));
return;
}
// Report bogus.
if (_mpwiBogus)
{
// We might have called this, but it is bogus...
GetErrorContext().ErrorRef(ErrorCode.ERR_BindToBogus, _mpwiBogus);
return;
}
bool bUseDelegateErrors = false;
Name nameErr = _pGroup.name;
// Check for an invoke.
if (_pGroup.GetOptionalObject() != null &&
_pGroup.GetOptionalObject().type != null &&
_pGroup.GetOptionalObject().type.isDelegateType() &&
_pGroup.name == GetSymbolLoader().GetNameManager().GetPredefName(PredefinedName.PN_INVOKE))
{
Debug.Assert(!_results.GetBestResult() || _results.GetBestResult().MethProp().getClass().IsDelegate());
Debug.Assert(!_results.GetBestResult() || _results.GetBestResult().GetType().getAggregate().IsDelegate());
bUseDelegateErrors = true;
nameErr = _pGroup.GetOptionalObject().type.getAggregate().name;
}
if (_results.GetBestResult())
{
// If we had some invalid arguments for best matching.
ReportErrorsForBestMatching(bUseDelegateErrors, nameErr);
}
else if (_results.GetUninferrableResult() || _mpwiCantInferInstArg)
{
if (!_results.GetUninferrableResult())
{
//copy the extension method for which instacne argument type inference failed
_results.GetUninferrableResult().Set(_mpwiCantInferInstArg.Sym.AsMethodSymbol(), _mpwiCantInferInstArg.GetType(), _mpwiCantInferInstArg.TypeArgs);
}
Debug.Assert(_results.GetUninferrableResult().Sym.IsMethodSymbol());
MethodSymbol sym = _results.GetUninferrableResult().Meth();
TypeArray pCurrentParameters = sym.Params;
// if we tried to bind to an extensionmethod and the instance argument Type Inference failed then the method does not exist
// on the type at all. this is treated as a lookup error
CType type = null;
if (_pGroup.GetOptionalObject() != null)
{
type = _pGroup.GetOptionalObject().type;
}
else if (_pGroup.GetOptionalLHS() != null)
{
type = _pGroup.GetOptionalLHS().type;
}
MethWithType mwtCantInfer = new MethWithType();
mwtCantInfer.Set(_results.GetUninferrableResult().Meth(), _results.GetUninferrableResult().GetType());
GetErrorContext().Error(ErrorCode.ERR_CantInferMethTypeArgs, mwtCantInfer);
}
else if (_mwtBadArity)
{
int cvar = _mwtBadArity.Meth().typeVars.size;
GetErrorContext().ErrorRef(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _mwtBadArity, new ErrArgSymKind(_mwtBadArity.Meth()), _pArguments.carg);
}
else if (_mpwiParamTypeConstraints)
{
// This will always report an error
TypeBind.CheckMethConstraints(GetSemanticChecker(), GetErrorContext(), new MethWithInst(_mpwiParamTypeConstraints));
}
else if (_pInvalidSpecifiedName != null)
{
// Give a better message for delegate invoke.
if (_pGroup.GetOptionalObject() != null &&
_pGroup.GetOptionalObject().type.IsAggregateType() &&
_pGroup.GetOptionalObject().type.AsAggregateType().GetOwningAggregate().IsDelegate())
{
GetErrorContext().Error(ErrorCode.ERR_BadNamedArgumentForDelegateInvoke, _pGroup.GetOptionalObject().type.AsAggregateType().GetOwningAggregate().name, _pInvalidSpecifiedName);
}
else
{
GetErrorContext().Error(ErrorCode.ERR_BadNamedArgument, _pGroup.name, _pInvalidSpecifiedName);
}
}
else if (_pNameUsedInPositionalArgument != null)
{
GetErrorContext().Error(ErrorCode.ERR_NamedArgumentUsedInPositional, _pNameUsedInPositionalArgument);
}
else
{
CParameterizedError error;
if (_pDelegate != null)
{
GetErrorContext().MakeError(out error, ErrorCode.ERR_MethDelegateMismatch, nameErr, _pDelegate);
GetErrorContext().AddRelatedTypeLoc(error, _pDelegate);
}
else
{
// The number of arguments must be wrong.
if (_fCandidatesUnsupported)
{
GetErrorContext().MakeError(out error, ErrorCode.ERR_BindToBogus, nameErr);
}
else if (bUseDelegateErrors)
{
Debug.Assert(0 == (_pGroup.flags & EXPRFLAG.EXF_CTOR));
GetErrorContext().MakeError(out error, ErrorCode.ERR_BadDelArgCount, nameErr, _pArguments.carg);
}
else
{
if (0 != (_pGroup.flags & EXPRFLAG.EXF_CTOR))
{
Debug.Assert(!_pGroup.GetParentType().IsTypeParameterType());
GetErrorContext().MakeError(out error, ErrorCode.ERR_BadCtorArgCount, _pGroup.GetParentType(), _pArguments.carg);
}
else
{
GetErrorContext().MakeError(out error, ErrorCode.ERR_BadArgCount, nameErr, _pArguments.carg);
}
}
}
// Report possible matches (same name and is accesible). We stored these in m_swtWrongCount.
for (int i = 0; i < _nWrongCount; i++)
{
if (GetSemanticChecker().CheckAccess(
_swtWrongCount[i].Sym,
_swtWrongCount[i].GetType(),
_pExprBinder.ContextForMemberLookup(),
GetTypeQualifier(_pGroup)))
{
GetErrorContext().AddRelatedSymLoc(error, _swtWrongCount[i].Sym);
}
}
GetErrorContext().SubmitError(error);
}
}
private void ReportErrorsForBestMatching(bool bUseDelegateErrors, Name nameErr)
{
// Best matching overloaded method 'name' had some invalid arguments.
if (_pDelegate != null)
{
GetErrorContext().ErrorRef(ErrorCode.ERR_MethDelegateMismatch, nameErr, _pDelegate, _results.GetBestResult());
return;
}
if (_bBindingCollectionAddArgs)
{
if (ReportErrorsForCollectionAdd())
{
return;
}
}
if (bUseDelegateErrors)
{
// Point to the Delegate, not the Invoke method
GetErrorContext().Error(ErrorCode.ERR_BadDelArgTypes, _results.GetBestResult().GetType());
}
else
{
if (_results.GetBestResult().Sym.IsMethodSymbol() && _results.GetBestResult().Sym.AsMethodSymbol().IsExtension() && _pGroup.GetOptionalObject() != null)
{
GetErrorContext().Error(ErrorCode.ERR_BadExtensionArgTypes, _pGroup.GetOptionalObject().type, _pGroup.name, _results.GetBestResult().Sym);
}
else if (_bBindingCollectionAddArgs)
{
GetErrorContext().Error(ErrorCode.ERR_BadArgTypesForCollectionAdd, _results.GetBestResult());
}
else
{
GetErrorContext().Error(ErrorCode.ERR_BadArgTypes, _results.GetBestResult());
}
}
// Argument X: cannot convert type 'Y' to type 'Z'
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pBestParameters.Item(ivar);
if (!_pExprBinder.canConvert(_pArguments.prgexpr[ivar], var))
{
// See if they just differ in out / ref.
CType argStripped = _pArguments.types.Item(ivar).IsParameterModifierType() ?
_pArguments.types.Item(ivar).AsParameterModifierType().GetParameterType() : _pArguments.types.Item(ivar);
CType varStripped = var.IsParameterModifierType() ? var.AsParameterModifierType().GetParameterType() : var;
if (argStripped == varStripped)
{
if (varStripped != var)
{
// The argument is wrong in ref / out-ness.
GetErrorContext().Error(ErrorCode.ERR_BadArgRef, ivar + 1, (var.IsParameterModifierType() && var.AsParameterModifierType().isOut) ? "out" : "ref");
}
else
{
CType argument = _pArguments.types.Item(ivar);
// the argument is decorated, but doesn't needs a 'ref' or 'out'
GetErrorContext().Error(ErrorCode.ERR_BadArgExtraRef, ivar + 1, (argument.IsParameterModifierType() && argument.AsParameterModifierType().isOut) ? "out" : "ref");
}
}
else
{
// if we tried to bind to an extensionmethod and the instance argument conversion failed then the method does not exist
// on the type at all.
Symbol sym = _results.GetBestResult().Sym;
if (ivar == 0 && sym.IsMethodSymbol() && sym.AsMethodSymbol().IsExtension() && _pGroup.GetOptionalObject() != null &&
!_pExprBinder.canConvertInstanceParamForExtension(_pGroup.GetOptionalObject(), sym.AsMethodSymbol().Params.Item(0)))
{
if (!_pGroup.GetOptionalObject().type.getBogus())
{
GetErrorContext().Error(ErrorCode.ERR_BadInstanceArgType, _pGroup.GetOptionalObject().type, var);
}
}
else
{
GetErrorContext().Error(ErrorCode.ERR_BadArgType, ivar + 1, new ErrArg(_pArguments.types.Item(ivar), ErrArgFlags.Unique), new ErrArg(var, ErrArgFlags.Unique));
}
}
}
}
}
private bool ReportErrorsForCollectionAdd()
{
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pBestParameters.Item(ivar);
if (var.IsParameterModifierType())
{
GetErrorContext().ErrorRef(ErrorCode.ERR_InitializerAddHasParamModifiers, _results.GetBestResult());
return true;
}
}
return false;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond.Expressions
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
public class UntaggedParser<R> : IParser
{
static readonly ITransform skipStructTransform = new Transform(
Base: baseParser => baseParser.Skip(Expression.Constant(BondDataType.BT_STRUCT)));
RuntimeSchema schema;
readonly UntaggedReader<R> reader;
readonly DeferredSkip deferredSkip;
readonly int hierarchyDepth;
class DeferredSkip
{
public readonly List<Action<R>> Lambdas = new List<Action<R>>();
public readonly Dictionary<RuntimeSchema, int> Index =
new Dictionary<RuntimeSchema, int>(new TypeDefComparer());
public readonly HashSet<RuntimeSchema> InProgress =
new HashSet<RuntimeSchema>(new TypeDefComparer());
}
public UntaggedParser(RuntimeSchema schema)
: this(new UntaggedReader<R>(), new DeferredSkip(), schema)
{
Audit.ArgRule(schema.HasValue, "UntaggedParser requires runtime schema");
}
public UntaggedParser(Type type)
: this(Schema.GetRuntimeSchema(type))
{
Audit.ArgNotNull(type, "type");
}
UntaggedParser(UntaggedParser<R> that, RuntimeSchema schema)
: this(that.reader, that.deferredSkip, schema)
{}
UntaggedParser(UntaggedReader<R> reader, DeferredSkip deferredSkip, RuntimeSchema schema)
{
this.reader = reader;
this.schema = schema;
this.deferredSkip = deferredSkip;
hierarchyDepth = schema.GetHierarchyDepth();
}
public ParameterExpression ReaderParam { get { return reader.Param; } }
public Expression ReaderValue { get { return reader.Param; } }
public int HierarchyDepth { get { return hierarchyDepth; } }
public bool IsBonded { get { return schema.IsBonded; } }
public Expression Apply(ITransform transform)
{
Debug.Assert(schema.IsStruct);
var body = new List<Expression>
{
transform.Begin
};
if (schema.HasBase)
body.Add(transform.Base(new UntaggedParser<R>(this, schema.GetBaseSchema())));
// Performs left outer join of schema fields with transform fields.
// The result contains entry for each schema field. For fields not handled
// by the transform default to Skip.
body.AddRange(
from fieldDef in schema.StructDef.fields
join transfromField in transform.Fields on fieldDef.id equals transfromField.Id into fields
from knownField in fields.DefaultIfEmpty()
select Field(transform, fieldDef, knownField));
body.Add(transform.End);
return Expression.Block(body);
}
private Expression Field(ITransform transform, FieldDef fieldDef, IField field)
{
var fieldId = Expression.Constant(fieldDef.id);
var fieldType = Expression.Constant(fieldDef.type.id);
var fieldParser = new UntaggedParser<R>(this, schema.GetFieldSchema(fieldDef));
return Expression.IfThenElse(reader.ReadFieldOmitted(),
field != null ? field.Omitted : Expression.Empty(),
field != null ?
field.Value(fieldParser, fieldType) :
transform.UnknownField(fieldParser, fieldType, fieldId) ?? fieldParser.Skip(fieldType));
}
public Expression Container(BondDataType? expectedType, ContainerHandler handler)
{
Debug.Assert(schema.IsContainer);
var count = Expression.Variable(typeof(int), "count");
var loop = handler(
new UntaggedParser<R>(this, schema.GetElementSchema()),
Expression.Constant(schema.TypeDef.element.id),
Expression.GreaterThan(Expression.PostDecrementAssign(count), Expression.Constant(0)),
count);
return Expression.Block(
new[] { count },
Expression.Assign(count, reader.ReadContainerBegin()),
loop,
reader.ReadContainerEnd());
}
public Expression Map(BondDataType? expectedKeyType, BondDataType? expectedValueType, MapHandler handler)
{
Debug.Assert(schema.IsMap);
var count = Expression.Variable(typeof(int), "count");
var loop = handler(
new UntaggedParser<R>(this, schema.GetKeySchema()),
new UntaggedParser<R>(this, schema.GetElementSchema()),
Expression.Constant(schema.TypeDef.key.id),
Expression.Constant(schema.TypeDef.element.id),
Expression.GreaterThan(Expression.PostDecrementAssign(count), Expression.Constant(0)),
Expression.Empty(),
count);
return Expression.Block(
new[] { count },
Expression.Assign(count, reader.ReadContainerBegin()),
loop,
reader.ReadContainerEnd());
}
public Expression Blob(Expression count)
{
return reader.ReadBytes(count);
}
public Expression Scalar(Expression valueType, BondDataType expectedType, ValueHandler handler)
{
Debug.Assert(valueType is ConstantExpression);
return handler(reader.Read((BondDataType)(valueType as ConstantExpression).Value));
}
public Expression Bonded(ValueHandler handler)
{
if (schema.IsBonded)
{
return handler(reader.ReadMarshaledBonded());
}
var bondedCtor = typeof(BondedVoid<>).MakeGenericType(typeof(R))
.GetConstructor(typeof(R), typeof(RuntimeSchema));
return Expression.Block(
handler(Expression.New(bondedCtor, reader.Param, Expression.Constant(schema))),
SkipStruct());
}
public Expression Skip(Expression valueType)
{
Debug.Assert(valueType is ConstantExpression);
var dataType = (BondDataType)(valueType as ConstantExpression).Value;
Debug.Assert(schema.TypeDef.id == dataType);
switch (dataType)
{
case BondDataType.BT_SET:
return SkipSet();
case BondDataType.BT_LIST:
return SkipList();
case BondDataType.BT_MAP:
return SkipMap();
case BondDataType.BT_STRUCT:
return SkipStruct();
default:
return reader.Skip(dataType);
}
}
Expression SkipSet()
{
return Container(null, (valueParser, elementType, next, count) =>
ControlExpression.While(next, valueParser.Skip(elementType)));
}
Expression SkipList()
{
return Container(null, (valueParser, elementType, next, count) =>
{
Debug.Assert(elementType is ConstantExpression);
var elementDataType = (BondDataType)(elementType as ConstantExpression).Value;
if (elementDataType == BondDataType.BT_UINT8 || elementDataType == BondDataType.BT_INT8)
return reader.SkipBytes(count);
else
return ControlExpression.While(next, valueParser.Skip(elementType));
});
}
Expression SkipMap()
{
return Map(null, null, (keyParser, valueParser, keyType, valueType, nextKey, nextValue, count) =>
ControlExpression.While(nextKey,
Expression.Block(
keyParser.Skip(keyType),
valueParser.Skip(valueType))));
}
Expression SkipStruct()
{
if (deferredSkip.InProgress.Contains(schema))
{
int index;
if (!deferredSkip.Index.TryGetValue(schema, out index))
{
index = deferredSkip.Lambdas.Count;
deferredSkip.Index[schema] = index;
deferredSkip.Lambdas.Add(null);
deferredSkip.Lambdas[index] = Expression.Lambda<Action<R>>(
Apply(skipStructTransform), reader.Param).Compile();
}
var lambdas = deferredSkip.Lambdas;
return SkipStruct(r => lambdas[index](r));
}
deferredSkip.InProgress.Add(schema);
var skip = Apply(skipStructTransform);
deferredSkip.InProgress.Remove(schema);
return skip;
}
Expression SkipStruct(Expression<Action<R>> skip)
{
return Expression.Invoke(skip, reader.Param);
}
public override bool Equals(object that)
{
Debug.Assert(that is UntaggedParser<R>);
return Comparer.Equal(schema.TypeDef, (that as UntaggedParser<R>).schema.TypeDef);
}
public override int GetHashCode()
{
return schema.TypeDef.CalculateHashCode();
}
}
}
| |
#region BSD License
/*
Copyright (c) 2004 - 2008
Matthew Holmes (matthew@wildfiregames.com),
Dan Moorehead (dan05a@gmail.com),
C.J. Adams-Collier (cjac@colliertech.org),
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Nodes;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Targets
{
/// <summary>
///
/// </summary>
[Target("nant")]
public class NAntTarget : ITarget
{
#region Fields
private Kernel m_Kernel;
#endregion
#region Private Methods
private static string PrependPath(string path)
{
string tmpPath = Helper.NormalizePath(path, '/');
Regex regex = new Regex(@"(\w):/(\w+)");
Match match = regex.Match(tmpPath);
//if(match.Success || tmpPath[0] == '.' || tmpPath[0] == '/')
//{
tmpPath = Helper.NormalizePath(tmpPath);
//}
// else
// {
// tmpPath = Helper.NormalizePath("./" + tmpPath);
// }
return tmpPath;
}
private static string BuildReference(SolutionNode solution, ProjectNode currentProject, ReferenceNode refr)
{
if (!String.IsNullOrEmpty(refr.Path))
{
return refr.Path;
}
if (solution.ProjectsTable.ContainsKey(refr.Name))
{
ProjectNode projectRef = (ProjectNode) solution.ProjectsTable[refr.Name];
string finalPath =
Helper.NormalizePath(refr.Name + GetProjectExtension(projectRef), '/');
return finalPath;
}
ProjectNode project = (ProjectNode) refr.Parent;
// Do we have an explicit file reference?
string fileRef = FindFileReference(refr.Name, project);
if (fileRef != null)
{
return fileRef;
}
// Is there an explicit path in the project ref?
if (refr.Path != null)
{
return Helper.NormalizePath(refr.Path + "/" + refr.Name + GetProjectExtension(project), '/');
}
// No, it's an extensionless GAC ref, but nant needs the .dll extension anyway
return refr.Name + ".dll";
}
public static string GetRefFileName(string refName)
{
if (ExtensionSpecified(refName))
{
return refName;
}
else
{
return refName + ".dll";
}
}
private static bool ExtensionSpecified(string refName)
{
return refName.EndsWith(".dll") || refName.EndsWith(".exe");
}
private static string GetProjectExtension(ProjectNode project)
{
string extension = ".dll";
if (project.Type == ProjectType.Exe || project.Type == ProjectType.WinExe)
{
extension = ".exe";
}
return extension;
}
private static string FindFileReference(string refName, ProjectNode project)
{
foreach (ReferencePathNode refPath in project.ReferencePaths)
{
string fullPath = Helper.MakeFilePath(refPath.Path, refName);
if (File.Exists(fullPath))
{
return fullPath;
}
fullPath = Helper.MakeFilePath(refPath.Path, refName, "dll");
if (File.Exists(fullPath))
{
return fullPath;
}
fullPath = Helper.MakeFilePath(refPath.Path, refName, "exe");
if (File.Exists(fullPath))
{
return fullPath;
}
}
return null;
}
/// <summary>
/// Gets the XML doc file.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="conf">The conf.</param>
/// <returns></returns>
public static string GetXmlDocFile(ProjectNode project, ConfigurationNode conf)
{
if (conf == null)
{
throw new ArgumentNullException("conf");
}
if (project == null)
{
throw new ArgumentNullException("project");
}
string docFile = (string)conf.Options["XmlDocFile"];
// if(docFile != null && docFile.Length == 0)//default to assembly name if not specified
// {
// return Path.GetFileNameWithoutExtension(project.AssemblyName) + ".xml";
// }
return docFile;
}
private void WriteProject(SolutionNode solution, ProjectNode project)
{
string projFile = Helper.MakeFilePath(project.FullPath, project.Name + GetProjectExtension(project), "build");
StreamWriter ss = new StreamWriter(projFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(projFile));
bool hasDoc = false;
using (ss)
{
ss.WriteLine("<?xml version=\"1.0\" ?>");
ss.WriteLine("<project name=\"{0}\" default=\"build\">", project.Name);
ss.WriteLine(" <target name=\"{0}\">", "build");
ss.WriteLine(" <echo message=\"Build Directory is ${project::get-base-directory()}/${build.dir}\" />");
ss.WriteLine(" <mkdir dir=\"${project::get-base-directory()}/${build.dir}\" />");
ss.WriteLine(" <copy todir=\"${project::get-base-directory()}/${build.dir}\" flatten=\"true\">");
ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}\">");
foreach (ReferenceNode refr in project.References)
{
if (refr.LocalCopy)
{
ss.WriteLine(" <include name=\"{0}", Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReference(solution, project, refr)) + "\" />", '/'));
}
}
ss.WriteLine(" </fileset>");
ss.WriteLine(" </copy>");
if (project.ConfigFile != null && project.ConfigFile.Length!=0)
{
ss.Write(" <copy file=\"" + project.ConfigFile + "\" tofile=\"${project::get-base-directory()}/${build.dir}/${project::get-name()}");
if (project.Type == ProjectType.Library)
{
ss.Write(".dll.config\"");
}
else
{
ss.Write(".exe.config\"");
}
ss.WriteLine(" />");
}
// Add the content files to just be copied
ss.WriteLine(" {0}", "<copy todir=\"${project::get-base-directory()}/${build.dir}\">");
ss.WriteLine(" {0}", "<fileset basedir=\".\">");
foreach (string file in project.Files)
{
// Ignore if we aren't content
if (project.Files.GetBuildAction(file) != BuildAction.Content)
continue;
// Create a include tag
ss.WriteLine(" {0}", "<include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />");
}
ss.WriteLine(" {0}", "</fileset>");
ss.WriteLine(" {0}", "</copy>");
ss.Write(" <csc ");
ss.Write(" target=\"{0}\"", project.Type.ToString().ToLower());
ss.Write(" debug=\"{0}\"", "${build.debug}");
ss.Write(" platform=\"${build.platform}\"");
foreach (ConfigurationNode conf in project.Configurations)
{
if (conf.Options.KeyFile != "")
{
ss.Write(" keyfile=\"{0}\"", conf.Options.KeyFile);
break;
}
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" unsafe=\"{0}\"", conf.Options.AllowUnsafe);
break;
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" warnaserror=\"{0}\"", conf.Options.WarningsAsErrors);
break;
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" define=\"{0}\"", conf.Options.CompilerDefines);
break;
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" nostdlib=\"{0}\"", conf.Options["NoStdLib"]);
break;
}
ss.Write(" main=\"{0}\"", project.StartupObject);
foreach (ConfigurationNode conf in project.Configurations)
{
if (GetXmlDocFile(project, conf) != "")
{
ss.Write(" doc=\"{0}\"", "${project::get-base-directory()}/${build.dir}/" + GetXmlDocFile(project, conf));
hasDoc = true;
}
break;
}
ss.Write(" output=\"{0}", "${project::get-base-directory()}/${build.dir}/${project::get-name()}");
if (project.Type == ProjectType.Library)
{
ss.Write(".dll\"");
}
else
{
ss.Write(".exe\"");
}
if (project.AppIcon != null && project.AppIcon.Length != 0)
{
ss.Write(" win32icon=\"{0}\"", Helper.NormalizePath(project.AppIcon, '/'));
}
// This disables a very different behavior between VS and NAnt. With Nant,
// If you have using System.Xml; it will ensure System.Xml.dll is referenced,
// but not in VS. This will force the behaviors to match, so when it works
// in nant, it will work in VS.
ss.Write(" noconfig=\"true\"");
ss.WriteLine(">");
ss.WriteLine(" <resources prefix=\"{0}\" dynamicprefix=\"true\" >", project.RootNamespace);
foreach (string file in project.Files)
{
switch (project.Files.GetBuildAction(file))
{
case BuildAction.EmbeddedResource:
ss.WriteLine(" {0}", "<include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />");
break;
default:
if (project.Files.GetSubType(file) != SubType.Code && project.Files.GetSubType(file) != SubType.Settings)
{
ss.WriteLine(" <include name=\"{0}\" />", file.Substring(0, file.LastIndexOf('.')) + ".resx");
}
break;
}
}
//if (project.Files.GetSubType(file).ToString() != "Code")
//{
// ps.WriteLine(" <EmbeddedResource Include=\"{0}\">", file.Substring(0, file.LastIndexOf('.')) + ".resx");
ss.WriteLine(" </resources>");
ss.WriteLine(" <sources failonempty=\"true\">");
foreach (string file in project.Files)
{
switch (project.Files.GetBuildAction(file))
{
case BuildAction.Compile:
ss.WriteLine(" <include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />");
break;
default:
break;
}
}
ss.WriteLine(" </sources>");
ss.WriteLine(" <references basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <lib>");
ss.WriteLine(" <include name=\"${project::get-base-directory()}\" />");
foreach(ReferencePathNode refPath in project.ReferencePaths)
{
ss.WriteLine(" <include name=\"${project::get-base-directory()}/" + refPath.Path.TrimEnd('/', '\\') + "\" />");
}
ss.WriteLine(" </lib>");
foreach (ReferenceNode refr in project.References)
{
string path = Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReference(solution, project, refr)), '/');
if (refr.Path != null) {
if (ExtensionSpecified(refr.Name))
{
ss.WriteLine (" <include name=\"" + path + refr.Name + "\"/>");
}
else
{
ss.WriteLine (" <include name=\"" + path + refr.Name + ".dll\"/>");
}
}
else
{
ss.WriteLine (" <include name=\"" + path + "\" />");
}
}
ss.WriteLine(" </references>");
ss.WriteLine(" </csc>");
foreach (ConfigurationNode conf in project.Configurations)
{
if (!String.IsNullOrEmpty(conf.Options.OutputPath))
{
string targetDir = Helper.NormalizePath(conf.Options.OutputPath, '/');
ss.WriteLine(" <echo message=\"Copying from [${project::get-base-directory()}/${build.dir}/] to [${project::get-base-directory()}/" + targetDir + "\" />");
ss.WriteLine(" <mkdir dir=\"${project::get-base-directory()}/" + targetDir + "\"/>");
ss.WriteLine(" <copy todir=\"${project::get-base-directory()}/" + targetDir + "\">");
ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}/${build.dir}/\" >");
ss.WriteLine(" <include name=\"*.dll\"/>");
ss.WriteLine(" <include name=\"*.exe\"/>");
ss.WriteLine(" <include name=\"*.mdb\" if='${build.debug}'/>");
ss.WriteLine(" <include name=\"*.pdb\" if='${build.debug}'/>");
ss.WriteLine(" </fileset>");
ss.WriteLine(" </copy>");
break;
}
}
ss.WriteLine(" </target>");
ss.WriteLine(" <target name=\"clean\">");
ss.WriteLine(" <delete dir=\"${bin.dir}\" failonerror=\"false\" />");
ss.WriteLine(" <delete dir=\"${obj.dir}\" failonerror=\"false\" />");
ss.WriteLine(" </target>");
ss.WriteLine(" <target name=\"doc\" description=\"Creates documentation.\">");
if (hasDoc)
{
ss.WriteLine(" <property name=\"doc.target\" value=\"\" />");
ss.WriteLine(" <if test=\"${platform::is-unix()}\">");
ss.WriteLine(" <property name=\"doc.target\" value=\"Web\" />");
ss.WriteLine(" </if>");
ss.WriteLine(" <ndoc failonerror=\"false\" verbose=\"true\">");
ss.WriteLine(" <assemblies basedir=\"${project::get-base-directory()}\">");
ss.Write(" <include name=\"${build.dir}/${project::get-name()}");
if (project.Type == ProjectType.Library)
{
ss.WriteLine(".dll\" />");
}
else
{
ss.WriteLine(".exe\" />");
}
ss.WriteLine(" </assemblies>");
ss.WriteLine(" <summaries basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <include name=\"${build.dir}/${project::get-name()}.xml\"/>");
ss.WriteLine(" </summaries>");
ss.WriteLine(" <referencepaths basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <include name=\"${build.dir}\" />");
// foreach(ReferenceNode refr in project.References)
// {
// string path = Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReferencePath(solution, refr)), '/');
// if (path != "")
// {
// ss.WriteLine(" <include name=\"{0}\" />", path);
// }
// }
ss.WriteLine(" </referencepaths>");
ss.WriteLine(" <documenters>");
ss.WriteLine(" <documenter name=\"MSDN\">");
ss.WriteLine(" <property name=\"OutputDirectory\" value=\"${project::get-base-directory()}/${build.dir}/doc/${project::get-name()}\" />");
ss.WriteLine(" <property name=\"OutputTarget\" value=\"${doc.target}\" />");
ss.WriteLine(" <property name=\"HtmlHelpName\" value=\"${project::get-name()}\" />");
ss.WriteLine(" <property name=\"IncludeFavorites\" value=\"False\" />");
ss.WriteLine(" <property name=\"Title\" value=\"${project::get-name()} SDK Documentation\" />");
ss.WriteLine(" <property name=\"SplitTOCs\" value=\"False\" />");
ss.WriteLine(" <property name=\"DefaulTOC\" value=\"\" />");
ss.WriteLine(" <property name=\"ShowVisualBasic\" value=\"True\" />");
ss.WriteLine(" <property name=\"AutoDocumentConstructors\" value=\"True\" />");
ss.WriteLine(" <property name=\"ShowMissingSummaries\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingRemarks\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingParams\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingReturns\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingValues\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"DocumentInternals\" value=\"False\" />");
ss.WriteLine(" <property name=\"DocumentPrivates\" value=\"False\" />");
ss.WriteLine(" <property name=\"DocumentProtected\" value=\"True\" />");
ss.WriteLine(" <property name=\"DocumentEmptyNamespaces\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"IncludeAssemblyVersion\" value=\"True\" />");
ss.WriteLine(" </documenter>");
ss.WriteLine(" </documenters>");
ss.WriteLine(" </ndoc>");
}
ss.WriteLine(" </target>");
ss.WriteLine("</project>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void WriteCombine(SolutionNode solution)
{
m_Kernel.Log.Write("Creating NAnt build files");
foreach (ProjectNode project in solution.Projects)
{
if (m_Kernel.AllowProject(project.FilterGroups))
{
m_Kernel.Log.Write("...Creating project: {0}", project.Name);
WriteProject(solution, project);
}
}
m_Kernel.Log.Write("");
string combFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "build");
StreamWriter ss = new StreamWriter(combFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(combFile));
using (ss)
{
ss.WriteLine("<?xml version=\"1.0\" ?>");
ss.WriteLine("<project name=\"{0}\" default=\"build\">", solution.Name);
ss.WriteLine(" <echo message=\"Using '${nant.settings.currentframework}' Framework\"/>");
ss.WriteLine();
//ss.WriteLine(" <property name=\"dist.dir\" value=\"dist\" />");
//ss.WriteLine(" <property name=\"source.dir\" value=\"source\" />");
ss.WriteLine(" <property name=\"bin.dir\" value=\"bin\" />");
ss.WriteLine(" <property name=\"obj.dir\" value=\"obj\" />");
ss.WriteLine(" <property name=\"doc.dir\" value=\"doc\" />");
ss.WriteLine(" <property name=\"project.main.dir\" value=\"${project::get-base-directory()}\" />");
// Use the active configuration, which is the first configuration name in the prebuild file.
Dictionary<string,string> emittedConfigurations = new Dictionary<string, string>();
ss.WriteLine(" <property name=\"project.config\" value=\"{0}\" />", solution.ActiveConfig);
ss.WriteLine();
foreach (ConfigurationNode conf in solution.Configurations)
{
// If the name isn't in the emitted configurations, we give a high level target to the
// platform specific on. This lets "Debug" point to "Debug-AnyCPU".
if (!emittedConfigurations.ContainsKey(conf.Name))
{
// Add it to the dictionary so we only emit one.
emittedConfigurations.Add(conf.Name, conf.Platform);
// Write out the target block.
ss.WriteLine(" <target name=\"{0}\" description=\"{0}|{1}\" depends=\"{0}-{1}\">", conf.Name, conf.Platform);
ss.WriteLine(" </target>");
ss.WriteLine();
}
// Write out the target for the configuration.
ss.WriteLine(" <target name=\"{0}-{1}\" description=\"{0}|{1}\">", conf.Name, conf.Platform);
ss.WriteLine(" <property name=\"project.config\" value=\"{0}\" />", conf.Name);
ss.WriteLine(" <property name=\"build.debug\" value=\"{0}\" />", conf.Options["DebugInformation"].ToString().ToLower());
ss.WriteLine("\t\t <property name=\"build.platform\" value=\"{0}\" />", conf.Platform);
ss.WriteLine(" </target>");
ss.WriteLine();
}
ss.WriteLine(" <target name=\"net-1.1\" description=\"Sets framework to .NET 1.1\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-1.1\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"net-2.0\" description=\"Sets framework to .NET 2.0\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-2.0\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"net-3.5\" description=\"Sets framework to .NET 3.5\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-3.5\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"mono-1.0\" description=\"Sets framework to mono 1.0\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-1.0\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"mono-2.0\" description=\"Sets framework to mono 2.0\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-2.0\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"mono-3.5\" description=\"Sets framework to mono 3.5\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-3.5\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"init\" description=\"\">");
ss.WriteLine(" <call target=\"${project.config}\" />");
ss.WriteLine(" <property name=\"sys.os.platform\"");
ss.WriteLine(" value=\"${platform::get-name()}\"");
ss.WriteLine(" />");
ss.WriteLine(" <echo message=\"Platform ${sys.os.platform}\" />");
ss.WriteLine(" <property name=\"build.dir\" value=\"${bin.dir}/${project.config}\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
// sdague - ok, this is an ugly hack, but what it lets
// us do is native include of files into the nant
// created files from all .nant/*include files. This
// lets us keep using prebuild, but allows for
// extended nant targets to do build and the like.
try
{
Regex re = new Regex(".include$");
DirectoryInfo nantdir = new DirectoryInfo(".nant");
foreach (FileSystemInfo item in nantdir.GetFileSystemInfos())
{
if (item is DirectoryInfo) { }
else if (item is FileInfo)
{
if (re.Match(item.FullName) !=
System.Text.RegularExpressions.Match.Empty)
{
Console.WriteLine("Including file: " + item.FullName);
using (FileStream fs = new FileStream(item.FullName,
FileMode.Open,
FileAccess.Read,
FileShare.None))
{
using (StreamReader sr = new StreamReader(fs))
{
ss.WriteLine("<!-- included from {0} -->", (item).FullName);
while (sr.Peek() != -1)
{
ss.WriteLine(sr.ReadLine());
}
ss.WriteLine();
}
}
}
}
}
}
catch { }
// ss.WriteLine(" <include buildfile=\".nant/local.include\" />");
// ss.WriteLine(" <target name=\"zip\" description=\"\">");
// ss.WriteLine(" <zip zipfile=\"{0}-{1}.zip\">", solution.Name, solution.Version);
// ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}\">");
// ss.WriteLine(" <include name=\"${project::get-base-directory()}/**/*.cs\" />");
// // ss.WriteLine(" <include name=\"${project.main.dir}/**/*\" />");
// ss.WriteLine(" </fileset>");
// ss.WriteLine(" </zip>");
// ss.WriteLine(" <echo message=\"Building zip target\" />");
// ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"clean\" description=\"\">");
ss.WriteLine(" <echo message=\"Deleting all builds from all configurations\" />");
//ss.WriteLine(" <delete dir=\"${dist.dir}\" failonerror=\"false\" />");
// justincc: FIXME FIXME FIXME - A temporary OpenSim hack to clean up files when "nant clean" is executed.
// Should be replaced with extreme prejudice once anybody finds out if the CleanFiles stuff works or there is
// another working mechanism for specifying this stuff
ss.WriteLine(" <delete failonerror=\"false\">");
ss.WriteLine(" <fileset basedir=\"${bin.dir}\">");
ss.WriteLine(" <include name=\"OpenSim*.dll\"/>");
ss.WriteLine(" <include name=\"OpenSim*.dll.mdb\"/>");
ss.WriteLine(" <include name=\"OpenSim*.exe\"/>");
ss.WriteLine(" <include name=\"OpenSim*.exe.mdb\"/>");
ss.WriteLine(" <include name=\"ScriptEngines/*\"/>");
ss.WriteLine(" <include name=\"Physics/*.dll\"/>");
ss.WriteLine(" <include name=\"Physics/*.dll.mdb\"/>");
ss.WriteLine(" <exclude name=\"OpenSim.32BitLaunch.exe\"/>");
ss.WriteLine(" <exclude name=\"ScriptEngines/Default.lsl\"/>");
ss.WriteLine(" </fileset>");
ss.WriteLine(" </delete>");
if (solution.Cleanup != null && solution.Cleanup.CleanFiles.Count > 0)
{
foreach (CleanFilesNode cleanFile in solution.Cleanup.CleanFiles)
{
ss.WriteLine(" <delete failonerror=\"false\">");
ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <include name=\"{0}/*\"/>", cleanFile.Pattern);
ss.WriteLine(" <include name=\"{0}\"/>", cleanFile.Pattern);
ss.WriteLine(" </fileset>");
ss.WriteLine(" </delete>");
}
}
ss.WriteLine(" <delete dir=\"${obj.dir}\" failonerror=\"false\" />");
foreach (ProjectNode project in solution.Projects)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.Write(" <nant buildfile=\"{0}\"",
Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/'));
ss.WriteLine(" target=\"clean\" />");
}
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"build\" depends=\"init\" description=\"\">");
foreach (ProjectNode project in solution.ProjectsTableOrder)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.Write(" <nant buildfile=\"{0}\"",
Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/'));
ss.WriteLine(" target=\"build\" />");
}
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"build-release\" depends=\"Release, init, build\" description=\"Builds in Release mode\" />");
ss.WriteLine();
ss.WriteLine(" <target name=\"build-debug\" depends=\"Debug, init, build\" description=\"Builds in Debug mode\" />");
ss.WriteLine();
//ss.WriteLine(" <target name=\"package\" depends=\"clean, doc, copyfiles, zip\" description=\"Builds in Release mode\" />");
ss.WriteLine(" <target name=\"package\" depends=\"clean, doc\" description=\"Builds all\" />");
ss.WriteLine();
ss.WriteLine(" <target name=\"doc\" depends=\"build-release\">");
ss.WriteLine(" <echo message=\"Generating all documentation from all builds\" />");
foreach (ProjectNode project in solution.Projects)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.Write(" <nant buildfile=\"{0}\"",
Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/'));
ss.WriteLine(" target=\"doc\" />");
}
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine("</project>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void CleanProject(ProjectNode project)
{
m_Kernel.Log.Write("...Cleaning project: {0}", project.Name);
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name + GetProjectExtension(project), "build");
Helper.DeleteIfExists(projectFile);
}
private void CleanSolution(SolutionNode solution)
{
m_Kernel.Log.Write("Cleaning NAnt build files for", solution.Name);
string slnFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "build");
Helper.DeleteIfExists(slnFile);
foreach (ProjectNode project in solution.Projects)
{
CleanProject(project);
}
m_Kernel.Log.Write("");
}
#endregion
#region ITarget Members
/// <summary>
/// Writes the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public void Write(Kernel kern)
{
if (kern == null)
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach (SolutionNode solution in kern.Solutions)
{
WriteCombine(solution);
}
m_Kernel = null;
}
/// <summary>
/// Cleans the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public virtual void Clean(Kernel kern)
{
if (kern == null)
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach (SolutionNode sol in kern.Solutions)
{
CleanSolution(sol);
}
m_Kernel = null;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
return "nant";
}
}
#endregion
}
}
| |
// DataColumnMappingCollectionTest.cs - NUnit Test Cases for Testing the
// DataColumnMappingCollection class
//
// Author: Ameya Sailesh Gargesh (ameya_13@yahoo.com)
//
// (C) Ameya Gargesh
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.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 NUnit.Framework;
using System;
using System.Data;
using System.Data.Common;
namespace MonoTests.System.Data.Common
{
[TestFixture]
public class DataColumnMappingCollectionTest : Assertion
{
//DataTableMapping tableMap;
DataColumnMappingCollection columnMapCollection;
DataColumnMapping [] cols;
[SetUp]
public void GetReady()
{
cols=new DataColumnMapping[5];
cols[0]=new DataColumnMapping("sourceName","dataSetName");
cols[1]=new DataColumnMapping("sourceID","dataSetID");
cols[2]=new DataColumnMapping("sourceAddress","dataSetAddress");
cols[3]=new DataColumnMapping("sourcePhone","dataSetPhone");
cols[4]=new DataColumnMapping("sourcePIN","dataSetPIN");
columnMapCollection=new DataColumnMappingCollection();
}
[TearDown]
public void Clean()
{
columnMapCollection.Clear();
}
[Test]
public void Add()
{
DataColumnMapping col1=new DataColumnMapping("sourceName","dataSetName");
int t=columnMapCollection.Add((Object)col1);
AssertEquals("test1",0,t);
bool eq1=col1.Equals(columnMapCollection[0]);
AssertEquals("test2",true,eq1);
AssertEquals("test3",1,columnMapCollection.Count);
DataColumnMapping col2;
col2=columnMapCollection.Add("sourceID","dataSetID");
bool eq2=col2.Equals(columnMapCollection[1]);
AssertEquals("test4",true,eq2);
AssertEquals("test5",2,columnMapCollection.Count);
}
[Test]
[ExpectedException(typeof(InvalidCastException))]
public void AddException1()
{
DataColumnMappingCollection c=new DataColumnMappingCollection();
columnMapCollection.Add((Object)c);
}
[Test]
public void AddRange()
{
columnMapCollection.Add(new DataColumnMapping("sourceAge","dataSetAge"));
AssertEquals("test1",1,columnMapCollection.Count);
columnMapCollection.AddRange(cols);
AssertEquals("test2",6,columnMapCollection.Count);
bool eq;
eq=cols[0].Equals(columnMapCollection[1]);
AssertEquals("test3",true,eq);
eq=cols[1].Equals(columnMapCollection[2]);
AssertEquals("test4",true,eq);
eq=cols[0].Equals(columnMapCollection[0]);
AssertEquals("test5",false,eq);
eq=cols[1].Equals(columnMapCollection[0]);
AssertEquals("test6",false,eq);
}
[Test]
public void Clear()
{
DataColumnMapping col1=new DataColumnMapping("sourceName","dataSetName");
columnMapCollection.Add((Object)col1);
AssertEquals("test1",1,columnMapCollection.Count);
columnMapCollection.Clear();
AssertEquals("test2",0,columnMapCollection.Count);
columnMapCollection.AddRange(cols);
AssertEquals("test3",5,columnMapCollection.Count);
columnMapCollection.Clear();
AssertEquals("test4",0,columnMapCollection.Count);
}
[Test]
public void Contains()
{
DataColumnMapping col1=new DataColumnMapping("sourceName","dataSetName");
columnMapCollection.AddRange(cols);
bool eq;
eq=columnMapCollection.Contains((Object)cols[0]);
AssertEquals("test1",true,eq);
eq=columnMapCollection.Contains((Object)cols[1]);
AssertEquals("test2",true,eq);
eq=columnMapCollection.Contains((Object)col1);
AssertEquals("test3",false,eq);
eq=columnMapCollection.Contains(cols[0].SourceColumn);
AssertEquals("test4",true,eq);
eq=columnMapCollection.Contains(cols[1].SourceColumn);
AssertEquals("test5",true,eq);
eq=columnMapCollection.Contains(col1.SourceColumn);
AssertEquals("test6",true,eq);
eq=columnMapCollection.Contains(cols[0].DataSetColumn);
AssertEquals("test7",false,eq);
eq=columnMapCollection.Contains(cols[1].DataSetColumn);
AssertEquals("test8",false,eq);
eq=columnMapCollection.Contains(col1.DataSetColumn);
AssertEquals("test9",false,eq);
}
[Test]
[ExpectedException(typeof(InvalidCastException))]
public void ContainsException1()
{
Object o = new Object();
bool a = columnMapCollection.Contains(o);
}
[Test]
public void CopyTo()
{
DataColumnMapping [] colcops=new DataColumnMapping[5];
columnMapCollection.AddRange(cols);
columnMapCollection.CopyTo(colcops,0);
bool eq;
for (int i=0;i<5;i++)
{
eq=columnMapCollection[i].Equals(colcops[i]);
AssertEquals("test1"+i,true,eq);
}
colcops=null;
colcops=new DataColumnMapping[7];
columnMapCollection.CopyTo(colcops,2);
for (int i=0;i<5;i++)
{
eq=columnMapCollection[i].Equals(colcops[i+2]);
AssertEquals("test2"+i,true,eq);
}
eq=columnMapCollection[0].Equals(colcops[0]);
AssertEquals("test31",false,eq);
eq=columnMapCollection[0].Equals(colcops[1]);
AssertEquals("test32",false,eq);
}
[Test]
public void Equals()
{
// DataColumnMappingCollection collect2=new DataColumnMappingCollection();
columnMapCollection.AddRange(cols);
// collect2.AddRange(cols);
DataColumnMappingCollection copy1;
copy1=columnMapCollection;
// AssertEquals("test1",false,columnMapCollection.Equals(collect2));
AssertEquals("test2",true,columnMapCollection.Equals(copy1));
// AssertEquals("test3",false,collect2.Equals(columnMapCollection));
AssertEquals("test4",true,copy1.Equals(columnMapCollection));
// AssertEquals("test5",false,collect2.Equals(copy1));
AssertEquals("test6",true,copy1.Equals(columnMapCollection));
AssertEquals("test7",true,columnMapCollection.Equals(columnMapCollection));
// AssertEquals("test8",true,collect2.Equals(collect2));
AssertEquals("test9",true,copy1.Equals(copy1));
// AssertEquals("test10",false,Object.Equals(collect2,columnMapCollection));
AssertEquals("test11",true,Object.Equals(copy1,columnMapCollection));
// AssertEquals("test12",false,Object.Equals(columnMapCollection,collect2));
AssertEquals("test13",true,Object.Equals(columnMapCollection,copy1));
// AssertEquals("test14",false,Object.Equals(copy1,collect2));
AssertEquals("test15",true,Object.Equals(columnMapCollection,copy1));
AssertEquals("test16",true,Object.Equals(columnMapCollection,columnMapCollection));
// AssertEquals("test17",true,Object.Equals(collect2,collect2));
AssertEquals("test18",true,Object.Equals(copy1,copy1));
// AssertEquals("test10",false,Object.Equals(columnMapCollection,collect2));
AssertEquals("test11",true,Object.Equals(columnMapCollection,copy1));
// AssertEquals("test12",false,Object.Equals(collect2,columnMapCollection));
AssertEquals("test13",true,Object.Equals(copy1,columnMapCollection));
// AssertEquals("test14",false,Object.Equals(collect2,copy1));
AssertEquals("test15",true,Object.Equals(copy1,columnMapCollection));
}
[Test]
public void GetByDataSetColumn()
{
columnMapCollection.AddRange(cols);
bool eq;
DataColumnMapping col1;
col1=columnMapCollection.GetByDataSetColumn("dataSetName");
eq=(col1.DataSetColumn.Equals("dataSetName") && col1.SourceColumn.Equals("sourceName"));
AssertEquals("test1",true,eq);
col1=columnMapCollection.GetByDataSetColumn("dataSetID");
eq=(col1.DataSetColumn.Equals("dataSetID") && col1.SourceColumn.Equals("sourceID"));
AssertEquals("test2",true,eq);
col1=columnMapCollection.GetByDataSetColumn("datasetname");
eq=(col1.DataSetColumn.Equals("dataSetName") && col1.SourceColumn.Equals("sourceName"));
AssertEquals("test3",true,eq);
col1=columnMapCollection.GetByDataSetColumn("datasetid");
eq=(col1.DataSetColumn.Equals("dataSetID") && col1.SourceColumn.Equals("sourceID"));
AssertEquals("test4",true,eq);
}
[Test]
public void GetColumnMappingBySchemaAction()
{
columnMapCollection.AddRange(cols);
bool eq;
DataColumnMapping col1;
col1=DataColumnMappingCollection.GetColumnMappingBySchemaAction(columnMapCollection,"sourceName",MissingMappingAction.Passthrough);
eq=(col1.DataSetColumn.Equals("dataSetName") && col1.SourceColumn.Equals("sourceName"));
AssertEquals("test1",true,eq);
col1=DataColumnMappingCollection.GetColumnMappingBySchemaAction(columnMapCollection,"sourceID",MissingMappingAction.Passthrough);
eq=(col1.DataSetColumn.Equals("dataSetID") && col1.SourceColumn.Equals("sourceID"));
AssertEquals("test2",true,eq);
col1=DataColumnMappingCollection.GetColumnMappingBySchemaAction(columnMapCollection,"sourceData",MissingMappingAction.Passthrough);
eq=(col1.DataSetColumn.Equals("sourceData") && col1.SourceColumn.Equals("sourceData"));
AssertEquals("test3",true,eq);
eq=columnMapCollection.Contains(col1);
AssertEquals("test4",false,eq);
col1=DataColumnMappingCollection.GetColumnMappingBySchemaAction(columnMapCollection,"sourceData",MissingMappingAction.Ignore);
AssertEquals("test5",null,col1);
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void GetColumnMappingBySchemaActionException1()
{
DataColumnMappingCollection.GetColumnMappingBySchemaAction(columnMapCollection,"sourceName",MissingMappingAction.Error);
}
[Test]
public void IndexOf()
{
columnMapCollection.AddRange(cols);
int ind;
ind=columnMapCollection.IndexOf(cols[0]);
AssertEquals("test1",0,ind);
ind=columnMapCollection.IndexOf(cols[1]);
AssertEquals("test2",1,ind);
ind=columnMapCollection.IndexOf(cols[0].SourceColumn);
AssertEquals("test3",0,ind);
ind=columnMapCollection.IndexOf(cols[1].SourceColumn);
AssertEquals("test4",1,ind);
}
[Test]
public void IndexOfDataSetColumn()
{
columnMapCollection.AddRange(cols);
int ind;
ind=columnMapCollection.IndexOfDataSetColumn(cols[0].DataSetColumn);
AssertEquals("test1",0,ind);
ind=columnMapCollection.IndexOfDataSetColumn(cols[1].DataSetColumn);
AssertEquals("test2",1,ind);
ind=columnMapCollection.IndexOfDataSetColumn("datasetname");
AssertEquals("test3",0,ind);
ind=columnMapCollection.IndexOfDataSetColumn("datasetid");
AssertEquals("test4",1,ind);
ind=columnMapCollection.IndexOfDataSetColumn("sourcedeter");
AssertEquals("test5",-1,ind);
}
[Test]
public void Insert()
{
columnMapCollection.AddRange(cols);
DataColumnMapping mymap=new DataColumnMapping("sourceAge","dataSetAge");
columnMapCollection.Insert(3,mymap);
int ind=columnMapCollection.IndexOfDataSetColumn("dataSetAge");
AssertEquals("test1",3,ind);
}
[Test]
[Ignore ("This test is wrong. A mapping in a DataColumnMappingCollection must be identical.")]
public void Remove()
{
columnMapCollection.AddRange(cols);
DataColumnMapping mymap=new DataColumnMapping("sourceName","dataSetName");
columnMapCollection.Add(mymap);
columnMapCollection.Remove((Object)mymap);
bool eq=columnMapCollection.Contains((Object)mymap);
AssertEquals("test1",false,eq);
}
[Test]
[ExpectedException(typeof(InvalidCastException))]
public void RemoveException1()
{
String te="testingdata";
columnMapCollection.AddRange(cols);
columnMapCollection.Remove(te);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void RemoveException2()
{
columnMapCollection.AddRange(cols);
DataColumnMapping mymap=new DataColumnMapping("sourceAge","dataSetAge");
columnMapCollection.Remove(mymap);
}
[Test]
public void RemoveAt()
{
columnMapCollection.AddRange(cols);
bool eq;
columnMapCollection.RemoveAt(0);
eq=columnMapCollection.Contains(cols[0]);
AssertEquals("test1",false,eq);
eq=columnMapCollection.Contains(cols[1]);
AssertEquals("test2",true,eq);
columnMapCollection.RemoveAt("sourceID");
eq=columnMapCollection.Contains(cols[1]);
AssertEquals("test3",false,eq);
eq=columnMapCollection.Contains(cols[2]);
AssertEquals("test4",true,eq);
}
[Test]
[ExpectedException(typeof(IndexOutOfRangeException))]
public void RemoveAtException1()
{
columnMapCollection.RemoveAt(3);
}
[Test]
[ExpectedException(typeof(IndexOutOfRangeException))]
public void RemoveAtException2()
{
columnMapCollection.RemoveAt("sourceAge");
}
[Test]
public void ToStringTest()
{
AssertEquals("test1","System.Data.Common.DataColumnMappingCollection",columnMapCollection.ToString());
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using Model=UnityEngine.AssetBundles.GraphTool.DataModel.Version2;
namespace UnityEngine.AssetBundles.GraphTool {
public class BuildTargetUtility {
public const BuildTargetGroup DefaultTarget = BuildTargetGroup.Unknown;
/**
* from build target to human friendly string for display purpose.
*/
public static string TargetToHumaneString(UnityEditor.BuildTarget t) {
switch(t) {
case BuildTarget.Android:
return "Android";
case BuildTarget.iOS:
return "iOS";
case BuildTarget.PS4:
return "PlayStation 4";
case BuildTarget.PSM:
return "PlayStation Mobile";
case BuildTarget.PSP2:
return "PlayStation Vita";
case BuildTarget.SamsungTV:
return "Samsung TV";
case BuildTarget.StandaloneLinux:
return "Linux Standalone";
case BuildTarget.StandaloneLinux64:
return "Linux Standalone(64-bit)";
case BuildTarget.StandaloneLinuxUniversal:
return "Linux Standalone(Universal)";
case BuildTarget.StandaloneOSXIntel:
return "OSX Standalone";
case BuildTarget.StandaloneOSXIntel64:
return "OSX Standalone(64-bit)";
case BuildTarget.StandaloneOSXUniversal:
return "OSX Standalone(Universal)";
case BuildTarget.StandaloneWindows:
return "Windows Standalone";
case BuildTarget.StandaloneWindows64:
return "Windows Standalone(64-bit)";
case BuildTarget.Tizen:
return "Tizen";
case BuildTarget.tvOS:
return "tvOS";
case BuildTarget.WebGL:
return "WebGL";
case BuildTarget.WiiU:
return "Wii U";
case BuildTarget.WSAPlayer:
return "Windows Store Apps";
case BuildTarget.XboxOne:
return "Xbox One";
#if !UNITY_5_5_OR_NEWER
case BuildTarget.Nintendo3DS:
return "Nintendo 3DS";
case BuildTarget.PS3:
return "PlayStation 3";
case BuildTarget.XBOX360:
return "Xbox 360";
#endif
#if UNITY_5_5_OR_NEWER
case BuildTarget.N3DS:
return "Nintendo 3DS";
#endif
#if UNITY_5_6 || UNITY_5_6_OR_NEWER
case BuildTarget.Switch:
return "Nintendo Switch";
#endif
default:
return t.ToString() + "(deprecated)";
}
}
public enum PlatformNameType {
Default,
TextureImporter,
AudioImporter,
VideoClipImporter
}
public static string TargetToAssetBundlePlatformName(BuildTargetGroup g, PlatformNameType pnt = PlatformNameType.Default) {
return TargetToAssetBundlePlatformName (GroupToTarget (g), pnt);
}
//returns the same value defined in AssetBundleManager
public static string TargetToAssetBundlePlatformName(BuildTarget t, PlatformNameType pnt = PlatformNameType.Default)
{
switch(t) {
case BuildTarget.Android:
return "Android";
case BuildTarget.iOS:
return "iOS";
case BuildTarget.PS4:
return "PS4";
case BuildTarget.PSM:
return "PSM";
case BuildTarget.PSP2:
switch (pnt) {
case PlatformNameType.AudioImporter:
return "PSP2";
case PlatformNameType.TextureImporter:
return "PSP2";
case PlatformNameType.VideoClipImporter:
return "PSP2";
}
return "PSVita";
case BuildTarget.SamsungTV:
return "SamsungTV";
case BuildTarget.StandaloneLinux:
case BuildTarget.StandaloneLinux64:
case BuildTarget.StandaloneLinuxUniversal:
return "Linux";
case BuildTarget.StandaloneOSXIntel:
case BuildTarget.StandaloneOSXIntel64:
case BuildTarget.StandaloneOSXUniversal:
return "OSX";
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
switch (pnt) {
case PlatformNameType.AudioImporter:
return "Standalone";
case PlatformNameType.TextureImporter:
return "Standalone";
case PlatformNameType.VideoClipImporter:
return "Standalone";
}
return "Windows";
case BuildTarget.Tizen:
return "Tizen";
case BuildTarget.tvOS:
return "tvOS";
case BuildTarget.WebGL:
return "WebGL";
case BuildTarget.WiiU:
return "WiiU";
case BuildTarget.WSAPlayer:
switch (pnt) {
case PlatformNameType.AudioImporter:
return "WSA";
case PlatformNameType.VideoClipImporter:
return "WSA";
}
return "WindowsStoreApps";
case BuildTarget.XboxOne:
return "XboxOne";
#if !UNITY_5_5_OR_NEWER
case BuildTarget.Nintendo3DS:
return "N3DS";
case BuildTarget.PS3:
return "PS3";
case BuildTarget.XBOX360:
return "Xbox360";
#endif
#if UNITY_5_5_OR_NEWER
case BuildTarget.N3DS:
return "N3DS";
#endif
#if UNITY_5_6 || UNITY_5_6_OR_NEWER
case BuildTarget.Switch:
return "Switch";
#endif
default:
return t.ToString() + "(deprecated)";
}
}
/**
* from build target group to human friendly string for display purpose.
*/
public static string GroupToHumaneString(UnityEditor.BuildTargetGroup g) {
switch(g) {
case BuildTargetGroup.Android:
return "Android";
case BuildTargetGroup.iOS:
return "iOS";
case BuildTargetGroup.PS4:
return "PlayStation 4";
case BuildTargetGroup.PSM:
return "PlayStation Mobile";
case BuildTargetGroup.PSP2:
return "PlayStation Vita";
case BuildTargetGroup.SamsungTV:
return "Samsung TV";
case BuildTargetGroup.Standalone:
return "PC/Mac/Linux Standalone";
case BuildTargetGroup.Tizen:
return "Tizen";
case BuildTargetGroup.tvOS:
return "tvOS";
case BuildTargetGroup.WebGL:
return "WebGL";
case BuildTargetGroup.WiiU:
return "Wii U";
case BuildTargetGroup.WSA:
return "Windows Store Apps";
case BuildTargetGroup.XboxOne:
return "Xbox One";
case BuildTargetGroup.Unknown:
return "Unknown";
#if !UNITY_5_5_OR_NEWER
case BuildTargetGroup.Nintendo3DS:
return "Nintendo 3DS";
case BuildTargetGroup.PS3:
return "PlayStation 3";
case BuildTargetGroup.XBOX360:
return "Xbox 360";
#endif
#if UNITY_5_5_OR_NEWER
case BuildTargetGroup.N3DS:
return "Nintendo 3DS";
#endif
#if UNITY_5_6 || UNITY_5_6_OR_NEWER
case BuildTargetGroup.Facebook:
return "Facebook";
case BuildTargetGroup.Switch:
return "Nintendo Switch";
#endif
default:
return g.ToString() + "(deprecated)";
}
}
public static BuildTargetGroup TargetToGroup(UnityEditor.BuildTarget t) {
if((int)t == int.MaxValue) {
return BuildTargetGroup.Unknown;
}
switch(t) {
case BuildTarget.Android:
return BuildTargetGroup.Android;
case BuildTarget.iOS:
return BuildTargetGroup.iOS;
case BuildTarget.PS4:
return BuildTargetGroup.PS4;
case BuildTarget.PSM:
return BuildTargetGroup.PSM;
case BuildTarget.PSP2:
return BuildTargetGroup.PSP2;
case BuildTarget.SamsungTV:
return BuildTargetGroup.SamsungTV;
case BuildTarget.StandaloneLinux:
case BuildTarget.StandaloneLinux64:
case BuildTarget.StandaloneLinuxUniversal:
case BuildTarget.StandaloneOSXIntel:
case BuildTarget.StandaloneOSXIntel64:
case BuildTarget.StandaloneOSXUniversal:
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
return BuildTargetGroup.Standalone;
case BuildTarget.Tizen:
return BuildTargetGroup.Tizen;
case BuildTarget.tvOS:
return BuildTargetGroup.tvOS;
case BuildTarget.WebGL:
return BuildTargetGroup.WebGL;
case BuildTarget.WiiU:
return BuildTargetGroup.WiiU;
case BuildTarget.WSAPlayer:
return BuildTargetGroup.WSA;
case BuildTarget.XboxOne:
return BuildTargetGroup.XboxOne;
#if !UNITY_5_5_OR_NEWER
case BuildTarget.Nintendo3DS:
return BuildTargetGroup.Nintendo3DS;
case BuildTarget.PS3:
return BuildTargetGroup.PS3;
case BuildTarget.XBOX360:
return BuildTargetGroup.XBOX360;
#endif
#if UNITY_5_5_OR_NEWER
case BuildTarget.N3DS:
return BuildTargetGroup.N3DS;
#endif
#if UNITY_5_6 || UNITY_5_6_OR_NEWER
case BuildTarget.Switch:
return BuildTargetGroup.Switch;
#endif
default:
return BuildTargetGroup.Unknown;
}
}
public static BuildTarget GroupToTarget(UnityEditor.BuildTargetGroup g) {
switch(g) {
case BuildTargetGroup.Android:
return BuildTarget.Android;
case BuildTargetGroup.iOS:
return BuildTarget.iOS;
case BuildTargetGroup.PS4:
return BuildTarget.PS4;
case BuildTargetGroup.PSM:
return BuildTarget.PSM;
case BuildTargetGroup.PSP2:
return BuildTarget.PSP2;
case BuildTargetGroup.SamsungTV:
return BuildTarget.SamsungTV;
case BuildTargetGroup.Standalone:
return BuildTarget.StandaloneWindows;
case BuildTargetGroup.Tizen:
return BuildTarget.Tizen;
case BuildTargetGroup.tvOS:
return BuildTarget.tvOS;
case BuildTargetGroup.WebGL:
return BuildTarget.WebGL;
case BuildTargetGroup.WiiU:
return BuildTarget.WiiU;
case BuildTargetGroup.WSA:
return BuildTarget.WSAPlayer;
case BuildTargetGroup.XboxOne:
return BuildTarget.XboxOne;
#if !UNITY_5_5_OR_NEWER
case BuildTargetGroup.Nintendo3DS:
return BuildTarget.Nintendo3DS;
case BuildTargetGroup.PS3:
return BuildTarget.PS3;
case BuildTargetGroup.XBOX360:
return BuildTarget.XBOX360;
#endif
#if UNITY_5_5_OR_NEWER
case BuildTargetGroup.N3DS:
return BuildTarget.N3DS;
#endif
#if UNITY_5_6 || UNITY_5_6_OR_NEWER
case BuildTargetGroup.Switch:
return BuildTarget.Switch;
case BuildTargetGroup.Facebook:
return BuildTarget.StandaloneWindows; // TODO: Facebook can be StandardWindows or WebGL
#endif
default:
// temporarily assigned for default value (BuildTargetGroup.Unknown)
return (BuildTarget)int.MaxValue;
}
}
public static BuildTarget BuildTargetFromString (string val) {
return (BuildTarget)Enum.Parse(typeof(BuildTarget), val);
}
public static bool IsBuildTargetSupported(BuildTarget t) {
var objType = typeof(UnityEditor.BuildPipeline);
var method = objType.GetMethod("IsBuildTargetSupported", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
#if UNITY_5_6 || UNITY_5_6_OR_NEWER
BuildTargetGroup g = BuildTargetUtility.TargetToGroup(t);
//internal static extern bool IsBuildTargetSupported (BuildTargetGroup buildTargetGroup, BuildTarget target);
var retval = method.Invoke(null, new object[]{
System.Enum.ToObject(typeof(BuildTargetGroup), g),
System.Enum.ToObject(typeof(BuildTarget), t)});
#else
//internal static extern bool IsBuildTargetSupported (BuildTarget target);
var retval = method.Invoke(null, new object[]{System.Enum.ToObject(typeof(BuildTarget), t)});
#endif
return Convert.ToBoolean(retval);
}
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using System.Collections.Generic;
using Net.Pkcs11Interop.Common;
namespace Net.Pkcs11Interop.HighLevelAPI.MechanismParams
{
/// <summary>
/// Parameters returned by all OTP mechanisms in successful calls to Sign method
/// </summary>
public class CkOtpSignatureInfo : IDisposable
{
/// <summary>
/// Flag indicating whether instance has been disposed
/// </summary>
private bool _disposed = false;
/// <summary>
/// Platform specific CkOtpSignatureInfo
/// </summary>
private HighLevelAPI40.MechanismParams.CkOtpSignatureInfo _params40 = null;
/// <summary>
/// Platform specific CkOtpSignatureInfo
/// </summary>
private HighLevelAPI41.MechanismParams.CkOtpSignatureInfo _params41 = null;
/// <summary>
/// Platform specific CkOtpSignatureInfo
/// </summary>
private HighLevelAPI80.MechanismParams.CkOtpSignatureInfo _params80 = null;
/// <summary>
/// Platform specific CkOtpSignatureInfo
/// </summary>
private HighLevelAPI81.MechanismParams.CkOtpSignatureInfo _params81 = null;
/// <summary>
/// Flag indicating whether high level list of OTP parameters left this instance
/// </summary>
private bool _paramsLeftInstance = false;
/// <summary>
/// List of OTP parameters
/// </summary>
private List<CkOtpParam> _params = new List<CkOtpParam>();
/// <summary>
/// List of OTP parameters
/// </summary>
public IList<CkOtpParam> Params
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
// Since now it is the caller's responsibility to dispose parameters
_paramsLeftInstance = true;
return _params.AsReadOnly();
}
}
/// <summary>
/// Initializes a new instance of the CkOtpSignatureInfo class.
/// </summary>
/// <param name='signature'>Signature value returned by all OTP mechanisms in successful calls to Sign method</param>
public CkOtpSignatureInfo(byte[] signature)
{
if (Platform.UnmanagedLongSize == 4)
{
if (Platform.StructPackingSize == 0)
{
_params40 = new HighLevelAPI40.MechanismParams.CkOtpSignatureInfo(signature);
IList<HighLevelAPI40.MechanismParams.CkOtpParam> hlaParams = _params40.Params;
for (int i = 0; i < hlaParams.Count; i++)
_params.Add(new CkOtpParam(hlaParams[i]));
}
else
{
_params41 = new HighLevelAPI41.MechanismParams.CkOtpSignatureInfo(signature);
IList<HighLevelAPI41.MechanismParams.CkOtpParam> hlaParams = _params41.Params;
for (int i = 0; i < hlaParams.Count; i++)
_params.Add(new CkOtpParam(hlaParams[i]));
}
}
else
{
if (Platform.StructPackingSize == 0)
{
_params80 = new HighLevelAPI80.MechanismParams.CkOtpSignatureInfo(signature);
IList<HighLevelAPI80.MechanismParams.CkOtpParam> hlaParams = _params80.Params;
for (int i = 0; i < hlaParams.Count; i++)
_params.Add(new CkOtpParam(hlaParams[i]));
}
else
{
_params81 = new HighLevelAPI81.MechanismParams.CkOtpSignatureInfo(signature);
IList<HighLevelAPI81.MechanismParams.CkOtpParam> hlaParams = _params81.Params;
for (int i = 0; i < hlaParams.Count; i++)
_params.Add(new CkOtpParam(hlaParams[i]));
}
}
}
#region IDisposable
/// <summary>
/// Disposes object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes object
/// </summary>
/// <param name="disposing">Flag indicating whether managed resources should be disposed</param>
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// Dispose managed objects
if (_params40 != null)
{
_params40.Dispose();
_params40 = null;
}
if (_params41 != null)
{
_params41.Dispose();
_params41 = null;
}
if (_params80 != null)
{
_params80.Dispose();
_params80 = null;
}
if (_params81 != null)
{
_params81.Dispose();
_params81 = null;
}
if (_paramsLeftInstance == false)
{
for (int i = 0; i < _params.Count; i++)
{
if (_params[i] != null)
{
_params[i].Dispose();
_params[i] = null;
}
}
}
}
// Dispose unmanaged objects
_disposed = true;
}
}
/// <summary>
/// Class destructor that disposes object if caller forgot to do so
/// </summary>
~CkOtpSignatureInfo()
{
Dispose(false);
}
#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.IO;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Diagnostics.Tests
{
// These tests test the static Debug class. They cannot be run in parallel
[Collection("System.Diagnostics.Debug")]
public class DebugTests
{
private readonly string s_newline = // avoid Environment direct dependency, due to it being visible from both System.Private.Corelib and System.Runtime.Extensions
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "\r\n" : "\n";
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public void Asserts()
{
VerifyLogged(() => { Debug.Assert(true); }, "");
VerifyLogged(() => { Debug.Assert(true, "assert passed"); }, "");
VerifyLogged(() => { Debug.Assert(true, "assert passed", "nothing is wrong"); }, "");
VerifyLogged(() => { Debug.Assert(true, "assert passed", "nothing is wrong {0} {1}", 'a', 'b'); }, "");
VerifyAssert(() => { Debug.Assert(false); }, "");
VerifyAssert(() => { Debug.Assert(false, "assert passed"); }, "assert passed");
VerifyAssert(() => { Debug.Assert(false, "assert passed", "nothing is wrong"); }, "assert passed", "nothing is wrong");
VerifyAssert(() => { Debug.Assert(false, "assert passed", "nothing is wrong {0} {1}", 'a', 'b'); }, "assert passed", "nothing is wrong a b");
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public void Fail()
{
VerifyAssert(() => { Debug.Fail("something bad happened"); }, "something bad happened");
VerifyAssert(() => { Debug.Fail("something bad happened", "really really bad"); }, "something bad happened", "really really bad");
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public void Write()
{
VerifyLogged(() => { Debug.Write(5); }, "5");
VerifyLogged(() => { Debug.Write((string)null); }, "");
VerifyLogged(() => { Debug.Write((object)null); }, "");
VerifyLogged(() => { Debug.Write(5, "category"); }, "category:5");
VerifyLogged(() => { Debug.Write((object)null, "category"); }, "category:");
VerifyLogged(() => { Debug.Write("logged"); }, "logged");
VerifyLogged(() => { Debug.Write("logged", "category"); }, "category:logged");
VerifyLogged(() => { Debug.Write("logged", (string)null); }, "logged");
string longString = new string('d', 8192);
VerifyLogged(() => { Debug.Write(longString); }, longString);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public void Print()
{
VerifyLogged(() => { Debug.Print("logged"); }, "logged");
VerifyLogged(() => { Debug.Print("logged {0}", 5); }, "logged 5");
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public void WriteLine()
{
VerifyLogged(() => { Debug.WriteLine(5); }, "5" + s_newline);
VerifyLogged(() => { Debug.WriteLine((string)null); }, s_newline);
VerifyLogged(() => { Debug.WriteLine((object)null); }, s_newline);
VerifyLogged(() => { Debug.WriteLine(5, "category"); }, "category:5" + s_newline);
VerifyLogged(() => { Debug.WriteLine((object)null, "category"); }, "category:" + s_newline);
VerifyLogged(() => { Debug.WriteLine("logged"); }, "logged" + s_newline);
VerifyLogged(() => { Debug.WriteLine("logged", "category"); }, "category:logged" + s_newline);
VerifyLogged(() => { Debug.WriteLine("logged", (string)null); }, "logged" + s_newline);
VerifyLogged(() => { Debug.WriteLine("{0} {1}", 'a', 'b'); }, "a b" + s_newline);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public void WriteIf()
{
VerifyLogged(() => { Debug.WriteIf(true, 5); }, "5");
VerifyLogged(() => { Debug.WriteIf(false, 5); }, "");
VerifyLogged(() => { Debug.WriteIf(true, 5, "category"); }, "category:5");
VerifyLogged(() => { Debug.WriteIf(false, 5, "category"); }, "");
VerifyLogged(() => { Debug.WriteIf(true, "logged"); }, "logged");
VerifyLogged(() => { Debug.WriteIf(false, "logged"); }, "");
VerifyLogged(() => { Debug.WriteIf(true, "logged", "category"); }, "category:logged");
VerifyLogged(() => { Debug.WriteIf(false, "logged", "category"); }, "");
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public void WriteLineIf()
{
VerifyLogged(() => { Debug.WriteLineIf(true, 5); }, "5" + s_newline);
VerifyLogged(() => { Debug.WriteLineIf(false, 5); }, "");
VerifyLogged(() => { Debug.WriteLineIf(true, 5, "category"); }, "category:5" + s_newline);
VerifyLogged(() => { Debug.WriteLineIf(false, 5, "category"); }, "");
VerifyLogged(() => { Debug.WriteLineIf(true, "logged"); }, "logged" + s_newline);
VerifyLogged(() => { Debug.WriteLineIf(false, "logged"); }, "");
VerifyLogged(() => { Debug.WriteLineIf(true, "logged", "category"); }, "category:logged" + s_newline);
VerifyLogged(() => { Debug.WriteLineIf(false, "logged", "category"); }, "");
}
[Theory]
[InlineData(2)]
[InlineData(4)]
[InlineData(3)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public void Indentation(int indentSize)
{
Debug.IndentLevel = 0;
Debug.IndentSize = indentSize;
VerifyLogged(() => { Debug.WriteLine("pizza"); }, "pizza" + s_newline);
Debug.Indent();
string expectedIndent = new string(' ', indentSize);
VerifyLogged(() => { Debug.WriteLine("pizza"); }, expectedIndent + "pizza" + s_newline);
Debug.Indent();
expectedIndent = new string(' ', indentSize * 2);
VerifyLogged(() => { Debug.WriteLine("pizza"); }, expectedIndent + "pizza" + s_newline);
Debug.Unindent();
Debug.Unindent();
}
static void VerifyLogged(Action test, string expectedOutput)
{
// First use our test logger to verify the output
Debug.IDebugLogger oldLogger = Debug.s_logger;
Debug.s_logger = WriteLogger.Instance;
try
{
WriteLogger.Instance.Clear();
test();
#if DEBUG
Assert.Equal(expectedOutput, WriteLogger.Instance.LoggedOutput);
#else
Assert.Equal(string.Empty, WriteLogger.Instance.LoggedOutput);
#endif
}
finally
{
Debug.s_logger = oldLogger;
}
// Then also use the actual logger for this platform, just to verify
// that nothing fails.
test();
}
static void VerifyAssert(Action test, params string[] expectedOutputStrings)
{
Debug.IDebugLogger oldLogger = Debug.s_logger;
Debug.s_logger = WriteLogger.Instance;
try
{
WriteLogger.Instance.Clear();
test();
#if DEBUG
for (int i = 0; i < expectedOutputStrings.Length; i++)
{
Assert.Contains(expectedOutputStrings[i], WriteLogger.Instance.LoggedOutput);
Assert.Contains(expectedOutputStrings[i], WriteLogger.Instance.AssertUIOutput);
}
#else
Assert.Equal(string.Empty, WriteLogger.Instance.LoggedOutput);
Assert.Equal(string.Empty, WriteLogger.Instance.AssertUIOutput);
#endif
}
finally
{
Debug.s_logger = oldLogger;
}
}
class WriteLogger : Debug.IDebugLogger
{
public static readonly WriteLogger Instance = new WriteLogger();
private WriteLogger()
{
}
public string LoggedOutput
{
get;
private set;
}
public string AssertUIOutput
{
get;
private set;
}
public void Clear()
{
LoggedOutput = string.Empty;
AssertUIOutput = string.Empty;
}
public void ShowAssertDialog(string stackTrace, string message, string detailMessage)
{
AssertUIOutput += stackTrace + message + detailMessage;
}
public void WriteCore(string message)
{
Assert.NotNull(message);
LoggedOutput += message;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Dataload
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Datastream;
using NUnit.Framework;
/// <summary>
/// Data streamer tests.
/// </summary>
public sealed class DataStreamerTest
{
/** Cache name. */
private const string CacheName = "partitioned";
/** Node. */
private IIgnite _grid;
/** Node 2. */
private IIgnite _grid2;
/** Cache. */
private ICache<int, int?> _cache;
/// <summary>
/// Initialization routine.
/// </summary>
[TestFixtureSetUp]
public void InitClient()
{
_grid = Ignition.Start(TestUtils.GetTestConfiguration());
_grid2 = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = "grid1"
});
_cache = _grid.CreateCache<int, int?>(CacheName);
}
/// <summary>
/// Fixture teardown.
/// </summary>
[TestFixtureTearDown]
public void StopGrids()
{
Ignition.StopAll(true);
}
/// <summary>
///
/// </summary>
[SetUp]
public void BeforeTest()
{
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
for (int i = 0; i < 100; i++)
_cache.Remove(i);
}
[TearDown]
public void AfterTest()
{
TestUtils.AssertHandleRegistryIsEmpty(1000, _grid);
}
/// <summary>
/// Test data streamer property configuration. Ensures that at least no exceptions are thrown.
/// </summary>
[Test]
public void TestPropertyPropagation()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
Assert.AreEqual(CacheName, ldr.CacheName);
Assert.AreEqual(TimeSpan.Zero, ldr.AutoFlushInterval);
ldr.AutoFlushInterval = TimeSpan.FromMinutes(5);
Assert.AreEqual(5, ldr.AutoFlushInterval.TotalMinutes);
#pragma warning disable 618 // Type or member is obsolete
Assert.AreEqual(5 * 60 * 1000, ldr.AutoFlushFrequency);
ldr.AutoFlushFrequency = 9000;
Assert.AreEqual(9000, ldr.AutoFlushFrequency);
Assert.AreEqual(9, ldr.AutoFlushInterval.TotalSeconds);
#pragma warning restore 618 // Type or member is obsolete
Assert.IsFalse(ldr.AllowOverwrite);
ldr.AllowOverwrite = true;
Assert.IsTrue(ldr.AllowOverwrite);
ldr.AllowOverwrite = false;
Assert.IsFalse(ldr.AllowOverwrite);
Assert.IsFalse(ldr.SkipStore);
ldr.SkipStore = true;
Assert.IsTrue(ldr.SkipStore);
ldr.SkipStore = false;
Assert.IsFalse(ldr.SkipStore);
Assert.AreEqual(DataStreamerDefaults.DefaultPerNodeBufferSize, ldr.PerNodeBufferSize);
ldr.PerNodeBufferSize = 1;
Assert.AreEqual(1, ldr.PerNodeBufferSize);
ldr.PerNodeBufferSize = 2;
Assert.AreEqual(2, ldr.PerNodeBufferSize);
Assert.AreEqual(DataStreamerDefaults.DefaultPerThreadBufferSize, ldr.PerThreadBufferSize);
ldr.PerThreadBufferSize = 1;
Assert.AreEqual(1, ldr.PerThreadBufferSize);
ldr.PerThreadBufferSize = 2;
Assert.AreEqual(2, ldr.PerThreadBufferSize);
Assert.AreEqual(0, ldr.PerNodeParallelOperations);
var ops = DataStreamerDefaults.DefaultParallelOperationsMultiplier *
IgniteConfiguration.DefaultThreadPoolSize;
ldr.PerNodeParallelOperations = ops;
Assert.AreEqual(ops, ldr.PerNodeParallelOperations);
ldr.PerNodeParallelOperations = 2;
Assert.AreEqual(2, ldr.PerNodeParallelOperations);
Assert.AreEqual(DataStreamerDefaults.DefaultTimeout, ldr.Timeout);
ldr.Timeout = TimeSpan.MaxValue;
Assert.AreEqual(TimeSpan.MaxValue, ldr.Timeout);
ldr.Timeout = TimeSpan.FromSeconds(1.5);
Assert.AreEqual(1.5, ldr.Timeout.TotalSeconds);
}
}
/// <summary>
/// Tests removal without <see cref="IDataStreamer{TK,TV}.AllowOverwrite"/>.
/// </summary>
[Test]
public void TestRemoveNoOverwrite()
{
_cache.Put(1, 1);
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.Remove(1);
}
Assert.IsTrue(_cache.ContainsKey(1));
}
/// <summary>
/// Test data add/remove.
/// </summary>
[Test]
public void TestAddRemove()
{
IDataStreamer<int, int> ldr;
using (ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
Assert.IsFalse(ldr.Task.IsCompleted);
ldr.AllowOverwrite = true;
// Additions.
var task = ldr.GetCurrentBatchTask();
ldr.Add(1, 1);
ldr.Flush();
Assert.AreEqual(1, _cache.Get(1));
Assert.IsTrue(task.IsCompleted);
Assert.IsFalse(ldr.Task.IsCompleted);
task = ldr.GetCurrentBatchTask();
ldr.Add(new KeyValuePair<int, int>(2, 2));
ldr.Flush();
Assert.AreEqual(2, _cache.Get(2));
Assert.IsTrue(task.IsCompleted);
task = ldr.GetCurrentBatchTask();
ldr.Add(new [] { new KeyValuePair<int, int>(3, 3), new KeyValuePair<int, int>(4, 4) });
ldr.Flush();
Assert.AreEqual(3, _cache.Get(3));
Assert.AreEqual(4, _cache.Get(4));
Assert.IsTrue(task.IsCompleted);
// Removal.
task = ldr.GetCurrentBatchTask();
ldr.Remove(1);
ldr.Flush();
Assert.IsFalse(_cache.ContainsKey(1));
Assert.IsTrue(task.IsCompleted);
// Mixed.
ldr.Add(5, 5);
ldr.Remove(2);
ldr.Add(new KeyValuePair<int, int>(7, 7));
ldr.Add(6, 6);
ldr.Remove(4);
ldr.Add(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(9, 9), new KeyValuePair<int, int>(10, 10) });
ldr.Add(new KeyValuePair<int, int>(8, 8));
ldr.Remove(3);
ldr.Add(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(11, 11), new KeyValuePair<int, int>(12, 12) });
ldr.Flush();
for (int i = 2; i < 5; i++)
Assert.IsFalse(_cache.ContainsKey(i));
for (int i = 5; i < 13; i++)
Assert.AreEqual(i, _cache.Get(i));
}
Assert.IsTrue(ldr.Task.Wait(5000));
}
/// <summary>
/// Test data add/remove.
/// </summary>
[Test]
public void TestAddRemoveObsolete()
{
#pragma warning disable 618 // Type or member is obsolete
IDataStreamer<int, int> ldr;
using (ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
Assert.IsFalse(ldr.Task.IsCompleted);
ldr.AllowOverwrite = true;
// Additions.
var task = ldr.AddData(1, 1);
ldr.Flush();
Assert.AreEqual(1, _cache.Get(1));
Assert.IsTrue(task.IsCompleted);
Assert.IsFalse(ldr.Task.IsCompleted);
task = ldr.AddData(new KeyValuePair<int, int>(2, 2));
ldr.Flush();
Assert.AreEqual(2, _cache.Get(2));
Assert.IsTrue(task.IsCompleted);
task = ldr.AddData(new [] { new KeyValuePair<int, int>(3, 3), new KeyValuePair<int, int>(4, 4) });
ldr.Flush();
Assert.AreEqual(3, _cache.Get(3));
Assert.AreEqual(4, _cache.Get(4));
Assert.IsTrue(task.IsCompleted);
// Removal.
task = ldr.RemoveData(1);
ldr.Flush();
Assert.IsFalse(_cache.ContainsKey(1));
Assert.IsTrue(task.IsCompleted);
// Mixed.
ldr.AddData(5, 5);
ldr.RemoveData(2);
ldr.AddData(new KeyValuePair<int, int>(7, 7));
ldr.AddData(6, 6);
ldr.RemoveData(4);
ldr.AddData(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(9, 9), new KeyValuePair<int, int>(10, 10) });
ldr.AddData(new KeyValuePair<int, int>(8, 8));
ldr.RemoveData(3);
ldr.AddData(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(11, 11), new KeyValuePair<int, int>(12, 12) });
ldr.Flush();
for (int i = 2; i < 5; i++)
Assert.IsFalse(_cache.ContainsKey(i));
for (int i = 5; i < 13; i++)
Assert.AreEqual(i, _cache.Get(i));
}
Assert.IsTrue(ldr.Task.Wait(5000));
#pragma warning restore 618 // Type or member is obsolete
}
/// <summary>
/// Tests object graphs with loops.
/// </summary>
[Test]
public void TestObjectGraphs()
{
var obj1 = new Container();
var obj2 = new Container();
var obj3 = new Container();
var obj4 = new Container();
obj1.Inner = obj2;
obj2.Inner = obj1;
obj3.Inner = obj1;
obj4.Inner = new Container();
using (var ldr = _grid.GetDataStreamer<int, Container>(CacheName))
{
ldr.AllowOverwrite = true;
ldr.Add(1, obj1);
ldr.Add(2, obj2);
ldr.Add(3, obj3);
ldr.Add(4, obj4);
}
var cache = _grid.GetCache<int, Container>(CacheName);
var res = cache[1];
Assert.AreEqual(res, res.Inner.Inner);
Assert.IsNotNull(cache[2].Inner);
Assert.IsNotNull(cache[2].Inner.Inner);
Assert.IsNotNull(cache[3].Inner);
Assert.IsNotNull(cache[3].Inner.Inner);
Assert.IsNotNull(cache[4].Inner);
Assert.IsNull(cache[4].Inner.Inner);
}
/// <summary>
/// Test "tryFlush".
/// </summary>
[Test]
public void TestTryFlushObsolete()
{
#pragma warning disable 618 // Type or member is obsolete
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
var fut = ldr.AddData(1, 1);
ldr.TryFlush();
fut.Wait();
Assert.AreEqual(1, _cache.Get(1));
}
#pragma warning restore 618 // Type or member is obsolete
}
/// <summary>
/// Test FlushAsync.
/// </summary>
[Test]
public void TestFlushAsync()
{
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.Add(1, 1);
ldr.FlushAsync().Wait();
Assert.AreEqual(1, _cache.Get(1));
}
}
/// <summary>
/// Test buffer size adjustments.
/// </summary>
[Test]
public void TestBufferSize()
{
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
const int timeout = 5000;
var part1 = GetPrimaryPartitionKeys(_grid, 4);
var part2 = GetPrimaryPartitionKeys(_grid2, 4);
ldr.Add(part1[0], part1[0]);
var task = ldr.GetCurrentBatchTask();
Thread.Sleep(100);
Assert.IsFalse(task.IsCompleted);
ldr.PerNodeBufferSize = 2;
ldr.PerThreadBufferSize = 1;
ldr.Add(part2[0], part2[0]);
ldr.Add(part1[1], part1[1]);
ldr.Add(part2[1], part2[1]);
Assert.IsTrue(task.Wait(timeout));
Assert.AreEqual(part1[0], _cache.Get(part1[0]));
Assert.AreEqual(part1[1], _cache.Get(part1[1]));
Assert.AreEqual(part2[0], _cache.Get(part2[0]));
Assert.AreEqual(part2[1], _cache.Get(part2[1]));
var task2 = ldr.GetCurrentBatchTask();
ldr.Add(new[]
{
new KeyValuePair<int, int>(part1[2], part1[2]),
new KeyValuePair<int, int>(part1[3], part1[3]),
new KeyValuePair<int, int>(part2[2], part2[2]),
new KeyValuePair<int, int>(part2[3], part2[3])
});
Assert.IsTrue(task2.Wait(timeout));
Assert.AreEqual(part1[2], _cache.Get(part1[2]));
Assert.AreEqual(part1[3], _cache.Get(part1[3]));
Assert.AreEqual(part2[2], _cache.Get(part2[2]));
Assert.AreEqual(part2[3], _cache.Get(part2[3]));
}
}
/// <summary>
/// Gets the primary partition keys.
/// </summary>
private static int[] GetPrimaryPartitionKeys(IIgnite ignite, int count)
{
var affinity = ignite.GetAffinity(CacheName);
var localNode = ignite.GetCluster().GetLocalNode();
var part = affinity.GetPrimaryPartitions(localNode).First();
return Enumerable.Range(0, int.MaxValue)
.Where(k => affinity.GetPartition(k) == part)
.Take(count)
.ToArray();
}
/// <summary>
/// Test close.
/// </summary>
[Test]
public void TestClose()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
var fut = ldr.GetCurrentBatchTask();
ldr.Add(1, 1);
ldr.Close(false);
Assert.IsTrue(fut.Wait(5000));
Assert.AreEqual(1, _cache.Get(1));
}
}
/// <summary>
/// Test close with cancellation.
/// </summary>
[Test]
public void TestCancel()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
var fut = ldr.GetCurrentBatchTask();
ldr.Add(1, 1);
ldr.Close(true);
Assert.IsTrue(fut.Wait(5000));
Assert.IsFalse(_cache.ContainsKey(1));
}
}
/// <summary>
/// Tests that streamer gets collected when there are no references to it.
/// </summary>
[Test]
public void TestFinalizer()
{
// Create streamer reference in a different thread to defeat Debug mode quirks.
var streamerRef = Task.Factory.StartNew
(() => new WeakReference(_grid.GetDataStreamer<int, int>(CacheName))).Result;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.IsNull(streamerRef.Target);
}
/// <summary>
/// Test auto-flush feature.
/// </summary>
[Test]
public void TestAutoFlushObsolete()
{
#pragma warning disable 618 // Type or member is obsolete
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
// Test auto flush turning on.
var fut = ldr.AddData(1, 1);
Thread.Sleep(100);
Assert.IsFalse(fut.IsCompleted);
ldr.AutoFlushFrequency = 1000;
fut.Wait();
// Test forced flush after frequency change.
fut = ldr.AddData(2, 2);
ldr.AutoFlushFrequency = long.MaxValue;
fut.Wait();
// Test another forced flush after frequency change.
fut = ldr.AddData(3, 3);
ldr.AutoFlushFrequency = 1000;
fut.Wait();
// Test flush before stop.
fut = ldr.AddData(4, 4);
ldr.AutoFlushFrequency = 0;
fut.Wait();
// Test flush after second turn on.
fut = ldr.AddData(5, 5);
ldr.AutoFlushFrequency = 1000;
fut.Wait();
Assert.AreEqual(1, _cache.Get(1));
Assert.AreEqual(2, _cache.Get(2));
Assert.AreEqual(3, _cache.Get(3));
Assert.AreEqual(4, _cache.Get(4));
Assert.AreEqual(5, _cache.Get(5));
}
#pragma warning restore 618 // Type or member is obsolete
}
/// <summary>
/// Test auto-flush feature.
/// </summary>
[Test]
public void TestAutoFlush()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
// Test auto flush turning on.
var fut = ldr.GetCurrentBatchTask();
ldr.Add(1, 1);
Thread.Sleep(100);
Assert.IsFalse(fut.IsCompleted);
ldr.AutoFlushInterval = TimeSpan.FromSeconds(1);
fut.Wait();
// Test forced flush after frequency change.
fut = ldr.GetCurrentBatchTask();
ldr.Add(2, 2);
ldr.AutoFlushInterval = TimeSpan.MaxValue;
fut.Wait();
// Test another forced flush after frequency change.
fut = ldr.GetCurrentBatchTask();
ldr.Add(3, 3);
ldr.AutoFlushInterval = TimeSpan.FromSeconds(1);
fut.Wait();
// Test flush before stop.
fut = ldr.GetCurrentBatchTask();
ldr.Add(4, 4);
ldr.AutoFlushInterval = TimeSpan.Zero;
fut.Wait();
// Test flush after second turn on.
fut = ldr.GetCurrentBatchTask();
ldr.Add(5, 5);
ldr.AutoFlushInterval = TimeSpan.FromSeconds(1);
fut.Wait();
Assert.AreEqual(1, _cache.Get(1));
Assert.AreEqual(2, _cache.Get(2));
Assert.AreEqual(3, _cache.Get(3));
Assert.AreEqual(4, _cache.Get(4));
Assert.AreEqual(5, _cache.Get(5));
}
}
/// <summary>
/// Test multithreaded behavior.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestMultithreaded()
{
int entriesPerThread = 100000;
int threadCnt = 8;
for (int i = 0; i < 5; i++)
{
_cache.Clear();
Assert.AreEqual(0, _cache.GetSize());
Stopwatch watch = new Stopwatch();
watch.Start();
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.PerNodeBufferSize = 1024;
int ctr = 0;
TestUtils.RunMultiThreaded(() =>
{
int threadIdx = Interlocked.Increment(ref ctr);
int startIdx = (threadIdx - 1) * entriesPerThread;
int endIdx = startIdx + entriesPerThread;
for (int j = startIdx; j < endIdx; j++)
{
// ReSharper disable once AccessToDisposedClosure
ldr.Add(j, j);
if (j % 100000 == 0)
Console.WriteLine("Put [thread=" + threadIdx + ", cnt=" + j + ']');
}
}, threadCnt);
}
Console.WriteLine("Iteration " + i + ": " + watch.ElapsedMilliseconds);
watch.Reset();
for (int j = 0; j < threadCnt * entriesPerThread; j++)
Assert.AreEqual(j, j);
}
}
/// <summary>
/// Tests custom receiver.
/// </summary>
[Test]
public void TestStreamReceiver()
{
TestStreamReceiver(new StreamReceiverBinarizable());
TestStreamReceiver(new StreamReceiverSerializable());
}
/// <summary>
/// Tests StreamVisitor.
/// </summary>
[Test]
public void TestStreamVisitor()
{
#if !NETCOREAPP // Serializing delegates is not supported on this platform.
TestStreamReceiver(new StreamVisitor<int, int>((c, e) => c.Put(e.Key, e.Value + 1)));
#endif
}
/// <summary>
/// Tests StreamTransformer.
/// </summary>
[Test]
public void TestStreamTransformer()
{
TestStreamReceiver(new StreamTransformer<int, int, int, int>(new EntryProcessorSerializable()));
TestStreamReceiver(new StreamTransformer<int, int, int, int>(new EntryProcessorBinarizable()));
}
[Test]
public void TestStreamTransformerIsInvokedForDuplicateKeys()
{
var cache = _grid.GetOrCreateCache<string, long>("c");
using (var streamer = _grid.GetDataStreamer<string, long>(cache.Name))
{
streamer.AllowOverwrite = true;
streamer.Receiver = new StreamTransformer<string, long, object, object>(new CountingEntryProcessor());
var words = Enumerable.Repeat("a", 3).Concat(Enumerable.Repeat("b", 2));
foreach (var word in words)
{
streamer.Add(word, 1L);
}
}
Assert.AreEqual(3, cache.Get("a"));
Assert.AreEqual(2, cache.Get("b"));
}
/// <summary>
/// Tests specified receiver.
/// </summary>
private void TestStreamReceiver(IStreamReceiver<int, int> receiver)
{
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.AllowOverwrite = true;
ldr.Receiver = new StreamReceiverBinarizable();
ldr.Receiver = receiver; // check double assignment
Assert.AreEqual(ldr.Receiver, receiver);
for (var i = 0; i < 100; i++)
ldr.Add(i, i);
ldr.Flush();
for (var i = 0; i < 100; i++)
Assert.AreEqual(i + 1, _cache.Get(i));
}
}
/// <summary>
/// Tests the stream receiver in keepBinary mode.
/// </summary>
[Test]
public void TestStreamReceiverKeepBinary()
{
// ReSharper disable once LocalVariableHidesMember
var cache = _grid.GetCache<int, BinarizableEntry>(CacheName);
using (var ldr0 = _grid.GetDataStreamer<int, int>(CacheName))
using (var ldr = ldr0.WithKeepBinary<int, IBinaryObject>())
{
ldr.Receiver = new StreamReceiverKeepBinary();
ldr.AllowOverwrite = true;
for (var i = 0; i < 100; i++)
ldr.Add(i, _grid.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry {Val = i}));
ldr.Flush();
for (var i = 0; i < 100; i++)
Assert.AreEqual(i + 1, cache.Get(i).Val);
// Repeating WithKeepBinary call: valid args.
Assert.AreSame(ldr, ldr.WithKeepBinary<int, IBinaryObject>());
// Invalid type args.
var ex = Assert.Throws<InvalidOperationException>(() => ldr.WithKeepBinary<string, IBinaryObject>());
Assert.AreEqual(
"Can't change type of binary streamer. WithKeepBinary has been called on an instance of " +
"binary streamer with incompatible generic arguments.", ex.Message);
}
}
/// <summary>
/// Streamer test with destroyed cache.
/// </summary>
[Test]
public void TestDestroyCache()
{
var cache = _grid.CreateCache<int, int>(TestUtils.TestName);
var streamer = _grid.GetDataStreamer<int, int>(cache.Name);
streamer.Add(1, 2);
streamer.FlushAsync().Wait();
_grid.DestroyCache(cache.Name);
streamer.Add(2, 3);
var ex = Assert.Throws<AggregateException>(() => streamer.Flush()).GetBaseException();
Assert.IsNotNull(ex);
Assert.AreEqual("class org.apache.ignite.IgniteCheckedException: DataStreamer data loading failed.",
ex.Message);
Assert.Throws<CacheException>(() => streamer.Close(true));
}
/// <summary>
/// Streamer test with destroyed cache.
/// </summary>
[Test]
public void TestDestroyCacheObsolete()
{
#pragma warning disable 618 // Type or member is obsolete
var cache = _grid.CreateCache<int, int>(TestUtils.TestName);
var streamer = _grid.GetDataStreamer<int, int>(cache.Name);
var task = streamer.AddData(1, 2);
streamer.Flush();
task.Wait();
_grid.DestroyCache(cache.Name);
streamer.AddData(2, 3);
var ex = Assert.Throws<AggregateException>(() => streamer.Flush()).GetBaseException();
Assert.IsNotNull(ex);
Assert.AreEqual("class org.apache.ignite.IgniteCheckedException: DataStreamer data loading failed.",
ex.Message);
Assert.Throws<CacheException>(() => streamer.Close(true));
#pragma warning restore 618 // Type or member is obsolete
}
#if NETCOREAPP
/// <summary>
/// Tests async streamer usage.
/// Using async cache and streamer operations within the streamer means that we end up on different threads.
/// Streamer is thread-safe and is expected to handle this well.
/// </summary>
[Test]
public async Task TestStreamerAsyncAwait()
{
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.AllowOverwrite = true;
ldr.Add(Enumerable.Range(1, 500).ToDictionary(x => x, x => -x));
Assert.IsFalse(await _cache.ContainsKeysAsync(new[] {1, 2}));
var flushTask = ldr.FlushAsync();
Assert.IsFalse(flushTask.IsCompleted);
await flushTask;
Assert.AreEqual(-1, await _cache.GetAsync(1));
Assert.AreEqual(-2, await _cache.GetAsync(2));
// Remove.
var batchTask = ldr.GetCurrentBatchTask();
Assert.IsFalse(batchTask.IsCompleted);
Assert.IsFalse(batchTask.IsFaulted);
ldr.Remove(1);
var flushTask2 = ldr.FlushAsync();
Assert.AreSame(batchTask, flushTask2);
await flushTask2;
Assert.IsTrue(batchTask.IsCompleted);
Assert.IsFalse(await _cache.ContainsKeyAsync(1));
// Empty buffer flush is allowed.
await ldr.FlushAsync();
await ldr.FlushAsync();
}
}
#endif
/// <summary>
/// Test binarizable receiver.
/// </summary>
private class StreamReceiverBinarizable : IStreamReceiver<int, int>
{
/** <inheritdoc /> */
public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries)
{
cache.PutAll(entries.ToDictionary(x => x.Key, x => x.Value + 1));
}
}
/// <summary>
/// Test binary receiver.
/// </summary>
[Serializable]
private class StreamReceiverKeepBinary : IStreamReceiver<int, IBinaryObject>
{
/** <inheritdoc /> */
public void Receive(ICache<int, IBinaryObject> cache, ICollection<ICacheEntry<int, IBinaryObject>> entries)
{
var binary = cache.Ignite.GetBinary();
cache.PutAll(entries.ToDictionary(x => x.Key, x =>
binary.ToBinary<IBinaryObject>(new BinarizableEntry
{
Val = x.Value.Deserialize<BinarizableEntry>().Val + 1
})));
}
}
/// <summary>
/// Test serializable receiver.
/// </summary>
[Serializable]
private class StreamReceiverSerializable : IStreamReceiver<int, int>
{
/** <inheritdoc /> */
public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries)
{
cache.PutAll(entries.ToDictionary(x => x.Key, x => x.Value + 1));
}
}
/// <summary>
/// Test entry processor.
/// </summary>
[Serializable]
private class EntryProcessorSerializable : ICacheEntryProcessor<int, int, int, int>
{
/** <inheritdoc /> */
public int Process(IMutableCacheEntry<int, int> entry, int arg)
{
entry.Value = entry.Key + 1;
return 0;
}
}
/// <summary>
/// Test entry processor.
/// </summary>
private class EntryProcessorBinarizable : ICacheEntryProcessor<int, int, int, int>, IBinarizable
{
/** <inheritdoc /> */
public int Process(IMutableCacheEntry<int, int> entry, int arg)
{
entry.Value = entry.Key + 1;
return 0;
}
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
// No-op.
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
// No-op.
}
}
/// <summary>
/// Binarizable entry.
/// </summary>
private class BinarizableEntry
{
public int Val { get; set; }
}
/// <summary>
/// Container class.
/// </summary>
private class Container
{
public Container Inner;
}
private class CountingEntryProcessor : ICacheEntryProcessor<string, long, object, object>
{
public object Process(IMutableCacheEntry<string, long> e, object arg)
{
e.Value++;
return null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
namespace Aardvark.Base.Coder
{
public partial class StreamCodeWriter : BinaryWriter
{
private const int c_bufferSize = 262144;
private byte[] m_buffer = new byte[c_bufferSize];
#region Constructors
public StreamCodeWriter(Stream output)
: base(output)
{
}
public StreamCodeWriter(Stream output, Encoding encoding)
: base(output, encoding)
{
}
#endregion
#region Primitive writers
public new void Write(string data)
{
base.Write(data);
}
public void Write(Guid data)
{
Write(data.ToString());
}
public void Write(Symbol value)
{
if (value.IsNegative)
{
Write(true);
Write((-value).ToString());
}
else
{
Write(false);
Write(value.ToString());
}
}
public void WriteGuidSymbol(Symbol value)
{
var bytes = value.ToGuid().ToByteArray();
Write(bytes, 0, 16);
}
public void WritePositiveSymbol(Symbol value) { Write(value.ToString()); }
#endregion
#region Write Transformations
public void Write(Euclidean3f t) { Write(t.Rot); Write(t.Trans); }
public void Write(Euclidean3d t) { Write(t.Rot); Write(t.Trans); }
public void Write(Rot2f t) { Write(t.Angle); }
public void Write(Rot2d t) { Write(t.Angle); }
public void Write(Rot3f t) { Write(t.W); Write(t.V); }
public void Write(Rot3d t) { Write(t.W); Write(t.V); }
public void Write(Scale3f t) { Write(t.V); }
public void Write(Scale3d t) { Write(t.V); }
public void Write(Shift3f t) { Write(t.V); }
public void Write(Shift3d t) { Write(t.V); }
public void Write(Similarity3f t) { Write(t.Scale); Write(t.Euclidean); }
public void Write(Similarity3d t) { Write(t.Scale); Write(t.Euclidean); }
public void Write(Trafo2f t) { Write(t.Forward); Write(t.Backward); }
public void Write(Trafo2d t) { Write(t.Forward); Write(t.Backward); }
public void Write(Trafo3f t) { Write(t.Forward); Write(t.Backward); }
public void Write(Trafo3d t) { Write(t.Forward); Write(t.Backward); }
#endregion
#region
public void Write(CameraExtrinsics c)
{
Write(c.Rotation); Write(c.Translation);
}
public void Write(CameraIntrinsics c)
{
Write(c.FocalLength);
Write(c.PrincipalPoint);
Write(c.Skew);
Write(c.K1); Write(c.K2); Write(c.K3);
Write(c.P1); Write(c.P2);
}
#endregion
#region Write Arrays and Lists
[StructLayout(LayoutKind.Explicit)]
struct ByteArrayUnion
{
[FieldOffset(0)]
public byte[] bytes;
[FieldOffset(0)]
public Array structs;
}
public void WriteArray(byte[] array, long index, long count)
{
Write(array, (int)index, (int)count);
}
public void WriteArray<T>(T[] array, long index, long count)
where T : struct
{
if (count < 1) return;
unsafe
{
var sizeOfT = Marshal.SizeOf(typeof(T));
var hack = new ByteArrayUnion();
hack.structs = array;
fixed (byte* pBytes = hack.bytes)
{
var offset = index * sizeOfT;
int itemsPerBlock = c_bufferSize / sizeOfT;
do
{
int blockSize = count > (long)itemsPerBlock
? itemsPerBlock : (int)count;
var byteBlockSize = blockSize * sizeOfT;
fixed (byte* p = m_buffer)
{
for (int i = 0; i < byteBlockSize; i++)
p[i] = pBytes[offset++];
}
base.Write(m_buffer, 0, byteBlockSize);
count -= (long)blockSize;
}
while (count > 0);
}
}
}
public void WriteArray<T>(T[,] array, long count)
where T : struct
{
if (count < 1) return;
unsafe
{
var sizeOfT = Marshal.SizeOf(typeof(T));
var hack = new ByteArrayUnion();
hack.structs = array;
fixed (byte* pBytes = hack.bytes)
{
#if __MonoCS__
long offset = 0;
#else
long offset = 2 * 2 * sizeof(int);
#endif
int itemsPerBlock = c_bufferSize / sizeOfT;
do
{
int blockSize = count > (long)itemsPerBlock
? itemsPerBlock : (int)count;
var byteBlockSize = blockSize * sizeOfT;
fixed (byte* p = m_buffer)
{
for (int i = 0; i < byteBlockSize; i++)
p[i] = pBytes[offset++];
}
base.Write(m_buffer, 0, byteBlockSize);
count -= (long)blockSize;
}
while (count > 0);
}
}
}
public void WriteArray<T>(T[, ,] array, long count)
where T : struct
{
if (count < 1) return;
unsafe
{
var sizeOfT = Marshal.SizeOf(typeof(T));
var hack = new ByteArrayUnion();
hack.structs = array;
fixed (byte* pBytes = hack.bytes)
{
#if __MonoCS__
long offset = 0;
#else
long offset = 3 * 2 * sizeof(int);
#endif
int itemsPerBlock = c_bufferSize / sizeOfT;
do
{
int blockSize = count > (long)itemsPerBlock
? itemsPerBlock : (int)count;
var byteBlockSize = blockSize * sizeOfT;
fixed (byte* p = m_buffer)
{
for (int i = 0; i < byteBlockSize; i++)
p[i] = pBytes[offset++];
}
base.Write(m_buffer, 0, byteBlockSize);
count -= (long)blockSize;
}
while (count > 0);
}
}
}
public void WriteList<T>(List<T> buffer, int index, int count)
where T: struct
{
var dataObjectField = buffer.GetType().GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance);
var arrayValue = (T[])dataObjectField.GetValue(buffer);
WriteArray(arrayValue, (long)index, (long)count);
}
#endregion
#region Close
public override void Close()
{
base.Close();
m_buffer = null;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
namespace UnityEngine.UI
{
/// <summary>
/// Labels are graphics that display text.
/// </summary>
[AddComponentMenu("UI/Text", 10)]
public class Text : MaskableGraphic, ILayoutElement
{
[SerializeField] private FontData m_FontData = FontData.defaultFontData;
[TextArea(3, 10)][SerializeField] protected string m_Text = String.Empty;
private TextGenerator m_TextCache;
private TextGenerator m_TextCacheForLayout;
static protected Material s_DefaultText = null;
// We use this flag instead of Unregistering/Registering the callback to avoid allocation.
[NonSerialized] protected bool m_DisableFontTextureRebuiltCallback = false;
protected Text()
{
useLegacyMeshGeneration = false;
}
/// <summary>
/// Get or set the material used by this Text.
/// </summary>
public TextGenerator cachedTextGenerator
{
get { return m_TextCache ?? (m_TextCache = (m_Text.Length != 0 ? new TextGenerator(m_Text.Length) : new TextGenerator())); }
}
public TextGenerator cachedTextGeneratorForLayout
{
get { return m_TextCacheForLayout ?? (m_TextCacheForLayout = new TextGenerator()); }
}
/// <summary>
/// Text's texture comes from the font.
/// </summary>
public override Texture mainTexture
{
get
{
if (font != null && font.material != null && font.material.mainTexture != null)
return font.material.mainTexture;
if (m_Material != null)
return m_Material.mainTexture;
return base.mainTexture;
}
}
public void FontTextureChanged()
{
// Only invoke if we are not destroyed.
if (!this)
{
FontUpdateTracker.UntrackText(this);
return;
}
if (m_DisableFontTextureRebuiltCallback)
return;
cachedTextGenerator.Invalidate();
if (!IsActive())
return;
// this is a bit hacky, but it is currently the
// cleanest solution....
// if we detect the font texture has changed and are in a rebuild loop
// we just regenerate the verts for the new UV's
if (CanvasUpdateRegistry.IsRebuildingGraphics() || CanvasUpdateRegistry.IsRebuildingLayout())
UpdateGeometry();
else
SetAllDirty();
}
public Font font
{
get
{
return m_FontData.font;
}
set
{
if (m_FontData.font == value)
return;
FontUpdateTracker.UntrackText(this);
m_FontData.font = value;
FontUpdateTracker.TrackText(this);
SetAllDirty();
}
}
/// <summary>
/// Text that's being displayed by the Text.
/// </summary>
public virtual string text
{
get
{
return m_Text;
}
set
{
if (String.IsNullOrEmpty(value))
{
if (String.IsNullOrEmpty(m_Text))
return;
m_Text = "";
SetVerticesDirty();
}
else if (m_Text != value)
{
m_Text = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
}
/// <summary>
/// Whether this Text will support rich text.
/// </summary>
public bool supportRichText
{
get
{
return m_FontData.richText;
}
set
{
if (m_FontData.richText == value)
return;
m_FontData.richText = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
/// <summary>
/// Wrap mode used by the text.
/// </summary>
public bool resizeTextForBestFit
{
get
{
return m_FontData.bestFit;
}
set
{
if (m_FontData.bestFit == value)
return;
m_FontData.bestFit = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public int resizeTextMinSize
{
get
{
return m_FontData.minSize;
}
set
{
if (m_FontData.minSize == value)
return;
m_FontData.minSize = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public int resizeTextMaxSize
{
get
{
return m_FontData.maxSize;
}
set
{
if (m_FontData.maxSize == value)
return;
m_FontData.maxSize = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
/// <summary>
/// Alignment anchor used by the text.
/// </summary>
public TextAnchor alignment
{
get
{
return m_FontData.alignment;
}
set
{
if (m_FontData.alignment == value)
return;
m_FontData.alignment = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public int fontSize
{
get
{
return m_FontData.fontSize;
}
set
{
if (m_FontData.fontSize == value)
return;
m_FontData.fontSize = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public HorizontalWrapMode horizontalOverflow
{
get
{
return m_FontData.horizontalOverflow;
}
set
{
if (m_FontData.horizontalOverflow == value)
return;
m_FontData.horizontalOverflow = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public VerticalWrapMode verticalOverflow
{
get
{
return m_FontData.verticalOverflow;
}
set
{
if (m_FontData.verticalOverflow == value)
return;
m_FontData.verticalOverflow = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public float lineSpacing
{
get
{
return m_FontData.lineSpacing;
}
set
{
if (m_FontData.lineSpacing == value)
return;
m_FontData.lineSpacing = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
/// <summary>
/// Font style used by the Text's text.
/// </summary>
public FontStyle fontStyle
{
get
{
return m_FontData.fontStyle;
}
set
{
if (m_FontData.fontStyle == value)
return;
m_FontData.fontStyle = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public float pixelsPerUnit
{
get
{
var localCanvas = canvas;
if (!localCanvas)
return 1;
// For dynamic fonts, ensure we use one pixel per pixel on the screen.
if (!font || font.dynamic)
return localCanvas.scaleFactor;
// For non-dynamic fonts, calculate pixels per unit based on specified font size relative to font object's own font size.
if (m_FontData.fontSize <= 0 || font.fontSize <= 0)
return 1;
return font.fontSize / (float)m_FontData.fontSize;
}
}
protected override void OnEnable()
{
base.OnEnable();
cachedTextGenerator.Invalidate();
FontUpdateTracker.TrackText(this);
}
protected override void OnDisable()
{
FontUpdateTracker.UntrackText(this);
base.OnDisable();
}
protected override void UpdateGeometry()
{
if (font != null)
{
base.UpdateGeometry();
}
}
#if UNITY_EDITOR
protected override void Reset()
{
font = Resources.GetBuiltinResource<Font>("Arial.ttf");
}
#endif
public TextGenerationSettings GetGenerationSettings(Vector2 extents)
{
var settings = new TextGenerationSettings();
settings.generationExtents = extents;
if (font != null && font.dynamic)
{
settings.fontSize = m_FontData.fontSize;
settings.resizeTextMinSize = m_FontData.minSize;
settings.resizeTextMaxSize = m_FontData.maxSize;
}
// Other settings
settings.textAnchor = m_FontData.alignment;
settings.scaleFactor = pixelsPerUnit;
settings.color = color;
settings.font = font;
settings.pivot = rectTransform.pivot;
settings.richText = m_FontData.richText;
settings.lineSpacing = m_FontData.lineSpacing;
settings.fontStyle = m_FontData.fontStyle;
settings.resizeTextForBestFit = m_FontData.bestFit;
settings.updateBounds = false;
settings.horizontalOverflow = m_FontData.horizontalOverflow;
settings.verticalOverflow = m_FontData.verticalOverflow;
return settings;
}
static public Vector2 GetTextAnchorPivot(TextAnchor anchor)
{
switch (anchor)
{
case TextAnchor.LowerLeft: return new Vector2(0, 0);
case TextAnchor.LowerCenter: return new Vector2(0.5f, 0);
case TextAnchor.LowerRight: return new Vector2(1, 0);
case TextAnchor.MiddleLeft: return new Vector2(0, 0.5f);
case TextAnchor.MiddleCenter: return new Vector2(0.5f, 0.5f);
case TextAnchor.MiddleRight: return new Vector2(1, 0.5f);
case TextAnchor.UpperLeft: return new Vector2(0, 1);
case TextAnchor.UpperCenter: return new Vector2(0.5f, 1);
case TextAnchor.UpperRight: return new Vector2(1, 1);
default: return Vector2.zero;
}
}
readonly UIVertex[] m_TempVerts = new UIVertex[4];
protected override void OnPopulateMesh(VertexHelper toFill)
{
if (font == null)
return;
// We don't care if we the font Texture changes while we are doing our Update.
// The end result of cachedTextGenerator will be valid for this instance.
// Otherwise we can get issues like Case 619238.
m_DisableFontTextureRebuiltCallback = true;
Vector2 extents = rectTransform.rect.size;
var settings = GetGenerationSettings(extents);
cachedTextGenerator.Populate(text, settings);
Rect inputRect = rectTransform.rect;
// get the text alignment anchor point for the text in local space
Vector2 textAnchorPivot = GetTextAnchorPivot(m_FontData.alignment);
Vector2 refPoint = Vector2.zero;
refPoint.x = (textAnchorPivot.x == 1 ? inputRect.xMax : inputRect.xMin);
refPoint.y = (textAnchorPivot.y == 0 ? inputRect.yMin : inputRect.yMax);
// Determine fraction of pixel to offset text mesh.
Vector2 roundingOffset = PixelAdjustPoint(refPoint) - refPoint;
// Apply the offset to the vertices
IList<UIVertex> verts = cachedTextGenerator.verts;
float unitsPerPixel = 1 / pixelsPerUnit;
//Last 4 verts are always a new line...
int vertCount = verts.Count - 4;
toFill.Clear();
if (roundingOffset != Vector2.zero)
{
for (int i = 0; i < vertCount; ++i)
{
int tempVertsIndex = i & 3;
m_TempVerts[tempVertsIndex] = verts[i];
m_TempVerts[tempVertsIndex].position *= unitsPerPixel;
m_TempVerts[tempVertsIndex].position.x += roundingOffset.x;
m_TempVerts[tempVertsIndex].position.y += roundingOffset.y;
if (tempVertsIndex == 3)
toFill.AddUIVertexQuad(m_TempVerts);
}
}
else
{
for (int i = 0; i < vertCount; ++i)
{
int tempVertsIndex = i & 3;
m_TempVerts[tempVertsIndex] = verts[i];
m_TempVerts[tempVertsIndex].position *= unitsPerPixel;
if (tempVertsIndex == 3)
toFill.AddUIVertexQuad(m_TempVerts);
}
}
m_DisableFontTextureRebuiltCallback = false;
}
public virtual void CalculateLayoutInputHorizontal() {}
public virtual void CalculateLayoutInputVertical() {}
public virtual float minWidth
{
get { return 0; }
}
public virtual float preferredWidth
{
get
{
var settings = GetGenerationSettings(Vector2.zero);
return cachedTextGeneratorForLayout.GetPreferredWidth(m_Text, settings) / pixelsPerUnit;
}
}
public virtual float flexibleWidth { get { return -1; } }
public virtual float minHeight
{
get { return 0; }
}
public virtual float preferredHeight
{
get
{
var settings = GetGenerationSettings(new Vector2(rectTransform.rect.size.x, 0.0f));
return cachedTextGeneratorForLayout.GetPreferredHeight(m_Text, settings) / pixelsPerUnit;
}
}
public virtual float flexibleHeight { get { return -1; } }
public virtual int layoutPriority { get { return 0; } }
#if UNITY_EDITOR
public override void OnRebuildRequested()
{
// After a Font asset gets re-imported the managed side gets deleted and recreated,
// that means the delegates are not persisted.
// so we need to properly enforce a consistent state here.
FontUpdateTracker.UntrackText(this);
FontUpdateTracker.TrackText(this);
// Also the textgenerator is no longer valid.
cachedTextGenerator.Invalidate();
base.OnRebuildRequested();
}
#endif // if UNITY_EDITOR
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using GTANetworkAPI;
public class HunterScript : Script
{
public HunterScript()
{
Event.OnResourceStart += startGM;
Event.OnResourceStop += stopGm;
Event.OnUpdate += update;
Event.OnPlayerDeath += dead;
//Event.OnPlayerRespawn += respawn;
Event.OnPlayerConnected += (player, cancel) => respawn(player);
Event.OnPlayerDisconnected += playerleft;
Event.OnPlayerConnected += (player, cancel) =>
{
if (API.GetAllPlayers().Count == 1 && !roundstarted)
{
roundstart();
}
};
}
private Vector3 _quadSpawn = new Vector3(-1564.36f, 4499.71f, 21.37f);
private NetHandle _quad;
private List<Vector3> _animalSpawnpoints = new List<Vector3>
{
new Vector3(-1488.76f, 4720.44f, 46.22f),
new Vector3(-1317.07f, 4642.76f, 108.31f),
new Vector3(-1291.08f, 4496.54f, 14.7f),
new Vector3(-1166.29f, 4409.41f, 8.87f),
new Vector3(-1522.33f, 4418.05f, 12.2f),
new Vector3(-1597.47f, 4483.42f, 17.4f),
};
private List<Vector3> _hunterSpawnpoints = new List<Vector3>
{
new Vector3(-1592.35f, 4486.51f, 17.57f),
new Vector3(-1572.83f, 4471.25f, 13.92f),
new Vector3(-1559.22f, 4467.11f, 18.74f),
new Vector3(-1515.67f, 4482.07f, 17.56f),
new Vector3(-1538.81f, 4443.99f, 11.53f),
};
private List<PedHash> _skinList = new List<PedHash>
{
PedHash.Hunter,
PedHash.Hillbilly01AMM,
PedHash.Hillbilly02AMM,
PedHash.Cletus,
PedHash.OldMan1aCutscene,
};
private List<Vector3> _checkpointPoses = new List<Vector3>
{
new Vector3(-1567.13f, 4541.15f, 17.26f),
new Vector3(-1582.11f, 4654.32f, 46.93f),
new Vector3(-1607.65f, 4369.2f, 2.45f),
new Vector3(-1336.23f, 4404.12f, 31.91f),
new Vector3(-1289.52f, 4498.14f, 14.8f),
new Vector3(-1268.58f, 4690.92f, 83.74f),
};
private List<NetHandle> _checkpoints = new List<NetHandle>();
private List<NetHandle> _checkpointBlips = new List<NetHandle>();
public bool roundstarted;
public Client animal;
private long roundStart;
private long lastIdleCheck;
private Vector3 lastIdlePosition;
private Client hawk;
private const int TEAM_ANIMAL = 2;
private const int TEAM_HUNTER = 1;
private Random r = new Random();
public void startGM()
{
roundstart();
}
public void stopGm()
{
var players = API.GetAllPlayers();
foreach (var player in players)
{
var pBlip = API.Exported.playerblips.getPlayerBlip(player);
API.SetBlipTransparency(pBlip, 255);
API.SetBlipSprite(pBlip, 1);
API.SetBlipColor(pBlip, 0);
API.SetPlayerTeam(player, 0);
API.SetEntityInvincible(player, false);
}
}
public void playerleft(Client player, byte type, string reason)
{
if (player == animal)
{
API.SendChatMessageToAll("The animal has left! Restarting...");
animal = null;
roundstarted = false;
roundstart();
}
}
public void roundstart()
{
var players = API.GetAllPlayers();
if (players.Count == 0) return;
API.DeleteEntity(breadcrumb);
API.DeleteEntity(_quad);
foreach (var c in _checkpoints)
{
API.DeleteEntity(c);
}
foreach (var c in _checkpointBlips)
{
API.DeleteEntity(c);
}
_checkpoints.Clear();
_checkpointBlips.Clear();
for(int i = 0; i < _checkpointPoses.Count; i++)
{
_checkpoints.Add(API.CreateMarker(1, _checkpointPoses[i], new Vector3(), new Vector3(),
/*new Vector3(10f, 10f, 3f)*/
10f // TODO: Fix scales?
, new Color(200, 255, 255, 0)));
var b = API.CreateBlip(_checkpointPoses[i]);
API.SetBlipColor(b, 66);
_checkpointBlips.Add(b);
}
_quad = API.CreateVehicle(VehicleHash.Blazer, _quadSpawn, 0, 0, 0);
animal = players[r.Next(players.Count)];
var aBlip = API.Exported.playerblips.getPlayerBlip(animal);
API.SetPlayerSkin(animal, PedHash.Deer);
API.SetPlayerTeam(animal, TEAM_ANIMAL);
API.SetBlipTransparency(aBlip, 0);
API.SetEntityInvincible(animal, false);
var spawnp = _animalSpawnpoints[r.Next(_animalSpawnpoints.Count)];
API.SetEntityPosition(animal.Handle, spawnp);
API.SetBlipSprite(aBlip, 141);
API.SetBlipColor(aBlip, 1);
API.SendChatMessageToPlayer(animal, "You are the animal! Collect all the checkpoints to win!");
roundStart = Environment.TickCount;
lastIdleCheck = Environment.TickCount;
lastBreadcrumb = Environment.TickCount;
roundstarted = true;
lastIdlePosition = spawnp;
if (players.Count > 3)
{
do
{
hawk = players[r.Next(players.Count)];
} while (hawk == animal);
}
foreach(var p in players)
{
if (p == animal)
continue;
Spawn(p, p == hawk);
}
}
public void Spawn(Client player, bool hawk = false)
{
var pBlip = API.Exported.playerblips.getPlayerBlip(player);
var spawnpoint = _hunterSpawnpoints[r.Next(_hunterSpawnpoints.Count)];
API.SpawnPlayer(player, spawnpoint, 0f);
if (!hawk)
{
var skin = _skinList[r.Next(_skinList.Count)];
API.SetPlayerSkin(player, skin);
API.GivePlayerWeapon(player, WeaponHash.PumpShotgun, 9999);
API.GivePlayerWeapon(player, WeaponHash.SniperRifle, 9999);
API.SetBlipTransparency(pBlip, 0);
API.SetBlipSprite(pBlip, 1);
}
else
{
API.SetPlayerSkin(player, PedHash.ChickenHawk);
API.SetBlipTransparency(pBlip, 255);
API.SetBlipSprite(pBlip, 422);
}
API.SetBlipColor(pBlip, 0);
//API.SetEntityPosition(player.handle, );
if (animal != null) API.SendChatMessageToPlayer(player, "~r~" + animal.Name + "~w~ is the animal! ~r~Hunt~w~ it!");
API.SetPlayerTeam(player, TEAM_HUNTER);
API.SetEntityInvincible(player, false);
}
public async void dead(Client player, NetHandle reason, uint weapon, CancelEventArgs cancel)
{
cancel.Cancel = true;
if (player == animal)
{
var killer = API.GetPlayerFromHandle(reason);
roundstarted = false;
API.SendChatMessageToAll("The animal has been killed" + (killer == null ? "!" : " by " + killer.Name + "!") + " The hunters win!");
API.SendChatMessageToAll("Starting next round in 15 seconds...");
animal = null;
roundstarted = false;
await Task.Delay(15000);
roundstart();
}
else
{
await Task.Run(async () =>
{
await Task.Delay(3000);
respawn(player);
});
}
}
public void respawn (Client player)
{
if (roundstarted && player != animal)
Spawn(player, player == hawk);
}
public async void update()
{
if (!roundstarted) return;
if (animal != null)
{
var pBlip = API.Exported.playerblips.getPlayerBlip(animal);
for(int i = 0; i < _checkpoints.Count; i++)
{
var pos = API.GetEntityPosition(_checkpoints[i]);
if (API.GetEntityPosition(animal.Handle).DistanceToSquared(pos) < 100f)
{
API.DeleteEntity(_checkpoints[i]);
API.DeleteEntity(_checkpointBlips[i]);
_checkpointBlips.RemoveAt(i);
_checkpoints.RemoveAt(i);
API.SendChatMessageToAll("The animal has picked up a checkpoint!");
if (_checkpoints.Count == 0)
{
roundstarted = false;
API.SendChatMessageToAll("The animal has collected all checkpoints! " + animal.Name + " has won!");
API.SendChatMessageToAll("Starting next round in 15 seconds...");
animal = null;
roundstarted = false;
//API.Sleep(15000);
await Task.Delay(15000);
roundstart();
break;
}
API.SetBlipTransparency(pBlip, 255);
//API.Sleep(5000);
await Task.Delay(5000);
API.SetBlipTransparency(pBlip, 0);
break;
}
}
if (Environment.TickCount - lastIdleCheck > 20000) // 20 secs
{
lastIdleCheck = Environment.TickCount;
if (API.GetEntityPosition(animal.Handle).DistanceToSquared(lastIdlePosition) < 5f)
{
API.SetBlipTransparency(pBlip, 255);
//API.Sleep(1000);
await Task.Delay(1000);
API.SetBlipTransparency(pBlip, 0);
}
else
{
API.SetBlipTransparency(pBlip, 0);
}
if (!breadcrumbLock) // breadcrumbs are very messy since i was debugging the blips not disappearing
{
breadcrumbLock = true;
breadcrumb = API.CreateBlip(lastIdlePosition);
API.SetBlipSprite(breadcrumb, 161);
API.SetBlipColor(breadcrumb, 1);
API.SetBlipTransparency(breadcrumb, 200);
lastBreadcrumb = Environment.TickCount;
}
if (animal != null)
lastIdlePosition = API.GetEntityPosition(animal.Handle);
}
if (Environment.TickCount - lastBreadcrumb > 15000 && breadcrumbLock)
{
API.DeleteEntity(breadcrumb);
breadcrumbLock = false;
}
}
}
private bool breadcrumbLock;
private NetHandle breadcrumb;
private long lastBreadcrumb;
}
| |
// 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.Drawing.Printing
{
using System.Globalization;
using System.Runtime.Serialization;
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins"]/*' />
/// <devdoc>
/// <para>
/// Specifies the margins of a printed page.
/// </para>
/// </devdoc>
[Serializable]
public class Margins : ICloneable
{
private int _left;
private int _right;
private int _top;
private int _bottom;
[OptionalField]
private double _doubleLeft;
[OptionalField]
private double _doubleRight;
[OptionalField]
private double _doubleTop;
[OptionalField]
private double _doubleBottom;
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Margins"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of a the <see cref='System.Drawing.Printing.Margins'/> class with one-inch margins.
/// </para>
/// </devdoc>
public Margins() : this(100, 100, 100, 100)
{
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Margins1"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of a the <see cref='System.Drawing.Printing.Margins'/> class with the specified left, right, top, and bottom
/// margins.
/// </para>
/// </devdoc>
public Margins(int left, int right, int top, int bottom)
{
CheckMargin(left, "left");
CheckMargin(right, "right");
CheckMargin(top, "top");
CheckMargin(bottom, "bottom");
_left = left;
_right = right;
_top = top;
_bottom = bottom;
_doubleLeft = (double)left;
_doubleRight = (double)right;
_doubleTop = (double)top;
_doubleBottom = (double)bottom;
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Left"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the left margin, in hundredths of an inch.
/// </para>
/// </devdoc>
public int Left
{
get { return _left; }
set
{
CheckMargin(value, "Left");
_left = value;
_doubleLeft = (double)value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Right"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the right margin, in hundredths of an inch.
/// </para>
/// </devdoc>
public int Right
{
get { return _right; }
set
{
CheckMargin(value, "Right");
_right = value;
_doubleRight = (double)value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Top"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the top margin, in hundredths of an inch.
/// </para>
/// </devdoc>
public int Top
{
get { return _top; }
set
{
CheckMargin(value, "Top");
_top = value;
_doubleTop = (double)value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Bottom"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the bottom margin, in hundredths of an inch.
/// </para>
/// </devdoc>
public int Bottom
{
get { return _bottom; }
set
{
CheckMargin(value, "Bottom");
_bottom = value;
_doubleBottom = (double)value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.DoubleLeft"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the left margin with double value, in hundredths of an inch.
/// When use the setter, the ranger of setting double value should between
/// 0 to Int.MaxValue;
/// </para>
/// </devdoc>
internal double DoubleLeft
{
get { return _doubleLeft; }
set
{
Left = (int)Math.Round(value);
_doubleLeft = value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.DoubleRight"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the right margin with double value, in hundredths of an inch.
/// When use the setter, the ranger of setting double value should between
/// 0 to Int.MaxValue;
/// </para>
/// </devdoc>
internal double DoubleRight
{
get { return _doubleRight; }
set
{
Right = (int)Math.Round(value);
_doubleRight = value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.DoubleTop"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the top margin with double value, in hundredths of an inch.
/// When use the setter, the ranger of setting double value should between
/// 0 to Int.MaxValue;
/// </para>
/// </devdoc>
internal double DoubleTop
{
get { return _doubleTop; }
set
{
Top = (int)Math.Round(value);
_doubleTop = value;
}
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.DoubleBottom"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the bottom margin with double value, in hundredths of an inch.
/// When use the setter, the ranger of setting double value should between
/// 0 to Int.MaxValue;
/// </para>
/// </devdoc>
internal double DoubleBottom
{
get { return _doubleBottom; }
set
{
Bottom = (int)Math.Round(value);
_doubleBottom = value;
}
}
[OnDeserialized()]
private void OnDeserializedMethod(StreamingContext context)
{
if (_doubleLeft == 0 && _left != 0)
{
_doubleLeft = (double)_left;
}
if (_doubleRight == 0 && _right != 0)
{
_doubleRight = (double)_right;
}
if (_doubleTop == 0 && _top != 0)
{
_doubleTop = (double)_top;
}
if (_doubleBottom == 0 && _bottom != 0)
{
_doubleBottom = (double)_bottom;
}
}
private void CheckMargin(int margin, string name)
{
if (margin < 0)
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx, name, margin, "0"));
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Clone"]/*' />
/// <devdoc>
/// <para>
/// Retrieves a duplicate of this object, member by member.
/// </para>
/// </devdoc>
public object Clone()
{
return MemberwiseClone();
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.Equals"]/*' />
/// <devdoc>
/// <para>
/// Compares this <see cref='System.Drawing.Printing.Margins'/> to a specified <see cref='System.Drawing.Printing.Margins'/> to see whether they
/// are equal.
/// </para>
/// </devdoc>
public override bool Equals(object obj)
{
Margins margins = obj as Margins;
if (margins == this) return true;
if (margins == null) return false;
return margins.Left == Left
&& margins.Right == Right
&& margins.Top == Top
&& margins.Bottom == Bottom;
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.GetHashCode"]/*' />
/// <devdoc>
/// <para>
/// Calculates and retrieves a hash code based on the left, right, top, and bottom
/// margins.
/// </para>
/// </devdoc>
public override int GetHashCode()
{
// return HashCodes.Combine(left, right, top, bottom);
uint left = (uint)Left;
uint right = (uint)Right;
uint top = (uint)Top;
uint bottom = (uint)Bottom;
uint result = left ^
((right << 13) | (right >> 19)) ^
((top << 26) | (top >> 6)) ^
((bottom << 7) | (bottom >> 25));
return unchecked((int)result);
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.operator=="]/*' />
/// <devdoc>
/// Tests whether two <see cref='System.Drawing.Printing.Margins'/> objects
/// are identical.
/// </devdoc>
public static bool operator ==(Margins m1, Margins m2)
{
if (object.ReferenceEquals(m1, null) != object.ReferenceEquals(m2, null))
{
return false;
}
if (!object.ReferenceEquals(m1, null))
{
return m1.Left == m2.Left && m1.Top == m2.Top && m1.Right == m2.Right && m1.Bottom == m2.Bottom;
}
return true;
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.operator!="]/*' />
/// <devdoc>
/// <para>
/// Tests whether two <see cref='System.Drawing.Printing.Margins'/> objects are different.
/// </para>
/// </devdoc>
public static bool operator !=(Margins m1, Margins m2)
{
return !(m1 == m2);
}
/// <include file='doc\Margins.uex' path='docs/doc[@for="Margins.ToString"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Provides some interesting information for the Margins in
/// String form.
/// </para>
/// </devdoc>
public override string ToString()
{
return "[Margins"
+ " Left=" + Left.ToString(CultureInfo.InvariantCulture)
+ " Right=" + Right.ToString(CultureInfo.InvariantCulture)
+ " Top=" + Top.ToString(CultureInfo.InvariantCulture)
+ " Bottom=" + Bottom.ToString(CultureInfo.InvariantCulture)
+ "]";
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// KGO Transfer Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KGO_TFRDataSet : EduHubDataSet<KGO_TFR>
{
/// <inheritdoc />
public override string Name { get { return "KGO_TFR"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KGO_TFRDataSet(EduHubContext Context)
: base(Context)
{
Index_KGO_TRANS_ID = new Lazy<NullDictionary<string, KGO_TFR>>(() => this.ToNullDictionary(i => i.KGO_TRANS_ID));
Index_ORIG_SCHOOL = new Lazy<Dictionary<string, IReadOnlyList<KGO_TFR>>>(() => this.ToGroupedDictionary(i => i.ORIG_SCHOOL));
Index_TID = new Lazy<Dictionary<int, KGO_TFR>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KGO_TFR" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KGO_TFR" /> fields for each CSV column header</returns>
internal override Action<KGO_TFR, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KGO_TFR, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "ORIG_SCHOOL":
mapper[i] = (e, v) => e.ORIG_SCHOOL = v;
break;
case "KGO_TRANS_ID":
mapper[i] = (e, v) => e.KGO_TRANS_ID = v;
break;
case "KGOKEY":
mapper[i] = (e, v) => e.KGOKEY = v;
break;
case "KGOKEY_NEW":
mapper[i] = (e, v) => e.KGOKEY_NEW = v;
break;
case "TITLE":
mapper[i] = (e, v) => e.TITLE = v;
break;
case "IMP_STATUS":
mapper[i] = (e, v) => e.IMP_STATUS = v;
break;
case "IMP_DATE":
mapper[i] = (e, v) => e.IMP_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KGO_TFR" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KGO_TFR" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KGO_TFR" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KGO_TFR}"/> of entities</returns>
internal override IEnumerable<KGO_TFR> ApplyDeltaEntities(IEnumerable<KGO_TFR> Entities, List<KGO_TFR> DeltaEntities)
{
HashSet<string> Index_KGO_TRANS_ID = new HashSet<string>(DeltaEntities.Select(i => i.KGO_TRANS_ID));
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.ORIG_SCHOOL;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = false;
overwritten = overwritten || Index_KGO_TRANS_ID.Remove(entity.KGO_TRANS_ID);
overwritten = overwritten || Index_TID.Remove(entity.TID);
if (entity.ORIG_SCHOOL.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, KGO_TFR>> Index_KGO_TRANS_ID;
private Lazy<Dictionary<string, IReadOnlyList<KGO_TFR>>> Index_ORIG_SCHOOL;
private Lazy<Dictionary<int, KGO_TFR>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find KGO_TFR by KGO_TRANS_ID field
/// </summary>
/// <param name="KGO_TRANS_ID">KGO_TRANS_ID value used to find KGO_TFR</param>
/// <returns>Related KGO_TFR entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGO_TFR FindByKGO_TRANS_ID(string KGO_TRANS_ID)
{
return Index_KGO_TRANS_ID.Value[KGO_TRANS_ID];
}
/// <summary>
/// Attempt to find KGO_TFR by KGO_TRANS_ID field
/// </summary>
/// <param name="KGO_TRANS_ID">KGO_TRANS_ID value used to find KGO_TFR</param>
/// <param name="Value">Related KGO_TFR entity</param>
/// <returns>True if the related KGO_TFR entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByKGO_TRANS_ID(string KGO_TRANS_ID, out KGO_TFR Value)
{
return Index_KGO_TRANS_ID.Value.TryGetValue(KGO_TRANS_ID, out Value);
}
/// <summary>
/// Attempt to find KGO_TFR by KGO_TRANS_ID field
/// </summary>
/// <param name="KGO_TRANS_ID">KGO_TRANS_ID value used to find KGO_TFR</param>
/// <returns>Related KGO_TFR entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGO_TFR TryFindByKGO_TRANS_ID(string KGO_TRANS_ID)
{
KGO_TFR value;
if (Index_KGO_TRANS_ID.Value.TryGetValue(KGO_TRANS_ID, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find KGO_TFR by ORIG_SCHOOL field
/// </summary>
/// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find KGO_TFR</param>
/// <returns>List of related KGO_TFR entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KGO_TFR> FindByORIG_SCHOOL(string ORIG_SCHOOL)
{
return Index_ORIG_SCHOOL.Value[ORIG_SCHOOL];
}
/// <summary>
/// Attempt to find KGO_TFR by ORIG_SCHOOL field
/// </summary>
/// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find KGO_TFR</param>
/// <param name="Value">List of related KGO_TFR entities</param>
/// <returns>True if the list of related KGO_TFR entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByORIG_SCHOOL(string ORIG_SCHOOL, out IReadOnlyList<KGO_TFR> Value)
{
return Index_ORIG_SCHOOL.Value.TryGetValue(ORIG_SCHOOL, out Value);
}
/// <summary>
/// Attempt to find KGO_TFR by ORIG_SCHOOL field
/// </summary>
/// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find KGO_TFR</param>
/// <returns>List of related KGO_TFR entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KGO_TFR> TryFindByORIG_SCHOOL(string ORIG_SCHOOL)
{
IReadOnlyList<KGO_TFR> value;
if (Index_ORIG_SCHOOL.Value.TryGetValue(ORIG_SCHOOL, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find KGO_TFR by TID field
/// </summary>
/// <param name="TID">TID value used to find KGO_TFR</param>
/// <returns>Related KGO_TFR entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGO_TFR FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find KGO_TFR by TID field
/// </summary>
/// <param name="TID">TID value used to find KGO_TFR</param>
/// <param name="Value">Related KGO_TFR entity</param>
/// <returns>True if the related KGO_TFR entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out KGO_TFR Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find KGO_TFR by TID field
/// </summary>
/// <param name="TID">TID value used to find KGO_TFR</param>
/// <returns>Related KGO_TFR entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGO_TFR TryFindByTID(int TID)
{
KGO_TFR value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KGO_TFR table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KGO_TFR]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KGO_TFR](
[TID] int IDENTITY NOT NULL,
[ORIG_SCHOOL] varchar(8) NOT NULL,
[KGO_TRANS_ID] varchar(30) NULL,
[KGOKEY] varchar(10) NULL,
[KGOKEY_NEW] varchar(10) NULL,
[TITLE] varchar(30) NULL,
[IMP_STATUS] varchar(15) NULL,
[IMP_DATE] datetime NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KGO_TFR_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE NONCLUSTERED INDEX [KGO_TFR_Index_KGO_TRANS_ID] ON [dbo].[KGO_TFR]
(
[KGO_TRANS_ID] ASC
);
CREATE CLUSTERED INDEX [KGO_TFR_Index_ORIG_SCHOOL] ON [dbo].[KGO_TFR]
(
[ORIG_SCHOOL] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGO_TFR]') AND name = N'KGO_TFR_Index_KGO_TRANS_ID')
ALTER INDEX [KGO_TFR_Index_KGO_TRANS_ID] ON [dbo].[KGO_TFR] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGO_TFR]') AND name = N'KGO_TFR_Index_TID')
ALTER INDEX [KGO_TFR_Index_TID] ON [dbo].[KGO_TFR] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGO_TFR]') AND name = N'KGO_TFR_Index_KGO_TRANS_ID')
ALTER INDEX [KGO_TFR_Index_KGO_TRANS_ID] ON [dbo].[KGO_TFR] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGO_TFR]') AND name = N'KGO_TFR_Index_TID')
ALTER INDEX [KGO_TFR_Index_TID] ON [dbo].[KGO_TFR] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KGO_TFR"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KGO_TFR"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KGO_TFR> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_KGO_TRANS_ID = new List<string>();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_KGO_TRANS_ID.Add(entity.KGO_TRANS_ID);
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[KGO_TFR] WHERE");
// Index_KGO_TRANS_ID
builder.Append("[KGO_TRANS_ID] IN (");
for (int index = 0; index < Index_KGO_TRANS_ID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// KGO_TRANS_ID
var parameterKGO_TRANS_ID = $"@p{parameterIndex++}";
builder.Append(parameterKGO_TRANS_ID);
command.Parameters.Add(parameterKGO_TRANS_ID, SqlDbType.VarChar, 30).Value = (object)Index_KGO_TRANS_ID[index] ?? DBNull.Value;
}
builder.AppendLine(") OR");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KGO_TFR data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KGO_TFR data set</returns>
public override EduHubDataSetDataReader<KGO_TFR> GetDataSetDataReader()
{
return new KGO_TFRDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KGO_TFR data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KGO_TFR data set</returns>
public override EduHubDataSetDataReader<KGO_TFR> GetDataSetDataReader(List<KGO_TFR> Entities)
{
return new KGO_TFRDataReader(new EduHubDataSetLoadedReader<KGO_TFR>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KGO_TFRDataReader : EduHubDataSetDataReader<KGO_TFR>
{
public KGO_TFRDataReader(IEduHubDataSetReader<KGO_TFR> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 11; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // ORIG_SCHOOL
return Current.ORIG_SCHOOL;
case 2: // KGO_TRANS_ID
return Current.KGO_TRANS_ID;
case 3: // KGOKEY
return Current.KGOKEY;
case 4: // KGOKEY_NEW
return Current.KGOKEY_NEW;
case 5: // TITLE
return Current.TITLE;
case 6: // IMP_STATUS
return Current.IMP_STATUS;
case 7: // IMP_DATE
return Current.IMP_DATE;
case 8: // LW_DATE
return Current.LW_DATE;
case 9: // LW_TIME
return Current.LW_TIME;
case 10: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // KGO_TRANS_ID
return Current.KGO_TRANS_ID == null;
case 3: // KGOKEY
return Current.KGOKEY == null;
case 4: // KGOKEY_NEW
return Current.KGOKEY_NEW == null;
case 5: // TITLE
return Current.TITLE == null;
case 6: // IMP_STATUS
return Current.IMP_STATUS == null;
case 7: // IMP_DATE
return Current.IMP_DATE == null;
case 8: // LW_DATE
return Current.LW_DATE == null;
case 9: // LW_TIME
return Current.LW_TIME == null;
case 10: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // ORIG_SCHOOL
return "ORIG_SCHOOL";
case 2: // KGO_TRANS_ID
return "KGO_TRANS_ID";
case 3: // KGOKEY
return "KGOKEY";
case 4: // KGOKEY_NEW
return "KGOKEY_NEW";
case 5: // TITLE
return "TITLE";
case 6: // IMP_STATUS
return "IMP_STATUS";
case 7: // IMP_DATE
return "IMP_DATE";
case 8: // LW_DATE
return "LW_DATE";
case 9: // LW_TIME
return "LW_TIME";
case 10: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "ORIG_SCHOOL":
return 1;
case "KGO_TRANS_ID":
return 2;
case "KGOKEY":
return 3;
case "KGOKEY_NEW":
return 4;
case "TITLE":
return 5;
case "IMP_STATUS":
return 6;
case "IMP_DATE":
return 7;
case "LW_DATE":
return 8;
case "LW_TIME":
return 9;
case "LW_USER":
return 10;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
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 AprDefectoCongenito class.
/// </summary>
[Serializable]
public partial class AprDefectoCongenitoCollection : ActiveList<AprDefectoCongenito, AprDefectoCongenitoCollection>
{
public AprDefectoCongenitoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>AprDefectoCongenitoCollection</returns>
public AprDefectoCongenitoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
AprDefectoCongenito 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_DefectoCongenito table.
/// </summary>
[Serializable]
public partial class AprDefectoCongenito : ActiveRecord<AprDefectoCongenito>, IActiveRecord
{
#region .ctors and Default Settings
public AprDefectoCongenito()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public AprDefectoCongenito(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public AprDefectoCongenito(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public AprDefectoCongenito(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_DefectoCongenito", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdDefectoCongenito = new TableSchema.TableColumn(schema);
colvarIdDefectoCongenito.ColumnName = "idDefectoCongenito";
colvarIdDefectoCongenito.DataType = DbType.Int32;
colvarIdDefectoCongenito.MaxLength = 0;
colvarIdDefectoCongenito.AutoIncrement = true;
colvarIdDefectoCongenito.IsNullable = false;
colvarIdDefectoCongenito.IsPrimaryKey = true;
colvarIdDefectoCongenito.IsForeignKey = false;
colvarIdDefectoCongenito.IsReadOnly = false;
colvarIdDefectoCongenito.DefaultSetting = @"";
colvarIdDefectoCongenito.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdDefectoCongenito);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = 50;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema);
colvarCreatedBy.ColumnName = "CreatedBy";
colvarCreatedBy.DataType = DbType.AnsiString;
colvarCreatedBy.MaxLength = 50;
colvarCreatedBy.AutoIncrement = false;
colvarCreatedBy.IsNullable = true;
colvarCreatedBy.IsPrimaryKey = false;
colvarCreatedBy.IsForeignKey = false;
colvarCreatedBy.IsReadOnly = false;
colvarCreatedBy.DefaultSetting = @"";
colvarCreatedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedBy);
TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema);
colvarCreatedOn.ColumnName = "CreatedOn";
colvarCreatedOn.DataType = DbType.DateTime;
colvarCreatedOn.MaxLength = 0;
colvarCreatedOn.AutoIncrement = false;
colvarCreatedOn.IsNullable = true;
colvarCreatedOn.IsPrimaryKey = false;
colvarCreatedOn.IsForeignKey = false;
colvarCreatedOn.IsReadOnly = false;
colvarCreatedOn.DefaultSetting = @"";
colvarCreatedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedOn);
TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema);
colvarModifiedBy.ColumnName = "ModifiedBy";
colvarModifiedBy.DataType = DbType.AnsiString;
colvarModifiedBy.MaxLength = 50;
colvarModifiedBy.AutoIncrement = false;
colvarModifiedBy.IsNullable = true;
colvarModifiedBy.IsPrimaryKey = false;
colvarModifiedBy.IsForeignKey = false;
colvarModifiedBy.IsReadOnly = false;
colvarModifiedBy.DefaultSetting = @"";
colvarModifiedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedBy);
TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema);
colvarModifiedOn.ColumnName = "ModifiedOn";
colvarModifiedOn.DataType = DbType.DateTime;
colvarModifiedOn.MaxLength = 0;
colvarModifiedOn.AutoIncrement = false;
colvarModifiedOn.IsNullable = true;
colvarModifiedOn.IsPrimaryKey = false;
colvarModifiedOn.IsForeignKey = false;
colvarModifiedOn.IsReadOnly = false;
colvarModifiedOn.DefaultSetting = @"";
colvarModifiedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedOn);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("APR_DefectoCongenito",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdDefectoCongenito")]
[Bindable(true)]
public int IdDefectoCongenito
{
get { return GetColumnValue<int>(Columns.IdDefectoCongenito); }
set { SetColumnValue(Columns.IdDefectoCongenito, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("CreatedBy")]
[Bindable(true)]
public string CreatedBy
{
get { return GetColumnValue<string>(Columns.CreatedBy); }
set { SetColumnValue(Columns.CreatedBy, value); }
}
[XmlAttribute("CreatedOn")]
[Bindable(true)]
public DateTime? CreatedOn
{
get { return GetColumnValue<DateTime?>(Columns.CreatedOn); }
set { SetColumnValue(Columns.CreatedOn, value); }
}
[XmlAttribute("ModifiedBy")]
[Bindable(true)]
public string ModifiedBy
{
get { return GetColumnValue<string>(Columns.ModifiedBy); }
set { SetColumnValue(Columns.ModifiedBy, value); }
}
[XmlAttribute("ModifiedOn")]
[Bindable(true)]
public DateTime? ModifiedOn
{
get { return GetColumnValue<DateTime?>(Columns.ModifiedOn); }
set { SetColumnValue(Columns.ModifiedOn, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.AprRelRecienNacidoDefectoCongenitoCollection colAprRelRecienNacidoDefectoCongenitoRecords;
public DalSic.AprRelRecienNacidoDefectoCongenitoCollection AprRelRecienNacidoDefectoCongenitoRecords
{
get
{
if(colAprRelRecienNacidoDefectoCongenitoRecords == null)
{
colAprRelRecienNacidoDefectoCongenitoRecords = new DalSic.AprRelRecienNacidoDefectoCongenitoCollection().Where(AprRelRecienNacidoDefectoCongenito.Columns.IdDefectoCongenito, IdDefectoCongenito).Load();
colAprRelRecienNacidoDefectoCongenitoRecords.ListChanged += new ListChangedEventHandler(colAprRelRecienNacidoDefectoCongenitoRecords_ListChanged);
}
return colAprRelRecienNacidoDefectoCongenitoRecords;
}
set
{
colAprRelRecienNacidoDefectoCongenitoRecords = value;
colAprRelRecienNacidoDefectoCongenitoRecords.ListChanged += new ListChangedEventHandler(colAprRelRecienNacidoDefectoCongenitoRecords_ListChanged);
}
}
void colAprRelRecienNacidoDefectoCongenitoRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colAprRelRecienNacidoDefectoCongenitoRecords[e.NewIndex].IdDefectoCongenito = IdDefectoCongenito;
}
}
#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 varNombre,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn)
{
AprDefectoCongenito item = new AprDefectoCongenito();
item.Nombre = varNombre;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
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 varIdDefectoCongenito,string varNombre,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn)
{
AprDefectoCongenito item = new AprDefectoCongenito();
item.IdDefectoCongenito = varIdDefectoCongenito;
item.Nombre = varNombre;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
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 IdDefectoCongenitoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn CreatedByColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn CreatedOnColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn ModifiedByColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn ModifiedOnColumn
{
get { return Schema.Columns[5]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdDefectoCongenito = @"idDefectoCongenito";
public static string Nombre = @"nombre";
public static string CreatedBy = @"CreatedBy";
public static string CreatedOn = @"CreatedOn";
public static string ModifiedBy = @"ModifiedBy";
public static string ModifiedOn = @"ModifiedOn";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colAprRelRecienNacidoDefectoCongenitoRecords != null)
{
foreach (DalSic.AprRelRecienNacidoDefectoCongenito item in colAprRelRecienNacidoDefectoCongenitoRecords)
{
if (item.IdDefectoCongenito != IdDefectoCongenito)
{
item.IdDefectoCongenito = IdDefectoCongenito;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colAprRelRecienNacidoDefectoCongenitoRecords != null)
{
colAprRelRecienNacidoDefectoCongenitoRecords.SaveAll();
}
}
#endregion
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
namespace _4PosBackOffice.NET
{
internal partial class frmStockMultiCost : System.Windows.Forms.Form
{
private ADODB.Recordset withEventsField_adoPrimaryRS;
public ADODB.Recordset adoPrimaryRS {
get { return withEventsField_adoPrimaryRS; }
set {
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord;
}
withEventsField_adoPrimaryRS = value;
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord;
}
}
}
bool mbChangedByCode;
int mvBookMark;
bool mbEditFlag;
bool mbAddNewFlag;
bool mbDataChanged;
string gFilter;
string gFilterSQL;
private StdFormat.StdDataFormat withEventsField_myfmt;
public StdFormat.StdDataFormat myfmt {
get { return withEventsField_myfmt; }
set {
if (withEventsField_myfmt != null) {
withEventsField_myfmt.UnFormat -= myfmt_UnFormat;
}
withEventsField_myfmt = value;
if (withEventsField_myfmt != null) {
withEventsField_myfmt.UnFormat += myfmt_UnFormat;
}
}
}
private void loadLanguage()
{
//frmStockMultiCost = No Code [Edit Stock Item Costs]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmStockMultiCost.Caption = rsLang("LanguageLayoutLnk_Description"): frmStockMultiCost.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//lblHeading = No Code [Using the "Stock Item Selector"...]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lblHeading.Caption = rsLang("LanguageLayoutLnk_Description"): lblHeading.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1006;
//Filter|Checked
if (modRecordSet.rsLang.RecordCount){cmdFilter.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdFilter.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1085;
//Print|Checked
if (modRecordSet.rsLang.RecordCount){cmdPrint.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdPrint.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmStockMultiCost.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void myfmt_UnFormat(StdFormat.StdDataValue DataValue)
{
var _with1 = DataValue;
if (Information.IsNumeric(_with1.value)) {
if (Strings.InStr(_with1.value, ".")) {
_with1.value = Strings.FormatNumber(_with1.value, 2);
} else {
_with1.value = Strings.FormatNumber(_with1.value / 100, 2);
}
}
}
private void cmdFilter_Click(System.Object eventSender, System.EventArgs eventArgs)
{
My.MyProject.Forms.frmFilter.loadFilter(ref gFilter);
getNamespace();
}
private void getNamespace()
{
if (string.IsNullOrEmpty(gFilter)) {
this.lblHeading.Text = "";
} else {
My.MyProject.Forms.frmFilter.buildCriteria(ref gFilter);
this.lblHeading.Text = My.MyProject.Forms.frmFilter.gHeading;
}
gFilterSQL = My.MyProject.Forms.frmFilter.gCriteria;
if (string.IsNullOrEmpty(gFilterSQL)) {
gFilterSQL = " WHERE StockItem.StockItem_Disabled=0 AND StockItem.StockItem_Discontinued=0 ";
} else {
gFilterSQL = gFilterSQL + " AND StockItem.StockItem_Disabled=0 AND StockItem.StockItem_Discontinued=0 ";
}
adoPrimaryRS = modRecordSet.getRS(ref "SELECT StockItem_Name,StockItem_Quantity,StockItem_ListCost FROM StockItem " + gFilterSQL + " ORDER BY StockItem_Name");
//Display the list of Titles in the DataCombo
grdDataGrid.DataSource = adoPrimaryRS;
grdDataGrid.Columns[0].HeaderText = "Stock Name";
grdDataGrid.Columns[0].DefaultCellStyle.Alignment = MSDataGridLib.AlignmentConstants.dbgLeft;
grdDataGrid.Columns[0].Frozen = true;
grdDataGrid.Columns[1].HeaderText = "Quantity";
grdDataGrid.Columns[1].DefaultCellStyle.Alignment = MSDataGridLib.AlignmentConstants.dbgRight;
grdDataGrid.Columns[1].Width = sizeConvertors.twipsToPixels(900, true);
//UPGRADE_WARNING: Couldn't resolve default property of object grdDataGrid.Columns().DataFormat.Type. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
grdDataGrid.Columns[1].DefaultCellStyle.Format = 1;
//grdDataGrid.Columns(1).NumberFormat = "#,##0"
grdDataGrid.Columns[2].HeaderText = "Cost";
grdDataGrid.Columns[2].DefaultCellStyle.Alignment = MSDataGridLib.AlignmentConstants.dbgRight;
grdDataGrid.Columns[2].Width = sizeConvertors.twipsToPixels(900, true);
grdDataGrid.Columns[2].DefaultCellStyle.Format = myfmt;
//grdDataGrid.Columns(2).NumberFormat = "#,##0.00"
frmStockMultiCost_Resize(this, new System.EventArgs());
mbDataChanged = false;
}
private void cmdPrint_Click(System.Object eventSender, System.EventArgs eventArgs)
{
CrystalDecisions.CrystalReports.Engine.ReportDocument Report = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
ADODB.Recordset rs = default(ADODB.Recordset);
bool ltype = false;
Report.Load("cryStockItemCost.rpt");
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
rs = modRecordSet.getRS(ref "SELECT * FROM Company");
Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name"));
Report.SetParameterValue("txtTilte", this.Text);
Report.SetParameterValue("txtFilter", this.lblHeading.Text);
rs.Close();
//Report.Database.SetDataSource(adoPrimaryRS, 3)
Report.Database.Tables(1).SetDataSource(adoPrimaryRS);
//Report.VerifyOnEveryPrint = True
My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtTilte").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report;
My.MyProject.Forms.frmReportShow.mReport = Report;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
}
private void frmStockMultiCost_Load(System.Object eventSender, System.EventArgs eventArgs)
{
myfmt = new StdFormat.StdDataFormat();
myfmt.Type = StdFormat.FormatType.fmtCustom;
gFilter = "stockitem";
getNamespace();
mbDataChanged = false;
loadLanguage();
}
private void frmStockMultiCost_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 27) {
KeyAscii = 0;
cmdClose_Click(cmdClose, new System.EventArgs());
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
//UPGRADE_WARNING: Event frmStockMultiCost.Resize may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
private void frmStockMultiCost_Resize(System.Object eventSender, System.EventArgs eventArgs)
{
// ERROR: Not supported in C#: OnErrorStatement
//This will resize the grid when the form is resized
System.Windows.Forms.Application.DoEvents();
grdDataGrid.Height = sizeConvertors.twipsToPixels(sizeConvertors.pixelToTwips(this.ClientRectangle.Height, false) - 30 - sizeConvertors.pixelToTwips(picButtons.Height, false), false);
grdDataGrid.Columns[0].Width = sizeConvertors.twipsToPixels(sizeConvertors.pixelToTwips(grdDataGrid.Width, true) - 1800 - 580, true);
}
private void frmStockMultiCost_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
//UPGRADE_WARNING: Screen property Screen.MousePointer has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"'
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
}
private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This will display the current record position for this recordset
}
private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This is where you put validation code
//This event gets called when the following actions occur
bool bCancel = false;
switch (adReason) {
case ADODB.EventReasonEnum.adRsnAddNew:
break;
case ADODB.EventReasonEnum.adRsnClose:
break;
case ADODB.EventReasonEnum.adRsnDelete:
break;
case ADODB.EventReasonEnum.adRsnFirstChange:
break;
case ADODB.EventReasonEnum.adRsnMove:
break;
case ADODB.EventReasonEnum.adRsnRequery:
break;
case ADODB.EventReasonEnum.adRsnResynch:
break;
case ADODB.EventReasonEnum.adRsnUndoAddNew:
break;
case ADODB.EventReasonEnum.adRsnUndoDelete:
break;
case ADODB.EventReasonEnum.adRsnUndoUpdate:
break;
case ADODB.EventReasonEnum.adRsnUpdate:
break;
}
if (bCancel)
adStatus = ADODB.EventStatusEnum.adStatusCancel;
}
private void cmdCancel_Click()
{
// ERROR: Not supported in C#: OnErrorStatement
mbEditFlag = false;
mbAddNewFlag = false;
adoPrimaryRS.CancelUpdate();
//UPGRADE_WARNING: Couldn't resolve default property of object mvBookMark. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
if (mvBookMark > 0) {
//UPGRADE_WARNING: Couldn't resolve default property of object mvBookMark. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
adoPrimaryRS.Bookmark = mvBookMark;
} else {
adoPrimaryRS.MoveFirst();
}
mbDataChanged = false;
}
//UPGRADE_NOTE: update was upgraded to update_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
private void update_Renamed()
{
// ERROR: Not supported in C#: OnErrorStatement
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
if (mbAddNewFlag) {
adoPrimaryRS.MoveLast();
//move to the new record
}
mbEditFlag = false;
mbAddNewFlag = false;
mbDataChanged = false;
return;
UpdateErr:
Interaction.MsgBox(Err().Description);
}
private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
{
update_Renamed();
this.Close();
}
private void goFirst()
{
// ERROR: Not supported in C#: OnErrorStatement
adoPrimaryRS.MoveFirst();
mbDataChanged = false;
return;
GoFirstError:
Interaction.MsgBox(Err().Description);
}
private void goLast()
{
// ERROR: Not supported in C#: OnErrorStatement
adoPrimaryRS.MoveLast();
mbDataChanged = false;
return;
GoLastError:
Interaction.MsgBox(Err().Description);
}
private void grdDataGrid_CellValueChanged(System.Object eventSender, DataGridViewCellEventArgs eventArgs)
{
// If grdDataGrid.Columns(ColIndex).DataFormat.Format = "#,##0.00" Then
// grdDataGrid.Columns(ColIndex).DataFormat = 0
// End If
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.HtmlParser.Parser;
using OpenLiveWriter.Interop.Windows;
namespace OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl
{
internal partial class TreeCategorySelector : UserControl, ICategorySelector
{
private readonly CategoryContext _ctx;
private string _lastQuery = "";
private bool _initMode;
internal class DoubleClicklessTreeView : TreeView
{
public DoubleClicklessTreeView()
{
SetStyle(ControlStyles.DoubleBuffer, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM.LBUTTONDBLCLK)
{
m.Msg = (int)WM.LBUTTONDOWN;
}
base.WndProc(ref m);
}
}
public TreeCategorySelector()
{
Debug.Assert(DesignMode);
InitializeComponent();
}
public TreeCategorySelector(CategoryContext ctx)
{
_ctx = ctx;
InitializeComponent();
// TODO: Whoops, missed UI Freeze... add this later
//treeView.AccessibleName = Res.Get(StringId.CategorySelector);
// On Windows XP, checkboxes and images seem to be mutually exclusive. Vista works fine though.
if (Environment.OSVersion.Version.Major >= 6)
{
imageList.Images.Add(new Bitmap(imageList.ImageSize.Width, imageList.ImageSize.Height));
treeView.ImageList = imageList;
treeView.ImageIndex = 0;
}
LoadCategories();
treeView.BeforeCollapse += delegate (object sender, TreeViewCancelEventArgs e) { e.Cancel = true; };
treeView.AfterCheck += treeView1_AfterCheck;
treeView.ItemHeight = (int) DisplayHelper.ScaleY(treeView.ItemHeight);
treeView.LostFocus += delegate { treeView.Invalidate(); };
}
private delegate void Walker(TreeNode n);
void WalkNodes(TreeNodeCollection nodes, Walker walker)
{
foreach (TreeNode n in nodes)
{
walker(n);
WalkNodes(n.Nodes, walker);
}
}
public override Size GetPreferredSize(Size proposedSize)
{
int width = 0;
int height = 0;
WalkNodes(treeView.Nodes, delegate (TreeNode n)
{
width = Math.Max(width, n.Bounds.Right);
height = Math.Max(height, n.Bounds.Bottom);
});
width += Padding.Left + Padding.Right;
height += Padding.Top + Padding.Bottom;
return new Size(width, height);
}
void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (_initMode)
return;
List<BlogPostCategory> categories = new List<BlogPostCategory>(_ctx.SelectedCategories);
TreeNode realTreeNode = (TreeNode)e.Node.Tag;
realTreeNode.Checked = e.Node.Checked;
BlogPostCategory category = (BlogPostCategory)(realTreeNode.Tag);
if (e.Node.Checked)
{
// Fix bug 587012: Category control can display one category repeatedly if
// checked category is added from search box after refresh
categories.Remove(category);
categories.Add(category);
}
else
categories.Remove(category);
_ctx.SelectedCategories = categories.ToArray();
}
public static TreeNode[] CategoriesToNodes(BlogPostCategory[] categories)
{
Array.Sort(categories);
Dictionary<string, TreeNode> catToNode = new Dictionary<string, TreeNode>();
TreeNode[] allNodes = new TreeNode[categories.Length];
for (int i = 0; i < categories.Length; i++)
{
// TODO: This will need to be rewritten to deal with the fact that
// ID doesn't work effectively in the face of hierarchy and new categories
allNodes[i] = new TreeNode(HtmlUtils.UnEscapeEntities(categories[i].Name, HtmlUtils.UnEscapeMode.Default));
allNodes[i].Tag = categories[i];
// TODO:
// This is necessary due to bug in categories, where multiple
// new categories with the same name (but different parents)
// have the same ID. When that bug is fixed this check should be
// replaced with an assertion.
if (!catToNode.ContainsKey(categories[i].Id))
catToNode.Add(categories[i].Id, allNodes[i]);
}
for (int i = 0; i < allNodes.Length; i++)
{
TreeNode node = allNodes[i];
string parent = ((BlogPostCategory)node.Tag).Parent;
if (!string.IsNullOrEmpty(parent) && catToNode.ContainsKey(parent))
{
catToNode[parent].Nodes.Add(node);
allNodes[i] = null;
}
}
return (TreeNode[])ArrayHelper.Compact(allNodes);
}
private TreeNode[] RealNodes { get; set; } = new TreeNode[0];
private static TreeNode[] FilteredNodes(IEnumerable nodes, Predicate<TreeNode> predicate)
{
List<TreeNode> results = null;
foreach (TreeNode node in nodes)
{
TreeNode[] filteredChildNodes = FilteredNodes(node.Nodes, predicate);
if (filteredChildNodes.Length > 0 || predicate(node))
{
if (results == null)
results = new List<TreeNode>();
TreeNode newNode = new TreeNode(node.Text, filteredChildNodes);
newNode.Tag = node;
newNode.Checked = node.Checked;
results.Add(newNode);
}
}
if (results == null)
return new TreeNode[0];
return results.ToArray();
}
private TreeNode FindFirstMatch(TreeNodeCollection nodes, Predicate<TreeNode> predicate)
{
foreach (TreeNode node in nodes)
{
if (predicate(node))
return node;
TreeNode child = FindFirstMatch(node.Nodes, predicate);
if (child != null)
return child;
}
return null;
}
private TreeNode SelectLastNode(TreeNodeCollection nodes)
{
if (nodes.Count == 0)
return null;
TreeNode lastNode = nodes[nodes.Count - 1];
return SelectLastNode(lastNode.Nodes) ?? lastNode;
}
private bool KeepNodes(ICollection nodes, Predicate<TreeNode> predicate)
{
bool keptAny = false;
// The ArrayList wrapper is to prevent changing the enumerator while
// still enumerating, which causes bugs
foreach (TreeNode node in new ArrayList(nodes))
{
if (KeepNodes(node.Nodes, predicate) || predicate(node))
keptAny = true;
else
node.Remove();
}
return keptAny;
}
public void LoadCategories()
{
_initMode = true;
try
{
RealNodes = CategoriesToNodes(_ctx.Categories);
treeView.Nodes.Clear();
treeView.Nodes.AddRange(FilteredNodes(RealNodes, delegate { return true; }));
HashSet selectedCategories = new HashSet();
selectedCategories.AddAll(_ctx.SelectedCategories);
if (selectedCategories.Count > 0)
WalkNodes(treeView.Nodes, delegate (TreeNode n)
{
n.Checked = selectedCategories.Contains(((TreeNode)n.Tag).Tag as BlogPostCategory);
});
treeView.ExpandAll();
}
finally
{
_initMode = false;
}
}
public void Filter(string criteria)
{
treeView.BeginUpdate();
try
{
Predicate<TreeNode> prefixPredicate = delegate (TreeNode node)
{
return node.Text.ToLower(CultureInfo.CurrentCulture).IndexOf(criteria, StringComparison.CurrentCultureIgnoreCase) >= 0;
};
if (criteria.Length > 0 && criteria.StartsWith(_lastQuery))
{
KeepNodes(treeView.Nodes, prefixPredicate);
}
else
{
treeView.Nodes.Clear();
if (criteria.Length == 0)
treeView.Nodes.AddRange(FilteredNodes(RealNodes, delegate { return true; }));
else
{
treeView.Nodes.AddRange(FilteredNodes(RealNodes, prefixPredicate));
}
}
treeView.ExpandAll();
if (treeView.Nodes.Count > 0)
treeView.Nodes[0].EnsureVisible();
Predicate<TreeNode> equalityPredicate = delegate (TreeNode n) { return n.Text.ToLower(CultureInfo.CurrentCulture) == criteria; };
if (treeView.SelectedNode == null || !equalityPredicate(treeView.SelectedNode))
{
TreeNode firstMatch = FindFirstMatch(treeView.Nodes, equalityPredicate);
if (firstMatch != null)
treeView.SelectedNode = firstMatch;
else if (treeView.SelectedNode == null || !prefixPredicate(treeView.SelectedNode))
{
firstMatch = FindFirstMatch(treeView.Nodes, prefixPredicate);
if (firstMatch != null)
treeView.SelectedNode = firstMatch;
}
}
}
finally
{
treeView.EndUpdate();
}
_lastQuery = criteria;
}
public void SelectCategory(BlogPostCategory category)
{
WalkNodes(treeView.Nodes, delegate (TreeNode n)
{
if (category.Equals(((TreeNode)n.Tag).Tag))
{
if (!n.Checked)
n.Checked = true;
treeView.SelectedNode = n;
n.EnsureVisible();
}
});
}
public void UpArrow()
{
TreeNode selectedNode = treeView.SelectedNode;
if (selectedNode == null)
{
if (treeView.Nodes.Count > 0)
{
treeView.SelectedNode = SelectLastNode(treeView.Nodes);
}
}
else
{
TreeNode nextNode = selectedNode.PrevVisibleNode;
if (nextNode != null)
treeView.SelectedNode = nextNode;
}
treeView.SelectedNode?.EnsureVisible();
treeView.Focus();
}
public void DownArrow()
{
TreeNode selectedNode = treeView.SelectedNode;
if (selectedNode == null)
{
if (treeView.Nodes.Count > 0)
{
treeView.SelectedNode = treeView.Nodes[0];
}
}
else
{
TreeNode nextNode = selectedNode.NextVisibleNode;
if (nextNode != null)
treeView.SelectedNode = nextNode;
}
treeView.SelectedNode?.EnsureVisible();
treeView.Focus();
}
void ICategorySelector.Enter()
{
if (treeView.SelectedNode != null)
treeView.SelectedNode.Checked = !treeView.SelectedNode.Checked;
}
void ICategorySelector.CtrlEnter()
{
if (treeView.SelectedNode != null && !treeView.SelectedNode.Checked)
treeView.SelectedNode.Checked = true;
FindForm().Close();
}
}
}
| |
using Aspose.Email.Live.Demos.UI.Config;
using Aspose.Email.Live.Demos.UI.FileProcessing;
using Aspose.Email.Live.Demos.UI.Helpers;
using Aspose.Email.Live.Demos.UI.Models;
using Aspose.Email.Live.Demos.UI.Services;
using Aspose.Email.Live.Demos.UI.Services.Email;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Aspose.Email.Live.Demos.UI.Controllers
{
public abstract class AsposeEmailBaseApiController : ApiControllerBase
{
public ILogger Logger { get; }
public IEmailService EmailService { get; }
public IStorageService StorageService { get; }
public IConfiguration Configuration { get; }
protected AsposeEmailBaseApiController(ILogger logger,
IConfiguration config,
IStorageService storageService,
IEmailService emailService)
{
Logger = logger;
Configuration = config;
StorageService = storageService;
EmailService = emailService;
}
private static readonly FormOptions _defaultFormOptions = new FormOptions();
/// <summary>
/// Prepare upload files and return as folder and names
/// </summary>
public async Task<IDictionary<string, byte[]>> UploadFiles()
{
try
{
if (this.Request.Content.Headers.ContentType == null || !MultipartRequestHelper.IsMultipartContentType(this.Request.Content.Headers.ContentType.MediaType))
throw new BadRequestException();
var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(this.Request.Content.Headers.ContentType.ToString()), _defaultFormOptions.MultipartBoundaryLengthLimit);
var files = new Dictionary<string, byte[]>();
using (var stream = await Request.Content.ReadAsStreamAsync())
{
var reader = new MultipartReader(boundary, stream);
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
if (hasContentDispositionHeader)
{
// This check assumes that there's a file
// present without form data. If form data
// is present, this method immediately fails
// and returns the model error.
if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition) && !MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
{
// ignore section
//ModelState.AddModelError("File", $"The request couldn't be processed (Error 2).");
//throw new BadRequestException();
}
else
{
// Don't trust the file name sent by the client. To display
// the file name, HTML-encode the value.
var trustedFileNameForDisplay = WebUtility.HtmlEncode(contentDisposition.FileName.Value ?? contentDisposition.Name.Value);
//var trustedFileNameForFileStorage = Path.GetRandomFileName();
// **WARNING!**
// In the following example, the file is saved without
// scanning the file's contents. In most production
// scenarios, an anti-virus/anti-malware scanner API
// is used on the file before making the file available
// for download or for use by other systems.
// For more information, see the topic that accompanies
// this sample.
var streamedFileContent = await FileHelpers.ProcessStreamedFile(section, ModelState, AppConstants.MaxFileSize);
if (!ModelState.IsValid)
throw new BadRequestException();
var initialName = trustedFileNameForDisplay;
var name = Path.GetFileNameWithoutExtension(initialName);
var ext = Path.GetExtension(initialName);
var counter = 1;
while (files.ContainsKey(trustedFileNameForDisplay))
{
if (string.IsNullOrEmpty(ext))
trustedFileNameForDisplay = $"{name} ({++counter})";
else
trustedFileNameForDisplay = $"{name} ({++counter}).{ext}";
}
files[trustedFileNameForDisplay] = streamedFileContent;
}
}
// Drain any remaining section body that hasn't been consumed and
// read the headers for the next section.
section = await reader.ReadNextSectionAsync();
}
}
return files;
}
catch (Exception ex)
{
Logger.LogEmailError(ex, "UploadFiles");
throw new BadRequestException("Error while uploading the files", ex);
}
}
protected Task<Response> Process(string appName, string folder, string fileName, Action<IEmailService, IOutputHandler, IDictionary<string, byte[]>> process)
{
return GetFromStorageAndHandle(appName, folder, fileName, (IDictionary<string, byte[]> files) =>
{
var processor = new CustomSingleOrZipFileProcessor(StorageService, Configuration, Logger)
{
ProductName = AsposeEmail + appName,
CustomFilesProcessMethod = (IDictionary<string, byte[]> files, IOutputHandler handler) =>
{
process(EmailService, handler, files);
}
};
return processor.Process(files);
},
(ex, files) => new Response() { StatusCode = 400, Status = ex.Message },
(ex, files) => new Response() { StatusCode = 500, Status = "Error on processing: " + ex.Message }.WithTrace(Configuration, ex));
}
protected Task<Response> Process(string appName, Action<IEmailService, IOutputHandler, IDictionary<string, byte[]>> process)
{
return UploadAndHandle(appName, (IDictionary<string, byte[]> files) =>
{
var processor = new CustomSingleOrZipFileProcessor(StorageService, Configuration, Logger)
{
ProductName = AsposeEmail + appName,
CustomFilesProcessMethod = (IDictionary<string, byte[]> files, IOutputHandler handler) =>
{
process(EmailService, handler, files);
}
};
return processor.Process(files);
},
(ex, files) => new Response() { StatusCode = 400, Status = ex.Message },
(ex, files) => new Response() { StatusCode = 500, Status = "Error on processing: " + ex.Message }.WithTrace(Configuration, ex));
}
protected async Task<T> GetFromStorageAndHandle<T>(string appName, string folder, string fileName,
Func<IDictionary<string, byte[]>, Task<T>> process,
Func<BadRequestException, IDictionary<string, byte[]>, T> badRequestHandler,
Func<Exception, IDictionary<string, byte[]>, T> exceptionHandler)
{
IDictionary<string, byte[]> uploaded = null;
try
{
using (var input = await StorageService.ReadFile(folder, fileName))
{
uploaded = new Dictionary<string, byte[]>()
{
{ fileName, input.ToArray() }
};
}
if (uploaded.IsNullOrEmpty())
throw new BadRequestException("No files provided");
if (uploaded.Count > 10)
throw new BadRequestException("Maximum 10 files allowed");
return await process(uploaded);
}
catch (BadRequestException ex)
{
return badRequestHandler(ex, uploaded);
}
catch (Exception ex)
{
Logger.LogEmailError(ex, appName);
return exceptionHandler(ex, uploaded);
}
}
protected async Task<T> UploadAndHandle<T>(string appName,
Func<IDictionary<string, byte[]>, T> process,
Func<BadRequestException, IDictionary<string, byte[]>, T> badRequestHandler,
Func<Exception, IDictionary<string, byte[]>, T> exceptionHandler)
{
IDictionary<string, byte[]> uploaded = null;
try
{
uploaded = await UploadFiles();
if (uploaded.IsNullOrEmpty())
throw new BadRequestException("No files provided");
if (uploaded.Count > 10)
throw new BadRequestException("Maximum 10 files allowed");
return process(uploaded);
}
catch (BadRequestException ex)
{
return badRequestHandler(ex, uploaded);
}
catch (Exception ex)
{
Logger.LogEmailError(ex, appName);
return exceptionHandler(ex, uploaded);
}
}
protected async Task<T> UploadAndHandle<T>(string appName,
Func<IDictionary<string, byte[]>, Task<T>> process,
Func<BadRequestException, IDictionary<string, byte[]>, T> badRequestHandler,
Func<Exception, IDictionary<string, byte[]>, T> exceptionHandler)
{
IDictionary<string, byte[]> uploaded = null;
try
{
uploaded = await UploadFiles();
return await process(uploaded);
}
catch (BadRequestException ex)
{
return badRequestHandler(ex, uploaded);
}
/*catch (FormatNotSupportedException ex)
{
return badRequestHandler(ex, uploaded.folderName, uploaded.fileNames);
}
catch (NotSupportedException ex)
{
return badRequestHandler(ex, uploaded.folderName, uploaded.fileNames);
}*/
catch (Exception ex)
{
Logger.LogEmailError(ex, appName);
return exceptionHandler(ex, uploaded);
}
}
protected byte[] ReadAndRemoveAsBytes(IDictionary<string, byte[]> files, string ending)
{
var keyFile = files.FirstOrDefault(x => x.Key.EndsWith(ending));
if (keyFile.Value != null)
{
files.Remove(keyFile.Key);
return keyFile.Value;
}
return null;
}
protected string ReadAndRemoveAsText(IDictionary<string, byte[]> files, string ending)
{
var keyFile = files.FirstOrDefault(x => x.Key.EndsWith(ending));
if (keyFile.Value != null)
{
files.Remove(keyFile.Key);
return Encoding.UTF8.GetString(keyFile.Value);
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Music.Web.Areas.HelpPage.ModelDescriptions;
using Music.Web.Areas.HelpPage.Models;
namespace Music.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Platform.VirtualFileSystem.Providers
{
public abstract class DirectoryDelegationWrapper
: NodeDelegationWrapper, IDirectory
{
public virtual event NodeActivityEventHandler RecursiveActivity
{
add
{
lock (this)
{
if (RecursiveActivityEvent == null)
{
this.Wrappee.Renamed += new NodeActivityEventHandler(DelegateRecursiveActivityEvent);
}
RecursiveActivityEvent = (NodeActivityEventHandler)Delegate.Combine(RecursiveActivityEvent, value);
}
}
remove
{
lock (this)
{
RecursiveActivityEvent = (NodeActivityEventHandler)Delegate.Remove(RecursiveActivityEvent, value);
if (RecursiveActivityEvent == null)
{
this.Wrappee.Renamed -= new NodeActivityEventHandler(DelegateRecursiveActivityEvent);
}
}
}
}
private NodeActivityEventHandler RecursiveActivityEvent;
private void DelegateRecursiveActivityEvent(object sender, NodeActivityEventArgs eventArgs)
{
OnRecursiveActivityEvent(eventArgs);
}
protected void OnRecursiveActivityEvent(NodeActivityEventArgs eventArgs)
{
lock (this)
{
if (RecursiveActivityEvent != null)
{
RecursiveActivityEvent(this, eventArgs);
}
}
}
public virtual event NodeActivityEventHandler DirectoryActivity
{
add
{
lock (this)
{
if (DirectoryActivityEvent == null)
{
this.Wrappee.Renamed += new NodeActivityEventHandler(DelegateDirectoryActivityEvent);
}
DirectoryActivityEvent = (NodeActivityEventHandler)Delegate.Combine(DirectoryActivityEvent, value);
}
}
remove
{
lock (this)
{
DirectoryActivityEvent = (NodeActivityEventHandler)Delegate.Remove(DirectoryActivityEvent, value);
if (DirectoryActivityEvent == null)
{
this.Wrappee.Renamed -= new NodeActivityEventHandler(DelegateDirectoryActivityEvent);
}
}
}
}
private NodeActivityEventHandler DirectoryActivityEvent;
private void DelegateDirectoryActivityEvent(object sender, NodeActivityEventArgs eventArgs)
{
OnDirectoryActivityEvent(eventArgs);
}
protected void OnDirectoryActivityEvent(NodeActivityEventArgs eventArgs)
{
lock (this)
{
if (DirectoryActivityEvent != null)
{
DirectoryActivityEvent(this, eventArgs);
}
}
}
public virtual event JumpPointEventHandler JumpPointAdded
{
add
{
lock (this)
{
if (JumpPointAddedEvent == null)
{
this.Wrappee.JumpPointAdded += DelegateJumpPointAddedEvent;
}
JumpPointAddedEvent = (JumpPointEventHandler)Delegate.Combine(JumpPointAddedEvent, value);
}
}
remove
{
lock (this)
{
JumpPointAddedEvent = (JumpPointEventHandler)Delegate.Remove(JumpPointAddedEvent, value);
if (JumpPointAddedEvent == null)
{
this.Wrappee.JumpPointAdded -= DelegateJumpPointAddedEvent;
}
}
}
}
private JumpPointEventHandler JumpPointAddedEvent;
private void DelegateJumpPointAddedEvent(object sender, JumpPointEventArgs eventArgs)
{
OnJumpPointAddedEvent(eventArgs);
}
protected void OnJumpPointAddedEvent(JumpPointEventArgs eventArgs)
{
lock (this)
{
if (JumpPointAddedEvent != null)
{
JumpPointAddedEvent(this, eventArgs);
}
}
}
public virtual event JumpPointEventHandler JumpPointRemoved
{
add
{
lock (this)
{
if (JumpPointRemovedEvent == null)
{
this.Wrappee.JumpPointRemoved += DelegateJumpPointRemovedEvent;
}
JumpPointRemovedEvent = (JumpPointEventHandler)Delegate.Combine(JumpPointRemovedEvent, value);
}
}
remove
{
lock (this)
{
JumpPointRemovedEvent = (JumpPointEventHandler)Delegate.Remove(JumpPointRemovedEvent, value);
if (JumpPointRemovedEvent == null)
{
this.Wrappee.JumpPointRemoved -= DelegateJumpPointRemovedEvent;
}
}
}
}
private JumpPointEventHandler JumpPointRemovedEvent;
private void DelegateJumpPointRemovedEvent(object sender, JumpPointEventArgs eventArgs)
{
OnJumpPointRemovedEvent(eventArgs);
}
protected void OnJumpPointRemovedEvent(JumpPointEventArgs eventArgs)
{
lock (this)
{
if (JumpPointRemovedEvent != null)
{
JumpPointRemovedEvent(this, eventArgs);
}
}
}
protected DirectoryDelegationWrapper(IDirectory innerDirectory)
: base(innerDirectory)
{
}
protected DirectoryDelegationWrapper(IDirectory innerDirectory, INodeResolver resolver, Converter<INode, INode> nodeAdapter)
: base(innerDirectory, resolver, nodeAdapter)
{
}
public virtual IEnumerable<INode> Walk()
{
if (this.NodeAdapter == ConverterUtils<INode, INode>.NoConvert)
{
return this.Wrappee.Walk();
}
else
{
return AdaptedWalk();
}
}
private IEnumerable<INode> AdaptedWalk()
{
foreach (var node in this.Wrappee.Walk())
{
yield return NodeAdapter(node);
}
}
IDirectory IDirectory.Refresh()
{
return (IDirectory)this.Refresh();
}
public virtual IEnumerable<INode> Walk(NodeType nodeType)
{
if (NodeAdapter == ConverterUtils<INode, INode>.NoConvert)
{
return this.Wrappee.Walk(nodeType);
}
else
{
return AdaptedWalk(nodeType);
}
}
private IEnumerable<INode> AdaptedWalk(NodeType nodeType)
{
foreach (var node in this.Wrappee.Walk(nodeType))
{
yield return NodeAdapter(node);
}
}
public new virtual IDirectory Wrappee
{
get
{
return (IDirectory)base.Wrappee;
}
}
public virtual IEnumerable<IFile> GetFiles()
{
return GetFiles(PredicateUtils<IFile>.AlwaysTrue);
}
public virtual IEnumerable<IFile> GetFiles(Predicate<IFile> acceptFile)
{
foreach (INode node in this.GetChildren(NodeType.File, PredicateUtils<INode>.AlwaysTrue))
{
var file = (IFile)node;
var adaptedFile = (IFile)this.NodeAdapter(file);
if (acceptFile(adaptedFile))
{
yield return adaptedFile;
}
}
}
public virtual IEnumerable<IDirectory> GetDirectories()
{
return GetDirectories(PredicateUtils<IDirectory>.AlwaysTrue);
}
public virtual IEnumerable<IDirectory> GetDirectories(Predicate<IDirectory> acceptDirectory)
{
foreach (var node in this.GetChildren(NodeType.Directory, PredicateUtils<INode>.AlwaysTrue))
{
var dir = (IDirectory)node;
var adaptedDir = (IDirectory)NodeAdapter(dir);
if (acceptDirectory(adaptedDir))
{
yield return adaptedDir;
}
}
}
public virtual bool ChildExists(string name)
{
var node = this.Wrappee.Resolve(name);
node.Refresh();
node.CheckAccess(FileSystemSecuredOperation.View);
return node.Exists;
}
public virtual IEnumerable<string> GetChildNames()
{
return GetChildNames(NodeType.Any);
}
public virtual IEnumerable<string> GetChildNames(NodeType nodeType)
{
return GetChildNames(nodeType, PredicateUtils<string>.AlwaysTrue);
}
public virtual IEnumerable<string> GetChildNames(Predicate<string> acceptName)
{
return GetChildNames(NodeType.Any, acceptName);
}
public virtual IEnumerable<string> GetChildNames(NodeType nodeType, Predicate<string> acceptName)
{
return this.Wrappee.GetChildNames(nodeType, acceptName);
}
public virtual IEnumerable<INode> GetChildren()
{
return GetChildren(NodeType.Any);
}
public virtual IEnumerable<INode> GetChildren(NodeType nodeType)
{
return GetChildren(nodeType, PredicateUtils<INode>.AlwaysTrue);
}
public virtual IEnumerable<INode> GetChildren(Predicate<INode> acceptNode)
{
return GetChildren(NodeType.Any, acceptNode);
}
public virtual IEnumerable<INode> GetChildren(NodeType nodeType, Predicate<INode> acceptNode)
{
foreach (var node in this.Wrappee.GetChildren(nodeType))
{
var adaptedNode = NodeAdapter(node);
if (acceptNode(adaptedNode))
{
yield return adaptedNode;
}
}
}
public override INode Refresh()
{
Refresh(DirectoryRefreshMask.All);
return this;
}
public virtual IDirectory Refresh(DirectoryRefreshMask mask)
{
this.Wrappee.Refresh(mask);
return this;
}
public virtual IDirectory Delete(bool recursive)
{
this.Wrappee.Delete(recursive);
return this;
}
IDirectory IDirectory.Create()
{
return this.Wrappee.Create();
}
IDirectory IDirectory.Create(bool createParent)
{
return this.Wrappee.Create(createParent);
}
public virtual IFileSystem CreateView()
{
return CreateView(this.Address.Scheme);
}
public virtual IFileSystem CreateView(string scheme, FileSystemOptions options)
{
return this.Wrappee.CreateView(scheme, options);
}
public IFileSystem CreateView(string scheme)
{
return CreateView(scheme, FileSystemOptions.Default);
}
public IFileSystem CreateView(FileSystemOptions options)
{
return CreateView(this.Address.Scheme, options);
}
public virtual INode AddJumpPoint(INode node)
{
return this.Wrappee.AddJumpPoint(node);
}
public virtual INode AddJumpPoint(string name, INode node)
{
return this.Wrappee.AddJumpPoint(name, node);
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal {
public partial class ServersEditService {
/// <summary>
/// asyncTasks control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks;
/// <summary>
/// ServerHeaderControl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ServerHeaderControl ServerHeaderControl;
/// <summary>
/// lblGroup control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblGroup;
/// <summary>
/// litGroup control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litGroup;
/// <summary>
/// lblProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblProvider;
/// <summary>
/// litProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litProvider;
/// <summary>
/// lblName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblName;
/// <summary>
/// txtServiceName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtServiceName;
/// <summary>
/// vldServiceNameRequired control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator vldServiceNameRequired;
/// <summary>
/// lblComments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblComments;
/// <summary>
/// txtComments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtComments;
/// <summary>
/// rowInstallResults control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow rowInstallResults;
/// <summary>
/// lblServiceInstallationResults control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblServiceInstallationResults;
/// <summary>
/// blInstallResults control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.BulletedList blInstallResults;
/// <summary>
/// SettingsHeader control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel SettingsHeader;
/// <summary>
/// SettingsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel SettingsPanel;
/// <summary>
/// serviceProps control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder serviceProps;
/// <summary>
/// DnsRecrodsHeader control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel DnsRecrodsHeader;
/// <summary>
/// DnsRecrodsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel DnsRecrodsPanel;
/// <summary>
/// GlobalDnsRecordsControl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.GlobalDnsRecordsControl GlobalDnsRecordsControl;
/// <summary>
/// pnlQuota control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlQuota;
/// <summary>
/// tblQuota control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTable tblQuota;
/// <summary>
/// lblQuotaName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblQuotaName;
/// <summary>
/// txtQuotaValue control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtQuotaValue;
/// <summary>
/// tblCluster control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTable tblCluster;
/// <summary>
/// lblClusters control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblClusters;
/// <summary>
/// ddlClusters control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlClusters;
/// <summary>
/// valCluster control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator valCluster;
/// <summary>
/// cmdDeleteCluster control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdDeleteCluster;
/// <summary>
/// lblNewCluster control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblNewCluster;
/// <summary>
/// txtClusterName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtClusterName;
/// <summary>
/// valNewCluster control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator valNewCluster;
/// <summary>
/// cmdAddCluster control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdAddCluster;
/// <summary>
/// btnUpdate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnUpdate;
/// <summary>
/// btnCancel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancel;
/// <summary>
/// btnDelete control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnDelete;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Win32.SafeHandles
{
[System.Security.SecurityCriticalAttribute]
public sealed partial class SafeFileHandle : System.Runtime.InteropServices.SafeHandle
{
public SafeFileHandle(System.IntPtr preexistingHandle, bool ownsHandle) : base(default(System.IntPtr), default(bool)) { }
[System.Security.SecurityCriticalAttribute]
protected override bool ReleaseHandle() { return default(bool); }
}
}
namespace System.IO
{
public static partial class Directory
{
public static System.IO.DirectoryInfo CreateDirectory(string path) { return default(System.IO.DirectoryInfo); }
public static void Delete(string path) { }
public static void Delete(string path, bool recursive) { }
public static System.Collections.Generic.IEnumerable<string> EnumerateDirectories(string path) { return default(System.Collections.Generic.IEnumerable<string>); }
public static System.Collections.Generic.IEnumerable<string> EnumerateDirectories(string path, string searchPattern) { return default(System.Collections.Generic.IEnumerable<string>); }
public static System.Collections.Generic.IEnumerable<string> EnumerateDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { return default(System.Collections.Generic.IEnumerable<string>); }
public static System.Collections.Generic.IEnumerable<string> EnumerateFiles(string path) { return default(System.Collections.Generic.IEnumerable<string>); }
public static System.Collections.Generic.IEnumerable<string> EnumerateFiles(string path, string searchPattern) { return default(System.Collections.Generic.IEnumerable<string>); }
public static System.Collections.Generic.IEnumerable<string> EnumerateFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { return default(System.Collections.Generic.IEnumerable<string>); }
public static System.Collections.Generic.IEnumerable<string> EnumerateFileSystemEntries(string path) { return default(System.Collections.Generic.IEnumerable<string>); }
public static System.Collections.Generic.IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern) { return default(System.Collections.Generic.IEnumerable<string>); }
public static System.Collections.Generic.IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { return default(System.Collections.Generic.IEnumerable<string>); }
public static bool Exists(string path) { return default(bool); }
public static System.DateTime GetCreationTime(string path) { return default(System.DateTime); }
public static System.DateTime GetCreationTimeUtc(string path) { return default(System.DateTime); }
public static string GetCurrentDirectory() { return default(string); }
public static string[] GetDirectories(string path) { return default(string[]); }
public static string[] GetDirectories(string path, string searchPattern) { return default(string[]); }
public static string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { return default(string[]); }
public static string GetDirectoryRoot(string path) { return default(string); }
public static string[] GetFiles(string path) { return default(string[]); }
public static string[] GetFiles(string path, string searchPattern) { return default(string[]); }
public static string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { return default(string[]); }
public static string[] GetFileSystemEntries(string path) { return default(string[]); }
public static string[] GetFileSystemEntries(string path, string searchPattern) { return default(string[]); }
public static string[] GetFileSystemEntries(string path, string searchPattern, System.IO.SearchOption searchOption) { return default(string[]); }
public static System.DateTime GetLastAccessTime(string path) { return default(System.DateTime); }
public static System.DateTime GetLastAccessTimeUtc(string path) { return default(System.DateTime); }
public static System.DateTime GetLastWriteTime(string path) { return default(System.DateTime); }
public static System.DateTime GetLastWriteTimeUtc(string path) { return default(System.DateTime); }
public static System.IO.DirectoryInfo GetParent(string path) { return default(System.IO.DirectoryInfo); }
public static void Move(string sourceDirName, string destDirName) { }
public static void SetCreationTime(string path, System.DateTime creationTime) { }
public static void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { }
public static void SetCurrentDirectory(string path) { }
public static void SetLastAccessTime(string path, System.DateTime lastAccessTime) { }
public static void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { }
public static void SetLastWriteTime(string path, System.DateTime lastWriteTime) { }
public static void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { }
}
public sealed partial class DirectoryInfo : System.IO.FileSystemInfo
{
public DirectoryInfo(string path) { }
public override bool Exists { get { return default(bool); } }
public override string Name { get { return default(string); } }
public System.IO.DirectoryInfo Parent { get { return default(System.IO.DirectoryInfo); } }
public System.IO.DirectoryInfo Root { get { return default(System.IO.DirectoryInfo); } }
public void Create() { }
public System.IO.DirectoryInfo CreateSubdirectory(string path) { return default(System.IO.DirectoryInfo); }
public override void Delete() { }
public void Delete(bool recursive) { }
public System.Collections.Generic.IEnumerable<System.IO.DirectoryInfo> EnumerateDirectories() { return default(System.Collections.Generic.IEnumerable<System.IO.DirectoryInfo>); }
public System.Collections.Generic.IEnumerable<System.IO.DirectoryInfo> EnumerateDirectories(string searchPattern) { return default(System.Collections.Generic.IEnumerable<System.IO.DirectoryInfo>); }
public System.Collections.Generic.IEnumerable<System.IO.DirectoryInfo> EnumerateDirectories(string searchPattern, System.IO.SearchOption searchOption) { return default(System.Collections.Generic.IEnumerable<System.IO.DirectoryInfo>); }
public System.Collections.Generic.IEnumerable<System.IO.FileInfo> EnumerateFiles() { return default(System.Collections.Generic.IEnumerable<System.IO.FileInfo>); }
public System.Collections.Generic.IEnumerable<System.IO.FileInfo> EnumerateFiles(string searchPattern) { return default(System.Collections.Generic.IEnumerable<System.IO.FileInfo>); }
public System.Collections.Generic.IEnumerable<System.IO.FileInfo> EnumerateFiles(string searchPattern, System.IO.SearchOption searchOption) { return default(System.Collections.Generic.IEnumerable<System.IO.FileInfo>); }
public System.Collections.Generic.IEnumerable<System.IO.FileSystemInfo> EnumerateFileSystemInfos() { return default(System.Collections.Generic.IEnumerable<System.IO.FileSystemInfo>); }
public System.Collections.Generic.IEnumerable<System.IO.FileSystemInfo> EnumerateFileSystemInfos(string searchPattern) { return default(System.Collections.Generic.IEnumerable<System.IO.FileSystemInfo>); }
public System.Collections.Generic.IEnumerable<System.IO.FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { return default(System.Collections.Generic.IEnumerable<System.IO.FileSystemInfo>); }
public System.IO.DirectoryInfo[] GetDirectories() { return default(System.IO.DirectoryInfo[]); }
public System.IO.DirectoryInfo[] GetDirectories(string searchPattern) { return default(System.IO.DirectoryInfo[]); }
public System.IO.DirectoryInfo[] GetDirectories(string searchPattern, System.IO.SearchOption searchOption) { return default(System.IO.DirectoryInfo[]); }
public System.IO.FileInfo[] GetFiles() { return default(System.IO.FileInfo[]); }
public System.IO.FileInfo[] GetFiles(string searchPattern) { return default(System.IO.FileInfo[]); }
public System.IO.FileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { return default(System.IO.FileInfo[]); }
public System.IO.FileSystemInfo[] GetFileSystemInfos() { return default(System.IO.FileSystemInfo[]); }
public System.IO.FileSystemInfo[] GetFileSystemInfos(string searchPattern) { return default(System.IO.FileSystemInfo[]); }
public System.IO.FileSystemInfo[] GetFileSystemInfos(string searchPattern, System.IO.SearchOption searchOption) { return default(System.IO.FileSystemInfo[]); }
public void MoveTo(string destDirName) { }
public override string ToString() { return default(string); }
}
public static partial class File
{
public static void AppendAllLines(string path, System.Collections.Generic.IEnumerable<string> contents) { }
public static void AppendAllLines(string path, System.Collections.Generic.IEnumerable<string> contents, System.Text.Encoding encoding) { }
public static void AppendAllText(string path, string contents) { }
public static void AppendAllText(string path, string contents, System.Text.Encoding encoding) { }
public static System.IO.StreamWriter AppendText(string path) { return default(System.IO.StreamWriter); }
public static void Copy(string sourceFileName, string destFileName) { }
public static void Copy(string sourceFileName, string destFileName, bool overwrite) { }
public static System.IO.FileStream Create(string path) { return default(System.IO.FileStream); }
public static System.IO.FileStream Create(string path, int bufferSize) { return default(System.IO.FileStream); }
public static System.IO.FileStream Create(string path, int bufferSize, System.IO.FileOptions options) { return default(System.IO.FileStream); }
public static System.IO.StreamWriter CreateText(string path) { return default(System.IO.StreamWriter); }
public static void Delete(string path) { }
public static bool Exists(string path) { return default(bool); }
public static System.IO.FileAttributes GetAttributes(string path) { return default(System.IO.FileAttributes); }
public static System.DateTime GetCreationTime(string path) { return default(System.DateTime); }
public static System.DateTime GetCreationTimeUtc(string path) { return default(System.DateTime); }
public static System.DateTime GetLastAccessTime(string path) { return default(System.DateTime); }
public static System.DateTime GetLastAccessTimeUtc(string path) { return default(System.DateTime); }
public static System.DateTime GetLastWriteTime(string path) { return default(System.DateTime); }
public static System.DateTime GetLastWriteTimeUtc(string path) { return default(System.DateTime); }
public static void Move(string sourceFileName, string destFileName) { }
public static System.IO.FileStream Open(string path, System.IO.FileMode mode) { return default(System.IO.FileStream); }
public static System.IO.FileStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access) { return default(System.IO.FileStream); }
public static System.IO.FileStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { return default(System.IO.FileStream); }
public static System.IO.FileStream OpenRead(string path) { return default(System.IO.FileStream); }
public static System.IO.StreamReader OpenText(string path) { return default(System.IO.StreamReader); }
public static System.IO.FileStream OpenWrite(string path) { return default(System.IO.FileStream); }
public static byte[] ReadAllBytes(string path) { return default(byte[]); }
public static string[] ReadAllLines(string path) { return default(string[]); }
public static string[] ReadAllLines(string path, System.Text.Encoding encoding) { return default(string[]); }
public static string ReadAllText(string path) { return default(string); }
public static string ReadAllText(string path, System.Text.Encoding encoding) { return default(string); }
public static System.Collections.Generic.IEnumerable<string> ReadLines(string path) { return default(System.Collections.Generic.IEnumerable<string>); }
public static System.Collections.Generic.IEnumerable<string> ReadLines(string path, System.Text.Encoding encoding) { return default(System.Collections.Generic.IEnumerable<string>); }
public static void SetAttributes(string path, System.IO.FileAttributes fileAttributes) { }
public static void SetCreationTime(string path, System.DateTime creationTime) { }
public static void SetCreationTimeUtc(string path, System.DateTime creationTimeUtc) { }
public static void SetLastAccessTime(string path, System.DateTime lastAccessTime) { }
public static void SetLastAccessTimeUtc(string path, System.DateTime lastAccessTimeUtc) { }
public static void SetLastWriteTime(string path, System.DateTime lastWriteTime) { }
public static void SetLastWriteTimeUtc(string path, System.DateTime lastWriteTimeUtc) { }
public static void WriteAllBytes(string path, byte[] bytes) { }
public static void WriteAllLines(string path, System.Collections.Generic.IEnumerable<string> contents) { }
public static void WriteAllLines(string path, System.Collections.Generic.IEnumerable<string> contents, System.Text.Encoding encoding) { }
public static void WriteAllText(string path, string contents) { }
public static void WriteAllText(string path, string contents, System.Text.Encoding encoding) { }
}
public sealed partial class FileInfo : System.IO.FileSystemInfo
{
public FileInfo(string fileName) { }
public System.IO.DirectoryInfo Directory { get { return default(System.IO.DirectoryInfo); } }
public string DirectoryName { get { return default(string); } }
public override bool Exists { get { return default(bool); } }
public bool IsReadOnly { get { return default(bool); } set { } }
public long Length { get { return default(long); } }
public override string Name { get { return default(string); } }
public System.IO.StreamWriter AppendText() { return default(System.IO.StreamWriter); }
public System.IO.FileInfo CopyTo(string destFileName) { return default(System.IO.FileInfo); }
public System.IO.FileInfo CopyTo(string destFileName, bool overwrite) { return default(System.IO.FileInfo); }
public System.IO.FileStream Create() { return default(System.IO.FileStream); }
public System.IO.StreamWriter CreateText() { return default(System.IO.StreamWriter); }
public override void Delete() { }
public void MoveTo(string destFileName) { }
public System.IO.FileStream Open(System.IO.FileMode mode) { return default(System.IO.FileStream); }
public System.IO.FileStream Open(System.IO.FileMode mode, System.IO.FileAccess access) { return default(System.IO.FileStream); }
public System.IO.FileStream Open(System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { return default(System.IO.FileStream); }
public System.IO.FileStream OpenRead() { return default(System.IO.FileStream); }
public System.IO.StreamReader OpenText() { return default(System.IO.StreamReader); }
public System.IO.FileStream OpenWrite() { return default(System.IO.FileStream); }
public override string ToString() { return default(string); }
}
[System.FlagsAttribute]
public enum FileOptions
{
Asynchronous = 1073741824,
DeleteOnClose = 67108864,
Encrypted = 16384,
None = 0,
RandomAccess = 268435456,
SequentialScan = 134217728,
WriteThrough = -2147483648,
}
public partial class FileStream : System.IO.Stream
{
public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access) { }
public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize) { }
public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync) { }
public FileStream(string path, System.IO.FileMode mode) { }
public FileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access) { }
public FileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { }
public FileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize) { }
public FileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, bool useAsync) { }
public FileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options) { }
public override bool CanRead { get { return default(bool); } }
public override bool CanSeek { get { return default(bool); } }
public override bool CanWrite { get { return default(bool); } }
public virtual bool IsAsync { get { return default(bool); } }
public override long Length { get { return default(long); } }
public string Name { get { return default(string); } }
public override long Position { get { return default(long); } set { } }
public virtual Microsoft.Win32.SafeHandles.SafeFileHandle SafeFileHandle { get { return default(Microsoft.Win32.SafeHandles.SafeFileHandle); } }
protected override void Dispose(bool disposing) { }
~FileStream() { }
public override void Flush() { }
public virtual void Flush(bool flushToDisk) { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
public override int Read(byte[] array, int offset, int count) { array = default(byte[]); return default(int); }
public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); }
public override int ReadByte() { return default(int); }
public override long Seek(long offset, System.IO.SeekOrigin origin) { return default(long); }
public override void SetLength(long value) { }
public override void Write(byte[] array, int offset, int count) { }
public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
public override void WriteByte(byte value) { }
}
public abstract partial class FileSystemInfo
{
protected string FullPath;
protected string OriginalPath;
protected FileSystemInfo() { }
public System.IO.FileAttributes Attributes { get { return default(System.IO.FileAttributes); } set { } }
public System.DateTime CreationTime { get { return default(System.DateTime); } set { } }
public System.DateTime CreationTimeUtc { get { return default(System.DateTime); } set { } }
public abstract bool Exists { get; }
public string Extension { get { return default(string); } }
public virtual string FullName { get { return default(string); } }
public System.DateTime LastAccessTime { get { return default(System.DateTime); } set { } }
public System.DateTime LastAccessTimeUtc { get { return default(System.DateTime); } set { } }
public System.DateTime LastWriteTime { get { return default(System.DateTime); } set { } }
public System.DateTime LastWriteTimeUtc { get { return default(System.DateTime); } set { } }
public abstract string Name { get; }
public abstract void Delete();
public void Refresh() { }
}
public enum SearchOption
{
AllDirectories = 1,
TopDirectoryOnly = 0,
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
/// <devdoc>
/// Listens to the system directory change notifications and
/// raises events when a directory or file within a directory changes.
/// </devdoc>
public partial class FileSystemWatcher : Component, ISupportInitialize
{
/// <devdoc>
/// Private instance variables
/// </devdoc>
// Directory being monitored
private string _directory;
// Filter for name matching
private string _filter;
// The watch filter for the API call.
private const NotifyFilters c_defaultNotifyFilters = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
private NotifyFilters _notifyFilters = c_defaultNotifyFilters;
// Flag to watch subtree of this directory
private bool _includeSubdirectories = false;
// Flag to note whether we are attached to the thread pool and responding to changes
private bool _enabled = false;
// Are we in init?
private bool _initializing = false;
// Buffer size
private int _internalBufferSize = 8192;
// Used for synchronization
private bool _disposed;
private ISynchronizeInvoke _synchronizingObject;
// Event handlers
private FileSystemEventHandler _onChangedHandler = null;
private FileSystemEventHandler _onCreatedHandler = null;
private FileSystemEventHandler _onDeletedHandler = null;
private RenamedEventHandler _onRenamedHandler = null;
private ErrorEventHandler _onErrorHandler = null;
// To validate the input for "path"
private static readonly char[] s_wildcards = new char[] { '?', '*' };
private const int c_notifyFiltersValidMask = (int)(NotifyFilters.Attributes |
NotifyFilters.CreationTime |
NotifyFilters.DirectoryName |
NotifyFilters.FileName |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Security |
NotifyFilters.Size);
#if DEBUG
static FileSystemWatcher()
{
int s_notifyFiltersValidMask = 0;
foreach (int enumValue in Enum.GetValues(typeof(NotifyFilters)))
s_notifyFiltersValidMask |= enumValue;
Debug.Assert(c_notifyFiltersValidMask == s_notifyFiltersValidMask, "The NotifyFilters enum has changed. The c_notifyFiltersValidMask must be updated to reflect the values of the NotifyFilters enum.");
}
#endif
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class.
/// </devdoc>
public FileSystemWatcher()
{
_directory = string.Empty;
_filter = "*.*";
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class,
/// given the specified directory to monitor.
/// </devdoc>
public FileSystemWatcher(string path) : this(path, "*.*")
{
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class,
/// given the specified directory and type of files to monitor.
/// </devdoc>
public FileSystemWatcher(string path, string filter)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (filter == null)
throw new ArgumentNullException(nameof(filter));
// Early check for directory parameter so that an exception can be thrown as early as possible.
if (path.Length == 0)
throw new ArgumentException(SR.Format(SR.InvalidDirName, path), nameof(path));
if (!Directory.Exists(path))
throw new ArgumentException(SR.Format(SR.InvalidDirName_NotExists, path), nameof(path));
_directory = path;
_filter = filter;
}
/// <devdoc>
/// Gets or sets the type of changes to watch for.
/// </devdoc>
public NotifyFilters NotifyFilter
{
get
{
return _notifyFilters;
}
set
{
if (((int)value & ~c_notifyFiltersValidMask) != 0)
throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, nameof(value), (int)value, nameof(NotifyFilters)));
if (_notifyFilters != value)
{
_notifyFilters = value;
Restart();
}
}
}
/// <devdoc>
/// Gets or sets a value indicating whether the component is enabled.
/// </devdoc>
public bool EnableRaisingEvents
{
get
{
return _enabled;
}
set
{
if (_enabled == value)
{
return;
}
if (IsSuspended())
{
_enabled = value; // Alert the Component to start watching for events when EndInit is called.
}
else
{
if (value)
{
StartRaisingEventsIfNotDisposed(); // will set _enabled to true once successfully started
}
else
{
StopRaisingEvents(); // will set _enabled to false
}
}
}
}
/// <devdoc>
/// Gets or sets the filter string, used to determine what files are monitored in a directory.
/// </devdoc>
public string Filter
{
get
{
return _filter;
}
set
{
if (string.IsNullOrEmpty(value))
{
// Skip the string compare for "*.*" since it has no case-insensitive representation that differs from
// the case-sensitive representation.
_filter = "*.*";
}
else if (!string.Equals(_filter, value, PathInternal.StringComparison))
{
_filter = value;
}
}
}
/// <devdoc>
/// Gets or sets a value indicating whether subdirectories within the specified path should be monitored.
/// </devdoc>
public bool IncludeSubdirectories
{
get
{
return _includeSubdirectories;
}
set
{
if (_includeSubdirectories != value)
{
_includeSubdirectories = value;
Restart();
}
}
}
/// <devdoc>
/// Gets or sets the size of the internal buffer.
/// </devdoc>
public int InternalBufferSize
{
get
{
return _internalBufferSize;
}
set
{
if (_internalBufferSize != value)
{
if (value < 4096)
{
_internalBufferSize = 4096;
}
else
{
_internalBufferSize = value;
}
Restart();
}
}
}
/// <summary>Allocates a buffer of the requested internal buffer size.</summary>
/// <returns>The allocated buffer.</returns>
private byte[] AllocateBuffer()
{
try
{
return new byte[_internalBufferSize];
}
catch (OutOfMemoryException)
{
throw new OutOfMemoryException(SR.Format(SR.BufferSizeTooLarge, _internalBufferSize));
}
}
/// <devdoc>
/// Gets or sets the path of the directory to watch.
/// </devdoc>
public string Path
{
get
{
return _directory;
}
set
{
value = (value == null) ? string.Empty : value;
if (!string.Equals(_directory, value, PathInternal.StringComparison))
{
if (value.Length == 0)
throw new ArgumentException(SR.Format(SR.InvalidDirName, value), nameof(Path));
if (!Directory.Exists(value))
throw new ArgumentException(SR.Format(SR.InvalidDirName_NotExists, value), nameof(Path));
_directory = value;
Restart();
}
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is changed.
/// </devdoc>
public event FileSystemEventHandler Changed
{
add
{
_onChangedHandler += value;
}
remove
{
_onChangedHandler -= value;
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is created.
/// </devdoc>
public event FileSystemEventHandler Created
{
add
{
_onCreatedHandler += value;
}
remove
{
_onCreatedHandler -= value;
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is deleted.
/// </devdoc>
public event FileSystemEventHandler Deleted
{
add
{
_onDeletedHandler += value;
}
remove
{
_onDeletedHandler -= value;
}
}
/// <devdoc>
/// Occurs when the internal buffer overflows.
/// </devdoc>
public event ErrorEventHandler Error
{
add
{
_onErrorHandler += value;
}
remove
{
_onErrorHandler -= value;
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/>
/// is renamed.
/// </devdoc>
public event RenamedEventHandler Renamed
{
add
{
_onRenamedHandler += value;
}
remove
{
_onRenamedHandler -= value;
}
}
/// <devdoc>
/// </devdoc>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
//Stop raising events cleans up managed and
//unmanaged resources.
StopRaisingEvents();
// Clean up managed resources
_onChangedHandler = null;
_onCreatedHandler = null;
_onDeletedHandler = null;
_onRenamedHandler = null;
_onErrorHandler = null;
}
else
{
FinalizeDispose();
}
}
finally
{
_disposed = true;
base.Dispose(disposing);
}
}
/// <devdoc>
/// Sees if the name given matches the name filter we have.
/// </devdoc>
/// <internalonly/>
private bool MatchPattern(string relativePath)
{
string name = System.IO.Path.GetFileName(relativePath);
return name != null ?
PatternMatcher.StrictMatchPattern(_filter, name) :
false;
}
/// <devdoc>
/// Raises the event to each handler in the list.
/// </devdoc>
/// <internalonly/>
private void NotifyInternalBufferOverflowEvent()
{
_onErrorHandler?.Invoke(this, new ErrorEventArgs(
new InternalBufferOverflowException(SR.Format(SR.FSW_BufferOverflow, _directory))));
}
/// <devdoc>
/// Raises the event to each handler in the list.
/// </devdoc>
/// <internalonly/>
private void NotifyRenameEventArgs(WatcherChangeTypes action, string name, string oldName)
{
// filter if there's no handler or neither new name or old name match a specified pattern
RenamedEventHandler handler = _onRenamedHandler;
if (handler != null &&
(MatchPattern(name) || MatchPattern(oldName)))
{
handler(this, new RenamedEventArgs(action, _directory, name, oldName));
}
}
/// <devdoc>
/// Raises the event to each handler in the list.
/// </devdoc>
/// <internalonly/>
private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, string name)
{
FileSystemEventHandler handler = null;
switch (changeType)
{
case WatcherChangeTypes.Created:
handler = _onCreatedHandler;
break;
case WatcherChangeTypes.Deleted:
handler = _onDeletedHandler;
break;
case WatcherChangeTypes.Changed:
handler = _onChangedHandler;
break;
default:
Debug.Fail("Unknown FileSystemEvent change type! Value: " + changeType);
break;
}
if (handler != null && MatchPattern(string.IsNullOrEmpty(name) ? _directory : name))
{
handler(this, new FileSystemEventArgs(changeType, _directory, name));
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Changed'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnChanged(FileSystemEventArgs e)
{
InvokeOn(e, _onChangedHandler);
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Created'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnCreated(FileSystemEventArgs e)
{
InvokeOn(e, _onCreatedHandler);
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Deleted'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnDeleted(FileSystemEventArgs e)
{
InvokeOn(e, _onDeletedHandler);
}
private void InvokeOn(FileSystemEventArgs e, FileSystemEventHandler handler)
{
if (handler != null)
{
ISynchronizeInvoke syncObj = SynchronizingObject;
if (syncObj != null && syncObj.InvokeRequired)
syncObj.BeginInvoke(handler, new object[] { this, e });
else
handler(this, e);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Error'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnError(ErrorEventArgs e)
{
ErrorEventHandler handler = _onErrorHandler;
if (handler != null)
{
ISynchronizeInvoke syncObj = SynchronizingObject;
if (syncObj != null && syncObj.InvokeRequired)
syncObj.BeginInvoke(handler, new object[] { this, e });
else
handler(this, e);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Renamed'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnRenamed(RenamedEventArgs e)
{
RenamedEventHandler handler = _onRenamedHandler;
if (handler != null)
{
ISynchronizeInvoke syncObj = SynchronizingObject;
if (syncObj != null && syncObj.InvokeRequired)
syncObj.BeginInvoke(handler, new object[] { this, e });
else
handler(this, e);
}
}
public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) =>
WaitForChanged(changeType, Timeout.Infinite);
public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout)
{
// The full framework implementation doesn't do any argument validation, so
// none is done here, either.
var tcs = new TaskCompletionSource<WaitForChangedResult>();
FileSystemEventHandler fseh = null;
RenamedEventHandler reh = null;
// Register the event handlers based on what events are desired. The full framework
// doesn't register for the Error event, so this doesn't either.
if ((changeType & (WatcherChangeTypes.Created | WatcherChangeTypes.Deleted | WatcherChangeTypes.Changed)) != 0)
{
fseh = (s, e) =>
{
if ((e.ChangeType & changeType) != 0)
{
tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, oldName: null, timedOut: false));
}
};
if ((changeType & WatcherChangeTypes.Created) != 0) Created += fseh;
if ((changeType & WatcherChangeTypes.Deleted) != 0) Deleted += fseh;
if ((changeType & WatcherChangeTypes.Changed) != 0) Changed += fseh;
}
if ((changeType & WatcherChangeTypes.Renamed) != 0)
{
reh = (s, e) =>
{
if ((e.ChangeType & changeType) != 0)
{
tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, e.OldName, timedOut: false));
}
};
Renamed += reh;
}
try
{
// Enable the FSW if it wasn't already.
bool wasEnabled = EnableRaisingEvents;
if (!wasEnabled)
{
EnableRaisingEvents = true;
}
// Block until an appropriate event arrives or until we timeout.
Debug.Assert(EnableRaisingEvents, "Expected EnableRaisingEvents to be true");
tcs.Task.Wait(timeout);
// Reset the enabled state to what it was.
EnableRaisingEvents = wasEnabled;
}
finally
{
// Unregister the event handlers.
if (reh != null)
{
Renamed -= reh;
}
if (fseh != null)
{
if ((changeType & WatcherChangeTypes.Changed) != 0) Changed -= fseh;
if ((changeType & WatcherChangeTypes.Deleted) != 0) Deleted -= fseh;
if ((changeType & WatcherChangeTypes.Created) != 0) Created -= fseh;
}
}
// Return the results.
return tcs.Task.IsCompletedSuccessfully ?
tcs.Task.Result :
WaitForChangedResult.TimedOutResult;
}
/// <devdoc>
/// Stops and starts this object.
/// </devdoc>
/// <internalonly/>
private void Restart()
{
if ((!IsSuspended()) && _enabled)
{
StopRaisingEvents();
StartRaisingEventsIfNotDisposed();
}
}
private void StartRaisingEventsIfNotDisposed()
{
//Cannot allocate the directoryHandle and the readBuffer if the object has been disposed; finalization has been suppressed.
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
StartRaisingEvents();
}
public override ISite Site
{
get
{
return base.Site;
}
set
{
base.Site = value;
// set EnableRaisingEvents to true at design time so the user
// doesn't have to manually.
if (Site != null && Site.DesignMode)
EnableRaisingEvents = true;
}
}
public ISynchronizeInvoke SynchronizingObject
{
get
{
return _synchronizingObject;
}
set
{
_synchronizingObject = value;
}
}
public void BeginInit()
{
bool oldEnabled = _enabled;
StopRaisingEvents();
_enabled = oldEnabled;
_initializing = true;
}
public void EndInit()
{
_initializing = false;
// Start listening to events if _enabled was set to true at some point.
if (_directory.Length != 0 && _enabled)
StartRaisingEvents();
}
private bool IsSuspended()
{
return _initializing || DesignMode;
}
}
}
| |
/*
Gaigen 2.5 Test Suite
*/
/*
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
using System;
namespace c3ga_ns {
/// <summary>This class can hold a specialized multivector of type bivector.
///
/// The coordinates are stored in type double.
///
/// The variable non-zero coordinates are:
/// - coordinate e1^e2 (array index: E1_E2 = 0)
/// - coordinate e2^e3 (array index: E2_E3 = 1)
/// - coordinate -1*e1^e3 (array index: E3_E1 = 2)
///
/// The type has no constant coordinates.
///
///
/// </summary>
public class bivector : mv_if
{
/// <summary>The e1^e2 coordinate.
/// </summary>
protected internal double m_e1_e2;
/// <summary>The e2^e3 coordinate.
/// </summary>
protected internal double m_e2_e3;
/// <summary>The -1*e1^e3 coordinate.
/// </summary>
protected internal double m_e3_e1;
/// <summary>Array indices of bivector coordinates.
/// </summary>
/// <summary>index of coordinate for e1^e2 in bivector
/// </summary>
public const int E1_E2 = 0;
/// <summary>index of coordinate for e2^e3 in bivector
/// </summary>
public const int E2_E3 = 1;
/// <summary>index of coordinate for -1*e1^e3 in bivector
/// </summary>
public const int E3_E1 = 2;
/// <summary>The order of coordinates (this is the type of the first argument of coordinate-handling functions.
/// </summary>
public enum CoordinateOrder {
coord_e1e2_e2e3_e3e1
};
public const CoordinateOrder coord_e1e2_e2e3_e3e1 = CoordinateOrder.coord_e1e2_e2e3_e3e1;
/// <summary>
/// Converts this multivector to a 'mv' (implementation of interface 'mv_interface')
/// </summary>
public mv to_mv()
{
return new mv(this);
}
/// <summary>
/// Constructs a new bivector with variable coordinates set to 0.
/// </summary>
public bivector() {Set();}
/// <summary>
/// Copy constructor.
/// </summary>
public bivector(bivector A) {Set(A);}
/// <summary>
/// Constructs a new bivector from mv.
/// </summary>
/// <param name="A">The value to copy. Coordinates that cannot be represented are silently dropped. </param>
public bivector(mv A /*, int filler */) {Set(A);}
/// <summary>
/// Constructs a new bivector. Coordinate values come from 'A'.
/// </summary>
public bivector(CoordinateOrder co, double[] A) {Set(co, A);}
/// <summary>
/// Constructs a new bivector with each coordinate specified.
/// </summary>
public bivector(CoordinateOrder co, double e1_e2, double e2_e3, double e3_e1) {
Set(co, e1_e2, e2_e3, e3_e1);
}
public void Set()
{
m_e1_e2 = m_e2_e3 = m_e3_e1 = 0.0;
}
public void Set(double scalarVal)
{
m_e1_e2 = m_e2_e3 = m_e3_e1 = 0.0;
}
public void Set(CoordinateOrder co, double _e1_e2, double _e2_e3, double _e3_e1)
{
m_e1_e2 = _e1_e2;
m_e2_e3 = _e2_e3;
m_e3_e1 = _e3_e1;
}
public void Set(CoordinateOrder co, double[] A)
{
m_e1_e2 = A[0];
m_e2_e3 = A[1];
m_e3_e1 = A[2];
}
public void Set(bivector a)
{
m_e1_e2 = a.m_e1_e2;
m_e2_e3 = a.m_e2_e3;
m_e3_e1 = a.m_e3_e1;
}
public void Set(mv src) {
if (src.c()[2] != null) {
double[] ptr = src.c()[2];
m_e1_e2 = ptr[0];
m_e2_e3 = ptr[2];
m_e3_e1 = -ptr[1];
}
else {
m_e1_e2 = 0.0;
m_e2_e3 = 0.0;
m_e3_e1 = 0.0;
}
}
/// <summary>Returns the absolute largest coordinate.
/// </summary>
public double LargestCoordinate() {
double maxValue = Math.Abs(m_e1_e2);
if (Math.Abs(m_e2_e3) > maxValue) { maxValue = Math.Abs(m_e2_e3); }
if (Math.Abs(m_e3_e1) > maxValue) { maxValue = Math.Abs(m_e3_e1); }
return maxValue;
}
/// <summary>Returns the absolute largest coordinate,
/// and the corresponding basis blade bitmap.
/// </summary>
public double LargestBasisBlade(int bm) {
double maxValue = Math.Abs(m_e1_e2);
bm = 0;
if (Math.Abs(m_e2_e3) > maxValue) { maxValue = Math.Abs(m_e2_e3); bm = 6; }
if (Math.Abs(m_e3_e1) > maxValue) { maxValue = Math.Abs(m_e3_e1); bm = 5; }
return maxValue;
}
/// <summary>
/// Returns this multivector, converted to a string.
/// The floating point formatter is controlled via c3ga.setStringFormat().
/// </summary>
public override string ToString() {
return c3ga.String(this);
}
/// <summary>
/// Returns this multivector, converted to a string.
/// The floating point formatter is "F".
/// </summary>
public string ToString_f() {
return ToString("F");
}
/// <summary>
/// Returns this multivector, converted to a string.
/// The floating point formatter is "E".
/// </summary>
public string ToString_e() {
return ToString("E");
}
/// <summary>
/// Returns this multivector, converted to a string.
/// The floating point formatter is "E20".
/// </summary>
public string ToString_e20() {
return ToString("E20");
}
/// <summary>
/// Returns this multivector, converted to a string.
/// <param name="fp">floating point format. Use 'null' for the default format (see setStringFormat()).</param>
/// </summary>
public string ToString(string fp) {
return c3ga.String(this, fp);
}
/// <summary>Returns the e1^e2 coordinate.
/// </summary>
public double get_e1_e2() { return m_e1_e2;}
/// <summary>Sets the e1^e2 coordinate.
/// </summary>
public void set_e1_e2(double e1_e2) { m_e1_e2 = e1_e2;}
/// <summary>Returns the e2^e3 coordinate.
/// </summary>
public double get_e2_e3() { return m_e2_e3;}
/// <summary>Sets the e2^e3 coordinate.
/// </summary>
public void set_e2_e3(double e2_e3) { m_e2_e3 = e2_e3;}
/// <summary>Returns the -1*e1^e3 coordinate.
/// </summary>
public double get_e3_e1() { return m_e3_e1;}
/// <summary>Sets the -1*e1^e3 coordinate.
/// </summary>
public void set_e3_e1(double e3_e1) { m_e3_e1 = e3_e1;}
/// <summary>Returns the scalar coordinate (which is always 0).
/// </summary>
public double get_scalar() { return 0.0;}
} // end of class bivector
} // end of namespace c3ga_ns
| |
namespace MoleculeMOTHardwareControl
{
partial class ControlWindow
{
/// <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 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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ControlWindow));
this.label3 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.printDialog1 = new System.Windows.Forms.PrintDialog();
this.tabControl = new System.Windows.Forms.TabControl();
this.splitPanel = new System.Windows.Forms.SplitContainer();
this.tableLayoutPanel8 = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel9 = new System.Windows.Forms.TableLayoutPanel();
this.messageBoxCollapseExpandButton = new System.Windows.Forms.Button();
this.label8 = new System.Windows.Forms.Label();
this.messageNumberPanel = new System.Windows.Forms.Panel();
this.messageNumber = new System.Windows.Forms.TextBox();
this.messageBox = new System.Windows.Forms.RichTextBox();
((System.ComponentModel.ISupportInitialize)(this.splitPanel)).BeginInit();
this.splitPanel.Panel1.SuspendLayout();
this.splitPanel.Panel2.SuspendLayout();
this.splitPanel.SuspendLayout();
this.tableLayoutPanel8.SuspendLayout();
this.tableLayoutPanel9.SuspendLayout();
this.messageNumberPanel.SuspendLayout();
this.SuspendLayout();
//
// label3
//
this.label3.Location = new System.Drawing.Point(0, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(100, 23);
this.label3.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(0, 0);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
//
// printDialog1
//
this.printDialog1.UseEXDialog = true;
//
// tabControl
//
this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl.Location = new System.Drawing.Point(3, 3);
this.tabControl.Multiline = true;
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
this.tabControl.Size = new System.Drawing.Size(689, 836);
this.tabControl.TabIndex = 0;
//
// splitPanel
//
this.splitPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitPanel.Location = new System.Drawing.Point(0, 0);
this.splitPanel.Name = "splitPanel";
this.splitPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitPanel.Panel1
//
this.splitPanel.Panel1.Controls.Add(this.tableLayoutPanel8);
//
// splitPanel.Panel2
//
this.splitPanel.Panel2.Controls.Add(this.messageBox);
this.splitPanel.Panel2Collapsed = true;
this.splitPanel.Size = new System.Drawing.Size(695, 882);
this.splitPanel.SplitterDistance = 724;
this.splitPanel.TabIndex = 1;
//
// tableLayoutPanel8
//
this.tableLayoutPanel8.ColumnCount = 1;
this.tableLayoutPanel8.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel8.Controls.Add(this.tabControl, 0, 0);
this.tableLayoutPanel8.Controls.Add(this.tableLayoutPanel9, 0, 1);
this.tableLayoutPanel8.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel8.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel8.Name = "tableLayoutPanel8";
this.tableLayoutPanel8.RowCount = 2;
this.tableLayoutPanel8.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel8.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 40F));
this.tableLayoutPanel8.Size = new System.Drawing.Size(695, 882);
this.tableLayoutPanel8.TabIndex = 1;
//
// tableLayoutPanel9
//
this.tableLayoutPanel9.BackColor = System.Drawing.SystemColors.ControlDark;
this.tableLayoutPanel9.ColumnCount = 3;
this.tableLayoutPanel9.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 4.848485F));
this.tableLayoutPanel9.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 95.15151F));
this.tableLayoutPanel9.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 42F));
this.tableLayoutPanel9.Controls.Add(this.messageBoxCollapseExpandButton, 2, 0);
this.tableLayoutPanel9.Controls.Add(this.label8, 1, 0);
this.tableLayoutPanel9.Controls.Add(this.messageNumberPanel, 0, 0);
this.tableLayoutPanel9.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel9.Location = new System.Drawing.Point(3, 845);
this.tableLayoutPanel9.Name = "tableLayoutPanel9";
this.tableLayoutPanel9.RowCount = 1;
this.tableLayoutPanel9.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel9.Size = new System.Drawing.Size(689, 34);
this.tableLayoutPanel9.TabIndex = 1;
//
// messageBoxCollapseExpandButton
//
this.messageBoxCollapseExpandButton.Anchor = System.Windows.Forms.AnchorStyles.None;
this.messageBoxCollapseExpandButton.BackColor = System.Drawing.Color.Transparent;
this.messageBoxCollapseExpandButton.Location = new System.Drawing.Point(656, 5);
this.messageBoxCollapseExpandButton.Name = "messageBoxCollapseExpandButton";
this.messageBoxCollapseExpandButton.Size = new System.Drawing.Size(23, 23);
this.messageBoxCollapseExpandButton.TabIndex = 0;
this.messageBoxCollapseExpandButton.Text = "+";
this.messageBoxCollapseExpandButton.UseVisualStyleBackColor = false;
this.messageBoxCollapseExpandButton.Click += new System.EventHandler(this.ToggleMessageBox);
//
// label8
//
this.label8.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(41, 10);
this.label8.Margin = new System.Windows.Forms.Padding(10, 0, 3, 0);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(55, 13);
this.label8.TabIndex = 2;
this.label8.Text = "Messages";
//
// messageNumberPanel
//
this.messageNumberPanel.BackColor = System.Drawing.Color.Black;
this.messageNumberPanel.Controls.Add(this.messageNumber);
this.messageNumberPanel.Location = new System.Drawing.Point(3, 3);
this.messageNumberPanel.Name = "messageNumberPanel";
this.messageNumberPanel.Size = new System.Drawing.Size(25, 28);
this.messageNumberPanel.TabIndex = 3;
//
// messageNumber
//
this.messageNumber.BackColor = System.Drawing.SystemColors.InfoText;
this.messageNumber.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.messageNumber.ForeColor = System.Drawing.Color.White;
this.messageNumber.Location = new System.Drawing.Point(3, 7);
this.messageNumber.Margin = new System.Windows.Forms.Padding(3, 3, 3, 6);
this.messageNumber.Name = "messageNumber";
this.messageNumber.Size = new System.Drawing.Size(20, 13);
this.messageNumber.TabIndex = 3;
this.messageNumber.Text = "0";
this.messageNumber.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// messageBox
//
this.messageBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.messageBox.Location = new System.Drawing.Point(0, 0);
this.messageBox.Name = "messageBox";
this.messageBox.Size = new System.Drawing.Size(150, 46);
this.messageBox.TabIndex = 0;
this.messageBox.Text = "";
//
// ControlWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(695, 882);
this.Controls.Add(this.splitPanel);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "ControlWindow";
this.Text = "Molecule MOT Hardware Controller";
this.splitPanel.Panel1.ResumeLayout(false);
this.splitPanel.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitPanel)).EndInit();
this.splitPanel.ResumeLayout(false);
this.tableLayoutPanel8.ResumeLayout(false);
this.tableLayoutPanel9.ResumeLayout(false);
this.tableLayoutPanel9.PerformLayout();
this.messageNumberPanel.ResumeLayout(false);
this.messageNumberPanel.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.PrintDialog printDialog1;
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.SplitContainer splitPanel;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel8;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel9;
private System.Windows.Forms.Button messageBoxCollapseExpandButton;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Panel messageNumberPanel;
private System.Windows.Forms.TextBox messageNumber;
private System.Windows.Forms.RichTextBox messageBox;
}
}
| |
/*
Copyright (c) 2010-2015 by Genstein and Jason Lautzenheiser.
This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper.
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.Drawing;
namespace Trizbort
{
public struct Vector
{
public Vector(float scalar)
{
X = scalar;
Y = scalar;
}
public Vector(float x, float y)
{
X = x;
Y = y;
}
public Vector(PointF point)
{
X = point.X;
Y = point.Y;
}
public Vector(SizeF size)
{
X = size.Width;
Y = size.Height;
}
public static Vector operator -(Vector a, Vector b)
{
return new Vector(a.X - b.X, a.Y - b.Y);
}
public static Vector operator -(Vector v, float scalar)
{
return new Vector(v.X - scalar, v.Y - scalar);
}
public static Vector operator +(Vector a, Vector b)
{
return new Vector(a.X + b.X, a.Y + b.Y);
}
public static Vector operator +(Vector v, float scalar)
{
return new Vector(v.X + scalar, v.Y + scalar);
}
public static Vector operator *(Vector v, float scalar)
{
return new Vector(v.X * scalar, v.Y * scalar);
}
public static Vector operator *(float scalar, Vector v)
{
return new Vector(v.X * scalar, v.Y * scalar);
}
public static Vector operator /(Vector v, float scalar)
{
return new Vector(v.X / scalar, v.Y / scalar);
}
public static bool operator ==(Vector a, Vector b)
{
return a.X == b.X && a.Y == b.Y;
}
public static bool operator !=(Vector a, Vector b)
{
return a.X != b.X || a.Y != b.Y;
}
public override bool Equals(object obj)
{
if (!(obj is Vector))
return false;
Vector other = (Vector)obj;
return this == other;
}
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode();
}
public PointF ToPointF()
{
return new PointF(X, Y);
}
public Point ToPoint()
{
return new Point((int)X, (int)Y);
}
public SizeF ToSizeF()
{
return new SizeF(X, Y);
}
public Size ToSize()
{
return new Size((int)X, (int)Y);
}
public float Dot(Vector other)
{
return Dot(this, other);
}
public static float Dot(Vector a, Vector b)
{
return a.X * b.X + a.Y * b.Y;
}
public float LengthSquared
{
get { return X * X + Y * Y; }
}
public float Length
{
get
{
return (float)Math.Sqrt(LengthSquared);
}
}
public Vector Abs()
{
return new Vector(Math.Abs(X), Math.Abs(Y));
}
public static float Distance(Vector a, Vector b)
{
return Math.Abs((b - a).Length);
}
public float Distance(Vector other)
{
return Distance(this, other);
}
public static Vector Normalize(Vector v)
{
Vector n = v;
n.Normalize();
return n;
}
public void Normalize()
{
var length = Length;
if (length == 0)
{
// avoid division by zero (NaN)
X = 0;
Y = 0;
}
else
{
X /= length;
Y /= length;
}
}
public void Negate()
{
X = -X;
Y = -Y;
}
public static float DistanceFromLineSegment(LineSegment line, Vector pos)
{
var delta = line.End - line.Start;
var direction = Vector.Normalize(delta);
float distanceAlongSegment = Vector.Dot(pos, direction) - Vector.Dot(line.Start, direction);
Vector nearest;
if (distanceAlongSegment < 0)
{
nearest = line.Start;
}
else if (distanceAlongSegment > delta.Length)
{
nearest = line.End;
}
else
{
nearest = line.Start + distanceAlongSegment * direction;
}
return Vector.Distance(nearest, pos);
}
public static float DistanceFromRect(Rect rect, Vector pos)
{
if (rect.Contains(pos))
{
return 0;
}
var nw = rect.GetCorner(CompassPoint.NorthWest);
var ne = rect.GetCorner(CompassPoint.NorthEast);
var sw = rect.GetCorner(CompassPoint.SouthWest);
var se = rect.GetCorner(CompassPoint.SouthEast);
var distanceFromTop = DistanceFromLineSegment(new LineSegment(nw, ne), pos);
var distanceFromRight = DistanceFromLineSegment(new LineSegment(ne, se), pos);
var distanceFromBottom = DistanceFromLineSegment(new LineSegment(se, sw), pos);
var distanceFromLeft = DistanceFromLineSegment(new LineSegment(sw, nw), pos);
return Math.Min(distanceFromTop, Math.Min(distanceFromLeft, Math.Min(distanceFromBottom, distanceFromRight)));
}
public float DistanceFromRect(Rect rect)
{
return DistanceFromRect(rect, this);
}
public float DistanceFromLineSegment(LineSegment line)
{
return DistanceFromLineSegment(line, this);
}
public static readonly Vector Zero = new Vector();
public float X;
public float Y;
}
}
| |
// DeflaterHuffman.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using ICSharpCode.SharpZipLib.Silverlight.Zip.Compression;
namespace ICSharpCode.SharpZipLib.Silverlight.Zip.Compression
{
/// <summary>
/// This is the DeflaterHuffman class.
///
/// This class is <i>not</i> thread safe. This is inherent in the API, due
/// to the split of Deflate and SetInput.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class DeflaterHuffman
{
const int BUFSIZE = 1 << (DeflaterConstants.DEFAULT_MEM_LEVEL + 6);
const int LITERAL_NUM = 286;
// Number of distance codes
const int DIST_NUM = 30;
// Number of codes used to transfer bit lengths
const int BITLEN_NUM = 19;
// repeat previous bit length 3-6 times (2 bits of repeat count)
const int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
const int REP_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
const int REP_11_138 = 18;
const int EOF_SYMBOL = 256;
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit length codes.
static readonly int[] BL_ORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
static readonly byte[] bit4Reverse = {
0,
8,
4,
12,
2,
10,
6,
14,
1,
9,
5,
13,
3,
11,
7,
15
};
static readonly short[] staticLCodes;
static readonly byte[] staticLLength;
static readonly short[] staticDCodes;
static readonly byte[] staticDLength;
class Tree
{
#region Instance Fields
public readonly short[] freqs;
public byte[] length;
public readonly int minNumCodes;
public int numCodes;
short[] codes;
readonly int[] bl_counts;
readonly int maxLength;
readonly DeflaterHuffman dh;
#endregion
#region Constructors
public Tree(DeflaterHuffman dh, int elems, int minCodes, int maxLength)
{
this.dh = dh;
minNumCodes = minCodes;
this.maxLength = maxLength;
freqs = new short[elems];
bl_counts = new int[maxLength];
}
#endregion
/// <summary>
/// Resets the internal state of the tree
/// </summary>
public void Reset()
{
for (int i = 0; i < freqs.Length; i++) {
freqs[i] = 0;
}
codes = null;
length = null;
}
public void WriteSymbol(int code)
{
// if (DeflaterConstants.DEBUGGING) {
// freqs[code]--;
// // Console.Write("writeSymbol("+freqs.length+","+code+"): ");
// }
dh.pending.WriteBits(codes[code] & 0xffff, length[code]);
}
/// <summary>
/// Set static codes and length
/// </summary>
/// <param name="staticCodes">new codes</param>
/// <param name="staticLengths">length for new codes</param>
public void SetStaticCodes(short[] staticCodes, byte[] staticLengths)
{
codes = staticCodes;
length = staticLengths;
}
/// <summary>
/// Build dynamic codes and lengths
/// </summary>
public void BuildCodes()
{
var nextCode = new int[maxLength];
var code = 0;
codes = new short[freqs.Length];
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("buildCodes: "+freqs.Length);
// }
for (int bits = 0; bits < maxLength; bits++) {
nextCode[bits] = code;
code += bl_counts[bits] << (15 - bits);
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("bits: " + ( bits + 1) + " count: " + bl_counts[bits]
// +" nextCode: "+code);
// }
}
for (int i=0; i < numCodes; i++) {
int bits = length[i];
if (bits > 0) {
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("codes["+i+"] = rev(" + nextCode[bits-1]+"),
// +bits);
// }
codes[i] = BitReverse(nextCode[bits-1]);
nextCode[bits-1] += 1 << (16 - bits);
}
}
}
public void BuildTree()
{
int numSymbols = freqs.Length;
/* heap is a priority queue, sorted by frequency, least frequent
* nodes first. The heap is a binary tree, with the property, that
* the parent node is smaller than both child nodes. This assures
* that the smallest node is the first parent.
*
* The binary tree is encoded in an array: 0 is root node and
* the nodes 2*n+1, 2*n+2 are the child nodes of node n.
*/
var heap = new int[numSymbols];
var heapLen = 0;
var maxCode = 0;
for (var n = 0; n < numSymbols; n++) {
int freq = freqs[n];
if (freq == 0)
{
continue;
}
// Insert n into heap
var pos = heapLen++;
int ppos;
while (pos > 0 && freqs[heap[ppos = (pos - 1) / 2]] > freq) {
heap[pos] = heap[ppos];
pos = ppos;
}
heap[pos] = n;
maxCode = n;
}
/* We could encode a single literal with 0 bits but then we
* don't see the literals. Therefore we force at least two
* literals to avoid this case. We don't care about order in
* this case, both literals get a 1 bit code.
*/
while (heapLen < 2) {
int node = maxCode < 2 ? ++maxCode : 0;
heap[heapLen++] = node;
}
numCodes = Math.Max(maxCode + 1, minNumCodes);
var numLeafs = heapLen;
var childs = new int[4 * heapLen - 2];
var values = new int[2 * heapLen - 1];
var numNodes = numLeafs;
for (var i = 0; i < heapLen; i++) {
var node = heap[i];
childs[2 * i] = node;
childs[2 * i + 1] = -1;
values[i] = freqs[node] << 8;
heap[i] = i;
}
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
do {
int first = heap[0];
int last = heap[--heapLen];
// Propagate the hole to the leafs of the heap
int ppos = 0;
int path = 1;
while (path < heapLen) {
if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) {
path++;
}
heap[ppos] = heap[path];
ppos = path;
path = path * 2 + 1;
}
/* Now propagate the last element down along path. Normally
* it shouldn't go too deep.
*/
int lastVal = values[last];
while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) {
heap[path] = heap[ppos];
}
heap[path] = last;
int second = heap[0];
// Create a new node father of first and second
last = numNodes++;
childs[2 * last] = first;
childs[2 * last + 1] = second;
int mindepth = Math.Min(values[first] & 0xff, values[second] & 0xff);
values[last] = lastVal = values[first] + values[second] - mindepth + 1;
// Again, propagate the hole to the leafs
ppos = 0;
path = 1;
while (path < heapLen) {
if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) {
path++;
}
heap[ppos] = heap[path];
ppos = path;
path = ppos * 2 + 1;
}
// Now propagate the new element down along path
while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) {
heap[path] = heap[ppos];
}
heap[path] = last;
} while (heapLen > 1);
if (heap[0] != childs.Length / 2 - 1) {
throw new SharpZipBaseException("Heap invariant violated");
}
BuildLength(childs);
}
/// <summary>
/// Get encoded length
/// </summary>
/// <returns>Encoded length, the sum of frequencies * lengths</returns>
public int GetEncodedLength()
{
int len = 0;
for (int i = 0; i < freqs.Length; i++) {
len += freqs[i] * length[i];
}
return len;
}
/// <summary>
/// Scan a literal or distance tree to determine the frequencies of the codes
/// in the bit length tree.
/// </summary>
public void CalcBLFreq(Tree blTree)
{
var curlen = -1; /* length of current code */
var i = 0;
while (i < numCodes) {
var count = 1; /* repeat count of the current code */
int nextlen = length[i];
int max_count; /* max repeat count */
int min_count; /* min repeat count */
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else {
max_count = 6;
min_count = 3;
if (curlen != nextlen) {
blTree.freqs[nextlen]++;
count = 0;
}
}
curlen = nextlen;
i++;
while (i < numCodes && curlen == length[i]) {
i++;
if (++count >= max_count) {
break;
}
}
if (count < min_count) {
blTree.freqs[curlen] += (short)count;
} else if (curlen != 0) {
blTree.freqs[REP_3_6]++;
} else if (count <= 10) {
blTree.freqs[REP_3_10]++;
} else {
blTree.freqs[REP_11_138]++;
}
}
}
/// <summary>
/// Write tree values
/// </summary>
/// <param name="blTree">Tree to write</param>
public void WriteTree(Tree blTree)
{
var curlen = -1; // length of current code
var i = 0;
while (i < numCodes) {
var count = 1; // repeat count of the current code
int nextlen = length[i];
int max_count; // max repeat count
int min_count; // min repeat count
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else {
max_count = 6;
min_count = 3;
if (curlen != nextlen) {
blTree.WriteSymbol(nextlen);
count = 0;
}
}
curlen = nextlen;
i++;
while (i < numCodes && curlen == length[i]) {
i++;
if (++count >= max_count) {
break;
}
}
if (count < min_count) {
while (count-- > 0) {
blTree.WriteSymbol(curlen);
}
} else if (curlen != 0) {
blTree.WriteSymbol(REP_3_6);
dh.pending.WriteBits(count - 3, 2);
} else if (count <= 10) {
blTree.WriteSymbol(REP_3_10);
dh.pending.WriteBits(count - 3, 3);
} else {
blTree.WriteSymbol(REP_11_138);
dh.pending.WriteBits(count - 11, 7);
}
}
}
void BuildLength(int[] childs)
{
length = new byte [freqs.Length];
var numNodes = childs.Length / 2;
var numLeafs = (numNodes + 1) / 2;
var overflow = 0;
for (var i = 0; i < maxLength; i++) {
bl_counts[i] = 0;
}
// First calculate optimal bit lengths
var lengths = new int[numNodes];
lengths[numNodes-1] = 0;
for (int i = numNodes - 1; i >= 0; i--) {
if (childs[2 * i + 1] != -1) {
int bitLength = lengths[i] + 1;
if (bitLength > maxLength) {
bitLength = maxLength;
overflow++;
}
lengths[childs[2 * i]] = lengths[childs[2 * i + 1]] = bitLength;
} else {
// A leaf node
var bitLength = lengths[i];
bl_counts[bitLength - 1]++;
length[childs[2*i]] = (byte) lengths[i];
}
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Tree "+freqs.Length+" lengths:");
// for (int i=0; i < numLeafs; i++) {
// //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]]
// + " len: "+length[childs[2*i]]);
// }
// }
if (overflow == 0) {
return;
}
int incrBitLen = maxLength - 1;
do {
// Find the first bit length which could increase:
while (bl_counts[--incrBitLen] == 0)
{
}
// Move this node one down and remove a corresponding
// number of overflow nodes.
do {
bl_counts[incrBitLen]--;
bl_counts[++incrBitLen]++;
overflow -= 1 << (maxLength - 1 - incrBitLen);
} while (overflow > 0 && incrBitLen < maxLength - 1);
} while (overflow > 0);
/* We may have overshot above. Move some nodes from maxLength to
* maxLength-1 in that case.
*/
bl_counts[maxLength-1] += overflow;
bl_counts[maxLength-2] -= overflow;
/* Now recompute all bit lengths, scanning in increasing
* frequency. It is simpler to reconstruct all lengths instead of
* fixing only the wrong ones. This idea is taken from 'ar'
* written by Haruhiko Okumura.
*
* The nodes were inserted with decreasing frequency into the childs
* array.
*/
int nodePtr = 2 * numLeafs;
for (int bits = maxLength; bits != 0; bits--) {
int n = bl_counts[bits-1];
while (n > 0) {
int childPtr = 2*childs[nodePtr++];
if (childs[childPtr + 1] == -1) {
// We found another leaf
length[childs[childPtr]] = (byte) bits;
n--;
}
}
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("*** After overflow elimination. ***");
// for (int i=0; i < numLeafs; i++) {
// //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]]
// + " len: "+length[childs[2*i]]);
// }
// }
}
}
#region Instance Fields
/// <summary>
/// Pending buffer to use
/// </summary>
public DeflaterPending pending;
readonly Tree literalTree;
readonly Tree distTree;
readonly Tree blTree;
// Buffer for distances
readonly short[] d_buf;
readonly byte[] l_buf;
int last_lit;
int extra_bits;
#endregion
static DeflaterHuffman()
{
// See RFC 1951 3.2.6
// Literal codes
staticLCodes = new short[LITERAL_NUM];
staticLLength = new byte[LITERAL_NUM];
int i = 0;
while (i < 144) {
staticLCodes[i] = BitReverse((0x030 + i) << 8);
staticLLength[i++] = 8;
}
while (i < 256) {
staticLCodes[i] = BitReverse((0x190 - 144 + i) << 7);
staticLLength[i++] = 9;
}
while (i < 280) {
staticLCodes[i] = BitReverse((0x000 - 256 + i) << 9);
staticLLength[i++] = 7;
}
while (i < LITERAL_NUM) {
staticLCodes[i] = BitReverse((0x0c0 - 280 + i) << 8);
staticLLength[i++] = 8;
}
// Distance codes
staticDCodes = new short[DIST_NUM];
staticDLength = new byte[DIST_NUM];
for (i = 0; i < DIST_NUM; i++) {
staticDCodes[i] = BitReverse(i << 11);
staticDLength[i] = 5;
}
}
/// <summary>
/// Construct instance with pending buffer
/// </summary>
/// <param name="pending">Pending buffer to use</param>
public DeflaterHuffman(DeflaterPending pending)
{
this.pending = pending;
literalTree = new Tree(this, LITERAL_NUM, 257, 15);
distTree = new Tree(this, DIST_NUM, 1, 15);
blTree = new Tree(this, BITLEN_NUM, 4, 7);
d_buf = new short[BUFSIZE];
l_buf = new byte [BUFSIZE];
}
/// <summary>
/// Reset internal state
/// </summary>
public void Reset()
{
last_lit = 0;
extra_bits = 0;
literalTree.Reset();
distTree.Reset();
blTree.Reset();
}
/// <summary>
/// Write all trees to pending buffer
/// </summary>
/// <param name="blTreeCodes">The number/rank of treecodes to send.</param>
public void SendAllTrees(int blTreeCodes)
{
blTree.BuildCodes();
literalTree.BuildCodes();
distTree.BuildCodes();
pending.WriteBits(literalTree.numCodes - 257, 5);
pending.WriteBits(distTree.numCodes - 1, 5);
pending.WriteBits(blTreeCodes - 4, 4);
for (int rank = 0; rank < blTreeCodes; rank++) {
pending.WriteBits(blTree.length[BL_ORDER[rank]], 3);
}
literalTree.WriteTree(blTree);
distTree.WriteTree(blTree);
}
/// <summary>
/// Compress current buffer writing data to pending buffer
/// </summary>
public void CompressBlock()
{
for (int i = 0; i < last_lit; i++) {
int litlen = l_buf[i] & 0xff;
int dist = d_buf[i];
if (dist-- != 0) {
// if (DeflaterConstants.DEBUGGING) {
// Console.Write("["+(dist+1)+","+(litlen+3)+"]: ");
// }
int lc = Lcode(litlen);
literalTree.WriteSymbol(lc);
int bits = (lc - 261) / 4;
if (bits > 0 && bits <= 5) {
pending.WriteBits(litlen & ((1 << bits) - 1), bits);
}
int dc = Dcode(dist);
distTree.WriteSymbol(dc);
bits = dc / 2 - 1;
if (bits > 0) {
pending.WriteBits(dist & ((1 << bits) - 1), bits);
}
} else {
// if (DeflaterConstants.DEBUGGING) {
// if (litlen > 32 && litlen < 127) {
// Console.Write("("+(char)litlen+"): ");
// } else {
// Console.Write("{"+litlen+"}: ");
// }
// }
literalTree.WriteSymbol(litlen);
}
}
literalTree.WriteSymbol(EOF_SYMBOL);
}
/// <summary>
/// Flush block to output with no compression
/// </summary>
/// <param name="stored">Data to write</param>
/// <param name="storedOffset">Index of first byte to write</param>
/// <param name="storedLength">Count of bytes to write</param>
/// <param name="lastBlock">True if this is the last block</param>
public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock)
{
pending.WriteBits((DeflaterConstants.STORED_BLOCK << 1) + (lastBlock ? 1 : 0), 3);
pending.AlignToByte();
pending.WriteShort(storedLength);
pending.WriteShort(~storedLength);
pending.WriteBlock(stored, storedOffset, storedLength);
Reset();
}
/// <summary>
/// Flush block to output with compression
/// </summary>
/// <param name="stored">Data to flush</param>
/// <param name="storedOffset">Index of first byte to flush</param>
/// <param name="storedLength">Count of bytes to flush</param>
/// <param name="lastBlock">True if this is the last block</param>
public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock)
{
literalTree.freqs[EOF_SYMBOL]++;
// Build trees
literalTree.BuildTree();
distTree.BuildTree();
// Calculate bitlen frequency
literalTree.CalcBLFreq(blTree);
distTree.CalcBLFreq(blTree);
// Build bitlen tree
blTree.BuildTree();
int blTreeCodes = 4;
for (int i = 18; i > blTreeCodes; i--) {
if (blTree.length[BL_ORDER[i]] > 0) {
blTreeCodes = i+1;
}
}
int opt_len = 14 + blTreeCodes * 3 + blTree.GetEncodedLength() +
literalTree.GetEncodedLength() + distTree.GetEncodedLength() +
extra_bits;
int static_len = extra_bits;
for (int i = 0; i < LITERAL_NUM; i++) {
static_len += literalTree.freqs[i] * staticLLength[i];
}
for (int i = 0; i < DIST_NUM; i++) {
static_len += distTree.freqs[i] * staticDLength[i];
}
if (opt_len >= static_len) {
// Force static trees
opt_len = static_len;
}
if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3) {
// Store Block
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Storing, since " + storedLength + " < " + opt_len
// + " <= " + static_len);
// }
FlushStoredBlock(stored, storedOffset, storedLength, lastBlock);
} else if (opt_len == static_len) {
// Encode with static tree
pending.WriteBits((DeflaterConstants.STATIC_TREES << 1) + (lastBlock ? 1 : 0), 3);
literalTree.SetStaticCodes(staticLCodes, staticLLength);
distTree.SetStaticCodes(staticDCodes, staticDLength);
CompressBlock();
Reset();
} else {
// Encode with dynamic tree
pending.WriteBits((DeflaterConstants.DYN_TREES << 1) + (lastBlock ? 1 : 0), 3);
SendAllTrees(blTreeCodes);
CompressBlock();
Reset();
}
}
/// <summary>
/// Get value indicating if internal buffer is full
/// </summary>
/// <returns>true if buffer is full</returns>
public bool IsFull()
{
return last_lit >= BUFSIZE;
}
/// <summary>
/// Add literal to buffer
/// </summary>
/// <param name="literal">Literal value to add to buffer.</param>
/// <returns>Value indicating internal buffer is full</returns>
public bool TallyLit(int literal)
{
// if (DeflaterConstants.DEBUGGING) {
// if (lit > 32 && lit < 127) {
// //Console.WriteLine("("+(char)lit+")");
// } else {
// //Console.WriteLine("{"+lit+"}");
// }
// }
d_buf[last_lit] = 0;
l_buf[last_lit++] = (byte)literal;
literalTree.freqs[literal]++;
return IsFull();
}
/// <summary>
/// Add distance code and length to literal and distance trees
/// </summary>
/// <param name="distance">Distance code</param>
/// <param name="length">Length</param>
/// <returns>Value indicating if internal buffer is full</returns>
public bool TallyDist(int distance, int length)
{
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("[" + distance + "," + length + "]");
// }
d_buf[last_lit] = (short)distance;
l_buf[last_lit++] = (byte)(length - 3);
int lc = Lcode(length - 3);
literalTree.freqs[lc]++;
if (lc >= 265 && lc < 285) {
extra_bits += (lc - 261) / 4;
}
int dc = Dcode(distance - 1);
distTree.freqs[dc]++;
if (dc >= 4) {
extra_bits += dc / 2 - 1;
}
return IsFull();
}
/// <summary>
/// Reverse the bits of a 16 bit value.
/// </summary>
/// <param name="toReverse">Value to reverse bits</param>
/// <returns>Value with bits reversed</returns>
public static short BitReverse(int toReverse)
{
return (short) (bit4Reverse[toReverse & 0xF] << 12 |
bit4Reverse[(toReverse >> 4) & 0xF] << 8 |
bit4Reverse[(toReverse >> 8) & 0xF] << 4 |
bit4Reverse[toReverse >> 12]);
}
static int Lcode(int length)
{
if (length == 255) {
return 285;
}
int code = 257;
while (length >= 8) {
code += 4;
length >>= 1;
}
return code + length;
}
static int Dcode(int distance)
{
int code = 0;
while (distance >= 4) {
code += 2;
distance >>= 1;
}
return code + distance;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="Constant.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Mapping.ViewGeneration.Structures
{
using System.Collections.Generic;
using System.Data.Common.CommandTrees;
using System.Data.Common.CommandTrees.ExpressionBuilder;
using System.Data.Common.Utils;
using System.Data.Mapping.ViewGeneration.CqlGeneration;
using System.Data.Metadata.Edm;
using System.Diagnostics;
using System.Text;
/// <summary>
/// This class denotes a constant that can be stored in multiconstants or projected in fields.
/// </summary>
internal abstract class Constant : InternalBase
{
#region Fields
internal static readonly IEqualityComparer<Constant> EqualityComparer = new CellConstantComparer();
internal static readonly Constant Null = NullConstant.Instance;
internal static readonly Constant NotNull = new NegatedConstant( new Constant[] { NullConstant.Instance });
internal static readonly Constant Undefined = UndefinedConstant.Instance;
/// <summary>
/// Represents scalar constants within a finite set that are not specified explicitly in the domain.
/// Currently only used as a Sentinel node to prevent expression optimization
/// </summary>
internal static readonly Constant AllOtherConstants = AllOtherConstantsConstant.Instance;
#endregion
#region Methods
internal abstract bool IsNull();
internal abstract bool IsNotNull();
internal abstract bool IsUndefined();
/// <summary>
/// Returns true if this constant contains not null.
/// Implemented in <see cref="NegatedConstant"/> class, all other implementations return false.
/// </summary>
internal abstract bool HasNotNull();
/// <summary>
/// Generates eSQL for the constant expression.
/// </summary>
/// <param name="outputMember">The member to which this constant is directed</param>
internal abstract StringBuilder AsEsql(StringBuilder builder, MemberPath outputMember, string blockAlias);
/// <summary>
/// Generates CQT for the constant expression.
/// </summary>
/// <param name="row">The input row.</param>
/// <param name="outputMember">The member to which this constant is directed</param>
internal abstract DbExpression AsCqt(DbExpression row, MemberPath outputMember);
public override bool Equals(object obj)
{
Constant cellConst = obj as Constant;
if (cellConst == null)
{
return false;
}
else
{
return IsEqualTo(cellConst);
}
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected abstract bool IsEqualTo(Constant right);
internal abstract string ToUserString();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static void ConstantsToUserString(StringBuilder builder, Set<Constant> constants)
{
bool isFirst = true;
foreach (Constant constant in constants)
{
if (isFirst == false)
{
builder.Append(System.Data.Entity.Strings.ViewGen_CommaBlank);
}
isFirst = false;
string constrStr = constant.ToUserString();
builder.Append(constrStr);
}
}
#endregion
#region Comparer class
private class CellConstantComparer : IEqualityComparer<Constant>
{
public bool Equals(Constant left, Constant right)
{
// Quick check with references
if (object.ReferenceEquals(left, right))
{
// Gets the Null and Undefined case as well
return true;
}
// One of them is non-null at least. So if the other one is
// null, we cannot be equal
if (left == null || right == null)
{
return false;
}
// Both are non-null at this point
return left.IsEqualTo(right);
}
public int GetHashCode(Constant key)
{
EntityUtil.CheckArgumentNull(key, "key");
return key.GetHashCode();
}
}
#endregion
#region Special constant classes (NullConstant, UndefinedConstant, AllOtherConstants)
private sealed class NullConstant : Constant
{
internal static readonly Constant Instance = new NullConstant();
private NullConstant() { }
#region Methods
internal override bool IsNull()
{
return true;
}
internal override bool IsNotNull()
{
return false;
}
internal override bool IsUndefined()
{
return false;
}
internal override bool HasNotNull()
{
return false;
}
internal override StringBuilder AsEsql(StringBuilder builder, MemberPath outputMember, string blockAlias)
{
Debug.Assert(outputMember.LeafEdmMember != null, "Constant can't correspond to an empty member path.");
EdmType constType = Helper.GetModelTypeUsage(outputMember.LeafEdmMember).EdmType;
builder.Append("CAST(NULL AS ");
CqlWriter.AppendEscapedTypeName(builder, constType);
builder.Append(')');
return builder;
}
internal override DbExpression AsCqt(DbExpression row, MemberPath outputMember)
{
Debug.Assert(outputMember.LeafEdmMember != null, "Constant can't correspond to an empty path.");
EdmType constType = Helper.GetModelTypeUsage(outputMember.LeafEdmMember).EdmType;
return TypeUsage.Create(constType).Null();
}
public override int GetHashCode()
{
return 0;
}
protected override bool IsEqualTo(Constant right)
{
Debug.Assert(Object.ReferenceEquals(this, Instance), "this must be == Instance for NullConstant");
return Object.ReferenceEquals(this, right);
}
internal override string ToUserString()
{
return System.Data.Entity.Strings.ViewGen_Null;
}
internal override void ToCompactString(StringBuilder builder)
{
builder.Append("NULL");
}
#endregion
}
private sealed class UndefinedConstant : Constant
{
internal static readonly Constant Instance = new UndefinedConstant();
private UndefinedConstant() { }
#region Methods
internal override bool IsNull()
{
return false;
}
internal override bool IsNotNull()
{
return false;
}
internal override bool IsUndefined()
{
return true;
}
internal override bool HasNotNull()
{
return false;
}
/// <summary>
/// Not supported in this class.
/// </summary>
internal override StringBuilder AsEsql(StringBuilder builder, MemberPath outputMember, string blockAlias)
{
Debug.Fail("Should not be called.");
return null; // To keep the compiler happy
}
/// <summary>
/// Not supported in this class.
/// </summary>
internal override DbExpression AsCqt(DbExpression row, MemberPath outputMember)
{
Debug.Fail("Should not be called.");
return null; // To keep the compiler happy
}
public override int GetHashCode()
{
return 0;
}
protected override bool IsEqualTo(Constant right)
{
Debug.Assert(Object.ReferenceEquals(this, Instance), "this must be == Instance for NullConstant");
return Object.ReferenceEquals(this, right);
}
/// <summary>
/// Not supported in this class.
/// </summary>
internal override string ToUserString()
{
Debug.Fail("We should not emit a message about Undefined constants to the user.");
return null;
}
internal override void ToCompactString(StringBuilder builder)
{
builder.Append("?");
}
#endregion
}
private sealed class AllOtherConstantsConstant : Constant
{
internal static readonly Constant Instance = new AllOtherConstantsConstant();
private AllOtherConstantsConstant() { }
#region Methods
internal override bool IsNull()
{
return false;
}
internal override bool IsNotNull()
{
return false;
}
internal override bool IsUndefined()
{
return false;
}
internal override bool HasNotNull()
{
return false;
}
/// <summary>
/// Not supported in this class.
/// </summary>
internal override StringBuilder AsEsql(StringBuilder builder, MemberPath outputMember, string blockAlias)
{
Debug.Fail("Should not be called.");
return null; // To keep the compiler happy
}
/// <summary>
/// Not supported in this class.
/// </summary>
internal override DbExpression AsCqt(DbExpression row, MemberPath outputMember)
{
Debug.Fail("Should not be called.");
return null; // To keep the compiler happy
}
public override int GetHashCode()
{
return 0;
}
protected override bool IsEqualTo(Constant right)
{
Debug.Assert(Object.ReferenceEquals(this, Instance), "this must be == Instance for NullConstant");
return Object.ReferenceEquals(this, right);
}
/// <summary>
/// Not supported in this class.
/// </summary>
internal override string ToUserString()
{
Debug.Fail("We should not emit a message about Undefined constants to the user.");
return null;
}
internal override void ToCompactString(StringBuilder builder)
{
builder.Append("AllOtherConstants");
}
#endregion
}
#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.Linq;
using System.Net.Http;
using Microsoft.Azure.Gallery;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
namespace Microsoft.Azure.Gallery
{
public partial class GalleryClient : ServiceClient<GalleryClient>, IGalleryClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IItemOperations _items;
/// <summary>
/// Operations for working with gallery items.
/// </summary>
public virtual IItemOperations Items
{
get { return this._items; }
}
/// <summary>
/// Initializes a new instance of the GalleryClient class.
/// </summary>
private GalleryClient()
: base()
{
this._items = new ItemOperations(this);
this._apiVersion = "2013-03-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the GalleryClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public GalleryClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the GalleryClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public GalleryClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://gallery.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the GalleryClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private GalleryClient(HttpClient httpClient)
: base(httpClient)
{
this._items = new ItemOperations(this);
this._apiVersion = "2013-03-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the GalleryClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public GalleryClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the GalleryClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public GalleryClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://gallery.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another GalleryClient
/// instance
/// </summary>
/// <param name='client'>
/// Instance of GalleryClient to clone to
/// </param>
protected override void Clone(ServiceClient<GalleryClient> client)
{
base.Clone(client);
if (client is GalleryClient)
{
GalleryClient clonedClient = ((GalleryClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using NetGore.Content;
using NetGore.Graphics;
using NetGore.IO;
namespace NetGore.Editor.Grhs
{
/// <summary>
/// TreeView used to display Grhs
/// </summary>
public class GrhTreeView : TreeView, IComparer, IComparer<TreeNode>
{
/// <summary>
/// If the EditGrhForm is enabled for individual Grhs. Default is false, and we instead rely on tags in the file names for graphics.
/// </summary>
public const bool EnableGrhEditor = false;
const int _drawImageOffset = 2;
static readonly IComparer<string> _nodeTextComparer = NaturalStringComparer.Instance;
string _filter;
public string Filter
{
get { return _filter; }
set
{
if (_filter == value)
return;
_filter = value;
RebuildTree();
}
}
/// <summary>
/// Timer to update the animated <see cref="Grh"/>s in the <see cref="GrhTreeView"/>.
/// </summary>
readonly Timer _animTimer = new Timer();
readonly ContextMenu _contextMenu = new ContextMenu();
bool _compactMode = true;
IContentManager _contentManager;
/// <summary>
/// Initializes a new instance of the <see cref="GrhTreeView"/> class.
/// </summary>
public GrhTreeView()
{
ImageList = new ImageList { ImageSize = new Size(GrhImageList.ImageWidth, GrhImageList.ImageHeight) };
DrawMode = TreeViewDrawMode.OwnerDrawAll;
}
/// <summary>
/// Notifies listeners when a GrhData is to be edited.
/// </summary>
public event TypedEventHandler<GrhTreeView, GrhTreeViewEditGrhDataEventArgs> EditGrhDataRequested;
/// <summary>
/// Notofies listeners after a new <see cref="GrhData"/> node is selected.
/// </summary>
public event EventHandler<GrhTreeViewEventArgs> GrhAfterSelect;
/// <summary>
/// Notifies listeners before a new <see cref="GrhData"/> node is selected.
/// </summary>
public event EventHandler<GrhTreeViewCancelEventArgs> GrhBeforeSelect;
/// <summary>
/// Notifies listeners when a <see cref="GrhData"/> node is clicked.
/// </summary>
public event EventHandler<GrhTreeNodeMouseClickEventArgs> GrhMouseClick;
/// <summary>
/// Notifies listeners when a <see cref="GrhData"/> node is double-clicked.
/// </summary>
public event EventHandler<GrhTreeNodeMouseClickEventArgs> GrhMouseDoubleClick;
/// <summary>
/// Adds a <see cref="GrhData"/> to the tree or updates it if it already exists.
/// </summary>
/// <param name="gd"><see cref="GrhData"/> to add or update.</param>
void AddGrhToTree(GrhData gd)
{
GrhTreeViewNode.Create(this, gd);
}
/// <summary>
/// Attempts to begin the editing of a <see cref="GrhData"/>.
/// </summary>
/// <param name="node">The <see cref="TreeNode"/> containing the <see cref="GrhData"/> to edit.</param>
/// <returns>True if the editing started successfully; otherwise false.</returns>
public bool BeginEditGrhData(TreeNode node)
{
if (_compactMode)
return false;
var gd = GetGrhData(node);
return BeginEditGrhData(node, gd, false);
}
/// <summary>
/// Attempts to begin the editing of a <see cref="GrhData"/>.
/// </summary>
/// <param name="gd">The <see cref="GrhData"/> to edit.</param>
/// <returns>True if the editing started successfully; otherwise false.</returns>
public bool BeginEditGrhData(GrhData gd)
{
if (_compactMode)
return false;
return BeginEditGrhData(gd, false);
}
/// <summary>
/// Attempts to begin the editing of a <see cref="GrhData"/>.
/// </summary>
/// <param name="gd">The <see cref="GrhData"/> to edit.</param>
/// <param name="deleteOnCancel">If true, the <paramref name="gd"/> will be deleted if the edit form is
/// closed by pressing "Cancel".</param>
/// <returns>True if the editing started successfully; otherwise false.</returns>
bool BeginEditGrhData(GrhData gd, bool deleteOnCancel)
{
var node = FindGrhDataNode(gd);
return BeginEditGrhData(node, gd, deleteOnCancel);
}
/// <summary>
/// Attempts to begin the editing of a <see cref="GrhData"/>.
/// </summary>
/// <param name="node">The <see cref="TreeNode"/> containing the <see cref="GrhData"/> to edit.</param>
/// <param name="gd">The <see cref="GrhData"/> to edit.</param>
/// <param name="deleteOnCancel">If true, the <paramref name="gd"/> will be deleted if the edit form is
/// closed by pressing "Cancel".</param>
/// <returns>True if the editing started successfully; otherwise false.</returns>
bool BeginEditGrhData(TreeNode node, GrhData gd, bool deleteOnCancel)
{
if (node == null || gd == null)
return false;
if (EditGrhDataRequested != null)
EditGrhDataRequested.Raise(this, new GrhTreeViewEditGrhDataEventArgs(node, gd, deleteOnCancel));
return true;
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="T:System.Windows.Forms.TreeView"/> and optionally
/// releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to
/// release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
GrhInfo.Removed -= GrhInfo_Removed;
try
{
if (_animTimer != null)
{
_animTimer.Stop();
_animTimer.Dispose();
}
if (_contextMenu != null)
_contextMenu.Dispose();
Nodes.Clear();
}
catch
{
}
}
base.Dispose(disposing);
}
void DuplicateGrhDataNode(GrhTreeViewNode node, string oldCategoryStart, string newCategoryStart)
{
var gd = node.GrhData;
if (gd is AutomaticAnimatedGrhData)
return;
// Replace the start of the categorization to the new category
var newCategory = newCategoryStart;
if (gd.Categorization.Category.ToString().Length > oldCategoryStart.Length)
newCategory += gd.Categorization.Category.ToString().Substring(oldCategoryStart.Length);
// Grab the new title
var newTitle = GrhInfo.GetUniqueTitle(newCategory, gd.Categorization.Title);
// Duplicate
var newGrhData = gd.Duplicate(new SpriteCategorization(newCategory, newTitle));
// Add the new one to the tree
UpdateGrhData(newGrhData);
}
void DuplicateNode(TreeNode node, string oldCategoryStart, string newCategoryStart)
{
if (node is GrhTreeViewNode)
DuplicateGrhDataNode((GrhTreeViewNode)node, oldCategoryStart, newCategoryStart);
else if (node is GrhTreeViewFolderNode)
{
var grhDataNodes = ((GrhTreeViewFolderNode)node).GetChildGrhDataNodes(true).ToImmutable();
foreach (var child in grhDataNodes)
{
DuplicateGrhDataNode(child, oldCategoryStart, newCategoryStart);
}
}
}
/// <summary>
/// Creates a duplicate of the tree nodes and structure from the root, giving it a unique name. All GrhDatas
/// under the node to be duplicated will be duplicated and placed in a new category with a new GrhIndex,
/// but with the same name and structure.
/// </summary>
/// <param name="root">Root <see cref="TreeNode"/> to duplicate from.</param>
public void DuplicateNodes(TreeNode root)
{
SpriteCategory category;
SpriteCategory newCategory;
if (root is GrhTreeViewNode)
{
category = ((GrhTreeViewNode)root).GrhData.Categorization.Category;
newCategory = category;
}
else
{
category = ((GrhTreeViewFolderNode)root).FullCategory;
newCategory = GrhInfo.GetUniqueCategory(category);
}
DuplicateNode(root, category.ToString(), newCategory.ToString());
}
public GrhTreeViewFolderNode FindFolder(string category)
{
var delimiters = new string[] { SpriteCategorization.Delimiter };
var categoryParts = category.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
GrhTreeViewFolderNode current = null;
var currentColl = Nodes;
for (var i = 0; i < categoryParts.Length; i++)
{
var subCategory = categoryParts[i];
current = currentColl.OfType<GrhTreeViewFolderNode>().FirstOrDefault(x => x.SubCategory == subCategory);
if (current == null)
return null;
currentColl = current.Nodes;
}
return current;
}
/// <summary>
/// Finds the <see cref="GrhTreeViewNode"/> for the given <see cref="GrhData"/>.
/// </summary>
/// <param name="grhData">The <see cref="GrhData"/> to find the <see cref="GrhTreeViewNode"/> for.</param>
/// <returns>The <see cref="GrhTreeViewNode"/> that is for the given <paramref name="grhData"/>, or null
/// if invalid or not found.</returns>
public GrhTreeViewNode FindGrhDataNode(GrhData grhData)
{
if (grhData == null)
return null;
var folder = FindFolder(grhData.Categorization.Category.ToString());
if (folder != null)
{
var existingNode = folder.Nodes.OfType<GrhTreeViewNode>().FirstOrDefault(x => x.GrhData == grhData);
if (existingNode != null)
return existingNode;
}
return null;
}
/// <summary>
/// Gets the category to use from the given <paramref name="node"/>.
/// </summary>
/// <param name="node">The <see cref="TreeNode"/> to get the category from.</param>
/// <returns>The category to use from the given <paramref name="node"/>.</returns>
public static SpriteCategory GetCategoryFromTreeNode(TreeNode node)
{
// Check for a valid node
if (node != null)
{
if (node is GrhTreeViewNode)
return ((GrhTreeViewNode)node).GrhData.Categorization.Category;
else if (node is GrhTreeViewFolderNode)
return ((GrhTreeViewFolderNode)node).FullCategory;
}
return "Uncategorized";
}
/// <summary>
/// Finds the <see cref="GrhData"/> for a given <see cref="TreeNode"/>.
/// </summary>
/// <param name="node"><see cref="TreeNode"/> to get the <see cref="GrhData"/> from.</param>
/// <returns><see cref="GrhData"/> for the <see cref="TreeNode"/>, or null if invalid.</returns>
public static GrhData GetGrhData(TreeNode node)
{
var casted = node as GrhTreeViewNode;
if (casted != null)
return casted.GrhData;
return null;
}
/// <summary>
/// Gets all of the visible <see cref="GrhTreeViewNode"/>s in this <see cref="GrhTreeView"/> that are animated.
/// </summary>
/// <param name="root">The root node.</param>
/// <returns>All of the visible <see cref="GrhTreeViewNode"/>s in this <see cref="GrhTreeView"/> that are animated.</returns>
static IEnumerable<GrhTreeViewNode> GetVisibleAnimatedGrhTreeViewNodes(IEnumerable root)
{
foreach (var node in root.OfType<TreeNode>())
{
if (!node.IsVisible)
continue;
var asGrhTreeViewNode = node as GrhTreeViewNode;
if (asGrhTreeViewNode != null && asGrhTreeViewNode.NeedsToUpdateImage)
{
// Return the node
yield return asGrhTreeViewNode;
}
else if (node.Nodes.Count > 0 && node.IsExpanded)
{
// Recursively add child nodes of this node if it is expanded
foreach (var child in GetVisibleAnimatedGrhTreeViewNodes(node.Nodes))
{
yield return child;
}
}
}
}
void GrhInfo_Removed(GrhData sender, EventArgs e)
{
var node = FindGrhDataNode(sender);
if (node != null)
node.Update();
}
void GrhTreeView_GrhMouseDoubleClick(object sender, GrhTreeNodeMouseClickEventArgs e)
{
if (e.Button == MouseButtons.Left && !(e.GrhData is AutomaticAnimatedGrhData))
BeginEditGrhData(e.Node);
}
void HighlightFolder(TreeNode root, TreeNode folder)
{
if (folder != null && (root == folder || (root.Parent == folder && IsGrhDataNode(root))))
{
// Highlight the folder, the Grhs in the folder, but not the folders in the folder
root.ForeColor = SystemColors.HighlightText;
root.BackColor = SystemColors.Highlight;
}
else
{
// Do not highlight anything else / remove old highlighting
root.ForeColor = ForeColor;
root.BackColor = BackColor;
}
// Recurse through the rest of the nodes
foreach (TreeNode child in root.Nodes)
{
HighlightFolder(child, folder);
}
}
/// <summary>
/// Initializes the <see cref="GrhTreeView"/> with all features.
/// </summary>
/// <param name="cm">The <see cref="IContentManager"/> used for loading content needed by the
/// <see cref="GrhTreeView"/>.</param>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "Grh")]
public void Initialize(IContentManager cm)
{
if (DesignMode)
return;
_contentManager = cm;
// Perform the compact initialization
InitializeCompact();
// Perform some extended initialization goodness
_compactMode = false;
// Event hooks
GrhMouseDoubleClick -= GrhTreeView_GrhMouseDoubleClick;
GrhMouseDoubleClick += GrhTreeView_GrhMouseDoubleClick;
// Set up the context menu for the GrhTreeView
#pragma warning disable 162
if (EnableGrhEditor)
{
_contextMenu.MenuItems.Add(new MenuItem("Edit", MenuClickEdit));
_contextMenu.MenuItems.Add(new MenuItem("New Grh", MenuClickNewGrh));
_contextMenu.MenuItems.Add(new MenuItem("Duplicate", MenuClickDuplicate));
}
#pragma warning restore 162
ContextMenu = _contextMenu;
AllowDrop = true;
}
/// <summary>
/// Initializes the <see cref="GrhTreeView"/>. Requires that the <see cref="GrhData"/>s are already
/// loaded and won't provide any additional features.
/// </summary>
public void InitializeCompact()
{
RealInitializeCompact();
}
/// <summary>
/// Checks if a <see cref="TreeNode"/> contains a <see cref="GrhData"/>, or is a folder.
/// </summary>
/// <param name="node">The <see cref="TreeNode"/> to check.</param>
/// <returns>True if a Grh, false if a folder.</returns>
static bool IsGrhDataNode(TreeNode node)
{
return node is GrhTreeViewNode;
}
void MenuClickDuplicate(object sender, EventArgs e)
{
var node = SelectedNode;
if (node == null)
return;
// Confirm the duplicate request
var count = NodeCount(node);
string text;
if (count <= 0)
{
Debug.Fail(string.Format("Somehow, we have a count of `{0}` nodes...", count));
return;
}
if (count == 1)
text = "Are you sure you wish to duplicate this node?";
else
text = string.Format("Are you sure you wish to duplicate these {0} nodes?", NodeCount(node));
if (MessageBox.Show(text, "Duplicate nodes?", MessageBoxButtons.YesNo) == DialogResult.No)
return;
DuplicateNodes(node);
}
void MenuClickEdit(object sender, EventArgs e)
{
var node = SelectedNode;
if (node == null)
return;
var gd = GetGrhData(node);
if (gd is AutomaticAnimatedGrhData)
return;
if (gd != null && node.Nodes.Count == 0)
{
// The TreeNode is a GrhData
BeginEditGrhData(node);
}
else if (gd == null)
{
// The TreeNode is a folder
node.BeginEdit();
}
}
void MenuClickNewGrh(object sender, EventArgs e)
{
if (_contentManager == null)
return;
// Create the new GrhData
var category = GetCategoryFromTreeNode(SelectedNode);
GrhData gd = GrhInfo.CreateGrhData(_contentManager, category);
UpdateGrhData(gd);
// Begin edit
BeginEditGrhData(gd, true);
}
/// <summary>
/// Counts the number of nodes under the root node, plus the root itself
/// </summary>
/// <param name="root">Root node to count from</param>
/// <returns>Number of nodes under the root node, plus the root itself</returns>
public static int NodeCount(TreeNode root)
{
// No root? No count
if (root == null)
return 0;
// 1 because we are counting ourself
var count = 1;
// Recursively count the children
foreach (TreeNode child in root.Nodes)
{
count += NodeCount(child);
}
return count;
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.TreeView.AfterExpand"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.TreeViewEventArgs"/> that contains the event data.</param>
protected override void OnAfterExpand(TreeViewEventArgs e)
{
base.OnAfterExpand(e);
var n = e.Node;
if (n == null)
return;
// For each of the GrhTreeViewNodes that are in the node that just expanded, ensure the image has been set for them
foreach (var c in n.Nodes.OfType<GrhTreeViewNode>())
{
c.EnsureImageIsSet();
}
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.TreeView.AfterLabelEdit"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.NodeLabelEditEventArgs"/> that contains the event data.</param>
protected override void OnAfterLabelEdit(NodeLabelEditEventArgs e)
{
if (_compactMode)
return;
base.OnAfterLabelEdit(e);
if (e.Node != null && e.Label != null)
{
e.CancelEdit = true;
e.Node.Text = e.Label;
UpdateGrhsToTree(e.Node);
Sort();
}
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.TreeView.AfterSelect"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.TreeViewEventArgs"/> that contains the event data.</param>
protected override void OnAfterSelect(TreeViewEventArgs e)
{
base.OnAfterSelect(e);
if (GrhAfterSelect == null || e.Node == null || !IsGrhDataNode(e.Node))
return;
var gd = GetGrhData(e.Node);
if (gd != null)
GrhAfterSelect.Raise(this, new GrhTreeViewEventArgs(gd, e));
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.TreeView.BeforeSelect"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.TreeViewCancelEventArgs"/> that contains the event data.</param>
protected override void OnBeforeSelect(TreeViewCancelEventArgs e)
{
base.OnBeforeSelect(e);
if (GrhBeforeSelect == null || e.Node == null || !IsGrhDataNode(e.Node))
return;
var gd = GetGrhData(e.Node);
if (gd != null)
GrhBeforeSelect.Raise(this, new GrhTreeViewCancelEventArgs(gd, e));
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.DragDrop"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.DragEventArgs"/> that contains the event data.</param>
protected override void OnDragDrop(DragEventArgs e)
{
if (_compactMode)
return;
base.OnDragDrop(e);
foreach (TreeNode child in Nodes)
{
HighlightFolder(child, null);
}
if (!e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
return;
var pt = PointToClient(new Point(e.X, e.Y));
var destNode = GetNodeAt(pt);
var newNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
TreeNode addedNode;
// Don't allow dropping onto itself
if (newNode == destNode)
return;
// If the destination node is a GrhData node, move the destination to the folder
if (IsGrhDataNode(destNode))
destNode = destNode.Parent;
// Check for a valid destination
if (destNode == null)
return;
if (IsGrhDataNode(newNode))
{
// Move a GrhData node
addedNode = (TreeNode)newNode.Clone();
destNode.Nodes.Add(addedNode);
destNode.Expand();
}
else
{
// Move a folder node
// Do not allow a node to be moved into its own child
var tmp = destNode;
while (tmp.Parent != null)
{
if (tmp.Parent == newNode)
return;
tmp = tmp.Parent;
}
addedNode = (TreeNode)newNode.Clone();
destNode.Nodes.Add(addedNode);
}
// If a node was added, we will want to update
destNode.Expand();
newNode.Remove();
UpdateGrhsToTree(addedNode);
SelectedNode = addedNode;
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.DragEnter"/> event.
/// </summary>
/// <param name="drgevent">A <see cref="T:System.Windows.Forms.DragEventArgs"/> that contains the event data.</param>
protected override void OnDragEnter(DragEventArgs drgevent)
{
if (_compactMode)
return;
drgevent.Effect = DragDropEffects.Move;
base.OnDragEnter(drgevent);
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.DragOver"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.DragEventArgs"/> that contains the event data.</param>
protected override void OnDragOver(DragEventArgs e)
{
base.OnDragOver(e);
if (_compactMode)
return;
var nodeOver = GetNodeAt(PointToClient(new Point(e.X, e.Y)));
if (nodeOver != null)
{
// Find the folder the node will drop into
var folderNode = nodeOver;
if (!IsGrhDataNode(folderNode))
folderNode = folderNode.Parent;
// Perform the highlighting
foreach (TreeNode child in Nodes)
{
HighlightFolder(child, folderNode);
}
}
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.TreeView.DrawNode"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.DrawTreeNodeEventArgs"/> that contains the event data.</param>
protected override void OnDrawNode(DrawTreeNodeEventArgs e)
{
// Perform the default drawing
e.DrawDefault = true;
// Draw the node's image
var casted = e.Node as IGrhTreeViewNode;
if (casted == null)
return;
var image = casted.Image;
if (image == null)
return;
var p = new Point(e.Node.Bounds.X - ImageList.ImageSize.Width - _drawImageOffset, e.Node.Bounds.Y);
e.Graphics.DrawImageUnscaled(image, p);
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.TreeView.ItemDrag"/> event.
/// </summary>
/// <param name="e">An <see cref="T:System.Windows.Forms.ItemDragEventArgs"/> that contains the event data.</param>
protected override void OnItemDrag(ItemDragEventArgs e)
{
if (_compactMode)
return;
base.OnItemDrag(e);
if (e.Button == MouseButtons.Left)
{
SelectedNode = (TreeNode)e.Item;
DoDragDrop(e.Item, DragDropEffects.Move);
}
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.MouseMove"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs"/> that contains the event data.</param>
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
var n = GetNodeAt(e.X, e.Y) as GrhTreeViewFolderNode;
if (n != null)
n.UpdateToolTip();
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.TreeView.NodeMouseClick"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.TreeNodeMouseClickEventArgs"/> that contains the
/// event data.</param>
protected override void OnNodeMouseClick(TreeNodeMouseClickEventArgs e)
{
base.OnNodeMouseClick(e);
// Change the SelectedNode to the clicked node (normally, right-click doesn't change the selected)
if (e.Node != null)
SelectedNode = e.Node;
// If there is no GrhMouseClick event, or this was a folder, there is nothing left to do
if (GrhMouseClick == null || e.Node == null || !IsGrhDataNode(e.Node))
return;
// Get the GrhData for the node clicked, raising the GrhMouseClick event if valid
var gd = GetGrhData(e.Node);
if (gd != null)
GrhMouseClick.Raise(this, new GrhTreeNodeMouseClickEventArgs(gd, e));
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.TreeView.NodeMouseDoubleClick"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.TreeNodeMouseClickEventArgs"/> that contains the
/// event data.</param>
protected override void OnNodeMouseDoubleClick(TreeNodeMouseClickEventArgs e)
{
base.OnNodeMouseDoubleClick(e);
// If there is no GrhMouseDoubleClick event, or this was a folder, there is nothing left to do
if (GrhMouseDoubleClick == null || e.Node == null || !IsGrhDataNode(e.Node))
return;
// Get the GrhData for the node double-clicked, raising the GrhMouseDoubleClick event if valid
var gd = GetGrhData(e.Node);
if (gd != null)
GrhMouseDoubleClick.Raise(this, new GrhTreeNodeMouseClickEventArgs(gd, e));
}
void RealInitializeCompact()
{
Enabled = false;
AllowDrop = false;
// Set the sort method
TreeViewNodeSorter = this;
// Build the tree
RebuildTree();
// Listen for GrhDatas being added/removed
GrhInfo.Removed -= GrhInfo_Removed;
GrhInfo.Removed += GrhInfo_Removed;
// Create the animate timer
_animTimer.Interval = 150;
_animTimer.Tick -= UpdateAnimations;
_animTimer.Tick += UpdateAnimations;
_animTimer.Start();
Enabled = true;
}
/// <summary>
/// Completely rebuilds the <see cref="GrhTreeView"/>.
/// </summary>
public void RebuildTree()
{
if (DesignMode)
return;
// Suspend the layout and updating while we massively alter the collection
BeginUpdate();
SuspendLayout();
try
{
// If there are any nodes already, keep track of which is selected
GrhTreeViewNode selectedGrhNode = SelectedNode as GrhTreeViewNode;
GrhData selectedGrhData = selectedGrhNode != null ? selectedGrhNode.GrhData : null;
// Clear any existing nodes (probably isn't any, but just in case...)
Nodes.Clear();
// Set up the filter
string[] filterWords = (Filter ?? string.Empty).Split(',').Distinct(StringComparer.OrdinalIgnoreCase).Select(x => x.Trim()).Where(x => x.Length > 0).ToArray();
if (filterWords.Length == 0)
filterWords = null;
// Iterate through all the GrhDatas
foreach (var grhData in GrhInfo.GrhDatas)
{
if (filterWords != null)
{
// With filtering
string cat = grhData.Categorization.ToString();
if (filterWords.Any(x => cat.Contains(x, StringComparison.OrdinalIgnoreCase)))
AddGrhToTree(grhData);
}
else
{
// No filtering
AddGrhToTree(grhData);
}
}
// Perform the initial sort
Sort();
// If we used filtering, expand all nodes
if (filterWords != null)
ExpandAll();
// Restore selection
if (selectedGrhData != null)
SelectedNode = FindGrhDataNode(selectedGrhData);
}
finally
{
// Resume the layout and updating
ResumeLayout();
EndUpdate();
}
}
/// <summary>
/// Forces a node's image to be refreshed.
/// </summary>
/// <param name="n">The node to refresh.</param>
internal void RefreshNodeImage(TreeNode n)
{
var w = ImageList.ImageSize.Width;
var rect = new Rectangle(n.Bounds.X - w - _drawImageOffset, n.Bounds.Y, w, n.Bounds.Height);
Invalidate(rect);
}
/// <summary>
/// Updates the visible animated <see cref="GrhTreeViewNode"/>s.
/// </summary>
void UpdateAnimations(object sender, EventArgs e)
{
foreach (var toUpdate in GetVisibleAnimatedGrhTreeViewNodes(Nodes))
{
toUpdate.UpdateIconImage();
}
}
/// <summary>
/// Updates a <see cref="GrhData"/>'s information in the tree.
/// </summary>
/// <param name="grhData"><see cref="GrhData"/> to update.</param>
public void UpdateGrhData(GrhData grhData)
{
GrhTreeViewNode.Create(this, grhData);
}
/// <summary>
/// Updates a GrhData's information in the tree
/// </summary>
/// <param name="grhIndex">Index of the GrhData to update</param>
public void UpdateGrhData(GrhIndex grhIndex)
{
UpdateGrhData(GrhInfo.GetData(grhIndex));
}
public void UpdateGrhDatas(IEnumerable<GrhData> grhDatas)
{
foreach (var grhData in grhDatas)
{
UpdateGrhData(grhData);
}
}
/// <summary>
/// Updates the GrhData categorizing to match the displayed tree. Used to make the GrhData categorization
/// be set based on the tree.
/// </summary>
/// <param name="root">Root TreeNode to start updating at</param>
static void UpdateGrhsToTree(TreeNode root)
{
if (!IsGrhDataNode(root))
{
// Node is a branch, so it should be a folder
foreach (TreeNode node in root.Nodes)
{
UpdateGrhsToTree(node);
}
}
else
{
var grhDataNode = root as GrhTreeViewNode;
if (grhDataNode == null)
return;
grhDataNode.SyncGrhData();
}
}
/// <summary>
/// Overrides <see cref="M:System.Windows.Forms.Control.WndProc(System.Windows.Forms.Message@)"/>.
/// </summary>
/// <param name="m">The Windows <see cref="T:System.Windows.Forms.Message"/> to process.</param>
protected override void WndProc(ref Message m)
{
const int WM_ERASEBKGND = 0x0014;
// Prevent the TreeView from erasing its own background, which helps reduce flickering
if (m.Msg == WM_ERASEBKGND)
m.Msg = 0x0000;
base.WndProc(ref m);
}
#region IComparer Members
/// <summary>
/// Compares two <see cref="TreeNode"/>s.
/// </summary>
/// <param name="a">First object.</param>
/// <param name="b">Second object.</param>
/// <returns>-1 if a is first, 1 if b is first, or 0 for no preference.</returns>
int IComparer.Compare(object a, object b)
{
return ((IComparer<TreeNode>)this).Compare(a as TreeNode, b as TreeNode);
}
#endregion
#region IComparer<TreeNode> Members
/// <summary>
/// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
/// </summary>
/// <returns>
/// Value Condition
/// Less than zero
/// <paramref name="x"/> is less than <paramref name="y"/>.
/// Zero
/// <paramref name="x"/> equals <paramref name="y"/>.
/// Greater than zero
/// <paramref name="x"/> is greater than <paramref name="y"/>.
/// </returns>
/// <param name="x">The first object to compare.</param><param name="y">The second object to compare.</param>
int IComparer<TreeNode>.Compare(TreeNode x, TreeNode y)
{
// Can't do much if either of the nodes are null... but no biggie, they never should be anyways
if (x == null || y == null)
return 0;
// Folders take priority
if (!IsGrhDataNode(x) && IsGrhDataNode(y))
return -1;
if (!IsGrhDataNode(y) && IsGrhDataNode(x))
return 1;
// Text sort
return _nodeTextComparer.Compare(x.Text, y.Text);
}
#endregion
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* 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 Box2D.Collision;
using Box2D.Collision.Shapes;
using Box2D.Common;
using Box2D.Dynamics;
using Box2D.Dynamics.Contacts;
using Box2D.Dynamics.Joints;
using CocosSharp;
using Random = System.Random;
namespace Box2D.TestBed
{
public static class Rand
{
public static Random Random = new Random(0x2eed2eed);
public static void Randomize(int seed)
{
Random = new Random(seed);
}
/// <summary>
/// Random number in range [-1,1]
/// </summary>
/// <returns></returns>
public static float RandomFloat()
{
return (float)(Random.NextDouble() * 2.0 - 1.0);
}
/// <summary>
/// Random floating point number in range [lo, hi]
/// </summary>
/// <param name="lo">The lo.</param>
/// <param name="hi">The hi.</param>
/// <returns></returns>
public static float RandomFloat(float lo, float hi)
{
float r = (float)Random.NextDouble();
r = (hi - lo) * r + lo;
return r;
}
}
public struct TestEntry
{
public Func<Test> CreateFcn;
public string Name;
}
public class DestructionListener : b2DestructionListener
{
public override void SayGoodbye(b2Fixture fixture)
{
}
public override void SayGoodbye(b2Joint joint)
{
if (test.m_mouseJoint == joint)
{
test.m_mouseJoint = null;
}
else
{
test.JointDestroyed(joint);
}
}
public Test test;
};
public class Settings
{
public b2Vec2 viewCenter = new b2Vec2(0.0f, 20.0f);
public float hz = 60.0f;
public int velocityIterations = 8;
public int positionIterations = 3;
public bool drawShapes = true;
public bool drawJoints = true;
public bool drawAABBs = false;
public bool drawPairs = false;
public bool drawContactPoints = false;
public int drawContactNormals = 0;
public int drawContactForces = 0;
public int drawFrictionForces = 0;
public bool drawCOMs = false;
public bool drawStats = true;
public bool drawProfile = true;
public int enableWarmStarting = 1;
public int enableContinuous = 1;
public int enableSubStepping = 0;
public bool pause = false;
public bool singleStep = false;
}
public class ContactPoint
{
public b2Fixture fixtureA;
public b2Fixture fixtureB;
public b2Vec2 normal;
public b2Vec2 position;
public b2PointState state;
};
public class QueryCallback : b2QueryCallback
{
public QueryCallback(b2Vec2 point)
{
m_point = point;
m_fixture = null;
}
public override bool ReportFixture(b2Fixture fixture)
{
b2Body body = fixture.Body;
if (body.BodyType == b2BodyType.b2_dynamicBody)
{
bool inside = fixture.TestPoint(m_point);
if (inside)
{
m_fixture = fixture;
// We are done, terminate the query.
return false;
}
}
// Continue the query.
return true;
}
public b2Vec2 m_point;
public b2Fixture m_fixture;
}
public class Test : b2ContactListener
{
public const int k_maxContactPoints = 2048;
public b2Body m_groundBody;
public b2AABB m_worldAABB;
public ContactPoint[] m_points = new ContactPoint[k_maxContactPoints];
public int m_pointCount;
public DestructionListener m_destructionListener;
public CCBox2dDraw m_debugDraw;
public int m_textLine;
public b2World m_world;
public b2Body m_bomb;
public b2MouseJoint m_mouseJoint;
public b2Vec2 m_bombSpawnPoint;
public bool m_bombSpawning;
public b2Vec2 m_mouseWorld;
public int m_stepCount;
#if PROFILING
public b2Profile m_maxProfile;
public b2Profile m_totalProfile;
#endif
public Test()
{
m_destructionListener = new DestructionListener();
m_debugDraw = new CCBox2dDraw("fonts/arial-12", 1);
b2Vec2 gravity = new b2Vec2();
gravity.Set(0.0f, -10.0f);
m_world = new b2World(gravity);
m_bomb = null;
m_textLine = 30;
m_mouseJoint = null;
m_pointCount = 0;
m_destructionListener.test = this;
m_world.SetDestructionListener(m_destructionListener);
m_world.SetContactListener(this);
m_world.SetDebugDraw(m_debugDraw);
m_world.SetContinuousPhysics(true);
m_world.SetWarmStarting(true);
m_bombSpawning = false;
m_stepCount = 0;
b2BodyDef bodyDef = new b2BodyDef();
m_groundBody = m_world.CreateBody(bodyDef);
}
public virtual void JointDestroyed(b2Joint joint)
{
}
public void DrawTitle(int x, int y, string title)
{
m_debugDraw.DrawString(x, y, title);
}
public virtual bool MouseDown(b2Vec2 p)
{
m_mouseWorld = p;
if (m_mouseJoint != null)
{
return false;
}
// Make a small box.
b2AABB aabb = new b2AABB();
b2Vec2 d = new b2Vec2();
d.Set(0.001f, 0.001f);
aabb.LowerBound = p - d;
aabb.UpperBound = p + d;
// Query the world for overlapping shapes.
QueryCallback callback = new QueryCallback(p);
m_world.QueryAABB(callback, aabb);
if (callback.m_fixture != null)
{
b2Body body = callback.m_fixture.Body;
b2MouseJointDef md = new b2MouseJointDef();
md.BodyA = m_groundBody;
md.BodyB = body;
md.target = p;
md.maxForce = 1000.0f * body.Mass;
m_mouseJoint = (b2MouseJoint) m_world.CreateJoint(md);
body.SetAwake(true);
return true;
}
return false;
}
public void SpawnBomb(b2Vec2 worldPt)
{
m_bombSpawnPoint = worldPt;
m_bombSpawning = true;
}
public void CompleteBombSpawn(b2Vec2 p)
{
if (m_bombSpawning == false)
{
return;
}
const float multiplier = 30.0f;
b2Vec2 vel = m_bombSpawnPoint - p;
vel *= multiplier;
LaunchBomb(m_bombSpawnPoint, vel);
m_bombSpawning = false;
}
public void ShiftMouseDown(b2Vec2 p)
{
m_mouseWorld = p;
if (m_mouseJoint != null)
{
return;
}
SpawnBomb(p);
}
public virtual void MouseUp(b2Vec2 p)
{
if (m_mouseJoint != null)
{
m_world.DestroyJoint(m_mouseJoint);
m_mouseJoint = null;
}
if (m_bombSpawning)
{
CompleteBombSpawn(p);
}
}
public void MouseMove(b2Vec2 p)
{
m_mouseWorld = p;
if (m_mouseJoint != null)
{
m_mouseJoint.SetTarget(p);
}
}
public void LaunchBomb()
{
b2Vec2 p = new b2Vec2(Rand.RandomFloat(-15.0f, 15.0f), 30.0f);
b2Vec2 v = -5.0f * p;
LaunchBomb(p, v);
}
public void LaunchBomb(b2Vec2 position, b2Vec2 velocity)
{
if (m_bomb != null)
{
m_world.DestroyBody(m_bomb);
m_bomb = null;
}
b2BodyDef bd = new b2BodyDef();
bd.type = b2BodyType.b2_dynamicBody;
bd.position = position;
bd.bullet = true;
m_bomb = m_world.CreateBody(bd);
m_bomb.LinearVelocity = velocity;
b2CircleShape circle = new b2CircleShape();
circle.Radius = 0.3f;
b2FixtureDef fd = new b2FixtureDef();
fd.shape = circle;
fd.density = 20.0f;
fd.restitution = 0.0f;
b2Vec2 minV = position - new b2Vec2(0.3f, 0.3f);
b2Vec2 maxV = position + new b2Vec2(0.3f, 0.3f);
b2AABB aabb = new b2AABB();
aabb.LowerBound = minV;
aabb.UpperBound = maxV;
m_bomb.CreateFixture(fd);
}
public void InternalDraw(Settings settings)
{
m_textLine = 30;
m_debugDraw.Begin();
Draw(settings);
m_debugDraw.End();
}
protected virtual void Draw(Settings settings)
{
m_world.DrawDebugData();
if (settings.drawStats)
{
int bodyCount = m_world.BodyCount;
int contactCount = m_world.ContactCount;
int jointCount = m_world.JointCount;
m_debugDraw.DrawString(5, m_textLine, "bodies/contacts/joints = {0}/{1}/{2}", bodyCount, contactCount,
jointCount);
m_textLine += 15;
int proxyCount = m_world.GetProxyCount();
int height = m_world.GetTreeHeight();
int balance = m_world.GetTreeBalance();
float quality = m_world.GetTreeQuality();
m_debugDraw.DrawString(5, m_textLine, "proxies/height/balance/quality = {0}/{1}/{2}/{3}", proxyCount,
height, balance, quality);
m_textLine += 15;
}
#if PROFILING
// Track maximum profile times
{
b2Profile p = m_world.Profile;
m_maxProfile.step = Math.Max(m_maxProfile.step, p.step);
m_maxProfile.collide = Math.Max(m_maxProfile.collide, p.collide);
m_maxProfile.solve = Math.Max(m_maxProfile.solve, p.solve);
m_maxProfile.solveInit = Math.Max(m_maxProfile.solveInit, p.solveInit);
m_maxProfile.solveVelocity = Math.Max(m_maxProfile.solveVelocity, p.solveVelocity);
m_maxProfile.solvePosition = Math.Max(m_maxProfile.solvePosition, p.solvePosition);
m_maxProfile.solveTOI = Math.Max(m_maxProfile.solveTOI, p.solveTOI);
m_maxProfile.broadphase = Math.Max(m_maxProfile.broadphase, p.broadphase);
m_totalProfile.step += p.step;
m_totalProfile.collide += p.collide;
m_totalProfile.solve += p.solve;
m_totalProfile.solveInit += p.solveInit;
m_totalProfile.solveVelocity += p.solveVelocity;
m_totalProfile.solvePosition += p.solvePosition;
m_totalProfile.solveTOI += p.solveTOI;
m_totalProfile.broadphase += p.broadphase;
}
if (settings.drawProfile)
{
b2Profile p = m_world.Profile;
b2Profile aveProfile = new b2Profile();
if (m_stepCount > 0)
{
float scale = 1.0f / m_stepCount;
aveProfile.step = scale * m_totalProfile.step;
aveProfile.collide = scale * m_totalProfile.collide;
aveProfile.solve = scale * m_totalProfile.solve;
aveProfile.solveInit = scale * m_totalProfile.solveInit;
aveProfile.solveVelocity = scale * m_totalProfile.solveVelocity;
aveProfile.solvePosition = scale * m_totalProfile.solvePosition;
aveProfile.solveTOI = scale * m_totalProfile.solveTOI;
aveProfile.broadphase = scale * m_totalProfile.broadphase;
}
m_debugDraw.DrawString(5, m_textLine, "step [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.step,
aveProfile.step, m_maxProfile.step);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "collide [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.collide,
aveProfile.collide, m_maxProfile.collide);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solve [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.solve,
aveProfile.solve, m_maxProfile.solve);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solve init [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.solveInit,
aveProfile.solveInit, m_maxProfile.solveInit);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solve velocity [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})",
p.solveVelocity, aveProfile.solveVelocity, m_maxProfile.solveVelocity);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solve position [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})",
p.solvePosition, aveProfile.solvePosition, m_maxProfile.solvePosition);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solveTOI [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.solveTOI,
aveProfile.solveTOI, m_maxProfile.solveTOI);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "broad-phase [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.broadphase,
aveProfile.broadphase, m_maxProfile.broadphase);
m_textLine += 15;
}
#endif
if (m_mouseJoint != null)
{
b2Vec2 p1 = m_mouseJoint.GetAnchorB();
b2Vec2 p2 = m_mouseJoint.GetTarget();
b2Color c = new b2Color();
c.Set(0.0f, 1.0f, 0.0f);
m_debugDraw.DrawPoint(p1, 4.0f, c);
m_debugDraw.DrawPoint(p2, 4.0f, c);
c.Set(0.8f, 0.8f, 0.8f);
m_debugDraw.DrawSegment(p1, p2, c);
}
if (m_bombSpawning)
{
b2Color c = new b2Color();
c.Set(0.0f, 0.0f, 1.0f);
m_debugDraw.DrawPoint(m_bombSpawnPoint, 4.0f, c);
c.Set(0.8f, 0.8f, 0.8f);
m_debugDraw.DrawSegment(m_mouseWorld, m_bombSpawnPoint, c);
}
if (settings.drawContactPoints)
{
//const float32 k_impulseScale = 0.1f;
float k_axisScale = 0.3f;
for (int i = 0; i < m_pointCount; ++i)
{
ContactPoint point = m_points[i];
if (point.state == b2PointState.b2_addState)
{
// Add
m_debugDraw.DrawPoint(point.position, 10.0f, new b2Color(0.3f, 0.95f, 0.3f));
}
else if (point.state == b2PointState.b2_persistState)
{
// Persist
m_debugDraw.DrawPoint(point.position, 5.0f, new b2Color(0.3f, 0.3f, 0.95f));
}
if (settings.drawContactNormals == 1)
{
b2Vec2 p1 = point.position;
b2Vec2 p2 = p1 + k_axisScale * point.normal;
m_debugDraw.DrawSegment(p1, p2, new b2Color(0.9f, 0.9f, 0.9f));
}
else if (settings.drawContactForces == 1)
{
//b2Vec2 p1 = point->position;
//b2Vec2 p2 = p1 + k_forceScale * point->normalForce * point->normal;
//DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f));
}
if (settings.drawFrictionForces == 1)
{
//b2Vec2 tangent = b2Cross(point->normal, 1.0f);
//b2Vec2 p1 = point->position;
//b2Vec2 p2 = p1 + k_forceScale * point->tangentForce * tangent;
//DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f));
}
}
}
}
public virtual void Step(Settings settings)
{
float timeStep = settings.hz > 0.0f ? 1.0f / settings.hz : 0.0f;
if (settings.pause)
{
if (settings.singleStep)
{
settings.singleStep = false;
}
else
{
timeStep = 0.0f;
}
m_debugDraw.DrawString(5, m_textLine, "****PAUSED****");
m_textLine += 15;
}
b2DrawFlags flags = 0;
if (settings.drawShapes) flags |= b2DrawFlags.e_shapeBit;
if (settings.drawJoints) flags |= b2DrawFlags.e_jointBit;
if (settings.drawAABBs) flags |= b2DrawFlags.e_aabbBit;
if (settings.drawPairs) flags |= b2DrawFlags.e_pairBit;
if (settings.drawCOMs) flags |= b2DrawFlags.e_centerOfMassBit;
m_debugDraw.SetFlags(flags);
m_world.SetWarmStarting(settings.enableWarmStarting > 0);
m_world.SetContinuousPhysics(settings.enableContinuous > 0);
m_world.SetSubStepping(settings.enableSubStepping > 0);
m_pointCount = 0;
m_world.Step(timeStep, settings.velocityIterations, settings.positionIterations);
if (timeStep > 0.0f)
{
++m_stepCount;
}
}
public virtual void Keyboard(char key)
{
}
public virtual void KeyboardUp(char key)
{
}
b2PointState[] state1 = new b2PointState[b2Settings.b2_maxManifoldPoints];
b2PointState[] state2 = new b2PointState[b2Settings.b2_maxManifoldPoints];
b2WorldManifold worldManifold = new b2WorldManifold();
public override void PreSolve(b2Contact contact, b2Manifold oldManifold)
{
b2Manifold manifold = contact.GetManifold();
if (manifold.pointCount == 0)
{
return;
}
b2Fixture fixtureA = contact.GetFixtureA();
b2Fixture fixtureB = contact.GetFixtureB();
b2Collision.b2GetPointStates(state1, state2, oldManifold, manifold);
contact.GetWorldManifold(ref worldManifold);
for (int i = 0; i < manifold.pointCount && m_pointCount < k_maxContactPoints; ++i)
{
ContactPoint cp = m_points[m_pointCount];
if (cp == null)
{
cp = new ContactPoint();
m_points[m_pointCount] = cp;
}
cp.fixtureA = fixtureA;
cp.fixtureB = fixtureB;
cp.position = worldManifold.points[i];
cp.normal = worldManifold.normal;
cp.state = state2[i];
++m_pointCount;
}
}
public override void PostSolve(b2Contact contact, ref b2ContactImpulse impulse)
{
}
public override void BeginContact(b2Contact contact) {}
public override void EndContact(b2Contact contact) {}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Data
{
/// <summary>
/// A class which contains information known to the grid server about a region
/// </summary>
[Serializable]
public class RegionProfileData
{
/// <summary>
/// The name of the region
/// </summary>
public string regionName = String.Empty;
/// <summary>
/// A 64-bit number combining map position into a (mostly) unique ID
/// </summary>
public ulong regionHandle;
/// <summary>
/// OGS/OpenSim Specific ID for a region
/// </summary>
public UUID UUID;
/// <summary>
/// Coordinates of the region
/// </summary>
public uint regionLocX;
public uint regionLocY;
public uint regionLocZ; // Reserved (round-robin, layers, etc)
/// <summary>
/// Authentication secrets
/// </summary>
/// <remarks>Not very secure, needs improvement.</remarks>
public string regionSendKey = String.Empty;
public string regionRecvKey = String.Empty;
public string regionSecret = String.Empty;
/// <summary>
/// Whether the region is online
/// </summary>
public bool regionOnline;
/// <summary>
/// Information about the server that the region is currently hosted on
/// </summary>
public string serverIP = String.Empty;
public uint serverPort;
public string serverURI = String.Empty;
public uint httpPort;
public uint remotingPort;
public string httpServerURI = String.Empty;
/// <summary>
/// Set of optional overrides. Can be used to create non-eulicidean spaces.
/// </summary>
public ulong regionNorthOverrideHandle;
public ulong regionSouthOverrideHandle;
public ulong regionEastOverrideHandle;
public ulong regionWestOverrideHandle;
/// <summary>
/// Optional: URI Location of the region database
/// </summary>
/// <remarks>Used for floating sim pools where the region data is not nessecarily coupled to a specific server</remarks>
public string regionDataURI = String.Empty;
/// <summary>
/// Region Asset Details
/// </summary>
public string regionAssetURI = String.Empty;
public string regionAssetSendKey = String.Empty;
public string regionAssetRecvKey = String.Empty;
/// <summary>
/// Region Userserver Details
/// </summary>
public string regionUserURI = String.Empty;
public string regionUserSendKey = String.Empty;
public string regionUserRecvKey = String.Empty;
/// <summary>
/// Region Map Texture Asset
/// </summary>
public UUID regionMapTextureID = new UUID("00000000-0000-1111-9999-000000000006");
/// <summary>
/// this particular mod to the file provides support within the spec for RegionProfileData for the
/// owner_uuid for the region
/// </summary>
public UUID owner_uuid = UUID.Zero;
/// <summary>
/// OGS/OpenSim Specific original ID for a region after move/split
/// </summary>
public UUID originUUID;
/// <summary>
/// The Maturity rating of the region
/// </summary>
public uint maturity;
//Data Wrappers
public string RegionName
{
get { return regionName; }
set { regionName = value; }
}
public ulong RegionHandle
{
get { return regionHandle; }
set { regionHandle = value; }
}
public UUID Uuid
{
get { return UUID; }
set { UUID = value; }
}
public uint RegionLocX
{
get { return regionLocX; }
set { regionLocX = value; }
}
public uint RegionLocY
{
get { return regionLocY; }
set { regionLocY = value; }
}
public uint RegionLocZ
{
get { return regionLocZ; }
set { regionLocZ = value; }
}
public string RegionSendKey
{
get { return regionSendKey; }
set { regionSendKey = value; }
}
public string RegionRecvKey
{
get { return regionRecvKey; }
set { regionRecvKey = value; }
}
public string RegionSecret
{
get { return regionSecret; }
set { regionSecret = value; }
}
public bool RegionOnline
{
get { return regionOnline; }
set { regionOnline = value; }
}
public string ServerIP
{
get { return serverIP; }
set { serverIP = value; }
}
public uint ServerPort
{
get { return serverPort; }
set { serverPort = value; }
}
public string ServerURI
{
get { return serverURI; }
set { serverURI = value; }
}
public uint ServerHttpPort
{
get { return httpPort; }
set { httpPort = value; }
}
public uint ServerRemotingPort
{
get { return remotingPort; }
set { remotingPort = value; }
}
public ulong NorthOverrideHandle
{
get { return regionNorthOverrideHandle; }
set { regionNorthOverrideHandle = value; }
}
public ulong SouthOverrideHandle
{
get { return regionSouthOverrideHandle; }
set { regionSouthOverrideHandle = value; }
}
public ulong EastOverrideHandle
{
get { return regionEastOverrideHandle; }
set { regionEastOverrideHandle = value; }
}
public ulong WestOverrideHandle
{
get { return regionWestOverrideHandle; }
set { regionWestOverrideHandle = value; }
}
public string RegionDataURI
{
get { return regionDataURI; }
set { regionDataURI = value; }
}
public string RegionAssetURI
{
get { return regionAssetURI; }
set { regionAssetURI = value; }
}
public string RegionAssetSendKey
{
get { return regionAssetSendKey; }
set { regionAssetSendKey = value; }
}
public string RegionAssetRecvKey
{
get { return regionAssetRecvKey; }
set { regionAssetRecvKey = value; }
}
public string RegionUserURI
{
get { return regionUserURI; }
set { regionUserURI = value; }
}
public string RegionUserSendKey
{
get { return regionUserSendKey; }
set { regionUserSendKey = value; }
}
public string RegionUserRecvKey
{
get { return regionUserRecvKey; }
set { regionUserRecvKey = value; }
}
public UUID RegionMapTextureID
{
get { return regionMapTextureID; }
set { regionMapTextureID = value; }
}
public UUID Owner_uuid
{
get { return owner_uuid; }
set { owner_uuid = value; }
}
public UUID OriginUUID
{
get { return originUUID; }
set { originUUID = value; }
}
public uint Maturity
{
get { return maturity; }
set { maturity = value; }
}
public byte AccessLevel
{
get { return Util.ConvertMaturityToAccessLevel(maturity); }
}
public RegionInfo ToRegionInfo()
{
return RegionInfo.Create(UUID, regionName, regionLocX, regionLocY, serverIP, httpPort, serverPort, remotingPort, serverURI);
}
public static RegionProfileData FromRegionInfo(RegionInfo regionInfo)
{
if (regionInfo == null)
{
return null;
}
return Create(regionInfo.RegionID, regionInfo.RegionName, regionInfo.RegionLocX,
regionInfo.RegionLocY, regionInfo.ExternalHostName,
(uint) regionInfo.ExternalEndPoint.Port, regionInfo.HttpPort, regionInfo.RemotingPort,
regionInfo.ServerURI, regionInfo.AccessLevel);
}
public static RegionProfileData Create(UUID regionID, string regionName, uint locX, uint locY, string externalHostName, uint regionPort, uint httpPort, uint remotingPort, string serverUri, byte access)
{
RegionProfileData regionProfile;
regionProfile = new RegionProfileData();
regionProfile.regionLocX = locX;
regionProfile.regionLocY = locY;
regionProfile.regionHandle =
Utils.UIntsToLong((regionProfile.regionLocX * Constants.RegionSize),
(regionProfile.regionLocY*Constants.RegionSize));
regionProfile.serverIP = externalHostName;
regionProfile.serverPort = regionPort;
regionProfile.httpPort = httpPort;
regionProfile.remotingPort = remotingPort;
regionProfile.serverURI = serverUri;
regionProfile.httpServerURI = "http://" + externalHostName + ":" + httpPort + "/";
regionProfile.UUID = regionID;
regionProfile.regionName = regionName;
regionProfile.maturity = access;
return regionProfile;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using Mercurial.Attributes;
namespace Mercurial
{
/// <summary>
/// This class implements the "hg log" command (<see href="http://www.selenic.com/mercurial/hg.1.html#log"/>):
/// show revision history of entire repository or files.
/// </summary>
public sealed class LogCommand : IncludeExcludeCommandBase<LogCommand>, IMercurialCommand<IEnumerable<Changeset>>
{
/// <summary>
/// This is the backing field for the <see cref="Users"/> property.
/// </summary>
private readonly List<string> _Users = new List<string>();
/// <summary>
/// This is the backing field for the <see cref="Keywords"/> property.
/// </summary>
private readonly List<string> _Keywords = new List<string>();
/// <summary>
/// This is the backing field for the <see cref="Revisions"/> property.
/// </summary>
private readonly List<RevSpec> _Revisions = new List<RevSpec>();
/// <summary>
/// This is the backing field for the <see cref="Path"/> property.
/// </summary>
private string _Path = string.Empty;
/// <summary>
/// This is the backing field for the <see cref="IncludeHiddenChangesets"/> property.
/// </summary>
private bool _IncludeHiddenChangesets;
/// <summary>
/// Initializes a new instance of the <see cref="LogCommand"/> class.
/// </summary>
public LogCommand()
: base("log")
{
// Do nothing here
}
/// <summary>
/// Gets or sets the date to show the log for, or <c>null</c> if no filtering on date should be done.
/// Default is <c>null</c>.
/// </summary>
[DateTimeArgument(NonNullOption = "--date", Format = "yyyy-MM-dd")]
[DefaultValue(null)]
public DateTime? Date
{
get;
set;
}
/// <summary>
/// Gets the collection of case-insensitive keywords to search the log for.
/// Default is empty which indicates no searching will be done.
/// </summary>
[RepeatableArgument(Option = "--keyword")]
public Collection<string> Keywords
{
get
{
return new Collection<string>(_Keywords);
}
}
/// <summary>
/// Gets or sets a value indicating whether to follow renames and copies when limiting the log.
/// Default is <c>false</c>.
/// </summary>
[BooleanArgument(TrueOption = "--follow")]
[DefaultValue(false)]
public bool FollowRenamesAndMoves
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether to only follow the first parent of merge changesets.
/// Default value is <c>false</c>.
/// </summary>
[BooleanArgument(TrueOption = "--follow-first")]
[DefaultValue(false)]
public bool OnlyFollowFirstParent
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether to include path actions (which files were modified, and the
/// type of modification) or not. Default is <c>false</c>.
/// </summary>
[BooleanArgument(TrueOption = "--verbose")]
[DefaultValue(false)]
public bool IncludePathActions
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether to include hidden changesets.
/// Default is <c>false</c>.
/// </summary>
[BooleanArgument(TrueOption = "--hidden")]
[DefaultValue(false)]
public bool IncludeHiddenChangesets
{
get
{
return _IncludeHiddenChangesets;
}
set
{
RequiresVersion(new Version(1, 9), "The IncludeHiddenChangesets property of the LogCommand");
_IncludeHiddenChangesets = value;
}
}
/// <summary>
/// Gets or sets the path to produce the log for, or <see cref="string.Empty"/> to produce
/// the log for the repository. Default is <see cref="string.Empty"/>.
/// </summary>
[NullableArgument]
[DefaultValue("")]
public string Path
{
get
{
return _Path;
}
set
{
_Path = (value ?? string.Empty).Trim();
}
}
/// <summary>
/// Gets the collection of users to produce the log for, or an empty collection to produce
/// the log for the repository. Default is an empty collection.
/// </summary>
[RepeatableArgument(Option = "--user")]
public Collection<string> Users
{
get
{
return new Collection<string>(_Users);
}
}
/// <summary>
/// Gets the collection of <see cref="Revisions"/> to process/include.
/// </summary>
[RepeatableArgument(Option = "--rev")]
public Collection<RevSpec> Revisions
{
get
{
return new Collection<RevSpec>(_Revisions);
}
}
#region IMercurialCommand<IEnumerable<Changeset>> Members
/// <summary>
/// Gets all the arguments to the <see cref="CommandBase{T}.Command"/>, or an
/// empty array if there are none.
/// </summary>
/// <value></value>
public override IEnumerable<string> Arguments
{
get
{
var arguments = new[]
{
"--style=xml", "-v"
};
return arguments.Concat(base.Arguments).ToArray();
}
}
/// <summary>
/// Gets the result of executing the command as a collection of <see cref="Changeset"/> objects.
/// </summary>
public IEnumerable<Changeset> Result
{
get;
private set;
}
#endregion
/// <summary>
/// Sets the <see cref="Date"/> property to the specified value and
/// returns this <see cref="LogCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="Date"/> property.
/// </param>
/// <returns>
/// This <see cref="LogCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public LogCommand WithDate(DateTime value)
{
Date = value;
return this;
}
/// <summary>
/// Sets the <see cref="FollowRenamesAndMoves"/> property to the specified value and
/// returns this <see cref="LogCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="FollowRenamesAndMoves"/> property,
/// defaults to <c>true</c>.
/// </param>
/// <returns>
/// This <see cref="LogCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public LogCommand WithFollowRenamesAndMoves(bool value = true)
{
FollowRenamesAndMoves = value;
return this;
}
/// <summary>
/// Sets the <see cref="OnlyFollowFirstParent"/> property to the specified value and
/// returns this <see cref="LogCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="OnlyFollowFirstParent"/> property,
/// defaults to <c>true</c>.
/// </param>
/// <returns>
/// This <see cref="LogCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public LogCommand WithOnlyFollowFirstParent(bool value = true)
{
OnlyFollowFirstParent = value;
return this;
}
/// <summary>
/// Sets the <see cref="IncludePathActions"/> property to the specified value and
/// returns this <see cref="LogCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="IncludePathActions"/> property,
/// defaults to <c>true</c>.
/// </param>
/// <returns>
/// This <see cref="LogCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public LogCommand WithIncludePathActions(bool value = true)
{
IncludePathActions = value;
return this;
}
/// <summary>
/// Sets the <see cref="IncludeHiddenChangesets"/> property to the specified value and
/// returns this <see cref="LogCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="IncludeHiddenChangesets"/> property,
/// defaults to <c>true</c>.
/// </param>
/// <returns>
/// This <see cref="LogCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public LogCommand WithIncludeHiddenChangesets(bool value = true)
{
IncludeHiddenChangesets = value;
return this;
}
/// <summary>
/// Sets the <see cref="Path"/> property to the specified value and
/// returns this <see cref="LogCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="Path"/> property.
/// </param>
/// <returns>
/// This <see cref="LogCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public LogCommand WithPath(string value)
{
Path = value;
return this;
}
/// <summary>
/// Adds the value to the <see cref="Revisions"/> collection property and
/// returns this <see cref="LogCommand"/> instance.
/// </summary>
/// <param name="value">
/// The value to add to the <see cref="Revisions"/> collection property.
/// </param>
/// <returns>
/// This <see cref="LogCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public LogCommand WithRevision(RevSpec value)
{
Revisions.Add(value);
return this;
}
/// <summary>
/// Adds the value to the <see cref="Keywords"/> collection property and
/// returns this <see cref="LogCommand"/> instance.
/// </summary>
/// <param name="value">
/// The value to add to the <see cref="Keywords"/> collection property.
/// </param>
/// <returns>
/// This <see cref="LogCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public LogCommand WithKeyword(string value)
{
Keywords.Add(value);
return this;
}
/// <summary>
/// Sets the <see cref="Users"/> property to the specified value and
/// returns this <see cref="LogCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="Users"/> property.
/// </param>
/// <returns>
/// This <see cref="LogCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public LogCommand WithUser(string value)
{
Users.Add(value);
return this;
}
/// <summary>
/// Parses the standard output for results.
/// </summary>
/// <param name="exitCode">The exit code.</param>
/// <param name="standardOutput">The standard output.</param>
protected override void ParseStandardOutputForResults(int exitCode, string standardOutput)
{
base.ParseStandardOutputForResults(exitCode, standardOutput);
Result = ChangesetXmlParser.LazyParse(standardOutput);
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Impl.Auth.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Impl.Auth
{
/// <summary>
/// <para>Digest authentication scheme as defined in RFC 2617. Both MD5 (default) and MD5-sess are supported. Currently only qop=auth or no qop is supported. qop=auth-int is unsupported. If auth and auth-int are provided, auth is used. </para><para>Credential charset is configured via the credential charset parameter. Since the digest username is included as clear text in the generated Authentication header, the charset of the username must be compatible with the http element charset. </para><para><para> </para><simplesectsep></simplesectsep><para>Rodney Waldhoff </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para>Ortwin Glueck </para><simplesectsep></simplesectsep><para>Sean C. Sullivan </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/DigestScheme
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/DigestScheme", AccessFlags = 33)]
public partial class DigestScheme : global::Org.Apache.Http.Impl.Auth.RFC2617Scheme
/* scope: __dot42__ */
{
/// <summary>
/// <para>Default constructor for the digest authetication scheme. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public DigestScheme() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Processes the Digest challenge.</para><para></para>
/// </summary>
/// <java-name>
/// processChallenge
/// </java-name>
[Dot42.DexImport("processChallenge", "(Lorg/apache/http/Header;)V", AccessFlags = 1)]
public override void ProcessChallenge(global::Org.Apache.Http.IHeader header) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests if the Digest authentication process has been completed.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if Digest authorization has been processed, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isComplete
/// </java-name>
[Dot42.DexImport("isComplete", "()Z", AccessFlags = 1)]
public override bool IsComplete() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns textual designation of the digest authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>digest</code> </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetSchemeName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns <code>false</code>. Digest authentication scheme is request based.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>false</code>. </para>
/// </returns>
/// <java-name>
/// isConnectionBased
/// </java-name>
[Dot42.DexImport("isConnectionBased", "()Z", AccessFlags = 1)]
public override bool IsConnectionBased() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// overrideParamter
/// </java-name>
[Dot42.DexImport("overrideParamter", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void OverrideParamter(string name, string value) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Produces a digest authorization string for the given set of Credentials, method name and URI.</para><para></para>
/// </summary>
/// <returns>
/// <para>a digest authorization string </para>
/// </returns>
/// <java-name>
/// authenticate
/// </java-name>
[Dot42.DexImport("authenticate", "(Lorg/apache/http/auth/Credentials;Lorg/apache/http/HttpRequest;)Lorg/apache/http" +
"/Header;", AccessFlags = 1)]
public override global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, global::Org.Apache.Http.IHttpRequest request) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHeader);
}
/// <summary>
/// <para>Creates a random cnonce value based on the current time.</para><para></para>
/// </summary>
/// <returns>
/// <para>The cnonce value as String. </para>
/// </returns>
/// <java-name>
/// createCnonce
/// </java-name>
[Dot42.DexImport("createCnonce", "()Ljava/lang/String;", AccessFlags = 9)]
public static string CreateCnonce() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns textual designation of the digest authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>digest</code> </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
public string SchemeName
{
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSchemeName(); }
}
}
/// <summary>
/// <para>Signals NTLM protocol failure.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/NTLMEngineException
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/NTLMEngineException", AccessFlags = 33)]
public partial class NTLMEngineException : global::Org.Apache.Http.Auth.AuthenticationException
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public NTLMEngineException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new NTLMEngineException with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public NTLMEngineException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new NTLMEngineException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public NTLMEngineException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <java-name>
/// org/apache/http/impl/auth/NTLMScheme
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/NTLMScheme", AccessFlags = 33)]
public partial class NTLMScheme : global::Org.Apache.Http.Impl.Auth.AuthSchemeBase
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/impl/auth/NTLMEngine;)V", AccessFlags = 1)]
public NTLMScheme(global::Org.Apache.Http.Impl.Auth.INTLMEngine engine) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns textual designation of the given authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the given authentication scheme </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetSchemeName() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getParameter
/// </java-name>
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1)]
public override string GetParameter(string name) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns authentication realm. If the concept of an authentication realm is not applicable to the given authentication scheme, returns <code>null</code>.</para><para></para>
/// </summary>
/// <returns>
/// <para>the authentication realm </para>
/// </returns>
/// <java-name>
/// getRealm
/// </java-name>
[Dot42.DexImport("getRealm", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetRealm() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Tests if the authentication scheme is provides authorization on a per connection basis instead of usual per request basis</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the scheme is connection based, <code>false</code> if the scheme is request based. </para>
/// </returns>
/// <java-name>
/// isConnectionBased
/// </java-name>
[Dot42.DexImport("isConnectionBased", "()Z", AccessFlags = 1)]
public override bool IsConnectionBased() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// parseChallenge
/// </java-name>
[Dot42.DexImport("parseChallenge", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 4)]
protected internal override void ParseChallenge(global::Org.Apache.Http.Util.CharArrayBuffer buffer, int pos, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// authenticate
/// </java-name>
[Dot42.DexImport("authenticate", "(Lorg/apache/http/auth/Credentials;Lorg/apache/http/HttpRequest;)Lorg/apache/http" +
"/Header;", AccessFlags = 1)]
public override global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, global::Org.Apache.Http.IHttpRequest request) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHeader);
}
/// <summary>
/// <para>Authentication process may involve a series of challenge-response exchanges. This method tests if the authorization process has been completed, either successfully or unsuccessfully, that is, all the required authorization challenges have been processed in their entirety.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the authentication process has been completed, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isComplete
/// </java-name>
[Dot42.DexImport("isComplete", "()Z", AccessFlags = 1)]
public override bool IsComplete() /* MethodBuilder.Create */
{
return default(bool);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal NTLMScheme() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns textual designation of the given authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the given authentication scheme </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
public string SchemeName
{
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSchemeName(); }
}
/// <summary>
/// <para>Returns authentication realm. If the concept of an authentication realm is not applicable to the given authentication scheme, returns <code>null</code>.</para><para></para>
/// </summary>
/// <returns>
/// <para>the authentication realm </para>
/// </returns>
/// <java-name>
/// getRealm
/// </java-name>
public string Realm
{
[Dot42.DexImport("getRealm", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetRealm(); }
}
}
/// <summary>
/// <para>Abstract NTLM authentication engine. The engine can be used to generate Type1 messages and Type3 messages in response to a Type2 challenge. </para><para>For details see </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/NTLMEngine
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/NTLMEngine", AccessFlags = 1537)]
public partial interface INTLMEngine
/* scope: __dot42__ */
{
/// <summary>
/// <para>Generates a Type1 message given the domain and workstation.</para><para></para>
/// </summary>
/// <returns>
/// <para>Type1 message </para>
/// </returns>
/// <java-name>
/// generateType1Msg
/// </java-name>
[Dot42.DexImport("generateType1Msg", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)]
string GenerateType1Msg(string domain, string workstation) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Generates a Type3 message given the user credentials and the authentication challenge.</para><para></para>
/// </summary>
/// <returns>
/// <para>Type3 response. </para>
/// </returns>
/// <java-name>
/// generateType3Msg
/// </java-name>
[Dot42.DexImport("generateType3Msg", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/la" +
"ng/String;)Ljava/lang/String;", AccessFlags = 1025)]
string GenerateType3Msg(string username, string password, string domain, string workstation, string challenge) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/DigestSchemeFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/DigestSchemeFactory", AccessFlags = 33)]
public partial class DigestSchemeFactory : global::Org.Apache.Http.Auth.IAuthSchemeFactory
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public DigestSchemeFactory() /* MethodBuilder.Create */
{
}
/// <java-name>
/// newInstance
/// </java-name>
[Dot42.DexImport("newInstance", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/auth/AuthScheme;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Auth.IAuthScheme NewInstance(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Auth.IAuthScheme);
}
}
/// <summary>
/// <para>Abstract authentication scheme class that serves as a basis for all authentication schemes supported by HttpClient. This class defines the generic way of parsing an authentication challenge. It does not make any assumptions regarding the format of the challenge nor does it impose any specific way of responding to that challenge.</para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/AuthSchemeBase
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/AuthSchemeBase", AccessFlags = 1057)]
public abstract partial class AuthSchemeBase : global::Org.Apache.Http.Auth.IAuthScheme
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public AuthSchemeBase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Processes the given challenge token. Some authentication schemes may involve multiple challenge-response exchanges. Such schemes must be able to maintain the state information when dealing with sequential challenges</para><para></para>
/// </summary>
/// <java-name>
/// processChallenge
/// </java-name>
[Dot42.DexImport("processChallenge", "(Lorg/apache/http/Header;)V", AccessFlags = 1)]
public virtual void ProcessChallenge(global::Org.Apache.Http.IHeader header) /* MethodBuilder.Create */
{
}
/// <java-name>
/// parseChallenge
/// </java-name>
[Dot42.DexImport("parseChallenge", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 1028)]
protected internal abstract void ParseChallenge(global::Org.Apache.Http.Util.CharArrayBuffer buffer, int pos, int len) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns <code>true</code> if authenticating against a proxy, <code>false</code> otherwise.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if authenticating against a proxy, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isProxy
/// </java-name>
[Dot42.DexImport("isProxy", "()Z", AccessFlags = 1)]
public virtual bool IsProxy() /* MethodBuilder.Create */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getSchemeName", "()Ljava/lang/String;", AccessFlags = 1025)]
public virtual string GetSchemeName() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(string);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getParameter", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)]
public virtual string GetParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(string);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getRealm", "()Ljava/lang/String;", AccessFlags = 1025)]
public virtual string GetRealm() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(string);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "isConnectionBased", "()Z", AccessFlags = 1025)]
public virtual bool IsConnectionBased() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "isComplete", "()Z", AccessFlags = 1025)]
public virtual bool IsComplete() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "authenticate", "(Lorg/apache/http/auth/Credentials;Lorg/apache/http/HttpRequest;)Lorg/apache/http" +
"/Header;", AccessFlags = 1025)]
public virtual global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, global::Org.Apache.Http.IHttpRequest request) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
public string SchemeName
{
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getSchemeName", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetSchemeName(); }
}
public string Realm
{
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getRealm", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetRealm(); }
}
}
/// <summary>
/// <para>Authentication credentials required to respond to a authentication challenge are invalid</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/UnsupportedDigestAlgorithmException
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/UnsupportedDigestAlgorithmException", AccessFlags = 33)]
public partial class UnsupportedDigestAlgorithmException : global::System.SystemException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new UnsupportedAuthAlgoritmException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public UnsupportedDigestAlgorithmException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new UnsupportedAuthAlgoritmException with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public UnsupportedDigestAlgorithmException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new UnsupportedAuthAlgoritmException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public UnsupportedDigestAlgorithmException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/BasicSchemeFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/BasicSchemeFactory", AccessFlags = 33)]
public partial class BasicSchemeFactory : global::Org.Apache.Http.Auth.IAuthSchemeFactory
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public BasicSchemeFactory() /* MethodBuilder.Create */
{
}
/// <java-name>
/// newInstance
/// </java-name>
[Dot42.DexImport("newInstance", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/auth/AuthScheme;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Auth.IAuthScheme NewInstance(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Auth.IAuthScheme);
}
}
/// <summary>
/// <para>Basic authentication scheme as defined in RFC 2617. </para><para><para> </para><simplesectsep></simplesectsep><para>Rodney Waldhoff </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para>Ortwin Glueck </para><simplesectsep></simplesectsep><para>Sean C. Sullivan </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/BasicScheme
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/BasicScheme", AccessFlags = 33)]
public partial class BasicScheme : global::Org.Apache.Http.Impl.Auth.RFC2617Scheme
/* scope: __dot42__ */
{
/// <summary>
/// <para>Default constructor for the basic authetication scheme. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public BasicScheme() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns textual designation of the basic authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>basic</code> </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetSchemeName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Processes the Basic challenge.</para><para></para>
/// </summary>
/// <java-name>
/// processChallenge
/// </java-name>
[Dot42.DexImport("processChallenge", "(Lorg/apache/http/Header;)V", AccessFlags = 1)]
public override void ProcessChallenge(global::Org.Apache.Http.IHeader header) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests if the Basic authentication process has been completed.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if Basic authorization has been processed, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isComplete
/// </java-name>
[Dot42.DexImport("isComplete", "()Z", AccessFlags = 1)]
public override bool IsComplete() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns <code>false</code>. Basic authentication scheme is request based.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>false</code>. </para>
/// </returns>
/// <java-name>
/// isConnectionBased
/// </java-name>
[Dot42.DexImport("isConnectionBased", "()Z", AccessFlags = 1)]
public override bool IsConnectionBased() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Produces basic authorization header for the given set of Credentials.</para><para></para>
/// </summary>
/// <returns>
/// <para>a basic authorization string </para>
/// </returns>
/// <java-name>
/// authenticate
/// </java-name>
[Dot42.DexImport("authenticate", "(Lorg/apache/http/auth/Credentials;Lorg/apache/http/HttpRequest;)Lorg/apache/http" +
"/Header;", AccessFlags = 1)]
public override global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, global::Org.Apache.Http.IHttpRequest request) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHeader);
}
/// <summary>
/// <para>Returns a basic <code>Authorization</code> header value for the given Credentials and charset.</para><para></para>
/// </summary>
/// <returns>
/// <para>a basic authorization header </para>
/// </returns>
/// <java-name>
/// authenticate
/// </java-name>
[Dot42.DexImport("authenticate", "(Lorg/apache/http/auth/Credentials;Ljava/lang/String;Z)Lorg/apache/http/Header;", AccessFlags = 9)]
public static global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, string charset, bool proxy) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHeader);
}
/// <summary>
/// <para>Returns textual designation of the basic authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>basic</code> </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
public string SchemeName
{
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSchemeName(); }
}
}
/// <summary>
/// <para>Abstract authentication scheme class that lays foundation for all RFC 2617 compliant authetication schemes and provides capabilities common to all authentication schemes defined in RFC 2617.</para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/RFC2617Scheme
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/RFC2617Scheme", AccessFlags = 1057)]
public abstract partial class RFC2617Scheme : global::Org.Apache.Http.Impl.Auth.AuthSchemeBase
/* scope: __dot42__ */
{
/// <summary>
/// <para>Default constructor for RFC2617 compliant authetication schemes. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public RFC2617Scheme() /* MethodBuilder.Create */
{
}
/// <java-name>
/// parseChallenge
/// </java-name>
[Dot42.DexImport("parseChallenge", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 4)]
protected internal override void ParseChallenge(global::Org.Apache.Http.Util.CharArrayBuffer buffer, int pos, int len) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns authentication parameters map. Keys in the map are lower-cased.</para><para></para>
/// </summary>
/// <returns>
/// <para>the map of authentication parameters </para>
/// </returns>
/// <java-name>
/// getParameters
/// </java-name>
[Dot42.DexImport("getParameters", "()Ljava/util/Map;", AccessFlags = 4, Signature = "()Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;")]
protected internal virtual global::Java.Util.IMap<string, string> GetParameters() /* MethodBuilder.Create */
{
return default(global::Java.Util.IMap<string, string>);
}
/// <summary>
/// <para>Returns authentication parameter with the given name, if available.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameter with the given name </para>
/// </returns>
/// <java-name>
/// getParameter
/// </java-name>
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1)]
public override string GetParameter(string name) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns authentication realm. The realm may not be null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the authentication realm </para>
/// </returns>
/// <java-name>
/// getRealm
/// </java-name>
[Dot42.DexImport("getRealm", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetRealm() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns authentication parameters map. Keys in the map are lower-cased.</para><para></para>
/// </summary>
/// <returns>
/// <para>the map of authentication parameters </para>
/// </returns>
/// <java-name>
/// getParameters
/// </java-name>
protected internal global::Java.Util.IMap<string, string> Parameters
{
[Dot42.DexImport("getParameters", "()Ljava/util/Map;", AccessFlags = 4, Signature = "()Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;")]
get{ return GetParameters(); }
}
/// <summary>
/// <para>Returns authentication realm. The realm may not be null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the authentication realm </para>
/// </returns>
/// <java-name>
/// getRealm
/// </java-name>
public string Realm
{
[Dot42.DexImport("getRealm", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetRealm(); }
}
}
}
| |
#region Header
/**
* JsonMapper.cs
* JSON to .Net object and object to JSON conversions.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace LitJson
{
internal struct PropertyMetadata
{
public MemberInfo Info;
public bool IsField;
public Type Type;
}
internal struct ArrayMetadata
{
private Type element_type;
private bool is_array;
private bool is_list;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsArray {
get { return is_array; }
set { is_array = value; }
}
public bool IsList {
get { return is_list; }
set { is_list = value; }
}
}
internal struct ObjectMetadata
{
private Type element_type;
private bool is_dictionary;
private IDictionary<string, PropertyMetadata> properties;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsDictionary {
get { return is_dictionary; }
set { is_dictionary = value; }
}
public IDictionary<string, PropertyMetadata> Properties {
get { return properties; }
set { properties = value; }
}
}
internal delegate void ExporterFunc (object obj, JsonWriter writer);
public delegate void ExporterFunc<T> (T obj, JsonWriter writer);
internal delegate object ImporterFunc (object input);
public delegate TValue ImporterFunc<TJson, TValue> (TJson input);
public delegate IJsonWrapper WrapperFactory ();
public class JsonMapper
{
#region Fields
private static int max_nesting_depth;
private static IFormatProvider datetime_format;
private static IDictionary<Type, ExporterFunc> base_exporters_table;
private static IDictionary<Type, ExporterFunc> custom_exporters_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> base_importers_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> custom_importers_table;
private static IDictionary<Type, ArrayMetadata> array_metadata;
private static readonly object array_metadata_lock = new Object ();
private static IDictionary<Type,
IDictionary<Type, MethodInfo>> conv_ops;
private static readonly object conv_ops_lock = new Object ();
private static IDictionary<Type, ObjectMetadata> object_metadata;
private static readonly object object_metadata_lock = new Object ();
private static IDictionary<Type,
IList<PropertyMetadata>> type_properties;
private static readonly object type_properties_lock = new Object ();
private static JsonWriter static_writer;
private static readonly object static_writer_lock = new Object ();
#endregion
#region Constructors
static JsonMapper ()
{
max_nesting_depth = 100;
array_metadata = new Dictionary<Type, ArrayMetadata> ();
conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> ();
object_metadata = new Dictionary<Type, ObjectMetadata> ();
type_properties = new Dictionary<Type,
IList<PropertyMetadata>> ();
static_writer = new JsonWriter ();
datetime_format = DateTimeFormatInfo.InvariantInfo;
base_exporters_table = new Dictionary<Type, ExporterFunc> ();
custom_exporters_table = new Dictionary<Type, ExporterFunc> ();
base_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
custom_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
RegisterBaseExporters ();
RegisterBaseImporters ();
}
#endregion
#region Private Methods
private static void AddArrayMetadata (Type type)
{
if (array_metadata.ContainsKey (type))
return;
ArrayMetadata data = new ArrayMetadata ();
data.IsArray = type.IsArray;
if (type.GetInterface ("System.Collections.IList") != null)
data.IsList = true;
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name != "Item")
continue;
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (int))
data.ElementType = p_info.PropertyType;
}
lock (array_metadata_lock) {
try {
array_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddObjectMetadata (Type type)
{
if (object_metadata.ContainsKey (type))
return;
ObjectMetadata data = new ObjectMetadata ();
if (type.GetInterface ("System.Collections.IDictionary") != null)
data.IsDictionary = true;
data.Properties = new Dictionary<string, PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item") {
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (string))
data.ElementType = p_info.PropertyType;
continue;
}
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.Type = p_info.PropertyType;
data.Properties.Add (p_info.Name, p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
p_data.Type = f_info.FieldType;
data.Properties.Add (f_info.Name, p_data);
}
lock (object_metadata_lock) {
try {
object_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddTypeProperties (Type type)
{
if (type_properties.ContainsKey (type))
return;
IList<PropertyMetadata> props = new List<PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item")
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.IsField = false;
props.Add (p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
props.Add (p_data);
}
lock (type_properties_lock) {
try {
type_properties.Add (type, props);
} catch (ArgumentException) {
return;
}
}
}
private static MethodInfo GetConvOp (Type t1, Type t2)
{
lock (conv_ops_lock) {
if (! conv_ops.ContainsKey (t1))
conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
}
if (conv_ops[t1].ContainsKey (t2))
return conv_ops[t1][t2];
MethodInfo op = t1.GetMethod (
"op_Implicit", new Type[] { t2 });
lock (conv_ops_lock) {
try {
conv_ops[t1].Add (t2, op);
} catch (ArgumentException) {
return conv_ops[t1][t2];
}
}
return op;
}
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
if (reader.Token == JsonToken.Null) {
if (! inst_type.IsClass)
throw new JsonException (String.Format (
"Can't assign null to an instance of type {0}",
inst_type));
return null;
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType ();
if (inst_type.IsAssignableFrom (json_type))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
inst_type)) {
ImporterFunc importer =
custom_importers_table[json_type][inst_type];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
inst_type)) {
ImporterFunc importer =
base_importers_table[json_type][inst_type];
return importer (reader.Value);
}
// Maybe it's an enum
if (inst_type.IsEnum)
return Enum.ToObject (inst_type, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (inst_type, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new ArrayList ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (reader.Token == JsonToken.ArrayEnd)
break;
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart) {
AddObjectMetadata (inst_type);
ObjectMetadata t_data = object_metadata[inst_type];
instance = Activator.CreateInstance (inst_type);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey (property)) {
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField) {
((FieldInfo) prop_data.Info).SetValue (
instance, ReadValue (prop_data.Type, reader));
} else {
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue (
instance,
ReadValue (prop_data.Type, reader),
null);
else
ReadValue (prop_data.Type, reader);
}
} else {
if (! t_data.IsDictionary)
throw new JsonException (String.Format (
"The type {0} doesn't have the " +
"property '{1}'", inst_type, property));
((IDictionary) instance).Add (
property, ReadValue (
t_data.ElementType, reader));
}
}
}
return instance;
}
private static IJsonWrapper ReadValue (WrapperFactory factory,
JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null)
return null;
IJsonWrapper instance = factory ();
if (reader.Token == JsonToken.String) {
instance.SetString ((string) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Double) {
instance.SetDouble ((double) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Int) {
instance.SetInt ((int) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Long) {
instance.SetLong ((long) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Boolean) {
instance.SetBoolean ((bool) reader.Value);
return instance;
}
if (reader.Token == JsonToken.ArrayStart) {
instance.SetJsonType (JsonType.Array);
while (true) {
IJsonWrapper item = ReadValue (factory, reader);
if (reader.Token == JsonToken.ArrayEnd)
break;
((IList) instance).Add (item);
}
}
else if (reader.Token == JsonToken.ObjectStart) {
instance.SetJsonType (JsonType.Object);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
((IDictionary) instance)[property] = ReadValue (
factory, reader);
}
}
return instance;
}
private static void RegisterBaseExporters ()
{
base_exporters_table[typeof (byte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((byte) obj));
};
base_exporters_table[typeof (char)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((char) obj));
};
base_exporters_table[typeof (DateTime)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((DateTime) obj,
datetime_format));
};
base_exporters_table[typeof (decimal)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((decimal) obj);
};
base_exporters_table[typeof (sbyte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((sbyte) obj));
};
base_exporters_table[typeof (short)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((short) obj));
};
base_exporters_table[typeof (ushort)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((ushort) obj));
};
base_exporters_table[typeof (uint)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToUInt64 ((uint) obj));
};
base_exporters_table[typeof (ulong)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((ulong) obj);
};
}
private static void RegisterBaseImporters ()
{
ImporterFunc importer;
importer = delegate (object input) {
return Convert.ToByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (byte), importer);
importer = delegate (object input) {
return Convert.ToUInt64 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ulong), importer);
importer = delegate (object input) {
return Convert.ToSByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (sbyte), importer);
importer = delegate (object input) {
return Convert.ToInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (short), importer);
importer = delegate (object input) {
return Convert.ToUInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ushort), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToSingle ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (float), importer);
importer = delegate (object input) {
return Convert.ToDouble ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (double), importer);
importer = delegate (object input) {
return Convert.ToDecimal ((double) input);
};
RegisterImporter (base_importers_table, typeof (double),
typeof (decimal), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((long) input);
};
RegisterImporter (base_importers_table, typeof (long),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToChar ((string) input);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (char), importer);
importer = delegate (object input) {
return Convert.ToDateTime ((string) input, datetime_format);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (DateTime), importer);
}
private static void RegisterImporter (
IDictionary<Type, IDictionary<Type, ImporterFunc>> table,
Type json_type, Type value_type, ImporterFunc importer)
{
if (! table.ContainsKey (json_type))
table.Add (json_type, new Dictionary<Type, ImporterFunc> ());
table[json_type][value_type] = importer;
}
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string) entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type = obj.GetType ();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (p_info.GetValue (obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
#endregion
public static string ToJson (object obj)
{
lock (static_writer_lock) {
static_writer.Reset ();
WriteValue (obj, static_writer, true, 0);
return static_writer.ToString ();
}
}
public static void ToJson (object obj, JsonWriter writer)
{
WriteValue (obj, writer, false, 0);
}
public static JsonData ToObject (JsonReader reader)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, reader);
}
public static JsonData ToObject (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json_reader);
}
public static JsonData ToObject (string json)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json);
}
public static T ToObject<T> (JsonReader reader)
{
return (T) ReadValue (typeof (T), reader);
}
public static T ToObject<T> (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (T) ReadValue (typeof (T), json_reader);
}
public static T ToObject<T> (string json)
{
JsonReader reader = new JsonReader (json);
return (T) ReadValue (typeof (T), reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
JsonReader reader)
{
return ReadValue (factory, reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
string json)
{
JsonReader reader = new JsonReader (json);
return ReadValue (factory, reader);
}
public static void RegisterExporter<T> (ExporterFunc<T> exporter)
{
ExporterFunc exporter_wrapper =
delegate (object obj, JsonWriter writer) {
exporter ((T) obj, writer);
};
custom_exporters_table[typeof (T)] = exporter_wrapper;
}
public static void RegisterImporter<TJson, TValue> (
ImporterFunc<TJson, TValue> importer)
{
ImporterFunc importer_wrapper =
delegate (object input) {
return importer ((TJson) input);
};
RegisterImporter (custom_importers_table, typeof (TJson),
typeof (TValue), importer_wrapper);
}
public static void UnregisterExporters ()
{
custom_exporters_table.Clear ();
}
public static void UnregisterImporters ()
{
custom_importers_table.Clear ();
}
}
}
| |
//
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.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;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using NDesk.Options;
namespace Manos.Tool
{
class Driver
{
public static readonly string COMPILED_TEMPLATES_ASSEMBLY = "CompiledTemplates.dll";
public static readonly string TEMPLATES_DIRECTORY = "Templates";
public static readonly string DEPLOYMENT_DIRECTORY = "Deployment";
private static Environment Environment = new Environment ();
private static StreamWriter output;
public static int Main (string[] args)
{
args = ParseGlobalOptions (args);
bool help = false;
Func<IList<string>, int> command = null;
var p = new OptionSet () {
{ "h|?|help", v => help = v != null },
{ "init|i", v => command = Init },
{ "server|s", v => command = Server },
{ "docs|d", v => command = Docs },
{ "build|b", v => command = Build },
{ "show-environment|se", v => command = ShowEnvironment },
{ "run|r=", v => command = a => { return Run(v, a); } },
};
List<string> extra = null;
try {
extra = p.Parse(args);
} catch (OptionException){
Console.WriteLine ("Try `manos --help' for more information.");
return 1;
}
if (help) {
ShowHelp (p);
return 0;
}
if (command == null) {
ShowHelp (p);
return 1;
}
command (extra);
return 0;
}
private static StreamWriter StreamForFile (string file)
{
if (file == null)
throw new ArgumentNullException ("file");
FileStream fs = new FileStream (file, FileMode.Create);
StreamWriter sw = new StreamWriter (fs);
sw.AutoFlush = true;
return sw;
}
private static void SetOutput (string file)
{
Console.WriteLine ("setting output: " + file);
output = StreamForFile (file);
Console.SetOut (output);
Console.SetError (output);
}
private static string [] ParseGlobalOptions (string [] args)
{
var p = new OptionSet () {
{ "-data-dir=", v => Environment.DataDirectory = v },
{ "-out|out=", v => SetOutput (v) },
};
List<string> extra = null;
try {
extra = p.Parse(args);
} catch (OptionException){
Console.WriteLine ("Try `manos --help' for more information.");
return null;
}
if (extra == null)
return null;
return extra.ToArray ();
}
private static int Init (IList<string> args)
{
if (args.Count < 1) {
Console.WriteLine ("manos --init <AppName>");
Console.WriteLine ("This will initialize a new application with the supplied name.");
}
Driver d = new Driver ();
try {
Console.WriteLine ("initing: {0}", args [0]);
d.Init (args [0]);
} catch (Exception e) {
Console.WriteLine ("error while initializing application:");
Console.WriteLine (e);
return 1;
}
return 0;
}
public void Init (string name)
{
InitCommand initer = new InitCommand (Environment, name);
initer.Run ();
}
private static int Server (IList<string> args)
{
Driver d = new Driver ();
try {
d.RunServer (args);
} catch (Exception e) {
Console.WriteLine ("error while serving application:");
Console.WriteLine (e);
return 1;
}
return 0;
}
public void RunServer (IList<string> args)
{
string port = null;
string securePort = null;
string certFile = null;
string keyFile = null;
string user = null;
string assembly = null;
string ipaddress = null;
var p = new OptionSet () {
{ "p|port=", v => port = v },
{ "P|secureport=", v => securePort = v },
{ "c|certfile=", v => certFile = v },
{ "k|keyfile=", v => keyFile = v },
{ "u|user=", v => user = v },
{ "a|assembly=", v=> assembly = v},
{ "l|listen=", v => ipaddress = v }
};
args = p.Parse(args);
ServerCommand cmd = new ServerCommand (Environment, args);
if(assembly != null)
{
cmd.ApplicationAssembly = assembly;
}
if (port != null) {
int pt;
if (!Int32.TryParse (port, out pt))
throw new ArgumentException ("Port value is not an integer.");
if (pt <= 0)
throw new ArgumentOutOfRangeException ("port", "Port must be a positive integer.");
cmd.Port = pt;
}
if (securePort != null) {
if (certFile == null)
throw new ArgumentException ("Certificate file required for TLS.");
if (keyFile == null)
throw new ArgumentException ("Certificate private key required for TLS.");
int pt;
if (!Int32.TryParse (securePort, out pt))
throw new ArgumentException ("Secure port value is not an integer.");
if (pt <= 0)
throw new ArgumentOutOfRangeException ("secureport", "Secure port must be a positive integer.");
cmd.SecurePort = pt;
cmd.CertificateFile = certFile;
cmd.KeyFile = keyFile;
}
if (user != null)
cmd.User = user;
if (ipaddress != null)
cmd.IPAddress = ipaddress;
cmd.Run ();
}
private static int Docs (IList<string> args)
{
Driver d = new Driver ();
try {
d.RunDocs ();
} catch (Exception e) {
Console.WriteLine ("error while serving application:");
Console.WriteLine (e);
return 1;
}
return 0;
}
public void RunDocs ()
{
DocsCommand cmd = new DocsCommand (Environment);
cmd.Run ();
}
private static int Build (IList<string> args)
{
Driver d = new Driver ();
try {
d.RunBuild ();
} catch (Exception e) {
Console.WriteLine ("error while building application:");
Console.WriteLine (e);
return 1;
}
return 0;
}
public void RunBuild ()
{
BuildCommand cmd = new BuildCommand (Environment);
cmd.Run ();
}
private static int ShowEnvironment (IList<string> args)
{
Console.WriteLine ("libdir: '{0}'", Environment.LibDirectory);
Console.WriteLine ("manosdir: '{0}'", Environment.ManosDirectory);
Console.WriteLine ("workingdir: '{0}'", Environment.WorkingDirectory);
Console.WriteLine ("datadir: '{0}'", Environment.DataDirectory);
Console.WriteLine ("datadir: '{0}'", Environment.DocsDirectory);
return 1;
}
private static void ShowHelp (OptionSet os)
{
Console.WriteLine ("manos usage is: manos [command] [options]");
Console.WriteLine ();
os.WriteOptionDescriptions (Console.Out);
}
private static int Run (string app, IList<string> args)
{
RunCommand cmd = new RunCommand ();
return cmd.Run (app, args);
}
}
}
| |
// ReSharper disable InconsistentNaming
using EasyNetQ.Tests.Mocking;
using Xunit;
using RabbitMQ.Client;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
namespace EasyNetQ.Tests
{
public class When_using_default_conventions
{
private Conventions conventions;
private ITypeNameSerializer typeNameSerializer;
public When_using_default_conventions()
{
typeNameSerializer = new DefaultTypeNameSerializer();
conventions = new Conventions(typeNameSerializer);
}
[Fact]
public void The_default_exchange_naming_convention_should_use_the_TypeNameSerializers_Serialize_method()
{
var result = conventions.ExchangeNamingConvention(typeof (TestMessage));
result.Should().Be(typeNameSerializer.Serialize(typeof(TestMessage)));
}
[Fact]
public void The_default_topic_naming_convention_should_return_an_empty_string()
{
var result = conventions.TopicNamingConvention(typeof (TestMessage));
result.Should().Be("");
}
[Fact]
public void The_default_queue_naming_convention_should_use_the_TypeNameSerializers_Serialize_method_then_an_underscore_then_the_subscription_id()
{
const string subscriptionId = "test";
var result = conventions.QueueNamingConvention(typeof (TestMessage), subscriptionId);
result.Should().Be(typeNameSerializer.Serialize(typeof(TestMessage)) + "_" + subscriptionId);
}
[Fact]
public void The_default_error_queue_name_should_be()
{
var result = conventions.ErrorQueueNamingConvention(new MessageReceivedInfo());
result.Should().Be("EasyNetQ_Default_Error_Queue");
}
[Fact]
public void The_default_error_exchange_name_should_be()
{
var info = new MessageReceivedInfo("consumer_tag", 0, false, "exchange", "routingKey", "queue");
var result = conventions.ErrorExchangeNamingConvention(info);
result.Should().Be("ErrorExchange_routingKey");
}
[Fact]
public void The_default_rpc_request_exchange_name_should_be()
{
var result = conventions.RpcRequestExchangeNamingConvention(typeof (object));
result.Should().Be("easy_net_q_rpc");
}
[Fact]
public void The_default_rpc_reply_exchange_name_should_be()
{
var result = conventions.RpcResponseExchangeNamingConvention(typeof(object));
result.Should().Be("easy_net_q_rpc");
}
[Fact]
public void The_default_rpc_routingkey_naming_convention_should_use_the_TypeNameSerializers_Serialize_method()
{
var result = conventions.RpcRoutingKeyNamingConvention(typeof(TestMessage));
result.Should().Be(typeNameSerializer.Serialize(typeof(TestMessage)));
}
}
public class When_using_QueueAttribute
{
private Conventions conventions;
private ITypeNameSerializer typeNameSerializer;
public When_using_QueueAttribute()
{
typeNameSerializer = new DefaultTypeNameSerializer();
conventions = new Conventions(typeNameSerializer);
}
[Theory]
[InlineData(typeof(AnnotatedTestMessage))]
[InlineData(typeof(IAnnotatedTestMessage))]
public void The_queue_naming_convention_should_use_attribute_queueName_then_an_underscore_then_the_subscription_id(Type messageType)
{
const string subscriptionId = "test";
var result = conventions.QueueNamingConvention(messageType, subscriptionId);
result.Should().Be("MyQueue" + "_" + subscriptionId);
}
[Theory]
[InlineData(typeof(AnnotatedTestMessage))]
[InlineData(typeof(IAnnotatedTestMessage))]
public void And_subscription_id_is_empty_the_queue_naming_convention_should_use_attribute_queueName(Type messageType)
{
const string subscriptionId = "";
var result = conventions.QueueNamingConvention(messageType, subscriptionId);
result.Should().Be("MyQueue");
}
[Theory]
[InlineData(typeof(EmptyQueueNameAnnotatedTestMessage))]
[InlineData(typeof(IEmptyQueueNameAnnotatedTestMessage))]
public void And_queueName_is_empty_should_use_the_TypeNameSerializers_Serialize_method_then_an_underscore_then_the_subscription_id(Type messageType)
{
const string subscriptionId = "test";
var result = conventions.QueueNamingConvention(messageType, subscriptionId);
result.Should().Be(typeNameSerializer.Serialize(messageType) + "_" + subscriptionId);
}
[Theory]
[InlineData(typeof(AnnotatedTestMessage))]
[InlineData(typeof(IAnnotatedTestMessage))]
public void The_exchange_name_convention_should_use_attribute_exchangeName(Type messageType)
{
var result = conventions.ExchangeNamingConvention(messageType);
result.Should().Be("MyExchange");
}
[Theory]
[InlineData(typeof(QueueNameOnlyAnnotatedTestMessage))]
[InlineData(typeof(IQueueNameOnlyAnnotatedTestMessage))]
public void And_exchangeName_not_specified_the_exchange_name_convention_should_use_the_TypeNameSerializers_Serialize_method(Type messageType)
{
var result = conventions.ExchangeNamingConvention(messageType);
result.Should().Be(typeNameSerializer.Serialize(messageType));
}
}
public class When_publishing_a_message : IDisposable
{
private MockBuilder mockBuilder;
private ITypeNameSerializer typeNameSerializer;
public When_publishing_a_message()
{
typeNameSerializer = new DefaultTypeNameSerializer();
var customConventions = new Conventions(typeNameSerializer)
{
ExchangeNamingConvention = x => "CustomExchangeNamingConvention",
QueueNamingConvention = (x, y) => "CustomQueueNamingConvention",
TopicNamingConvention = x => "CustomTopicNamingConvention"
};
mockBuilder = new MockBuilder(x => x.Register<IConventions>(customConventions));
mockBuilder.Bus.Publish(new TestMessage());
}
public void Dispose()
{
mockBuilder.Bus.Dispose();
}
[Fact]
public void Should_use_exchange_name_from_conventions_to_create_the_exchange()
{
mockBuilder.Channels[0].Received().ExchangeDeclare(
Arg.Is("CustomExchangeNamingConvention"),
Arg.Is("topic"),
Arg.Is(true),
Arg.Is(false),
Arg.Is<Dictionary<string, object>>(x => x.SequenceEqual(new Dictionary<string, object>())));
}
[Fact]
public void Should_use_exchange_name_from_conventions_as_the_exchange_to_publish_to()
{
mockBuilder.Channels[0].Received().BasicPublish(
Arg.Is("CustomExchangeNamingConvention"),
Arg.Any<string>(),
Arg.Is(false),
Arg.Any<IBasicProperties>(),
Arg.Any<ReadOnlyMemory<byte>>());
}
[Fact]
public void Should_use_topic_name_from_conventions_as_the_topic_to_publish_to()
{
mockBuilder.Channels[0].Received().BasicPublish(
Arg.Any<string>(),
Arg.Is("CustomTopicNamingConvention"),
Arg.Is(false),
Arg.Any<IBasicProperties>(),
Arg.Any<ReadOnlyMemory<byte>>());
}
}
public class When_registering_response_handler : IDisposable
{
private MockBuilder mockBuilder;
public When_registering_response_handler()
{
var customConventions = new Conventions(new DefaultTypeNameSerializer())
{
RpcRequestExchangeNamingConvention = messageType => "CustomRpcExchangeName",
RpcRoutingKeyNamingConvention = messageType => "CustomRpcRoutingKeyName"
};
mockBuilder = new MockBuilder(x => x.Register<IConventions>(customConventions));
mockBuilder.Bus.Respond<TestMessage, TestMessage>(t => new TestMessage());
}
public void Dispose()
{
mockBuilder.Bus.Dispose();
}
[Fact]
public void Should_correctly_bind_using_new_conventions()
{
mockBuilder.Channels[0].Received().QueueBind(
Arg.Is("CustomRpcRoutingKeyName"),
Arg.Is("CustomRpcExchangeName"),
Arg.Is("CustomRpcRoutingKeyName"),
Arg.Is<Dictionary<string, object>>(x => x.SequenceEqual(new Dictionary<string, object>())));
}
[Fact]
public void Should_declare_correct_exchange()
{
mockBuilder.Channels[0].Received().ExchangeDeclare(
Arg.Is("CustomRpcExchangeName"),
Arg.Is("direct"),
Arg.Is(true),
Arg.Is(false),
Arg.Is<Dictionary<string, object>>(x => x.SequenceEqual(new Dictionary<string, object>())));
}
}
}
// ReSharper restore InconsistentNaming
| |
using System;
namespace LumiSoft.Net.Dns.Client
{
/// <summary>
/// SOA record class.
/// </summary>
[Serializable]
public class DNS_rr_SOA : DNS_rr_base
{
private string m_NameServer = "";
private string m_AdminEmail = "";
private long m_Serial = 0;
private long m_Refresh = 0;
private long m_Retry = 0;
private long m_Expire = 0;
private long m_Minimum = 0;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="nameServer">Name server.</param>
/// <param name="adminEmail">Zone administrator email.</param>
/// <param name="serial">Version number of the original copy of the zone.</param>
/// <param name="refresh">Time interval(in seconds) before the zone should be refreshed.</param>
/// <param name="retry">Time interval(in seconds) that should elapse before a failed refresh should be retried.</param>
/// <param name="expire">Time value(in seconds) that specifies the upper limit on the time interval that can elapse before the zone is no longer authoritative.</param>
/// <param name="minimum">Minimum TTL(in seconds) field that should be exported with any RR from this zone.</param>
/// <param name="ttl">TTL value.</param>
public DNS_rr_SOA(string nameServer,string adminEmail,long serial,long refresh,long retry,long expire,long minimum,int ttl) : base(QTYPE.SOA,ttl)
{
m_NameServer = nameServer;
m_AdminEmail = adminEmail;
m_Serial = serial;
m_Refresh = refresh;
m_Retry = retry;
m_Expire = expire;
m_Minimum = minimum;
}
#region static method Parse
/// <summary>
/// Parses resource record from reply data.
/// </summary>
/// <param name="reply">DNS server reply data.</param>
/// <param name="offset">Current offset in reply data.</param>
/// <param name="rdLength">Resource record data length.</param>
/// <param name="ttl">Time to live in seconds.</param>
public static DNS_rr_SOA Parse(byte[] reply,ref int offset,int rdLength,int ttl)
{
/* RFC 1035 3.3.13. SOA RDATA format
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ MNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ RNAME /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| SERIAL |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| REFRESH |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| RETRY |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| EXPIRE |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| MINIMUM |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
MNAME The <domain-name> of the name server that was the
original or primary source of data for this zone.
RNAME A <domain-name> which specifies the mailbox of the
person responsible for this zone.
SERIAL The unsigned 32 bit version number of the original copy
of the zone. Zone transfers preserve this value. This
value wraps and should be compared using sequence space
arithmetic.
REFRESH A 32 bit time interval before the zone should be
refreshed.
RETRY A 32 bit time interval that should elapse before a
failed refresh should be retried.
EXPIRE A 32 bit time value that specifies the upper limit on
the time interval that can elapse before the zone is no
longer authoritative.
MINIMUM The unsigned 32 bit minimum TTL field that should be
exported with any RR from this zone.
*/
//---- Parse record -------------------------------------------------------------//
// MNAME
string nameserver = "";
Dns_Client.GetQName(reply,ref offset,ref nameserver);
// RNAME
string adminMailBox = "";
Dns_Client.GetQName(reply,ref offset,ref adminMailBox);
char[] adminMailBoxAr = adminMailBox.ToCharArray();
for(int i=0;i<adminMailBoxAr.Length;i++){
if(adminMailBoxAr[i] == '.'){
adminMailBoxAr[i] = '@';
break;
}
}
adminMailBox = new string(adminMailBoxAr);
// SERIAL
long serial = reply[offset++] << 24 | reply[offset++] << 16 | reply[offset++] << 8 | reply[offset++];
// REFRESH
long refresh = reply[offset++] << 24 | reply[offset++] << 16 | reply[offset++] << 8 | reply[offset++];
// RETRY
long retry = reply[offset++] << 24 | reply[offset++] << 16 | reply[offset++] << 8 | reply[offset++];
// EXPIRE
long expire = reply[offset++] << 24 | reply[offset++] << 16 | reply[offset++] << 8 | reply[offset++];
// MINIMUM
long minimum = reply[offset++] << 24 | reply[offset++] << 16 | reply[offset++] << 8 | reply[offset++];
//--------------------------------------------------------------------------------//
return new DNS_rr_SOA(nameserver,adminMailBox,serial,refresh,retry,expire,minimum,ttl);
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets name server.
/// </summary>
public string NameServer
{
get{ return m_NameServer; }
}
/// <summary>
/// Gets zone administrator email.
/// </summary>
public string AdminEmail
{
get{ return m_AdminEmail; }
}
/// <summary>
/// Gets version number of the original copy of the zone.
/// </summary>
public long Serial
{
get{ return m_Serial; }
}
/// <summary>
/// Gets time interval(in seconds) before the zone should be refreshed.
/// </summary>
public long Refresh
{
get{ return m_Refresh; }
}
/// <summary>
/// Gets time interval(in seconds) that should elapse before a failed refresh should be retried.
/// </summary>
public long Retry
{
get{ return m_Retry; }
}
/// <summary>
/// Gets time value(in seconds) that specifies the upper limit on the time interval that can elapse before the zone is no longer authoritative.
/// </summary>
public long Expire
{
get{ return m_Expire; }
}
/// <summary>
/// Gets minimum TTL(in seconds) field that should be exported with any RR from this zone.
/// </summary>
public long Minimum
{
get{ return m_Minimum; }
}
#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.Globalization;
public class DateTimeParseExact2
{
private const int c_MIN_STRING_LEN = 1;
private const int c_MAX_STRING_LEN = 2048;
private const int c_NUM_LOOPS = 100;
private static DateTimeStyles[] c_STYLES = new DateTimeStyles[7] {DateTimeStyles.AdjustToUniversal, DateTimeStyles.AllowInnerWhite, DateTimeStyles.AllowLeadingWhite, DateTimeStyles.AllowTrailingWhite , DateTimeStyles.AllowWhiteSpaces, DateTimeStyles.NoCurrentDateDefault, DateTimeStyles.None };
public static int Main()
{
DateTimeParseExact2 test = new DateTimeParseExact2();
TestLibrary.TestFramework.BeginTestCase("DateTimeParseExact2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
MyFormater formater = new MyFormater();
string dateBefore = "";
DateTime dateAfter;
TestLibrary.TestFramework.BeginScenario("PosTest1: DateTime.ParseExact(DateTime.Now)");
try
{
for(int i=0; i<c_STYLES.Length; i++)
{
dateBefore = DateTime.Now.ToString();
dateAfter = DateTime.ParseExact( dateBefore, new string[] {"G"}, formater, c_STYLES[i] );
if (!TestLibrary.Utilities.IsWindows &&
(c_STYLES[i]==DateTimeStyles.AdjustToUniversal)) // Mac prints offset
{
dateAfter = dateAfter.ToLocalTime();
}
if (!dateBefore.Equals(dateAfter.ToString()))
{
TestLibrary.TestFramework.LogError("001", "DateTime.ParseExact(" + dateBefore + ", G, " + c_STYLES[i] + ") did not equal " + dateAfter.ToString());
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string dateBefore = "";
DateTime dateAfter;
MyFormater formater = new MyFormater();
TestLibrary.TestFramework.BeginScenario("PosTest2: DateTime.ParseExact(DateTime.Now, g, formater, <invalid DateTimeStyles>)");
try
{
for(int i=-1024; i<1024; i++)
{
try
{
// skip the valid values
if (0 == (i & (int)DateTimeStyles.AdjustToUniversal)
&& 0 == (i & (int)DateTimeStyles.AssumeUniversal)
&& 0 == (i & (int)DateTimeStyles.AllowInnerWhite)
&& 0 == (i & (int)DateTimeStyles.AllowLeadingWhite)
&& 0 == (i & (int)DateTimeStyles.AllowTrailingWhite)
&& 0 == (i & (int)DateTimeStyles.AllowWhiteSpaces)
&& 0 == (i & (int)DateTimeStyles.NoCurrentDateDefault)
&& i != (int)DateTimeStyles.None
)
{
dateBefore = DateTime.Now.ToString();
dateAfter = DateTime.ParseExact( dateBefore, new string[] {"G"}, formater, (DateTimeStyles)i);
if (!dateBefore.Equals(dateAfter.ToString()))
{
TestLibrary.TestFramework.LogError("011", "DateTime.ParseExact(" + dateBefore + ", " + (DateTimeStyles)i + ") did not equal " + dateAfter.ToString());
retVal = false;
}
}
}
catch (System.ArgumentException)
{
//
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
MyFormater formater = new MyFormater();
TestLibrary.TestFramework.BeginScenario("NegTest1: DateTime.ParseExact(null)");
try
{
try
{
for(int i=0; i<c_STYLES.Length; i++)
{
DateTime.ParseExact(null, new string[] {"d"}, formater, c_STYLES[i]);
TestLibrary.TestFramework.LogError("029", "DateTime.ParseExact(null, d, " + c_STYLES[i] + ") should have thrown");
retVal = false;
}
}
catch (ArgumentNullException)
{
// expected
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("030", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
MyFormater formater = new MyFormater();
TestLibrary.TestFramework.BeginScenario("NegTest2: DateTime.ParseExact(String.Empty)");
try
{
try
{
for(int i=0; i<c_STYLES.Length; i++)
{
DateTime.ParseExact(String.Empty, new string[] {"d"}, formater, c_STYLES[i]);
TestLibrary.TestFramework.LogError("029", "DateTime.ParseExact(String.Empty, d, " + c_STYLES[i] + ") should have thrown");
retVal = false;
}
}
catch (ArgumentNullException)
{
// expected
}
}
catch (FormatException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("032", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
MyFormater formater = new MyFormater();
string strDateTime = "";
DateTime dateAfter;
string[] formats = new string[17] {"d", "D", "f", "F", "g", "G", "m", "M", "r", "R", "s", "t", "T", "u", "U", "y", "Y"};
string format;
int formatIndex;
TestLibrary.TestFramework.BeginScenario("NegTest3: DateTime.ParseExact(<garbage>)");
try
{
for (int i=0; i<c_NUM_LOOPS; i++)
{
for(int j=0; j<c_STYLES.Length; j++)
{
try
{
formatIndex = TestLibrary.Generator.GetInt32(-55) % 34;
if (0 <= formatIndex && formatIndex < 17)
{
format = formats[formatIndex];
}
else
{
format = TestLibrary.Generator.GetChar(-55) + "";
}
strDateTime = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
dateAfter = DateTime.ParseExact(strDateTime, new string[] {format}, formater, c_STYLES[j]);
TestLibrary.TestFramework.LogError("033", "DateTime.ParseExact(" + strDateTime + ", "+ format + ", " + c_STYLES[j] + ") should have thrown (" + dateAfter + ")");
retVal = false;
}
catch (FormatException)
{
// expected
}
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("034", "Failing date: " + strDateTime);
TestLibrary.TestFramework.LogError("034", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
MyFormater formater = new MyFormater();
string dateBefore = "";
DateTime dateAfter;
string[] formats = null;
TestLibrary.TestFramework.BeginScenario("NegTest4: DateTime.ParseExact(DateTime.Now, null)");
try
{
dateBefore = DateTime.Now.ToString();
dateAfter = DateTime.ParseExact( dateBefore, formats, formater, DateTimeStyles.NoCurrentDateDefault );
TestLibrary.TestFramework.LogError("035", "DateTime.ParseExact(" + dateBefore + ", null, " + DateTimeStyles.NoCurrentDateDefault + ") should have thrown " + dateAfter.ToString());
retVal = false;
}
catch (System.ArgumentNullException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("036", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("036", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
public class MyFormater : IFormatProvider
{
public object GetFormat(Type formatType)
{
if (typeof(IFormatProvider) == formatType)
{
return this;
}
else
{
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Managed ACL wrapper for files & directories.
**
**
===========================================================*/
using Microsoft.Win32.SafeHandles;
using Microsoft.Win32;
using System.Collections;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Principal;
using System;
namespace System.Security.AccessControl
{
// Constants from from winnt.h - search for FILE_WRITE_DATA, etc.
[Flags]
public enum FileSystemRights
{
// No None field - An ACE with the value 0 cannot grant nor deny.
ReadData = 0x000001,
ListDirectory = ReadData, // For directories
WriteData = 0x000002,
CreateFiles = WriteData, // For directories
AppendData = 0x000004,
CreateDirectories = AppendData, // For directories
ReadExtendedAttributes = 0x000008,
WriteExtendedAttributes = 0x000010,
ExecuteFile = 0x000020, // For files
Traverse = ExecuteFile, // For directories
// DeleteSubdirectoriesAndFiles only makes sense on directories, but
// the shell explicitly sets it for files in its UI. So we'll include
// it in FullControl.
DeleteSubdirectoriesAndFiles = 0x000040,
ReadAttributes = 0x000080,
WriteAttributes = 0x000100,
Delete = 0x010000,
ReadPermissions = 0x020000,
ChangePermissions = 0x040000,
TakeOwnership = 0x080000,
// From the Core File Services team, CreateFile always requires
// SYNCHRONIZE access. Very tricksy, CreateFile is.
Synchronize = 0x100000, // Can we wait on the handle?
FullControl = 0x1F01FF,
// These map to what Explorer sets, and are what most users want.
// However, an ACL editor will also want to set the Synchronize
// bit when allowing access, and exclude the synchronize bit when
// denying access.
Read = ReadData | ReadExtendedAttributes | ReadAttributes | ReadPermissions,
ReadAndExecute = Read | ExecuteFile,
Write = WriteData | AppendData | WriteExtendedAttributes | WriteAttributes,
Modify = ReadAndExecute | Write | Delete,
}
public sealed class FileSystemAccessRule : AccessRule
{
#region Constructors
//
// Constructor for creating access rules for file objects
//
public FileSystemAccessRule(
IdentityReference identity,
FileSystemRights fileSystemRights,
AccessControlType type)
: this(
identity,
AccessMaskFromRights(fileSystemRights, type),
false,
InheritanceFlags.None,
PropagationFlags.None,
type)
{
}
public FileSystemAccessRule(
String identity,
FileSystemRights fileSystemRights,
AccessControlType type)
: this(
new NTAccount(identity),
AccessMaskFromRights(fileSystemRights, type),
false,
InheritanceFlags.None,
PropagationFlags.None,
type)
{
}
//
// Constructor for creating access rules for folder objects
//
public FileSystemAccessRule(
IdentityReference identity,
FileSystemRights fileSystemRights,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type)
: this(
identity,
AccessMaskFromRights(fileSystemRights, type),
false,
inheritanceFlags,
propagationFlags,
type)
{
}
public FileSystemAccessRule(
String identity,
FileSystemRights fileSystemRights,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type)
: this(
new NTAccount(identity),
AccessMaskFromRights(fileSystemRights, type),
false,
inheritanceFlags,
propagationFlags,
type)
{
}
//
// Internal constructor to be called by public constructors
// and the access rule factory methods of {File|Folder}Security
//
internal FileSystemAccessRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type)
: base(
identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
type)
{
}
#endregion
#region Public properties
public FileSystemRights FileSystemRights
{
get { return RightsFromAccessMask(base.AccessMask); }
}
#endregion
#region Access mask to rights translation
// ACL's on files have a SYNCHRONIZE bit, and CreateFile ALWAYS
// asks for it. So for allows, let's always include this bit,
// and for denies, let's never include this bit unless we're denying
// full control. This is the right thing for users, even if it does
// make the model look asymmetrical from a purist point of view.
internal static int AccessMaskFromRights(FileSystemRights fileSystemRights, AccessControlType controlType)
{
if (fileSystemRights < (FileSystemRights)0 || fileSystemRights > FileSystemRights.FullControl)
throw new ArgumentOutOfRangeException(nameof(fileSystemRights), SR.Format(SR.Argument_InvalidEnumValue, fileSystemRights, nameof(AccessControl.FileSystemRights)));
Contract.EndContractBlock();
if (controlType == AccessControlType.Allow)
{
fileSystemRights |= FileSystemRights.Synchronize;
}
else if (controlType == AccessControlType.Deny)
{
if (fileSystemRights != FileSystemRights.FullControl &&
fileSystemRights != (FileSystemRights.FullControl & ~FileSystemRights.DeleteSubdirectoriesAndFiles))
fileSystemRights &= ~FileSystemRights.Synchronize;
}
return (int)fileSystemRights;
}
internal static FileSystemRights RightsFromAccessMask(int accessMask)
{
return (FileSystemRights)accessMask;
}
#endregion
}
public sealed class FileSystemAuditRule : AuditRule
{
#region Constructors
public FileSystemAuditRule(
IdentityReference identity,
FileSystemRights fileSystemRights,
AuditFlags flags)
: this(
identity,
fileSystemRights,
InheritanceFlags.None,
PropagationFlags.None,
flags)
{
}
public FileSystemAuditRule(
IdentityReference identity,
FileSystemRights fileSystemRights,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags)
: this(
identity,
AccessMaskFromRights(fileSystemRights),
false,
inheritanceFlags,
propagationFlags,
flags)
{
}
public FileSystemAuditRule(
String identity,
FileSystemRights fileSystemRights,
AuditFlags flags)
: this(
new NTAccount(identity),
fileSystemRights,
InheritanceFlags.None,
PropagationFlags.None,
flags)
{
}
public FileSystemAuditRule(
String identity,
FileSystemRights fileSystemRights,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags)
: this(
new NTAccount(identity),
AccessMaskFromRights(fileSystemRights),
false,
inheritanceFlags,
propagationFlags,
flags)
{
}
internal FileSystemAuditRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags)
: base(
identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
flags)
{
}
#endregion
#region Private methods
private static int AccessMaskFromRights(FileSystemRights fileSystemRights)
{
if (fileSystemRights < (FileSystemRights)0 || fileSystemRights > FileSystemRights.FullControl)
throw new ArgumentOutOfRangeException(nameof(fileSystemRights), SR.Format(SR.Argument_InvalidEnumValue, fileSystemRights, nameof(AccessControl.FileSystemRights)));
Contract.EndContractBlock();
return (int)fileSystemRights;
}
#endregion
#region Public properties
public FileSystemRights FileSystemRights
{
get { return FileSystemAccessRule.RightsFromAccessMask(base.AccessMask); }
}
#endregion
}
public abstract class FileSystemSecurity : NativeObjectSecurity
{
#region Member variables
private const ResourceType s_ResourceType = ResourceType.FileObject;
#endregion
[System.Security.SecurityCritical] // auto-generated
internal FileSystemSecurity(bool isContainer)
: base(isContainer, s_ResourceType, _HandleErrorCode, isContainer)
{
}
[System.Security.SecurityCritical] // auto-generated
internal FileSystemSecurity(bool isContainer, String name, AccessControlSections includeSections, bool isDirectory)
: base(isContainer, s_ResourceType, name, includeSections, _HandleErrorCode, isDirectory)
{
}
[System.Security.SecurityCritical] // auto-generated
internal FileSystemSecurity(bool isContainer, SafeFileHandle handle, AccessControlSections includeSections, bool isDirectory)
: base(isContainer, s_ResourceType, handle, includeSections, _HandleErrorCode, isDirectory)
{
}
[System.Security.SecurityCritical] // auto-generated
private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context)
{
System.Exception exception = null;
switch (errorCode)
{
case Interop.Errors.ERROR_INVALID_NAME:
exception = new ArgumentException(SR.Argument_InvalidName, nameof(name));
break;
case Interop.Errors.ERROR_INVALID_HANDLE:
exception = new ArgumentException(SR.AccessControl_InvalidHandle);
break;
case Interop.Errors.ERROR_FILE_NOT_FOUND:
if ((context != null) && (context is bool) && ((bool)context))
{ // DirectorySecurity
if ((name != null) && (name.Length != 0))
exception = new DirectoryNotFoundException(name);
else
exception = new DirectoryNotFoundException();
}
else
{
if ((name != null) && (name.Length != 0))
exception = new FileNotFoundException(name);
else
exception = new FileNotFoundException();
}
break;
default:
break;
}
return exception;
}
#region Factories
public sealed override AccessRule AccessRuleFactory(
IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type)
{
return new FileSystemAccessRule(
identityReference,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
type);
}
public sealed override AuditRule AuditRuleFactory(
IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags)
{
return new FileSystemAuditRule(
identityReference,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
flags);
}
#endregion
#region Internal Methods
internal AccessControlSections GetAccessControlSectionsFromChanges()
{
AccessControlSections persistRules = AccessControlSections.None;
if (AccessRulesModified)
persistRules = AccessControlSections.Access;
if (AuditRulesModified)
persistRules |= AccessControlSections.Audit;
if (OwnerModified)
persistRules |= AccessControlSections.Owner;
if (GroupModified)
persistRules |= AccessControlSections.Group;
return persistRules;
}
[System.Security.SecurityCritical] // auto-generated
internal void Persist(String fullPath)
{
WriteLock();
try
{
AccessControlSections persistRules = GetAccessControlSectionsFromChanges();
base.Persist(fullPath, persistRules);
OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false;
}
finally
{
WriteUnlock();
}
}
[System.Security.SecuritySafeCritical] // auto-generated
internal void Persist(SafeFileHandle handle, String fullPath)
{
WriteLock();
try
{
AccessControlSections persistRules = GetAccessControlSectionsFromChanges();
base.Persist(handle, persistRules);
OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false;
}
finally
{
WriteUnlock();
}
}
#endregion
#region Public Methods
public void AddAccessRule(FileSystemAccessRule rule)
{
base.AddAccessRule(rule);
//PersistIfPossible();
}
public void SetAccessRule(FileSystemAccessRule rule)
{
base.SetAccessRule(rule);
}
public void ResetAccessRule(FileSystemAccessRule rule)
{
base.ResetAccessRule(rule);
}
public bool RemoveAccessRule(FileSystemAccessRule rule)
{
if (rule == null)
throw new ArgumentNullException(nameof(rule));
Contract.EndContractBlock();
// If the rule to be removed matches what is there currently then
// remove it unaltered. That is, don't mask off the Synchronize bit.
// This is to avoid dangling synchronize bit
AuthorizationRuleCollection rules = GetAccessRules(true, true, rule.IdentityReference.GetType());
for (int i = 0; i < rules.Count; i++)
{
FileSystemAccessRule fsrule = rules[i] as FileSystemAccessRule;
if ((fsrule != null) && (fsrule.FileSystemRights == rule.FileSystemRights)
&& (fsrule.IdentityReference == rule.IdentityReference)
&& (fsrule.AccessControlType == rule.AccessControlType))
{
return base.RemoveAccessRule(rule);
}
}
// Mask off the synchronize bit (that is automatically added for Allow)
// before removing the ACL. The logic here should be same as Deny and hence
// fake a call to AccessMaskFromRights as though the ACL is for Deny
FileSystemAccessRule ruleNew = new FileSystemAccessRule(
rule.IdentityReference,
FileSystemAccessRule.AccessMaskFromRights(rule.FileSystemRights, AccessControlType.Deny),
rule.IsInherited,
rule.InheritanceFlags,
rule.PropagationFlags,
rule.AccessControlType);
return base.RemoveAccessRule(ruleNew);
}
public void RemoveAccessRuleAll(FileSystemAccessRule rule)
{
// We don't need to worry about the synchronize bit here
// AccessMask is ignored anyways in a RemoveAll call
base.RemoveAccessRuleAll(rule);
}
public void RemoveAccessRuleSpecific(FileSystemAccessRule rule)
{
if (rule == null)
throw new ArgumentNullException(nameof(rule));
Contract.EndContractBlock();
// If the rule to be removed matches what is there currently then
// remove it unaltered. That is, don't mask off the Synchronize bit
// This is to avoid dangling synchronize bit
AuthorizationRuleCollection rules = GetAccessRules(true, true, rule.IdentityReference.GetType());
for (int i = 0; i < rules.Count; i++)
{
FileSystemAccessRule fsrule = rules[i] as FileSystemAccessRule;
if ((fsrule != null) && (fsrule.FileSystemRights == rule.FileSystemRights)
&& (fsrule.IdentityReference == rule.IdentityReference)
&& (fsrule.AccessControlType == rule.AccessControlType))
{
base.RemoveAccessRuleSpecific(rule);
return;
}
}
// Mask off the synchronize bit (that is automatically added for Allow)
// before removing the ACL. The logic here should be same as Deny and hence
// fake a call to AccessMaskFromRights as though the ACL is for Deny
FileSystemAccessRule ruleNew = new FileSystemAccessRule(
rule.IdentityReference,
FileSystemAccessRule.AccessMaskFromRights(rule.FileSystemRights, AccessControlType.Deny),
rule.IsInherited,
rule.InheritanceFlags,
rule.PropagationFlags,
rule.AccessControlType);
base.RemoveAccessRuleSpecific(ruleNew);
}
public void AddAuditRule(FileSystemAuditRule rule)
{
base.AddAuditRule(rule);
}
public void SetAuditRule(FileSystemAuditRule rule)
{
base.SetAuditRule(rule);
}
public bool RemoveAuditRule(FileSystemAuditRule rule)
{
return base.RemoveAuditRule(rule);
}
public void RemoveAuditRuleAll(FileSystemAuditRule rule)
{
base.RemoveAuditRuleAll(rule);
}
public void RemoveAuditRuleSpecific(FileSystemAuditRule rule)
{
base.RemoveAuditRuleSpecific(rule);
}
#endregion
#region some overrides
public override Type AccessRightType
{
get { return typeof(System.Security.AccessControl.FileSystemRights); }
}
public override Type AccessRuleType
{
get { return typeof(System.Security.AccessControl.FileSystemAccessRule); }
}
public override Type AuditRuleType
{
get { return typeof(System.Security.AccessControl.FileSystemAuditRule); }
}
#endregion
}
public sealed class FileSecurity : FileSystemSecurity
{
#region Constructors
[System.Security.SecuritySafeCritical] // auto-generated
public FileSecurity()
: base(false)
{
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileSecurity(String fileName, AccessControlSections includeSections)
: base(false, fileName, includeSections, false)
{
String fullPath = Path.GetFullPath(fileName);
}
// Warning! Be exceedingly careful with this constructor. Do not make
// it public. We don't want to get into a situation where someone can
// pass in the string foo.txt and a handle to bar.exe, and we do a
// demand on the wrong file name.
[System.Security.SecurityCritical] // auto-generated
internal FileSecurity(SafeFileHandle handle, String fullPath, AccessControlSections includeSections)
: base(false, handle, includeSections, false)
{
}
#endregion
}
public sealed class DirectorySecurity : FileSystemSecurity
{
#region Constructors
[System.Security.SecuritySafeCritical] // auto-generated
public DirectorySecurity()
: base(true)
{
}
[System.Security.SecuritySafeCritical] // auto-generated
public DirectorySecurity(String name, AccessControlSections includeSections)
: base(true, name, includeSections, true)
{
String fullPath = Path.GetFullPath(name);
}
#endregion
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Created by Alex Maitland, maitlandalex@gmail.com */
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Google.GData.Analytics;
using Google.GData.Client;
using Google.GData.Client.LiveTests;
using Google.GData.Client.UnitTests;
using Google.Analytics;
using NUnit.Framework;
namespace Google.GData.Client.UnitTests.Analytics
{
[TestFixture, Category("Analytics")]
public class AnalyticsDataServiceTest : BaseLiveTestClass
{
private const string DataFeedUrl = "http://www.google.com/analytics/feeds/data";
private const string AccountFeedUrl = "http://www.google.com/analytics/feeds/accounts/default";
private string accountId;
private TestContext TestContext1;
protected override void ReadConfigFile()
{
base.ReadConfigFile();
if (unitTestConfiguration.Contains("analyticsUserName"))
{
this.userName = (string)unitTestConfiguration["analyticsUserName"];
Tracing.TraceInfo("Read userName value: " + this.userName);
}
if (unitTestConfiguration.Contains("analyticsPassWord"))
{
this.passWord = (string)unitTestConfiguration["analyticsPassWord"];
Tracing.TraceInfo("Read passWord value: " + this.passWord);
}
if (unitTestConfiguration.Contains("accountId"))
{
this.accountId = (string)unitTestConfiguration["accountId"];
Tracing.TraceInfo("Read accountId value: " + this.accountId);
}
}
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get { return TestContext1; }
set { TestContext1 = value; }
}
[Test]
public void QueryAccountIds()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
AccountQuery feedQuery = new AccountQuery(AccountFeedUrl);
AccountFeed actual = service.Query(feedQuery);
foreach (AccountEntry entry in actual.Entries)
{
Assert.IsNotNull(entry.Id);
Assert.IsNotNull(entry.ProfileId.Value);
if (this.accountId == null)
this.accountId = entry.ProfileId.Value;
}
}
[Test]
public void QueryBrowserMetrics()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Metrics = "ga:pageviews";
query.Dimensions = "ga:browser";
query.Sort = "ga:browser,ga:pageviews";
query.GAStartDate = DateTime.Now.AddDays(-14).ToString("yyyy-MM-dd");
query.GAEndDate = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");
query.NumberToRetrieve = 200;
DataFeed actual = service.Query(query);
XmlTextWriter writer = new XmlTextWriter("QueryBrowserMetricsOutput.xml", Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
actual.SaveToXml(writer);
foreach (DataEntry entry in actual.Entries)
{
Assert.IsNotNull(entry.Id);
}
}
[Test]
public void QueryProductCategoryResultForPeriod()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Dimensions = "ga:productCategory,ga:productName";
query.Metrics = "ga:itemRevenue,ga:itemQuantity";
query.Sort = "ga:productCategory";
query.GAStartDate = new DateTime(2009, 04, 19).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 25).ToString("yyyy-MM-dd");
DataFeed actual = service.Query(query);
Assert.IsNotNull(actual);
Assert.IsNotNull(actual.Entries);
foreach(DataEntry entry in actual.Entries)
{
Assert.AreEqual(2, entry.Dimensions.Count);
Assert.IsNotNull(entry.Dimensions[0]);
Assert.IsNotNull(entry.Dimensions[0].Name);
Assert.IsNotNull(entry.Dimensions[0].Value);
Assert.IsNotNull(entry.Dimensions[1]);
Assert.IsNotNull(entry.Dimensions[1].Name);
Assert.IsNotNull(entry.Dimensions[1].Value);
Assert.AreEqual(2, entry.Metrics.Count);
Assert.IsNotNull(entry.Metrics[0]);
Assert.IsNotNull(entry.Metrics[0].Name);
Assert.IsNotNull(entry.Metrics[0].Value);
Assert.IsNotNull(entry.Metrics[1]);
Assert.IsNotNull(entry.Metrics[1].Name);
Assert.IsNotNull(entry.Metrics[1].Value);
}
}
[Test]
public void QueryVisitorsResultForPeriod()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Metrics = "ga:visitors";
query.GAStartDate = new DateTime(2009, 04, 19).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 25).ToString("yyyy-MM-dd");
query.StartIndex = 1;
DataFeed actual = service.Query(query);
Assert.IsNotNull(actual.Aggregates);
Assert.AreEqual(1, actual.Aggregates.Metrics.Count);
}
[Test]
public void QuerySiteStatsResultForPeriod()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Metrics = "ga:pageviews,ga:visits,ga:newVisits,ga:transactions,ga:uniquePageviews";
query.GAStartDate = new DateTime(2009, 04, 19).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 25).ToString("yyyy-MM-dd");
query.StartIndex = 1;
DataFeed actual = service.Query(query);
Assert.IsNotNull(actual.Aggregates);
Assert.AreEqual(5, actual.Aggregates.Metrics.Count);
}
[Test]
public void QueryTransactionIdReturnAllResults()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
int currentIndex = 1;
const int resultsPerPage = 1000;
List<DataFeed> querys = new List<DataFeed>();
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Dimensions = "ga:transactionId,ga:date";
query.Metrics = "ga:transactionRevenue";
query.Sort = "ga:date";
query.GAStartDate = new DateTime(2009, 04, 01).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 30).ToString("yyyy-MM-dd");
query.NumberToRetrieve = resultsPerPage;
query.StartIndex = currentIndex;
DataFeed actual = service.Query(query);
querys.Add(actual);
double totalPages = Math.Round(((double)actual.TotalResults / (double)resultsPerPage) + 0.5);
for (int i = 1; i < totalPages; i++)
{
currentIndex += resultsPerPage;
query.StartIndex = currentIndex;
actual = service.Query(query);
querys.Add(actual);
}
for (int i = 0; i < querys.Count; i++)
{
foreach (DataEntry entry in querys[i].Entries)
{
Assert.IsNotNull(entry.Id);
}
}
}
[Test]
public void QueryTransactionIdReturn200Results()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Dimensions = "ga:transactionId,ga:date";
query.Metrics = "ga:transactionRevenue";
query.Sort = "ga:date";
query.GAStartDate = new DateTime(2009, 04, 01).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 30).ToString("yyyy-MM-dd");
query.NumberToRetrieve = 200;
DataFeed actual = service.Query(query);
Assert.AreEqual(200, actual.ItemsPerPage);
Assert.IsNotNull(actual.Aggregates);
Assert.AreEqual(1, actual.Aggregates.Metrics.Count);
foreach (DataEntry entry in actual.Entries)
{
Assert.IsNotNull(entry.Id);
}
}
[Test]
public void QueryPageViews()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Metrics = "ga:pageviews";
query.Dimensions = "ga:pageTitle";
query.Sort = "-ga:pageviews";
query.GAStartDate = DateTime.Now.AddDays(-14).ToString("yyyy-MM-dd");
query.GAEndDate = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");
query.NumberToRetrieve = 200;
DataFeed actual = service.Query(query);
Assert.IsNotNull(actual.Aggregates);
Assert.AreEqual(1, actual.Aggregates.Metrics.Count);
foreach (DataEntry entry in actual.Entries)
{
Assert.IsNotNull(entry.Id);
}
}
[Test]
public void TestAnalyticsModel()
{
RequestSettings settings = new RequestSettings("Unittests", this.userName, this.passWord);
AnalyticsRequest request = new AnalyticsRequest(settings);
Feed<Account> accounts = request.GetAccounts();
foreach (Account a in accounts.Entries)
{
Assert.IsNotNull(a.AccountId);
Assert.IsNotNull(a.ProfileId);
Assert.IsNotNull(a.WebPropertyId);
if (this.accountId == null)
this.accountId = a.TableId;
}
DataQuery q = new DataQuery(this.accountId, DateTime.Now.AddDays(-14), DateTime.Now.AddDays(-2), "ga:pageviews", "ga:pageTitle", "ga:pageviews");
Dataset set = request.Get(q);
foreach (Data d in set.Entries)
{
Assert.IsNotNull(d.Id);
Assert.IsNotNull(d.Metrics);
Assert.IsNotNull(d.Dimensions);
}
}
}
}
| |
using System.Collections.Generic;
using HipchatApiV2.Enums;
using HipchatApiV2.Requests;
using HipchatApiV2.Responses;
namespace HipchatApiV2
{
public interface IHipchatClient
{
/// <summary>
/// Get room details
/// </summary>
/// <param name="roomId">The id of the room</param>
/// <remarks>
/// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/get_room
/// </remarks>
HipchatGetRoomResponse GetRoom(int roomId);
/// <summary>
/// Get room details
/// </summary>
/// <param name="roomName">The name of the room. Valid length 1-100</param>
/// <remarks>
/// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/get_room
/// </remarks>
HipchatGetRoomResponse GetRoom(string roomName);
/// <summary>
/// Gets an OAuth token for requested grant type.
/// </summary>
/// <param name="grantType">The type of grant request</param>
/// <param name="scopes">List of scopes that is requested</param>
/// <param name="username">The user name to generate a token on behalf of. Only valid in
/// the 'Password' and 'ClientCredentials' grant types.</param>
/// <param name="code">The authorization code to exchange for an access token. Only valid in the 'AuthorizationCode' grant type</param>
/// <param name="redirectUri">The Url that was used to generate an authorization code, and it must match that value. Only valid in the 'AuthorizationCode' grant.</param>
/// <param name="password">The user's password to use for authentication when creating a token. Only valid in the 'Password' grant.</param>
/// <param name="refreshToken">The refresh token to use to generate a new access token. Only valid in the 'RefreshToken' grant.</param>
HipchatGenerateTokenResponse GenerateToken(
GrantType grantType,
IEnumerable<TokenScope> scopes,
string username = null,
string code = null,
string redirectUri = null,
string password = null,
string refreshToken = null);
/// <summary>
/// Sends a user a private message.
/// </summary>
/// <param name="idOrEmailOrMention">The id, email address, or mention name (beginning with an '@') of the user to send a message to.</param>
/// <param name="message">The message body. Valid length range: 1 - 10000.</param>
/// <param name="notify">Whether this message should trigger a user notification (change the tab color, play a sound, notify mobile phones, etc). Each recipient's notification preferences are taken into account.</param>
/// <param name="messageFormat">Determines how the message is treated by our server and rendered inside HipChat applications</param>
/// <remarks>
/// Auth required with scope 'send_message'. https://www.hipchat.com/docs/apiv2/method/private_message_user
/// </remarks>
void PrivateMessageUser(string idOrEmailOrMention, string message, bool notify = false,
HipchatMessageFormat messageFormat = HipchatMessageFormat.Text);
/// <summary>
/// Get emoticon details
/// </summary>
/// <param name="id">The emoticon id</param>
/// <returns>the emoticon details</returns>
/// <remarks>
/// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/get_emoticon
/// </remarks>
HipchatGetEmoticonResponse GetEmoticon(int id = 0);
/// <summary>
/// Get emoticon details
/// </summary>
/// <param name="shortcut">The emoticon shortcut</param>
/// <returns>the emoticon details</returns>
/// <remarks>
/// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/get_emoticon
/// </remarks>
HipchatGetEmoticonResponse GetEmoticon(string shortcut = "");
/// <summary>
/// Gets all emoticons for the current group
/// </summary>
/// <param name="startIndex">The start index for the result set</param>
/// <param name="maxResults">The maximum number of results</param>
/// <param name="type">The type of emoticons to get</param>
/// <returns>the matching set of emoticons</returns>
/// <remarks>
/// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/get_all_emoticons
/// </remarks>
HipchatGetAllEmoticonsResponse GetAllEmoticons(int startIndex = 0, int maxResults = 100, EmoticonType type = EmoticonType.All);
HipchatGetAllUsersResponse GetAllUsers(int startIndex = 0, int maxResults = 100, bool includeGuests = false,
bool includeDeleted = false);
/// <summary>
/// Gets information about the requested user
/// </summary>
/// <param name="emailOrMentionName">The users email address or mention name beginning with @</param>
/// <returns>an object with information about the user</returns>
/// <remarks>
/// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/view_user
/// </remarks>
HipchatGetUserInfoResponse GetUserInfo(string emailOrMentionName);
/// <summary>
/// Gets information about the requested user
/// </summary>
/// <param name="userId">The integer Id of the user</param>
/// <returns>an object with information about the user</returns>
/// <remarks>
/// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/view_user
/// </remarks>
HipchatGetUserInfoResponse GetUserInfo(int userId);
/// <summary>
/// Updates a room
/// </summary>
/// <param name="roomId">The room id</param>
/// <param name="request">The request to send</param>
/// <returns>true if the call was successful</returns>
/// <remarks>
/// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/update_room
/// </remarks>
bool UpdateRoom(int roomId, UpdateRoomRequest request);
/// <summary>
/// Updates a room
/// </summary>
/// <param name="roomName">The room name</param>
/// <param name="request">The request to send</param>
/// <returns>true if the call was successful</returns>
/// <remarks>
/// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/update_room
/// </remarks>
bool UpdateRoom(string roomName, UpdateRoomRequest request);
/// <summary>
/// Creates a webhook
/// </summary>
/// <param name="roomId">the id of the room</param>
/// <param name="url">the url to send the webhook POST to</param>
/// <param name="pattern">optional regex pattern to match against messages. Only applicable for message events</param>
/// <param name="eventType">The event to listen for</param>
/// <param name="name">label for this webhook</param>
/// <remarks>
/// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/create_webhook
/// </remarks>
CreateWebHookResponse CreateWebHook(int roomId, string url, string pattern, RoomEvent eventType, string name);
/// <summary>
/// Creates a webhook
/// </summary>
/// <param name="roomName">the name of the room</param>
/// <param name="url">the url to send the webhook POST to</param>
/// <param name="pattern">optional regex pattern to match against messages. Only applicable for message events</param>
/// <param name="eventType">The event to listen for</param>
/// <param name="name">label for this webhook</param>
/// <remarks>
/// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/create_webhook
/// </remarks>
CreateWebHookResponse CreateWebHook(string roomName, string url, string pattern, RoomEvent eventType, string name);
/// <summary>
/// Creates a webhook
/// </summary>
/// <param name="roomName">the name of the room</param>
/// <param name="request">the request to send</param>
/// <remarks>
/// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/create_webhook
/// </remarks>
CreateWebHookResponse CreateWebHook(string roomName, CreateWebHookRequest request);
/// <summary>
/// Creates a new room
/// </summary>
/// <param name="nameOfRoom">Name of the room. Valid Length 1-50</param>
/// <param name="guestAccess">Whether or not to enable guest access for this room</param>
/// <param name="ownerUserId">The id, email address, or mention name (beginning with an '@') of
/// the room's owner. Defaults to the current user.</param>
/// <param name="privacy">Whether the room is available for access by other users or not</param>
/// <returns>response containing id and link of the created room</returns>
/// <remarks>
/// Auth required with scope 'manage_rooms'. https://api.hipchat.com/v2/room
/// </remarks>
HipchatCreateRoomResponse CreateRoom(string nameOfRoom, bool guestAccess = false, string ownerUserId = null,
RoomPrivacy privacy = RoomPrivacy.Public);
/// <summary>
/// Creates a new room
/// </summary>
/// <returns>response containing id and link of the created room</returns>
/// <remarks>
/// Auth required with scope 'manage_rooms'. https://api.hipchat.com/v2/room
/// </remarks>
HipchatCreateRoomResponse CreateRoom(CreateRoomRequest request);
/// <summary>
/// Send a message to a room
/// </summary>
/// <param name="roomId">The id of the room</param>
/// <param name="message">message to send</param>
/// <param name="backgroundColor">the background color of the message, only applicable to html format message</param>
/// <param name="notify">if the message should notify</param>
/// <param name="messageFormat">the format of the message</param>
/// <returns>true if the message was sucessfully sent</returns>
/// <remarks>
/// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/send_room_notification
/// </remarks>
bool SendNotification(int roomId, string message, RoomColors backgroundColor = RoomColors.Yellow,
bool notify = false, HipchatMessageFormat messageFormat = HipchatMessageFormat.Html);
/// <summary>
/// Send a message to a room
/// </summary>
/// <param name="roomName">The name of the room</param>
/// <param name="message">message to send</param>
/// <param name="backgroundColor">the background color of the message, only applicable to html format message</param>
/// <param name="notify">if the message should notify</param>
/// <param name="messageFormat">the format of the message</param>
/// <returns>true if the message was sucessfully sent</returns>
/// <remarks>
/// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/send_room_notification
/// </remarks>
bool SendNotification(string roomName, string message, RoomColors backgroundColor = RoomColors.Yellow,
bool notify = false, HipchatMessageFormat messageFormat = HipchatMessageFormat.Html);
/// <summary>
/// Send a message to a room
/// </summary>
/// <param name="roomId">The id of the room</param>
/// <param name="request">The request containing the info about the notification to send</param>
/// <returns>true if the message successfully sent</returns>
/// <remarks>
/// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/send_room_notification
/// </remarks>
bool SendNotification(int roomId, SendRoomNotificationRequest request);
/// <summary>
/// Send a message to a room
/// </summary>
/// <param name="roomName">The id of the room</param>
/// <param name="request">The request containing the info about the notification to send</param>
/// <returns>true if the message successfully sent</returns>
/// <remarks>
/// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/send_room_notification
/// </remarks>
bool SendNotification(string roomName, SendRoomNotificationRequest request);
/// <summary>
/// Share a file with a room
/// </summary>
/// <param name="roomName">The id or name of the room</param>
/// <param name="fileFullPath">The full path of the file.</param>
/// <param name="message">The optional message.</param>
/// <returns>
/// true if the file was successfully shared
/// </returns>
/// <remarks>
/// Auth required with scope 'send_message'. https://www.hipchat.com/docs/apiv2/method/share_file_with_room
/// </remarks>
bool ShareFileWithRoom(string roomName, string fileFullPath, string message = null);
/// <summary>
/// Delets a room and kicks the current particpants.
/// </summary>
/// <param name="roomId">Id of the room.</param>
/// <returns>true if the room was successfully deleted</returns>
/// <remarks>
/// Authentication required with scope 'manage_rooms'. https://www.hipchat.com/docs/apiv2/method/delete_room
/// </remarks>
bool DeleteRoom(int roomId);
/// <summary>
/// Delets a room and kicks the current particpants.
/// </summary>
/// <param name="roomName">Name of the room.</param>
/// <returns>true if the room was successfully deleted</returns>
/// <remarks>
/// Authentication required with scope 'manage_rooms'. https://www.hipchat.com/docs/apiv2/method/delete_room
/// </remarks>
bool DeleteRoom(string roomName);
/// <summary>
/// List non-archived rooms for this group
/// </summary>
/// <param name="startIndex">The start index for the result set</param>
/// <param name="maxResults">The maximum number of results. Valid length 0-100</param>
/// <param name="includeArchived">Filter rooms</param>
/// <returns>A HipchatGetAllRoomsResponse</returns>
/// <remarks>
/// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/get_all_rooms
/// </remarks>
HipchatGetAllRoomsResponse GetAllRooms(int startIndex = 0, int maxResults = 100, bool includePrivate = false, bool includeArchived = false);
/// <summary>
/// Fetch chat history for this room
/// </summary>
/// <param name="roomName">Name of the room.</param>
/// <param name="date">Either the latest date to fetch history for in ISO-8601 format, or 'recent' to fetch the latest 75 messages. Note, paging isn't supported for 'recent', however they are real-time values, whereas date queries may not include the most recent messages.</param>
/// <param name="timezone">Your timezone. Must be a supported timezone name, please see wikipedia TZ database page.</param>
/// <param name="startIndex">The start index for the result set</param>
/// <param name="maxResults">The maximum number of results. Valid length 0-100</param>
/// <param name="reverse">Reverse the output such that the oldest message is first. For consistent paging, set to <c>false</c>.</param>
/// <returns>
/// A HipchatGetAllRoomsResponse
/// </returns>
/// <exception cref="System.ArgumentOutOfRangeException">
/// roomName;Valid roomName length is 1-100.
/// or
/// date;Valid date should be passed.
/// or
/// timezone;Valid timezone should be passed.
/// or
/// startIndex;startIndex must be between 0 and 100
/// or
/// maxResults;maxResults must be between 0 and 1000
/// </exception>
/// <remarks>
/// Authentication required, with scope view_group, view_messages. https://www.hipchat.com/docs/apiv2/method/view_room_history
/// </remarks>
HipchatViewRoomHistoryResponse ViewRoomHistory(string roomName, string date = "recent", string timezone = "UTC", int startIndex = 0, int maxResults = 100, bool reverse = true);
/// <summary>
/// Fetch latest chat history for this room
/// </summary>
/// <param name="roomName">Name of the room.</param>
/// <param name="notBefore">The id of the message that is oldest in the set of messages to be returned. The server will not return any messages that chronologically precede this message.</param>
/// <param name="timezone">Your timezone. Must be a supported timezone name, please see wikipedia TZ database page.</param>
/// <param name="startIndex">The start index for the result set</param>
/// <param name="maxResults">The maximum number of results. Valid length 0-100</param>
/// <returns>
/// A HipchatGetAllRoomsResponse
/// </returns>
/// <exception cref="System.ArgumentOutOfRangeException">
/// roomName;Valid roomName length is 1-100.
/// or
/// timezone;Valid timezone should be passed.
/// or
/// startIndex;startIndex must be between 0 and 100
/// or
/// maxResults;maxResults must be between 0 and 1000
/// </exception>
/// <remarks>
/// Authentication required, with scope view_messages. https://www.hipchat.com/docs/apiv2/method/view_recent_room_history
/// </remarks>
HipchatViewRoomHistoryResponse ViewRecentRoomHistory(string roomName, string notBefore = "", string timezone = "UTC", int startIndex = 0, int maxResults = 100);
/// <summary>
/// Gets all webhooks for this room
/// </summary>
/// <param name="roomName">The name of the room</param>
/// <param name="startIndex">The start index for the result set</param>
/// <param name="maxResults">The maximum number of results</param>
/// <returns>A GetAllWebhooks Response</returns>
/// <remarks>
/// Auth required, with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/get_all_webhooks
/// </remarks>
HipchatGetAllWebhooksResponse GetAllWebhooks(string roomName, int startIndex = 0, int maxResults = 0);
/// <summary>
/// Gets all webhooks for this room
/// </summary>
/// <param name="roomId">The id of the room</param>
/// <param name="startIndex">The start index for the result set</param>
/// <param name="maxResults">The maximum number of results</param>
/// <returns>A GetAllWebhooks Response</returns>
/// <remarks>
/// Auth required, with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/get_all_webhooks
/// </remarks>
HipchatGetAllWebhooksResponse GetAllWebhooks(int roomId, int startIndex = 0, int maxResults = 0);
/// <summary>
/// Deletes a webhook
/// </summary>
/// <param name="roomName">The name of the room</param>
/// <param name="webHookId">The id of the webhook</param>
/// <returns>true if the request was successful</returns>
/// <remarks>
/// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/delete_webhook
/// </remarks>
bool DeleteWebhook(string roomName, int webHookId);
/// <summary>
/// Deletes a webhook
/// </summary>
/// <param name="roomId">The id of the room</param>
/// <param name="webHookId">The id of the webhook</param>
/// <returns>true if the request was successful</returns>
/// <remarks>
/// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/delete_webhook
/// </remarks>
bool DeleteWebhook(int roomId, int webHookId);
/// <summary>
/// Set a room's topic. Useful for displaying statistics, important links, server status, you name it!
/// </summary>
/// <param name="roomName">The name of the room</param>
/// <param name="topic">The topic body. (Valid length 0 - 250)</param>
/// <returns>true if the call succeeded. There may be slight delay before topic change appears in the room </returns>
/// <remarks>
/// Auth required with scope 'admin_room'.
/// https://www.hipchat.com/docs/apiv2/method/set_topic
/// </remarks>
bool SetTopic(string roomName, string topic);
/// <summary>
/// Set a room's topic. Useful for displaying statistics, important links, server status, you name it!
/// </summary>
/// <param name="roomId">The id of the room</param>
/// <param name="topic">The topic body. (Valid length 0 - 250)</param>
/// <returns>true if the call succeeded. There may be slight delay before topic change appears in the room </returns>
/// <remarks>
/// Auth required with scope 'admin_room'.
/// https://www.hipchat.com/docs/apiv2/method/set_topic
/// </remarks>
bool SetTopic(int roomId, string topic);
/// <summary>
/// Create a new user
/// </summary>
/// <returns>A HipchatCreateUserReponse</returns>
/// <remarks>
/// Auth required with scope 'admin_group'. https://www.hipchat.com/docs/apiv2/method/create_user
/// </remarks>
HipchatCreateUserResponse CreateUser(CreateUserRequest request);
/// <summary>
/// Update a user. A guest cannot be updated.
/// </summary>
/// <param name="idOrEmail">The id, email address, or mention name (beginning with an '@') of the user to update.</param>
/// <param name="request">The request.</param>
/// <returns>true if the call succeeded. </returns>
/// <remarks>
/// Auth required with scope 'admin_group'. https://www.hipchat.com/docs/apiv2/method/update_user
/// Changing a user's name or admin status will cause them to be briefly disconnected.
/// Only works on non-deleted users
/// Any missing fields will be treated as deleted, so it is recommended to get the user, modify what you need, then call this resource to update
/// As communicated by the HipChat support the presence object cannot be updated using this API.
/// </remarks>
bool UpdateUser(string idOrEmail, UpdateUserRequest request);
/// <summary>
/// Delete a user
/// </summary>
/// <param name="idOrEmail">The id, email address, or mention name (beginning with an '@') of the user to delete.</param>
/// <returns>A HipchatDeleteUserReponse</returns>
/// <remarks>
/// Auth required with scope 'admin_group'. https://api.hipchat.com/v2/user/{id_or_email}
/// </remarks>
bool DeleteUser(string idOrEmail);
/// <summary>
/// Add a member to a private room
/// </summary>
/// <param name="roomName">The name of the room</param>
/// <param name="idOrEmail">The id, email address, or mention name (beginning with an '@') of the user to delete.</param>
/// <returns>true if the call succeeded. </returns>
/// <remarks>
/// Auth required with scope 'admin_room'.
/// https://www.hipchat.com/docs/apiv2/method/add_member
/// </remarks>
bool AddMember(string roomName, string idOrEmail);
/// <summary>
/// Update a user photo
/// </summary>
/// <param name="idOrEmail">The id, email address, or mention name (beginning with an '@') of the user to delete.</param>
/// <param name="photo"> Base64 string of the photo</param>
/// <returns>true if the call succeeded. </returns>
/// <remarks>
/// Auth required with scope 'admin_room'.
/// https://www.hipchat.com/docs/apiv2/method/update_photo
/// </remarks>
bool UpdatePhoto(string idOrEmail, string photo);
}
}
| |
/// <summary>
/// Copyright 2008 - 2012
/// 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.
/// </summary>
///
/// @project loon
/// @email javachenpeng@yahoo.com
namespace Loon.Utils.Collection {
public class ArrayList {
private object[] _items;
private bool _full;
private int _size;
public ArrayList():this(CollectionUtils.INITIAL_CAPACITY) {
}
public ArrayList(int length) {
this._items = new object[length + (length / 2)];
this._full = false;
this._size = length;
}
public void AddAll(ArrayList array) {
AddAll(array, 0, array._size);
}
public void AddAll(ArrayList array, int offset, int length) {
if (offset + length > array._size) {
throw new System.ArgumentException(
"offset + length must be <= size: " + offset + " + "
+ length + " <= " + array._size);
}
AddAll(array._items, offset, length);
}
public void AddAll(object[] array, int offset, int length) {
object[] items = this._items;
int sizeNeeded = _size + length;
if (sizeNeeded > items.Length) {
items = ExpandCapacity(MathUtils.Max(8, (_size + 1) * 2));
}
System.Array.Copy(array,offset,items,_size,length);
_size += length;
}
public void Add(int index, object element) {
if (index >= this._items.Length) {
object[] items = this._items;
if (_size == items.Length) {
items = ExpandCapacity(MathUtils.Max(8, (_size + 1) * 2));
}
} else {
this._items[index] = element;
}
this._size++;
}
public void Add(object element) {
if (this._full) {
object[] items = this._items;
if (_size == items.Length) {
items = ExpandCapacity(MathUtils.Max(8, (_size + 1) * 2));
}
items[_size] = element;
} else {
int size = this._items.Length;
for (int i = 0; i < size; i++) {
if (this._items[i] == null) {
this._items[i] = element;
if (i == size - 1) {
this._full = true;
}
break;
}
}
}
this._size++;
}
private object[] ExpandCapacity(int newSize) {
object[] items = this._items;
object[] obj = (object[]) System.Array.CreateInstance(items
.GetType().GetElementType(),newSize);
System.Array.Copy((items),0,(obj),0,MathUtils.Min(_size, obj.Length));
this._items = obj;
return obj;
}
public virtual object Clone() {
return this;
}
public bool Contains(object elem) {
for (int i = 0; i < this._items.Length; i++) {
if (this._items[i].Equals(elem)) {
return true;
}
}
return false;
}
public object Set(int index, object value_ren) {
if (index >= _size) {
throw new System.IndexOutOfRangeException(index.ToString());
}
object old = this._items[index];
_items[index] = value_ren;
return old;
}
public object Get(int index) {
if (index >= _size) {
throw new System.IndexOutOfRangeException(index.ToString());
}
return this._items[index];
}
public override int GetHashCode()
{
return base.GetHashCode() + _size;
}
public void Swap(int first, int second) {
if (first >= _size) {
throw new System.IndexOutOfRangeException(first.ToString().ToString());
}
if (second >= _size) {
throw new System.IndexOutOfRangeException(second.ToString().ToString());
}
object[] items = this._items;
object firstValue = items[first];
items[first] = items[second];
items[second] = firstValue;
}
public int IndexOf(object elem) {
for (int i = 0; i < this._items.Length; i++) {
if (this._items[i].Equals(elem)) {
return i;
}
}
return -1;
}
public int IndexOfIdenticalObject(object elem)
{
for (int i = 0; i < this._items.Length; i++)
{
if (this._items[i] == elem)
{
return i;
}
}
return -1;
}
public bool IsEmpty() {
if (this._size == 0) {
return true;
} else {
return false;
}
}
public int LastIndexOf(object elem) {
for (int i = this._items.Length - 1; i >= 0; i--) {
if (this._items[i].Equals(elem)) {
return i;
}
}
return -1;
}
public bool Remove(object value)
{
return Remove(value, false);
}
public bool Remove(object value, bool identity)
{
object[] items = this._items;
if (identity || value == null)
{
for (int i = 0; i < _size; i++)
{
if (items[i] == value)
{
Remove(i);
return true;
}
}
}
else
{
for (int i = 0; i < _size; i++)
{
if (value.Equals(items[i]))
{
Remove(i);
return true;
}
}
}
return false;
}
public object Remove(int index) {
if (index >= _size) {
throw new System.IndexOutOfRangeException(index.ToString());
}
object[] items = this._items;
object elem = items[index];
_size--;
System.Array.Copy((_items),index + 1,(_items),index,_size - index);
items[_size] = null;
return elem;
}
public void RemoveRange(int fromIndex, int toIndex) {
for (int i = fromIndex; i <= toIndex; i++) {
this.Remove(fromIndex);
}
}
public override bool Equals(object obj0) {
if (obj0 == (object) this) {
return true;
}
if (!(obj0 is ArrayList)) {
return false;
}
ArrayList array = (ArrayList) obj0;
int n = _size;
if (n != array._size) {
return false;
}
object[] items1 = this._items;
object[] items2 = array._items;
for (int i = 0; i < n; i++) {
object o1 = items1[i];
object o2 = items2[i];
if (!((o1 == null) ? o2 == null : o1.Equals(o2))) {
return false;
}
}
return true;
}
public object Last() {
return _items[(_size < 1) ? 0 : _size - 1];
}
public object First() {
return _items[0];
}
public object Pop() {
--_size;
object item = _items[_size];
_items[_size] = null;
return item;
}
public object Random() {
if (_size == 0) {
return null;
}
return _items[MathUtils.Random(0, _size - 1)];
}
public void Clear() {
object[] items = this._items;
for (int i = 0; i < items.Length; i++)
{
items[i] = null;
}
_size = 0;
}
public int Size() {
return this._size;
}
public object[] ToArray() {
object[] result = (object[]) System.Array.CreateInstance(_items
.GetType().GetElementType(),_size);
System.Array.Copy((_items),0,(result),0,_size);
return result;
}
public override string ToString() {
return ToString(',');
}
public string ToString(char split)
{
if (_size == 0) {
return "[]";
}
object[] items = this._items;
System.Text.StringBuilder buffer = new System.Text.StringBuilder(
CollectionUtils.INITIAL_CAPACITY);
buffer.Append('[');
buffer.Append(items[0]);
for (int i = 1; i < _size; i++) {
buffer.Append(split);
buffer.Append(items[i]);
}
buffer.Append(']');
return buffer.ToString();
}
/*
* public static void main(String[] args) { ArrayList list = new
* ArrayList(); list.add("A"); list.add("B"); list.add("C"); list.add("D");
* list.add("E"); list.add("F"); list.set(0, "Z"); list.pop();
* list.remove(0); System.out.println(list); }
*/
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Dfsc;
using System;
namespace Microsoft.Protocols.TestSuites.FileSharing.DFSC.TestSuite
{
public class DFSCTestUtility
{
private ITestSite baseTestSite;
private DFSCTestConfig testConfig;
#region consts
/// <summary>
/// Const types for DFSC cases
/// </summary>
public static class Consts
{
/// <summary>
/// Used for negative cases, stand for invalid path name.
/// </summary>
public const string InvalidComponent = "Invalid";
}
#endregion
public DFSCTestUtility(ITestSite baseTestSite, DFSCTestConfig testConfig)
{
this.baseTestSite = baseTestSite;
this.testConfig = testConfig;
}
#region General functions used by cases
/// <summary>
/// It's a general function used to connect server, create DFS referral packet and send packet.
/// </summary>
/// <param name="status">Returned status from server</param>
/// <param name="client">Client instance</param>
/// <param name="entryType">Version of DFS referral request</param>
/// <param name="reqPath">The requested DFS Path to resolve</param>
/// <param name="dcOrDFSServer">Server is DC or DFS server</param>
/// <param name="isEx">The request is REQ_GET_DFS_REFERRAL_EX or REQ_GET_DFS_REFERRAL</param>
/// <param name="containSiteName">If REQ_GET_DFS_REFERRAL_EX contains "SiteName" field</param>
/// <returns>The response packet</returns>
public DfscReferralResponsePacket SendAndReceiveDFSReferral(
out uint status,
DfscClient client,
ReferralEntryType_Values entryType,
string reqPath,
bool dcOrDFSServer,
bool isEx = false,
bool containSiteName = false)
{
string serverName;
if (dcOrDFSServer)
{
serverName = testConfig.DCServerName;
}
else
{
serverName = testConfig.DFSServerName;
}
baseTestSite.Log.Add(LogEntryKind.Debug, "Server name is {0}", serverName);
baseTestSite.Log.Add(LogEntryKind.Debug, "Request path is {0}", reqPath);
if (isEx)
{
baseTestSite.Log.Add(LogEntryKind.Debug, "The message is extended.");
}
else
{
baseTestSite.Log.Add(LogEntryKind.Debug, "The message is NOT extended.");
}
if (containSiteName)
{
baseTestSite.Log.Add(LogEntryKind.Debug, "The structure contains SiteName.");
}
else
{
baseTestSite.Log.Add(LogEntryKind.Debug, "The structure does not contain SiteName.");
}
client.Connect(serverName, testConfig.ClientComputerName, testConfig.DomainName, testConfig.UserName, testConfig.UserPassword, testConfig.Timeout,
testConfig.DefaultSecurityPackage, testConfig.UseServerGssToken, testConfig.TransportPreferredSMB);
DfscReferralRequestPacket reqPacket = null;
DfscReferralRequestEXPacket reqPacketEX = null;
if (isEx)
{
if (containSiteName)
{
reqPacketEX = client.CreateDfscReferralRequestPacketEX((ushort)entryType, reqPath, REQ_GET_DFS_REFERRAL_RequestFlags.SiteName, testConfig.SiteName);
}
else
{
reqPacketEX = client.CreateDfscReferralRequestPacketEX((ushort)entryType, reqPath, REQ_GET_DFS_REFERRAL_RequestFlags.None);
}
}
else
{
reqPacket = client.CreateDfscReferralRequestPacket((ushort)entryType, reqPath);
}
DfscReferralResponsePacket respPacket = client.SendAndRecieveDFSCReferralMessages(out status, testConfig.Timeout, reqPacketEX, reqPacket);
return respPacket;
}
/// <summary>
/// This function is only used to verify sysvol/root/link referral response.
/// It can not verify the response of Domain/DC referral request.
/// </summary>
/// <param name="referralResponseType">Type of DFS referral response</param>
/// <param name="entryType">Version of DFS referral</param>
/// <param name="reqPath">The requested DFS Path to resolve</param>
/// <param name="target">The resolved path</param>
/// <param name="respPacket">Packet of DFS referral response</param>
public void VerifyReferralResponse(
ReferralResponseType referralResponseType,
ReferralEntryType_Values entryType,
string reqPath,
string target,
DfscReferralResponsePacket respPacket)
{
if (ReferralResponseType.DCReferralResponse == referralResponseType || ReferralResponseType.DomainReferralResponse == referralResponseType)
return;
baseTestSite.Assert.AreEqual((ushort)reqPath.Length * 2, respPacket.ReferralResponse.PathConsumed,
"PathConsumed must be set to length in bytes of the DFS referral request path");
if (ReferralEntryType_Values.DFS_REFERRAL_V1 == entryType)
{
// Section 3.2.5.5 Receiving a Root Referral Request or Link Referral Request
// For a DFS referral version 1, the ReferralServers and StorageServers bits of the referral entry MUST be set to 1.
// Section 3.3.5.4 Receiving a sysvol Referral Request
// If the MaxReferralLevel field in the request is 1, the ReferralServers and StorageServers fields MUST be set to 1.
// Otherwise, the ReferralServers field MUST be set to 0 and the StorageServers field MUST be set to 1.
baseTestSite.Assert.AreEqual(ReferralHeaderFlags.S, respPacket.ReferralResponse.ReferralHeaderFlags & ReferralHeaderFlags.S,
"For a DFS referral version 1, the StorageServers bit of the referral entry MUST be set to 1.");
baseTestSite.Assert.AreEqual(ReferralHeaderFlags.R, respPacket.ReferralResponse.ReferralHeaderFlags & ReferralHeaderFlags.R,
"For a DFS referral version 1, the ReferralServers bit of the referral entry MUST be set to 1.");
}
else
{
// Section 3.2.5.5 Receiving a Root Referral Request or Link Referral Request
// If DFS root targets are returned or if DFS link targets are returned, the StorageServers bit of the referral entry MUST be set to 1.
// In all other cases, it MUST be set to 0.
// Section 3.3.5.4 Receiving a sysvol Referral Request
// If the MaxReferralLevel field in the request is 1, the ReferralServers and StorageServers fields MUST be set to 1.
// Otherwise, the ReferralServers field MUST be set to 0 and the StorageServers field MUST be set to 1.
// Check StorageServers bit
if (ReferralResponseType.RootTarget == referralResponseType
|| ReferralResponseType.LinkTarget == referralResponseType
|| ReferralResponseType.SysvolReferralResponse == referralResponseType)
{
baseTestSite.Assert.AreEqual(ReferralHeaderFlags.S, respPacket.ReferralResponse.ReferralHeaderFlags & ReferralHeaderFlags.S,
"StorageServers bit of the referral entry MUST be set to 1.");
}
else
{
baseTestSite.Assert.AreNotEqual(ReferralHeaderFlags.S, respPacket.ReferralResponse.ReferralHeaderFlags & ReferralHeaderFlags.S,
"StorageServers bit of the referral entry MUST be set to 0.");
}
// Check ReferralServers bit
if (ReferralResponseType.RootTarget == referralResponseType
|| ReferralResponseType.Interlink == referralResponseType)
{
baseTestSite.Assert.AreEqual(ReferralHeaderFlags.R, respPacket.ReferralResponse.ReferralHeaderFlags & ReferralHeaderFlags.R,
"ReferralServers bit of the referral entry MUST be set to 1.");
}
else
{
baseTestSite.Assert.AreNotEqual(ReferralHeaderFlags.R, respPacket.ReferralResponse.ReferralHeaderFlags & ReferralHeaderFlags.R,
"ReferralServers bit of the referral entry MUST be set to 0.");
}
}
uint timeToLive;
bool containTarget = false;
switch ((ReferralEntryType_Values)respPacket.VersionNumber)
{
case ReferralEntryType_Values.DFS_REFERRAL_V1:
DFS_REFERRAL_V1[] referralEntries_V1 = (DFS_REFERRAL_V1[])respPacket.ReferralResponse.ReferralEntries;
foreach (DFS_REFERRAL_V1 entry in referralEntries_V1)
{
baseTestSite.Assert.AreEqual((ushort)entryType, entry.VersionNumber, "VersionNumber must be set to " + entryType.ToString());
baseTestSite.Assert.AreEqual(0, entry.ReferralEntryFlags, "ReferralEntryFlags MUST be set to 0x0000 by the server and ignored on receipt by the client.");
if (ReferralResponseType.RootTarget == referralResponseType)
{
baseTestSite.Assert.AreEqual(0x0001, entry.ServerType, "The ServerType field MUST be set to 0x0001 if root targets are returned." +
"In all other cases, the ServerType field MUST be set to 0x0000.");
}
else
{
baseTestSite.Assert.AreEqual(0, entry.ServerType, "The ServerType field MUST be set to 0x0001 if root targets are returned." +
"In all other cases, the ServerType field MUST be set to 0x0000.");
}
baseTestSite.Log.Add(LogEntryKind.Debug, "ShareName is {0}", entry.ShareName);
if (!containTarget)
containTarget = target.Equals(entry.ShareName, StringComparison.OrdinalIgnoreCase);
}
break;
case ReferralEntryType_Values.DFS_REFERRAL_V2:
DFS_REFERRAL_V2[] referralEntries_V2 = (DFS_REFERRAL_V2[])respPacket.ReferralResponse.ReferralEntries;
timeToLive = referralEntries_V2[0].TimeToLive;
foreach (DFS_REFERRAL_V2 entry in referralEntries_V2)
{
baseTestSite.Assert.AreEqual(timeToLive, entry.TimeToLive, "TimeToLive must be the same");
baseTestSite.Assert.AreEqual((ushort)entryType, entry.VersionNumber, "VersionNumber must be set to " + entryType.ToString());
baseTestSite.Assert.AreEqual(0, entry.ReferralEntryFlags, "ReferralEntryFlags MUST be set to 0x0000 by the server and ignored on receipt by the client.");
if (ReferralResponseType.RootTarget == referralResponseType)
{
baseTestSite.Assert.AreEqual(0x0001, entry.ServerType, "The ServerType field MUST be set to 0x0001 if root targets are returned." +
"In all other cases, the ServerType field MUST be set to 0x0000.");
}
else
{
baseTestSite.Assert.AreEqual(0, entry.ServerType, "The ServerType field MUST be set to 0x0001 if root targets are returned." +
"In all other cases, the ServerType field MUST be set to 0x0000.");
}
baseTestSite.Assert.IsTrue(reqPath.Equals(entry.DFSPath, StringComparison.OrdinalIgnoreCase), "DFSPath must be {0}, actual is {1}", reqPath, entry.DFSPath);
baseTestSite.Assert.IsTrue(reqPath.Equals(entry.DFSAlternatePath, StringComparison.OrdinalIgnoreCase), "DFSAlternatePath must be {0}, actual is {1}", reqPath, entry.DFSAlternatePath);
baseTestSite.Log.Add(LogEntryKind.Debug, "DFSTargetPath is {0}", entry.DFSTargetPath);
if (!containTarget)
containTarget = target.Equals(entry.DFSTargetPath, StringComparison.OrdinalIgnoreCase);
timeToLive = entry.TimeToLive;
}
break;
case ReferralEntryType_Values.DFS_REFERRAL_V3:
case ReferralEntryType_Values.DFS_REFERRAL_V4:
DFS_REFERRAL_V3V4_NonNameListReferral[] referralEntries_V3V4 = (DFS_REFERRAL_V3V4_NonNameListReferral[])respPacket.ReferralResponse.ReferralEntries;
timeToLive = referralEntries_V3V4[0].TimeToLive;
bool firstTarget = true;
foreach (DFS_REFERRAL_V3V4_NonNameListReferral entry in referralEntries_V3V4)
{
baseTestSite.Assert.AreEqual(timeToLive, entry.TimeToLive, "TimeToLive must be the same");
baseTestSite.Assert.AreEqual((ushort)entryType, entry.VersionNumber, "VersionNumber must be set to " + entryType.ToString());
if (ReferralResponseType.RootTarget == referralResponseType)
{
baseTestSite.Assert.AreEqual(0x0001, entry.ServerType, "The ServerType field MUST be set to 0x0001 if root targets are returned." +
"In all other cases, the ServerType field MUST be set to 0x0000.");
}
else
{
baseTestSite.Assert.AreEqual(0, entry.ServerType, "The ServerType field MUST be set to 0x0001 if root targets are returned." +
"In all other cases, the ServerType field MUST be set to 0x0000.");
}
baseTestSite.Assert.IsTrue(reqPath.Equals(entry.DFSPath, StringComparison.OrdinalIgnoreCase), "DFSPath must be {0}, actual is {1}", reqPath, entry.DFSPath);
baseTestSite.Assert.IsTrue(reqPath.Equals(entry.DFSAlternatePath, StringComparison.OrdinalIgnoreCase), "DFSAlternatePath must be {0}, actual is {1}", reqPath, entry.DFSAlternatePath);
baseTestSite.Log.Add(LogEntryKind.Debug, "DFSTargetPath is {0}", entry.DFSTargetPath);
if (!containTarget)
{
containTarget = target.Equals(entry.DFSTargetPath, StringComparison.OrdinalIgnoreCase);
}
timeToLive = entry.TimeToLive;
if (ReferralEntryType_Values.DFS_REFERRAL_V3 == (ReferralEntryType_Values)respPacket.VersionNumber)
continue; // skip TargetSetBoundary check for version 3.
if (firstTarget)
{
baseTestSite.Assert.AreEqual(ReferralEntryFlags_Values.T, entry.ReferralEntryFlags, "TargetSetBoundary MUST be set to 1 for the first target.");
firstTarget = false;
}
else
{
baseTestSite.Assert.AreEqual(ReferralEntryFlags_Values.None, entry.ReferralEntryFlags, "TargetSetBoundary MUST be set to 0 for other targets.");
}
}
break;
default:
throw new InvalidOperationException("The version number of Referral Entry is not correct.");
}
baseTestSite.Assert.IsTrue(containTarget, "{0} response must contain {1}", Enum.GetName(typeof(ReferralResponseType), referralResponseType), target);
}
/// <summary>
/// It's not allowed to send REQ_GET_DFS_REFERRAL_EX over SMB transport.
/// </summary>
public void CheckEXOverSMB()
{
if (testConfig.TransportPreferredSMB)
{
baseTestSite.Assert.Inconclusive("REQ_GET_DFS_REFERRAL_EX can not be sent over SMB");
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Audio;
namespace FlatRedBall.Audio
{
#region Xml Docs
/// <summary>
/// Used to manage variables in a sound
/// </summary>
#endregion
public struct SoundVariableCollection
{
#region Fields
private Cue mCue;
// A cue can only be used once. How lame is that?
// So when the new cue is created, the variables are
// all tossed. Therefore, this is going to store off
// the variables so that the user can set them once and
// forget them.
internal Dictionary<string, float> mVariableValues;
#endregion
#region Properties
public float this[String variable]
{
get { return mCue.GetVariable(variable); }
set
{
mCue.SetVariable(variable, value);
if (mVariableValues.ContainsKey(variable))
{
mVariableValues[variable] = value;
}
else
{
mVariableValues.Add(variable, value);
}
}
}
internal Cue Cue
{
get { return mCue; }
set
{
mCue = value;
foreach (KeyValuePair<string, float> kvp in mVariableValues)
{
mCue.SetVariable(kvp.Key, kvp.Value);
}
}
}
#endregion
#region Constructor
internal SoundVariableCollection(Cue cue)
{
mVariableValues = new Dictionary<string,float>();
mCue = cue;
}
#endregion
#region Public Methods
#endregion
}
public class Sound
{
#region Delegates
internal delegate void OnCueRetrievedHandler();
#endregion
#region Fields
protected Cue mCue;
protected String mCueName;
protected string mSoundBankFile;
public SoundVariableCollection Variables;
#endregion
#region Properties
internal Cue Cue { get { return mCue; } }
public bool IsStopped { get { return mCue.IsStopped; } }
public bool IsPlaying { get { return mCue.IsPlaying; } }
public bool IsPaused { get { return mCue.IsPaused; } }
#endregion
#region Construction
internal Sound(Cue cue, String cueName, string soundBankFile)
{
mCue = cue;
mCueName = cueName;
mSoundBankFile = soundBankFile;
Variables = new SoundVariableCollection(mCue);
}
#endregion
#region Public Methods
internal event OnCueRetrievedHandler OnCueRetrieved;
#region Xml Docs
/// <summary>
/// Begins playback of this sound, or resumes playback (if it has been paused)
/// </summary>
#endregion
public void Play()
{
if (mCue.IsDisposed || mCue.IsStopped)
{
// Get the cue again, since it has gone out of scope
mCue = AudioManager.GetCue(mCueName, mSoundBankFile);
// Setting this will reset the variables.
Variables.Cue = mCue;
if (OnCueRetrieved != null)
{
OnCueRetrieved();
}
}
if (mCue.IsPaused)
{
mCue.Resume();
}
else if (!mCue.IsPlaying && mCue.IsPrepared)
{
if (OnCueRetrieved != null)
{
OnCueRetrieved();
}
mCue.Play();
}
}
#region Xml Docs
/// <summary>
/// Pauses playback of this sound
/// </summary>
#endregion
public void Pause()
{
if (mCue.IsPlaying)
{
mCue.Pause();
}
}
#region Xml Docs
/// <summary>
/// Stops playing this sound as authored
/// </summary>
#endregion
public void Stop()
{
if (mCue.IsPlaying || mCue.IsPaused)
{
mCue.Stop(AudioStopOptions.AsAuthored);
}
}
#region Xml Docs
/// <summary>
/// Stops playing this sound immediately
/// </summary>
#endregion
public void StopImmediately()
{
if (mCue.IsPlaying || mCue.IsPaused)
{
mCue.Stop(AudioStopOptions.Immediate);
}
}
#region Xml Docs
/// <summary>
/// Stops playing this sound as authored in the XACT project
/// </summary>
#endregion
public void StopAsAuthored()
{
if (mCue.IsPlaying || mCue.IsPaused)
{
mCue.Stop(AudioStopOptions.AsAuthored);
}
}
#endregion
}
}
| |
using System.Diagnostics.CodeAnalysis;
namespace Faithlife.Parsing;
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1414:Tuple types in signatures should have element names", Justification = "No better names.")]
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1128:Put constructor initializers on their own line", Justification = "More compact.")]
[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1502:Element should not be on a single line", Justification = "More compact.")]
public static partial class Parser
{
/// <summary>
/// Executes one parser after another.
/// </summary>
public static IParser<TAfter> Then<T1, T2, TAfter>(this IParser<T1> parser, IParser<T2> nextParser, Func<T1, T2, TAfter> combineValues) =>
new FuncThenParser<T1, T2, TAfter>(parser, nextParser, combineValues);
private abstract class ThenParser<T1, T2, TAfter> : Parser<TAfter>
{
protected ThenParser(IParser<T1> parser, IParser<T2> nextParser)
{
m_parser = parser ?? throw new ArgumentNullException(nameof(parser));
m_nextParser = nextParser ?? throw new ArgumentNullException(nameof(nextParser));
}
public override TAfter TryParse(bool skip, ref TextPosition position, out bool success)
{
var value = m_parser.TryParse(skip, ref position, out success);
if (!success)
return default!;
var nextValue = m_nextParser.TryParse(skip, ref position, out success);
if (!success)
return default!;
return skip ? default! : CombineValues(value, nextValue);
}
protected abstract TAfter CombineValues(T1 value, T2 nextValue);
private readonly IParser<T1> m_parser;
private readonly IParser<T2> m_nextParser;
}
private sealed class FuncThenParser<T1, T2, TAfter> : ThenParser<T1, T2, TAfter>
{
public FuncThenParser(IParser<T1> parser, IParser<T2> nextParser, Func<T1, T2, TAfter> combineValues)
: base(parser, nextParser)
{
m_combineValues = combineValues;
}
protected override TAfter CombineValues(T1 value, T2 nextValue) => m_combineValues(value, nextValue);
private readonly Func<T1, T2, TAfter> m_combineValues;
}
/// <summary>
/// Executes one parser after another.
/// </summary>
public static IParser<(T1, T2)> Then<T1, T2>(this IParser<T1> parser, IParser<T2> nextParser) =>
new ThenTupleParser<T1, T2>(parser, nextParser);
private sealed class ThenTupleParser<T1, T2> : ThenParser<T1, T2, (T1, T2)>
{
public ThenTupleParser(IParser<T1> parser, IParser<T2> nextParser) : base(parser, nextParser) { }
protected override (T1, T2) CombineValues(T1 value, T2 nextValue) =>
(value, nextValue);
}
/// <summary>
/// Executes one parser after another.
/// </summary>
public static IParser<(T1, T2, T3)> Then<T1, T2, T3>(this IParser<(T1, T2)> parser, IParser<T3> nextParser) =>
new ThenTupleParser<T1, T2, T3>(parser, nextParser);
private sealed class ThenTupleParser<T1, T2, T3> : ThenParser<(T1, T2), T3, (T1, T2, T3)>
{
public ThenTupleParser(IParser<(T1, T2)> parser, IParser<T3> nextParser) : base(parser, nextParser) { }
protected override (T1, T2, T3) CombineValues((T1, T2) value, T3 nextValue) =>
(value.Item1, value.Item2, nextValue);
}
/// <summary>
/// Executes one parser after another.
/// </summary>
public static IParser<(T1, T2, T3, T4)> Then<T1, T2, T3, T4>(this IParser<(T1, T2, T3)> parser, IParser<T4> nextParser) =>
new ThenTupleParser<T1, T2, T3, T4>(parser, nextParser);
private sealed class ThenTupleParser<T1, T2, T3, T4> : ThenParser<(T1, T2, T3), T4, (T1, T2, T3, T4)>
{
public ThenTupleParser(IParser<(T1, T2, T3)> parser, IParser<T4> nextParser) : base(parser, nextParser) { }
protected override (T1, T2, T3, T4) CombineValues((T1, T2, T3) value, T4 nextValue) =>
(value.Item1, value.Item2, value.Item3, nextValue);
}
/// <summary>
/// Executes one parser after another.
/// </summary>
public static IParser<(T1, T2, T3, T4, T5)> Then<T1, T2, T3, T4, T5>(this IParser<(T1, T2, T3, T4)> parser, IParser<T5> nextParser) =>
new ThenTupleParser<T1, T2, T3, T4, T5>(parser, nextParser);
private sealed class ThenTupleParser<T1, T2, T3, T4, T5> : ThenParser<(T1, T2, T3, T4), T5, (T1, T2, T3, T4, T5)>
{
public ThenTupleParser(IParser<(T1, T2, T3, T4)> parser, IParser<T5> nextParser) : base(parser, nextParser) { }
protected override (T1, T2, T3, T4, T5) CombineValues((T1, T2, T3, T4) value, T5 nextValue) =>
(value.Item1, value.Item2, value.Item3, value.Item4, nextValue);
}
/// <summary>
/// Executes one parser after another.
/// </summary>
public static IParser<(T1, T2, T3, T4, T5, T6)> Then<T1, T2, T3, T4, T5, T6>(this IParser<(T1, T2, T3, T4, T5)> parser, IParser<T6> nextParser) =>
new ThenTupleParser<T1, T2, T3, T4, T5, T6>(parser, nextParser);
private sealed class ThenTupleParser<T1, T2, T3, T4, T5, T6> : ThenParser<(T1, T2, T3, T4, T5), T6, (T1, T2, T3, T4, T5, T6)>
{
public ThenTupleParser(IParser<(T1, T2, T3, T4, T5)> parser, IParser<T6> nextParser) : base(parser, nextParser) { }
protected override (T1, T2, T3, T4, T5, T6) CombineValues((T1, T2, T3, T4, T5) value, T6 nextValue) =>
(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, nextValue);
}
/// <summary>
/// Executes one parser after another.
/// </summary>
public static IParser<(T1, T2, T3, T4, T5, T6, T7)> Then<T1, T2, T3, T4, T5, T6, T7>(this IParser<(T1, T2, T3, T4, T5, T6)> parser, IParser<T7> nextParser) =>
new ThenTupleParser<T1, T2, T3, T4, T5, T6, T7>(parser, nextParser);
private sealed class ThenTupleParser<T1, T2, T3, T4, T5, T6, T7> : ThenParser<(T1, T2, T3, T4, T5, T6), T7, (T1, T2, T3, T4, T5, T6, T7)>
{
public ThenTupleParser(IParser<(T1, T2, T3, T4, T5, T6)> parser, IParser<T7> nextParser) : base(parser, nextParser) { }
protected override (T1, T2, T3, T4, T5, T6, T7) CombineValues((T1, T2, T3, T4, T5, T6) value, T7 nextValue) =>
(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, nextValue);
}
/// <summary>
/// Executes one parser after another.
/// </summary>
public static IParser<(T1, T2, T3, T4, T5, T6, T7, T8)> Then<T1, T2, T3, T4, T5, T6, T7, T8>(this IParser<(T1, T2, T3, T4, T5, T6, T7)> parser, IParser<T8> nextParser) =>
new ThenTupleParser<T1, T2, T3, T4, T5, T6, T7, T8>(parser, nextParser);
private sealed class ThenTupleParser<T1, T2, T3, T4, T5, T6, T7, T8> : ThenParser<(T1, T2, T3, T4, T5, T6, T7), T8, (T1, T2, T3, T4, T5, T6, T7, T8)>
{
public ThenTupleParser(IParser<(T1, T2, T3, T4, T5, T6, T7)> parser, IParser<T8> nextParser) : base(parser, nextParser) { }
protected override (T1, T2, T3, T4, T5, T6, T7, T8) CombineValues((T1, T2, T3, T4, T5, T6, T7) value, T8 nextValue) =>
(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, nextValue);
}
/// <summary>
/// Executes one parser after another, ignoring the output of the second parser.
/// </summary>
public static IParser<T1> ThenSkip<T1, T2>(this IParser<T1> parser, IParser<T2> nextParser) =>
new ThenSkipTupleParser<T1, T2>(parser, nextParser);
private sealed class ThenSkipTupleParser<T1, T2> : Parser<T1>
{
public ThenSkipTupleParser(IParser<T1> parser, IParser<T2> nextParser)
{
m_parser = parser ?? throw new ArgumentNullException(nameof(parser));
m_nextParser = nextParser ?? throw new ArgumentNullException(nameof(nextParser));
}
public override T1 TryParse(bool skip, ref TextPosition position, out bool success)
{
var value = m_parser.TryParse(skip, ref position, out success);
if (!success)
return default!;
m_nextParser.TryParse(skip: true, ref position, out success);
if (!success)
return default!;
return value;
}
private readonly IParser<T1> m_parser;
private readonly IParser<T2> m_nextParser;
}
/// <summary>
/// Executes one parser after another, ignoring the output of the first parser.
/// </summary>
public static IParser<T2> SkipThen<T1, T2>(this IParser<T1> parser, IParser<T2> nextParser) =>
new SkipThenTupleParser<T1, T2>(parser, nextParser);
private sealed class SkipThenTupleParser<T1, T2> : Parser<T2>
{
public SkipThenTupleParser(IParser<T1> parser, IParser<T2> nextParser)
{
m_parser = parser ?? throw new ArgumentNullException(nameof(parser));
m_nextParser = nextParser ?? throw new ArgumentNullException(nameof(nextParser));
}
public override T2 TryParse(bool skip, ref TextPosition position, out bool success)
{
m_parser.TryParse(skip: true, ref position, out success);
if (!success)
return default!;
var nextValue = m_nextParser.TryParse(skip, ref position, out success);
if (!success)
return default!;
return nextValue;
}
private readonly IParser<T1> m_parser;
private readonly IParser<T2> m_nextParser;
}
/// <summary>
/// Converts any successfully parsed value.
/// </summary>
public static IParser<TAfter> Select<TBefore, TAfter>(this IParser<TBefore> parser, Func<TBefore, TAfter> convertValue)
{
if (convertValue is null)
throw new ArgumentNullException(nameof(convertValue));
return new SelectParser<TBefore, TAfter>(parser, convertValue);
}
private sealed class SelectParser<TBefore, TAfter> : Parser<TAfter>
{
public SelectParser(IParser<TBefore> parser, Func<TBefore, TAfter> convertValue) => (m_parser, m_convertValue) = (parser, convertValue);
public override TAfter TryParse(bool skip, ref TextPosition position, out bool success)
{
var value = m_parser.TryParse(skip, ref position, out success);
return success && !skip ? m_convertValue(value) : default!;
}
private readonly IParser<TBefore> m_parser;
private readonly Func<TBefore, TAfter> m_convertValue;
}
/// <summary>
/// Succeeds with the specified value if the parser is successful.
/// </summary>
public static IParser<TAfter> Success<TBefore, TAfter>(this IParser<TBefore> parser, TAfter value) =>
parser.SkipThen(Success(value));
/// <summary>
/// Fails even if the parser is successful.
/// </summary>
public static IParser<T> Failure<T>(this IParser<T> parser) => new ThenFailureParser<T>(parser);
private sealed class ThenFailureParser<T> : Parser<T>
{
public ThenFailureParser(IParser<T> parser) => m_parser = parser;
public override T TryParse(bool skip, ref TextPosition position, out bool success)
{
var endPosition = position;
m_parser.TryParse(skip: true, ref endPosition, out _);
success = false;
return default!;
}
private readonly IParser<T> m_parser;
}
/// <summary>
/// Concatenates the two successfully parsed collections.
/// </summary>
public static IParser<IReadOnlyList<T>> Concat<T>(this IParser<IEnumerable<T>> firstParser, IParser<IEnumerable<T>> secondParser) =>
firstParser.Then(secondParser, (firstValue, secondValue) => firstValue.Concat(secondValue).ToList());
/// <summary>
/// Appends a successfully parsed value to the end of a successfully parsed collection.
/// </summary>
public static IParser<IReadOnlyList<T>> Append<T>(this IParser<IEnumerable<T>> firstParser, IParser<T> secondParser) =>
firstParser.Concat(secondParser.Once());
/// <summary>
/// Executes one parser after another.
/// </summary>
public static IParser<TAfter> Then<TBefore, TAfter>(this IParser<TBefore> parser, Func<TBefore, IParser<TAfter>> convertValueToNextParser) =>
new ThenCreateParser<TBefore, TAfter>(parser, convertValueToNextParser);
private sealed class ThenCreateParser<TBefore, TAfter> : Parser<TAfter>
{
public ThenCreateParser(IParser<TBefore> parser, Func<TBefore, IParser<TAfter>> convertValueToNextParser)
{
m_parser = parser ?? throw new ArgumentNullException(nameof(parser));
m_convertValueToNextParser = convertValueToNextParser ?? throw new ArgumentNullException(nameof(convertValueToNextParser));
}
public override TAfter TryParse(bool skip, ref TextPosition position, out bool success)
{
var value = m_parser.TryParse(skip: false, ref position, out success);
return success ? m_convertValueToNextParser(value).TryParse(skip, ref position, out success) : default!;
}
private readonly IParser<TBefore> m_parser;
private readonly Func<TBefore, IParser<TAfter>> m_convertValueToNextParser;
}
/// <summary>
/// Used to support LINQ query syntax.
/// </summary>
public static IParser<TAfter> SelectMany<TBefore, TDuring, TAfter>(this IParser<TBefore> parser, Func<TBefore, IParser<TDuring>> selector, Func<TBefore, TDuring, TAfter> projector)
{
if (selector is null)
throw new ArgumentNullException(nameof(selector));
if (projector is null)
throw new ArgumentNullException(nameof(projector));
return parser.Then(t => selector(t).Select(u => projector(t, u)));
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Examples.Sql
{
using System;
using Apache.Ignite.Core;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.ExamplesDll.Binary;
/// <summary>
/// This example populates cache with sample data and runs SQL queries.
/// <para />
/// 1) Build the project Apache.Ignite.ExamplesDll (select it -> right-click -> Build).
/// 2) Set this class as startup object (Apache.Ignite.Examples project -> right-click -> Properties ->
/// Application -> Startup object);
/// 3) Start example (F5 or Ctrl+F5).
/// <para />
/// This example can be run with standalone Apache Ignite.NET node:
/// 1) Run %IGNITE_HOME%/platforms/dotnet/bin/Apache.Ignite.exe:
/// Apache.Ignite.exe -configFileName=platforms\dotnet\examples\apache.ignite.examples\app.config
/// 2) Start example.
/// </summary>
public class SqlExample
{
/// <summary>Organization cache name.</summary>
private const string OrganizationCacheName = "dotnet_cache_query_organization";
/// <summary>Employee cache name.</summary>
private const string EmployeeCacheName = "dotnet_cache_query_employee";
/// <summary>Employee cache name.</summary>
private const string EmployeeCacheNameColocated = "dotnet_cache_query_employee_colocated";
[STAThread]
public static void Main()
{
using (var ignite = Ignition.StartFromApplicationConfiguration())
{
Console.WriteLine();
Console.WriteLine(">>> Cache query example started.");
var employeeCache = ignite.GetOrCreateCache<int, Employee>(
new CacheConfiguration(EmployeeCacheName, new QueryEntity(typeof(int), typeof(Employee))));
var employeeCacheColocated = ignite.GetOrCreateCache<AffinityKey, Employee>(
new CacheConfiguration(EmployeeCacheNameColocated,
new QueryEntity(typeof(AffinityKey), typeof(Employee))));
var organizationCache = ignite.GetOrCreateCache<int, Organization>(
new CacheConfiguration(OrganizationCacheName, new QueryEntity(typeof(int), typeof(Organization))));
// Populate cache with sample data entries.
PopulateCache(employeeCache);
PopulateCache(employeeCacheColocated);
PopulateCache(organizationCache);
// Run SQL query example.
SqlQueryExample(employeeCache);
// Run SQL query with join example.
SqlJoinQueryExample(employeeCacheColocated);
// Run SQL query with distributed join example.
SqlDistributedJoinQueryExample(employeeCache);
// Run SQL fields query example.
SqlFieldsQueryExample(employeeCache);
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine(">>> Example finished, press any key to exit ...");
Console.ReadKey();
}
/// <summary>
/// Queries employees that have provided ZIP code in address.
/// </summary>
/// <param name="cache">Cache.</param>
private static void SqlQueryExample(ICache<int, Employee> cache)
{
const int zip = 94109;
var qry = cache.Query(new SqlQuery(typeof(Employee), "zip = ?", zip));
Console.WriteLine();
Console.WriteLine(">>> Employees with zipcode {0} (SQL):", zip);
foreach (var entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that work for organization with provided name.
/// </summary>
/// <param name="cache">Cache.</param>
private static void SqlJoinQueryExample(ICache<AffinityKey, Employee> cache)
{
const string orgName = "Apache";
var qry = cache.Query(new SqlQuery("Employee",
"from Employee, \"dotnet_cache_query_organization\".Organization " +
"where Employee.organizationId = Organization._key and Organization.name = ?", orgName));
Console.WriteLine();
Console.WriteLine(">>> Employees working for " + orgName + ":");
foreach (var entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that work for organization with provided name.
/// </summary>
/// <param name="cache">Cache.</param>
private static void SqlDistributedJoinQueryExample(ICache<int, Employee> cache)
{
const string orgName = "Apache";
var qry = cache.Query(new SqlQuery("Employee",
"from Employee, \"dotnet_cache_query_organization\".Organization " +
"where Employee.organizationId = Organization._key and Organization.name = ?", orgName)
{
EnableDistributedJoins = true
});
Console.WriteLine();
Console.WriteLine(">>> Employees working for " + orgName + ":");
foreach (var entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries names and salaries for all employees.
/// </summary>
/// <param name="cache">Cache.</param>
private static void SqlFieldsQueryExample(ICache<int, Employee> cache)
{
var qry = cache.Query(new SqlFieldsQuery("select name, salary from Employee"));
Console.WriteLine();
Console.WriteLine(">>> Employee names and their salaries:");
foreach (var row in qry)
Console.WriteLine(">>> [Name=" + row[0] + ", salary=" + row[1] + ']');
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<int, Organization> cache)
{
cache.Put(1, new Organization(
"Apache",
new Address("1065 East Hillsdale Blvd, Foster City, CA", 94404),
OrganizationType.Private,
DateTime.Now));
cache.Put(2, new Organization("Microsoft",
new Address("1096 Eddy Street, San Francisco, CA", 94109),
OrganizationType.Private,
DateTime.Now));
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<AffinityKey, Employee> cache)
{
cache.Put(new AffinityKey(1, 1), new Employee(
"James Wilson",
12500,
new Address("1096 Eddy Street, San Francisco, CA", 94109),
new[] {"Human Resources", "Customer Service"},
1));
cache.Put(new AffinityKey(2, 1), new Employee(
"Daniel Adams",
11000,
new Address("184 Fidler Drive, San Antonio, TX", 78130),
new[] {"Development", "QA"},
1));
cache.Put(new AffinityKey(3, 1), new Employee(
"Cristian Moss",
12500,
new Address("667 Jerry Dove Drive, Florence, SC", 29501),
new[] {"Logistics"},
1));
cache.Put(new AffinityKey(4, 2), new Employee(
"Allison Mathis",
25300,
new Address("2702 Freedom Lane, San Francisco, CA", 94109),
new[] {"Development"},
2));
cache.Put(new AffinityKey(5, 2), new Employee(
"Breana Robbin",
6500,
new Address("3960 Sundown Lane, Austin, TX", 78130),
new[] {"Sales"},
2));
cache.Put(new AffinityKey(6, 2), new Employee(
"Philip Horsley",
19800,
new Address("2803 Elsie Drive, Sioux Falls, SD", 57104),
new[] {"Sales"},
2));
cache.Put(new AffinityKey(7, 2), new Employee(
"Brian Peters",
10600,
new Address("1407 Pearlman Avenue, Boston, MA", 12110),
new[] {"Development", "QA"},
2));
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<int, Employee> cache)
{
cache.Put(1, new Employee(
"James Wilson",
12500,
new Address("1096 Eddy Street, San Francisco, CA", 94109),
new[] {"Human Resources", "Customer Service"},
1));
cache.Put(2, new Employee(
"Daniel Adams",
11000,
new Address("184 Fidler Drive, San Antonio, TX", 78130),
new[] {"Development", "QA"},
1));
cache.Put(3, new Employee(
"Cristian Moss",
12500,
new Address("667 Jerry Dove Drive, Florence, SC", 29501),
new[] {"Logistics"},
1));
cache.Put(4, new Employee(
"Allison Mathis",
25300,
new Address("2702 Freedom Lane, San Francisco, CA", 94109),
new[] {"Development"},
2));
cache.Put(5, new Employee(
"Breana Robbin",
6500,
new Address("3960 Sundown Lane, Austin, TX", 78130),
new[] {"Sales"},
2));
cache.Put(6, new Employee(
"Philip Horsley",
19800,
new Address("2803 Elsie Drive, Sioux Falls, SD", 57104),
new[] {"Sales"},
2));
cache.Put(7, new Employee(
"Brian Peters",
10600,
new Address("1407 Pearlman Avenue, Boston, MA", 12110),
new[] {"Development", "QA"},
2));
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.VirtualAddressV2Binding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBVirtualAddressV2VirtualAddressStatistics))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBObjectStatus))]
public partial class LocalLBVirtualAddressV2 : iControlInterface {
public LocalLBVirtualAddressV2() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_metadata
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void add_metadata(
string [] virtual_addresses,
string [] [] names,
string [] [] values
) {
this.Invoke("add_metadata", new object [] {
virtual_addresses,
names,
values});
}
public System.IAsyncResult Beginadd_metadata(string [] virtual_addresses,string [] [] names,string [] [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_metadata", new object[] {
virtual_addresses,
names,
values}, callback, asyncState);
}
public void Endadd_metadata(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void create(
string [] virtual_addresses,
string [] addresses,
string [] netmasks
) {
this.Invoke("create", new object [] {
virtual_addresses,
addresses,
netmasks});
}
public System.IAsyncResult Begincreate(string [] virtual_addresses,string [] addresses,string [] netmasks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
virtual_addresses,
addresses,
netmasks}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_virtual_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void delete_virtual_address(
string [] virtual_addresses
) {
this.Invoke("delete_virtual_address", new object [] {
virtual_addresses});
}
public System.IAsyncResult Begindelete_virtual_address(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_virtual_address", new object[] {
virtual_addresses}, callback, asyncState);
}
public void Enddelete_virtual_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_address(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_address", new object [] {
virtual_addresses});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_address(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_address", new object[] {
virtual_addresses}, callback, asyncState);
}
public string [] Endget_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBVirtualAddressV2VirtualAddressStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((LocalLBVirtualAddressV2VirtualAddressStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public LocalLBVirtualAddressV2VirtualAddressStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBVirtualAddressV2VirtualAddressStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_arp_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_arp_state(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_arp_state", new object [] {
virtual_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_arp_state(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_arp_state", new object[] {
virtual_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_arp_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_auto_delete_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_auto_delete_state(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_auto_delete_state", new object [] {
virtual_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_auto_delete_state(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_auto_delete_state", new object[] {
virtual_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_auto_delete_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_connection_limit(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_connection_limit", new object [] {
virtual_addresses});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_connection_limit(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_limit", new object[] {
virtual_addresses}, callback, asyncState);
}
public long [] Endget_connection_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_description", new object [] {
virtual_addresses});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
virtual_addresses}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_enabled_state(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_enabled_state", new object [] {
virtual_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_enabled_state(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_enabled_state", new object[] {
virtual_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_icmp_echo_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_icmp_echo_state(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_icmp_echo_state", new object [] {
virtual_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_icmp_echo_state(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_icmp_echo_state", new object[] {
virtual_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_icmp_echo_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_icmp_echo_state_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBVirtualAddressV2IcmpEchoType [] get_icmp_echo_state_v2(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_icmp_echo_state_v2", new object [] {
virtual_addresses});
return ((LocalLBVirtualAddressV2IcmpEchoType [])(results[0]));
}
public System.IAsyncResult Beginget_icmp_echo_state_v2(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_icmp_echo_state_v2", new object[] {
virtual_addresses}, callback, asyncState);
}
public LocalLBVirtualAddressV2IcmpEchoType [] Endget_icmp_echo_state_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBVirtualAddressV2IcmpEchoType [])(results[0]));
}
//-----------------------------------------------------------------------
// get_icmp_echo_state_v3
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBVirtualAddressV2IcmpEchoType2 [] get_icmp_echo_state_v3(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_icmp_echo_state_v3", new object [] {
virtual_addresses});
return ((LocalLBVirtualAddressV2IcmpEchoType2 [])(results[0]));
}
public System.IAsyncResult Beginget_icmp_echo_state_v3(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_icmp_echo_state_v3", new object[] {
virtual_addresses}, callback, asyncState);
}
public LocalLBVirtualAddressV2IcmpEchoType2 [] Endget_icmp_echo_state_v3(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBVirtualAddressV2IcmpEchoType2 [])(results[0]));
}
//-----------------------------------------------------------------------
// get_is_floating_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_is_floating_state(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_is_floating_state", new object [] {
virtual_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_is_floating_state(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_is_floating_state", new object[] {
virtual_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_is_floating_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_metadata
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_metadata(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_metadata", new object [] {
virtual_addresses});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_metadata(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_metadata", new object[] {
virtual_addresses}, callback, asyncState);
}
public string [] [] Endget_metadata(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_metadata_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_metadata_description(
string [] virtual_addresses,
string [] [] names
) {
object [] results = this.Invoke("get_metadata_description", new object [] {
virtual_addresses,
names});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_metadata_description(string [] virtual_addresses,string [] [] names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_metadata_description", new object[] {
virtual_addresses,
names}, callback, asyncState);
}
public string [] [] Endget_metadata_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_metadata_persistence
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonMetadataPersistence [] [] get_metadata_persistence(
string [] virtual_addresses,
string [] [] names
) {
object [] results = this.Invoke("get_metadata_persistence", new object [] {
virtual_addresses,
names});
return ((CommonMetadataPersistence [] [])(results[0]));
}
public System.IAsyncResult Beginget_metadata_persistence(string [] virtual_addresses,string [] [] names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_metadata_persistence", new object[] {
virtual_addresses,
names}, callback, asyncState);
}
public CommonMetadataPersistence [] [] Endget_metadata_persistence(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonMetadataPersistence [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_metadata_value
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_metadata_value(
string [] virtual_addresses,
string [] [] names
) {
object [] results = this.Invoke("get_metadata_value", new object [] {
virtual_addresses,
names});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_metadata_value(string [] virtual_addresses,string [] [] names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_metadata_value", new object[] {
virtual_addresses,
names}, callback, asyncState);
}
public string [] [] Endget_metadata_value(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_netmask
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_netmask(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_netmask", new object [] {
virtual_addresses});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_netmask(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_netmask", new object[] {
virtual_addresses}, callback, asyncState);
}
public string [] Endget_netmask(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_object_status
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBObjectStatus [] get_object_status(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_object_status", new object [] {
virtual_addresses});
return ((LocalLBObjectStatus [])(results[0]));
}
public System.IAsyncResult Beginget_object_status(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_object_status", new object[] {
virtual_addresses}, callback, asyncState);
}
public LocalLBObjectStatus [] Endget_object_status(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBObjectStatus [])(results[0]));
}
//-----------------------------------------------------------------------
// get_route_advertisement_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_route_advertisement_state(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_route_advertisement_state", new object [] {
virtual_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_route_advertisement_state(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_route_advertisement_state", new object[] {
virtual_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_route_advertisement_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_route_advertisement_state_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBVirtualAddressV2RouteAdvertisementType [] get_route_advertisement_state_v2(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_route_advertisement_state_v2", new object [] {
virtual_addresses});
return ((LocalLBVirtualAddressV2RouteAdvertisementType [])(results[0]));
}
public System.IAsyncResult Beginget_route_advertisement_state_v2(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_route_advertisement_state_v2", new object[] {
virtual_addresses}, callback, asyncState);
}
public LocalLBVirtualAddressV2RouteAdvertisementType [] Endget_route_advertisement_state_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBVirtualAddressV2RouteAdvertisementType [])(results[0]));
}
//-----------------------------------------------------------------------
// get_spanning_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_spanning_state(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_spanning_state", new object [] {
virtual_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_spanning_state(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_spanning_state", new object[] {
virtual_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_spanning_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBVirtualAddressV2VirtualAddressStatistics get_statistics(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_statistics", new object [] {
virtual_addresses});
return ((LocalLBVirtualAddressV2VirtualAddressStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
virtual_addresses}, callback, asyncState);
}
public LocalLBVirtualAddressV2VirtualAddressStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBVirtualAddressV2VirtualAddressStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_status_dependency_scope
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBVirtualAddressStatusDependency [] get_status_dependency_scope(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_status_dependency_scope", new object [] {
virtual_addresses});
return ((LocalLBVirtualAddressStatusDependency [])(results[0]));
}
public System.IAsyncResult Beginget_status_dependency_scope(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_status_dependency_scope", new object[] {
virtual_addresses}, callback, asyncState);
}
public LocalLBVirtualAddressStatusDependency [] Endget_status_dependency_scope(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBVirtualAddressStatusDependency [])(results[0]));
}
//-----------------------------------------------------------------------
// get_traffic_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_traffic_group(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_traffic_group", new object [] {
virtual_addresses});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_traffic_group(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_traffic_group", new object[] {
virtual_addresses}, callback, asyncState);
}
public string [] Endget_traffic_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// is_traffic_group_inherited
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_traffic_group_inherited(
string [] virtual_addresses
) {
object [] results = this.Invoke("is_traffic_group_inherited", new object [] {
virtual_addresses});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_traffic_group_inherited(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_traffic_group_inherited", new object[] {
virtual_addresses}, callback, asyncState);
}
public bool [] Endis_traffic_group_inherited(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_metadata
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void remove_all_metadata(
string [] virtual_addresses
) {
this.Invoke("remove_all_metadata", new object [] {
virtual_addresses});
}
public System.IAsyncResult Beginremove_all_metadata(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_metadata", new object[] {
virtual_addresses}, callback, asyncState);
}
public void Endremove_all_metadata(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_metadata
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void remove_metadata(
string [] virtual_addresses,
string [] [] names
) {
this.Invoke("remove_metadata", new object [] {
virtual_addresses,
names});
}
public System.IAsyncResult Beginremove_metadata(string [] virtual_addresses,string [] [] names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_metadata", new object[] {
virtual_addresses,
names}, callback, asyncState);
}
public void Endremove_metadata(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void reset_statistics(
string [] virtual_addresses
) {
this.Invoke("reset_statistics", new object [] {
virtual_addresses});
}
public System.IAsyncResult Beginreset_statistics(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
virtual_addresses}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_arp_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_arp_state(
string [] virtual_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_arp_state", new object [] {
virtual_addresses,
states});
}
public System.IAsyncResult Beginset_arp_state(string [] virtual_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_arp_state", new object[] {
virtual_addresses,
states}, callback, asyncState);
}
public void Endset_arp_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_auto_delete_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_auto_delete_state(
string [] virtual_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_auto_delete_state", new object [] {
virtual_addresses,
states});
}
public System.IAsyncResult Beginset_auto_delete_state(string [] virtual_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_auto_delete_state", new object[] {
virtual_addresses,
states}, callback, asyncState);
}
public void Endset_auto_delete_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_connection_limit(
string [] virtual_addresses,
long [] limits
) {
this.Invoke("set_connection_limit", new object [] {
virtual_addresses,
limits});
}
public System.IAsyncResult Beginset_connection_limit(string [] virtual_addresses,long [] limits, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_limit", new object[] {
virtual_addresses,
limits}, callback, asyncState);
}
public void Endset_connection_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_description(
string [] virtual_addresses,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
virtual_addresses,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] virtual_addresses,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
virtual_addresses,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_enabled_state(
string [] virtual_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_enabled_state", new object [] {
virtual_addresses,
states});
}
public System.IAsyncResult Beginset_enabled_state(string [] virtual_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_enabled_state", new object[] {
virtual_addresses,
states}, callback, asyncState);
}
public void Endset_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_icmp_echo_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_icmp_echo_state(
string [] virtual_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_icmp_echo_state", new object [] {
virtual_addresses,
states});
}
public System.IAsyncResult Beginset_icmp_echo_state(string [] virtual_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_icmp_echo_state", new object[] {
virtual_addresses,
states}, callback, asyncState);
}
public void Endset_icmp_echo_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_icmp_echo_state_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_icmp_echo_state_v2(
string [] virtual_addresses,
LocalLBVirtualAddressV2IcmpEchoType [] types
) {
this.Invoke("set_icmp_echo_state_v2", new object [] {
virtual_addresses,
types});
}
public System.IAsyncResult Beginset_icmp_echo_state_v2(string [] virtual_addresses,LocalLBVirtualAddressV2IcmpEchoType [] types, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_icmp_echo_state_v2", new object[] {
virtual_addresses,
types}, callback, asyncState);
}
public void Endset_icmp_echo_state_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_icmp_echo_state_v3
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_icmp_echo_state_v3(
string [] virtual_addresses,
LocalLBVirtualAddressV2IcmpEchoType2 [] types
) {
this.Invoke("set_icmp_echo_state_v3", new object [] {
virtual_addresses,
types});
}
public System.IAsyncResult Beginset_icmp_echo_state_v3(string [] virtual_addresses,LocalLBVirtualAddressV2IcmpEchoType2 [] types, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_icmp_echo_state_v3", new object[] {
virtual_addresses,
types}, callback, asyncState);
}
public void Endset_icmp_echo_state_v3(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_is_floating_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_is_floating_state(
string [] virtual_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_is_floating_state", new object [] {
virtual_addresses,
states});
}
public System.IAsyncResult Beginset_is_floating_state(string [] virtual_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_is_floating_state", new object[] {
virtual_addresses,
states}, callback, asyncState);
}
public void Endset_is_floating_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_metadata_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_metadata_description(
string [] virtual_addresses,
string [] [] names,
string [] [] descriptions
) {
this.Invoke("set_metadata_description", new object [] {
virtual_addresses,
names,
descriptions});
}
public System.IAsyncResult Beginset_metadata_description(string [] virtual_addresses,string [] [] names,string [] [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_metadata_description", new object[] {
virtual_addresses,
names,
descriptions}, callback, asyncState);
}
public void Endset_metadata_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_metadata_persistence
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_metadata_persistence(
string [] virtual_addresses,
string [] [] names,
CommonMetadataPersistence [] [] values
) {
this.Invoke("set_metadata_persistence", new object [] {
virtual_addresses,
names,
values});
}
public System.IAsyncResult Beginset_metadata_persistence(string [] virtual_addresses,string [] [] names,CommonMetadataPersistence [] [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_metadata_persistence", new object[] {
virtual_addresses,
names,
values}, callback, asyncState);
}
public void Endset_metadata_persistence(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_metadata_value
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_metadata_value(
string [] virtual_addresses,
string [] [] names,
string [] [] values
) {
this.Invoke("set_metadata_value", new object [] {
virtual_addresses,
names,
values});
}
public System.IAsyncResult Beginset_metadata_value(string [] virtual_addresses,string [] [] names,string [] [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_metadata_value", new object[] {
virtual_addresses,
names,
values}, callback, asyncState);
}
public void Endset_metadata_value(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_netmask
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_netmask(
string [] virtual_addresses,
string [] netmask
) {
this.Invoke("set_netmask", new object [] {
virtual_addresses,
netmask});
}
public System.IAsyncResult Beginset_netmask(string [] virtual_addresses,string [] netmask, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_netmask", new object[] {
virtual_addresses,
netmask}, callback, asyncState);
}
public void Endset_netmask(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_route_advertisement_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_route_advertisement_state(
string [] virtual_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_route_advertisement_state", new object [] {
virtual_addresses,
states});
}
public System.IAsyncResult Beginset_route_advertisement_state(string [] virtual_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_route_advertisement_state", new object[] {
virtual_addresses,
states}, callback, asyncState);
}
public void Endset_route_advertisement_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_route_advertisement_state_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_route_advertisement_state_v2(
string [] virtual_addresses,
LocalLBVirtualAddressV2RouteAdvertisementType [] states
) {
this.Invoke("set_route_advertisement_state_v2", new object [] {
virtual_addresses,
states});
}
public System.IAsyncResult Beginset_route_advertisement_state_v2(string [] virtual_addresses,LocalLBVirtualAddressV2RouteAdvertisementType [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_route_advertisement_state_v2", new object[] {
virtual_addresses,
states}, callback, asyncState);
}
public void Endset_route_advertisement_state_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_spanning_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_spanning_state(
string [] virtual_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_spanning_state", new object [] {
virtual_addresses,
states});
}
public System.IAsyncResult Beginset_spanning_state(string [] virtual_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_spanning_state", new object[] {
virtual_addresses,
states}, callback, asyncState);
}
public void Endset_spanning_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_status_dependency_scope
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_status_dependency_scope(
string [] virtual_addresses,
LocalLBVirtualAddressStatusDependency [] scopes
) {
this.Invoke("set_status_dependency_scope", new object [] {
virtual_addresses,
scopes});
}
public System.IAsyncResult Beginset_status_dependency_scope(string [] virtual_addresses,LocalLBVirtualAddressStatusDependency [] scopes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_status_dependency_scope", new object[] {
virtual_addresses,
scopes}, callback, asyncState);
}
public void Endset_status_dependency_scope(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_traffic_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddressV2",
RequestNamespace="urn:iControl:LocalLB/VirtualAddressV2", ResponseNamespace="urn:iControl:LocalLB/VirtualAddressV2")]
public void set_traffic_group(
string [] virtual_addresses,
string [] traffic_groups
) {
this.Invoke("set_traffic_group", new object [] {
virtual_addresses,
traffic_groups});
}
public System.IAsyncResult Beginset_traffic_group(string [] virtual_addresses,string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_traffic_group", new object[] {
virtual_addresses,
traffic_groups}, callback, asyncState);
}
public void Endset_traffic_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.VirtualAddressV2.IcmpEchoType", Namespace = "urn:iControl")]
public enum LocalLBVirtualAddressV2IcmpEchoType
{
IETYPE_ENABLED,
IETYPE_DISABLED,
IETYPE_SELECTIVE,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.VirtualAddressV2.IcmpEchoType2", Namespace = "urn:iControl")]
public enum LocalLBVirtualAddressV2IcmpEchoType2
{
IETYPE_2_UNKNOWN,
IETYPE_2_DISABLED,
IETYPE_2_ALWAYS,
IETYPE_2_SELECTIVE,
IETYPE_2_ANY,
IETYPE_2_ALL,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.VirtualAddressV2.RouteAdvertisementType", Namespace = "urn:iControl")]
public enum LocalLBVirtualAddressV2RouteAdvertisementType
{
RA_TYPE_UNKNOWN,
RA_TYPE_DISABLED,
RA_TYPE_ALWAYS,
RA_TYPE_SELECTIVE,
RA_TYPE_ANY,
RA_TYPE_ALL,
}
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.VirtualAddressV2.VirtualAddressStatisticEntry", Namespace = "urn:iControl")]
public partial class LocalLBVirtualAddressV2VirtualAddressStatisticEntry
{
private string virtual_addressField;
public string virtual_address
{
get { return this.virtual_addressField; }
set { this.virtual_addressField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.VirtualAddressV2.VirtualAddressStatistics", Namespace = "urn:iControl")]
public partial class LocalLBVirtualAddressV2VirtualAddressStatistics
{
private LocalLBVirtualAddressV2VirtualAddressStatisticEntry [] statisticsField;
public LocalLBVirtualAddressV2VirtualAddressStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
}
| |
using System;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
namespace Org.BouncyCastle.Crypto.Generators
{
/**
* generate suitable parameters for GOST3410.
*/
public class Gost3410ParametersGenerator
{
private int size;
private int typeproc;
private SecureRandom init_random;
/**
* initialise the key generator.
*
* @param size size of the key
* @param typeProcedure type procedure A,B = 1; A',B' - else
* @param random random byte source.
*/
public void Init(
int size,
int typeProcedure,
SecureRandom random)
{
this.size = size;
this.typeproc = typeProcedure;
this.init_random = random;
}
//Procedure A
private int procedure_A(int x0, int c, IBigInteger[] pq, int size)
{
//Verify and perform condition: 0<x<2^16; 0<c<2^16; c - odd.
while(x0<0 || x0>65536)
{
x0 = init_random.NextInt()/32768;
}
while((c<0 || c>65536) || (c/2==0))
{
c = init_random.NextInt()/32768 + 1;
}
IBigInteger C = BigInteger.ValueOf(c);
IBigInteger constA16 = BigInteger.ValueOf(19381);
//step1
IBigInteger[] y = new IBigInteger[1]; // begin length = 1
y[0] = BigInteger.ValueOf(x0);
//step 2
int[] t = new int[1]; // t - orders; begin length = 1
t[0] = size;
int s = 0;
for (int i=0; t[i]>=17; i++)
{
// extension array t
int[] tmp_t = new int[t.Length + 1]; ///////////////
Array.Copy(t,0,tmp_t,0,t.Length); // extension
t = new int[tmp_t.Length]; // array t
Array.Copy(tmp_t, 0, t, 0, tmp_t.Length); ///////////////
t[i+1] = t[i]/2;
s = i+1;
}
//step3
IBigInteger[] p = new IBigInteger[s+1];
p[s] = new BigInteger("8003",16); //set min prime number length 16 bit
int m = s-1; //step4
for (int i=0; i<s; i++)
{
int rm = t[m]/16; //step5
step6: for(;;)
{
//step 6
IBigInteger[] tmp_y = new BigInteger[y.Length]; ////////////////
Array.Copy(y,0,tmp_y,0,y.Length); // extension
y = new BigInteger[rm+1]; // array y
Array.Copy(tmp_y,0,y,0,tmp_y.Length); ////////////////
for (int j=0; j<rm; j++)
{
y[j+1] = (y[j].Multiply(constA16).Add(C)).Mod(BigInteger.Two.Pow(16));
}
//step 7
IBigInteger Ym = BigInteger.Zero;
for (int j=0; j<rm; j++)
{
Ym = Ym.Add(y[j].ShiftLeft(16*j));
}
y[0] = y[rm]; //step 8
//step 9
IBigInteger N = BigInteger.One.ShiftLeft(t[m]-1).Divide(p[m+1]).Add(
Ym.ShiftLeft(t[m]-1).Divide(p[m+1].ShiftLeft(16*rm)));
if (N.TestBit(0))
{
N = N.Add(BigInteger.One);
}
//step 10
for(;;)
{
//step 11
IBigInteger NByLastP = N.Multiply(p[m+1]);
if (NByLastP.BitLength > t[m])
{
goto step6; //step 12
}
p[m] = NByLastP.Add(BigInteger.One);
//step13
if (BigInteger.Two.ModPow(NByLastP, p[m]).CompareTo(BigInteger.One) == 0
&& BigInteger.Two.ModPow(N, p[m]).CompareTo(BigInteger.One) != 0)
{
break;
}
N = N.Add(BigInteger.Two);
}
if (--m < 0)
{
pq[0] = p[0];
pq[1] = p[1];
return y[0].IntValue; //return for procedure B step 2
}
break; //step 14
}
}
return y[0].IntValue;
}
//Procedure A'
private long procedure_Aa(long x0, long c, IBigInteger[] pq, int size)
{
//Verify and perform condition: 0<x<2^32; 0<c<2^32; c - odd.
while(x0<0 || x0>4294967296L)
{
x0 = init_random.NextInt()*2;
}
while((c<0 || c>4294967296L) || (c/2==0))
{
c = init_random.NextInt()*2+1;
}
IBigInteger C = BigInteger.ValueOf(c);
IBigInteger constA32 = BigInteger.ValueOf(97781173);
//step1
IBigInteger[] y = new IBigInteger[1]; // begin length = 1
y[0] = BigInteger.ValueOf(x0);
//step 2
int[] t = new int[1]; // t - orders; begin length = 1
t[0] = size;
int s = 0;
for (int i=0; t[i]>=33; i++)
{
// extension array t
int[] tmp_t = new int[t.Length + 1]; ///////////////
Array.Copy(t,0,tmp_t,0,t.Length); // extension
t = new int[tmp_t.Length]; // array t
Array.Copy(tmp_t, 0, t, 0, tmp_t.Length); ///////////////
t[i+1] = t[i]/2;
s = i+1;
}
//step3
IBigInteger[] p = new IBigInteger[s+1];
p[s] = new BigInteger("8000000B",16); //set min prime number length 32 bit
int m = s-1; //step4
for (int i=0; i<s; i++)
{
int rm = t[m]/32; //step5
step6: for(;;)
{
//step 6
IBigInteger[] tmp_y = new IBigInteger[y.Length]; ////////////////
Array.Copy(y,0,tmp_y,0,y.Length); // extension
y = new BigInteger[rm+1]; // array y
Array.Copy(tmp_y,0,y,0,tmp_y.Length); ////////////////
for (int j=0; j<rm; j++)
{
y[j+1] = (y[j].Multiply(constA32).Add(C)).Mod(BigInteger.Two.Pow(32));
}
//step 7
IBigInteger Ym = BigInteger.Zero;
for (int j=0; j<rm; j++)
{
Ym = Ym.Add(y[j].ShiftLeft(32*j));
}
y[0] = y[rm]; //step 8
//step 9
IBigInteger N = BigInteger.One.ShiftLeft(t[m]-1).Divide(p[m+1]).Add(
Ym.ShiftLeft(t[m]-1).Divide(p[m+1].ShiftLeft(32*rm)));
if (N.TestBit(0))
{
N = N.Add(BigInteger.One);
}
//step 10
for(;;)
{
//step 11
IBigInteger NByLastP = N.Multiply(p[m+1]);
if (NByLastP.BitLength > t[m])
{
goto step6; //step 12
}
p[m] = NByLastP.Add(BigInteger.One);
//step13
if (BigInteger.Two.ModPow(NByLastP, p[m]).CompareTo(BigInteger.One) == 0
&& BigInteger.Two.ModPow(N, p[m]).CompareTo(BigInteger.One) != 0)
{
break;
}
N = N.Add(BigInteger.Two);
}
if (--m < 0)
{
pq[0] = p[0];
pq[1] = p[1];
return y[0].LongValue; //return for procedure B' step 2
}
break; //step 14
}
}
return y[0].LongValue;
}
//Procedure B
private void procedure_B(int x0, int c, IBigInteger[] pq)
{
//Verify and perform condition: 0<x<2^16; 0<c<2^16; c - odd.
while(x0<0 || x0>65536)
{
x0 = init_random.NextInt()/32768;
}
while((c<0 || c>65536) || (c/2==0))
{
c = init_random.NextInt()/32768 + 1;
}
IBigInteger [] qp = new BigInteger[2];
IBigInteger q = null, Q = null, p = null;
IBigInteger C = BigInteger.ValueOf(c);
IBigInteger constA16 = BigInteger.ValueOf(19381);
//step1
x0 = procedure_A(x0, c, qp, 256);
q = qp[0];
//step2
x0 = procedure_A(x0, c, qp, 512);
Q = qp[0];
IBigInteger[] y = new IBigInteger[65];
y[0] = BigInteger.ValueOf(x0);
const int tp = 1024;
IBigInteger qQ = q.Multiply(Q);
step3:
for(;;)
{
//step 3
for (int j=0; j<64; j++)
{
y[j+1] = (y[j].Multiply(constA16).Add(C)).Mod(BigInteger.Two.Pow(16));
}
//step 4
IBigInteger Y = BigInteger.Zero;
for (int j=0; j<64; j++)
{
Y = Y.Add(y[j].ShiftLeft(16*j));
}
y[0] = y[64]; //step 5
//step 6
IBigInteger N = BigInteger.One.ShiftLeft(tp-1).Divide(qQ).Add(
Y.ShiftLeft(tp-1).Divide(qQ.ShiftLeft(1024)));
if (N.TestBit(0))
{
N = N.Add(BigInteger.One);
}
//step 7
for(;;)
{
//step 11
IBigInteger qQN = qQ.Multiply(N);
if (qQN.BitLength > tp)
{
goto step3; //step 9
}
p = qQN.Add(BigInteger.One);
//step10
if (BigInteger.Two.ModPow(qQN, p).CompareTo(BigInteger.One) == 0
&& BigInteger.Two.ModPow(q.Multiply(N), p).CompareTo(BigInteger.One) != 0)
{
pq[0] = p;
pq[1] = q;
return;
}
N = N.Add(BigInteger.Two);
}
}
}
//Procedure B'
private void procedure_Bb(long x0, long c, IBigInteger[] pq)
{
//Verify and perform condition: 0<x<2^32; 0<c<2^32; c - odd.
while(x0<0 || x0>4294967296L)
{
x0 = init_random.NextInt()*2;
}
while((c<0 || c>4294967296L) || (c/2==0))
{
c = init_random.NextInt()*2+1;
}
IBigInteger [] qp = new BigInteger[2];
IBigInteger q = null, Q = null, p = null;
IBigInteger C = BigInteger.ValueOf(c);
IBigInteger constA32 = BigInteger.ValueOf(97781173);
//step1
x0 = procedure_Aa(x0, c, qp, 256);
q = qp[0];
//step2
x0 = procedure_Aa(x0, c, qp, 512);
Q = qp[0];
IBigInteger[] y = new IBigInteger[33];
y[0] = BigInteger.ValueOf(x0);
const int tp = 1024;
IBigInteger qQ = q.Multiply(Q);
step3:
for(;;)
{
//step 3
for (int j=0; j<32; j++)
{
y[j+1] = (y[j].Multiply(constA32).Add(C)).Mod(BigInteger.Two.Pow(32));
}
//step 4
IBigInteger Y = BigInteger.Zero;
for (int j=0; j<32; j++)
{
Y = Y.Add(y[j].ShiftLeft(32*j));
}
y[0] = y[32]; //step 5
//step 6
IBigInteger N = BigInteger.One.ShiftLeft(tp-1).Divide(qQ).Add(
Y.ShiftLeft(tp-1).Divide(qQ.ShiftLeft(1024)));
if (N.TestBit(0))
{
N = N.Add(BigInteger.One);
}
//step 7
for(;;)
{
//step 11
IBigInteger qQN = qQ.Multiply(N);
if (qQN.BitLength > tp)
{
goto step3; //step 9
}
p = qQN.Add(BigInteger.One);
//step10
if (BigInteger.Two.ModPow(qQN, p).CompareTo(BigInteger.One) == 0
&& BigInteger.Two.ModPow(q.Multiply(N), p).CompareTo(BigInteger.One) != 0)
{
pq[0] = p;
pq[1] = q;
return;
}
N = N.Add(BigInteger.Two);
}
}
}
/**
* Procedure C
* procedure generates the a value from the given p,q,
* returning the a value.
*/
private IBigInteger procedure_C(IBigInteger p, IBigInteger q)
{
IBigInteger pSub1 = p.Subtract(BigInteger.One);
IBigInteger pSub1Divq = pSub1.Divide(q);
for(;;)
{
IBigInteger d = new BigInteger(p.BitLength, init_random);
// 1 < d < p-1
if (d.CompareTo(BigInteger.One) > 0 && d.CompareTo(pSub1) < 0)
{
IBigInteger a = d.ModPow(pSub1Divq, p);
if (a.CompareTo(BigInteger.One) != 0)
{
return a;
}
}
}
}
/**
* which generates the p , q and a values from the given parameters,
* returning the Gost3410Parameters object.
*/
public Gost3410Parameters GenerateParameters()
{
IBigInteger [] pq = new IBigInteger[2];
IBigInteger q = null, p = null, a = null;
int x0, c;
long x0L, cL;
if (typeproc==1)
{
x0 = init_random.NextInt();
c = init_random.NextInt();
switch(size)
{
case 512:
procedure_A(x0, c, pq, 512);
break;
case 1024:
procedure_B(x0, c, pq);
break;
default:
throw new ArgumentException("Ooops! key size 512 or 1024 bit.");
}
p = pq[0]; q = pq[1];
a = procedure_C(p, q);
//System.out.println("p:"+p.toString(16)+"\n"+"q:"+q.toString(16)+"\n"+"a:"+a.toString(16));
//System.out.println("p:"+p+"\n"+"q:"+q+"\n"+"a:"+a);
return new Gost3410Parameters(p, q, a, new Gost3410ValidationParameters(x0, c));
}
else
{
x0L = init_random.NextLong();
cL = init_random.NextLong();
switch(size)
{
case 512:
procedure_Aa(x0L, cL, pq, 512);
break;
case 1024:
procedure_Bb(x0L, cL, pq);
break;
default:
throw new InvalidOperationException("Ooops! key size 512 or 1024 bit.");
}
p = pq[0]; q = pq[1];
a = procedure_C(p, q);
//System.out.println("p:"+p.toString(16)+"\n"+"q:"+q.toString(16)+"\n"+"a:"+a.toString(16));
//System.out.println("p:"+p+"\n"+"q:"+q+"\n"+"a:"+a);
return new Gost3410Parameters(p, q, a, new Gost3410ValidationParameters(x0L, cL));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal sealed class OpenSslX509CertificateReader : ICertificatePal
{
private static DateTimeFormatInfo s_validityDateTimeFormatInfo;
private SafeX509Handle _cert;
private SafeEvpPKeyHandle _privateKey;
private X500DistinguishedName _subjectName;
private X500DistinguishedName _issuerName;
public static ICertificatePal FromHandle(IntPtr handle)
{
if (handle == IntPtr.Zero)
throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle));
return new OpenSslX509CertificateReader(Interop.Crypto.X509UpRef(handle));
}
public static ICertificatePal FromOtherCert(X509Certificate cert)
{
Debug.Assert(cert.Pal != null);
// Ensure private key is copied
OpenSslX509CertificateReader certPal = (OpenSslX509CertificateReader)cert.Pal;
return certPal.DuplicateHandles();
}
public static ICertificatePal FromBlob(byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
{
Debug.Assert(password != null);
ICertificatePal cert;
Exception openSslException;
if (TryReadX509Der(rawData, out cert) ||
TryReadX509Pem(rawData, out cert) ||
PkcsFormatReader.TryReadPkcs7Der(rawData, out cert) ||
PkcsFormatReader.TryReadPkcs7Pem(rawData, out cert) ||
PkcsFormatReader.TryReadPkcs12(rawData, password, out cert, out openSslException))
{
if (cert == null)
{
// Empty collection, most likely.
throw new CryptographicException();
}
return cert;
}
// Unsupported
Debug.Assert(openSslException != null);
throw openSslException;
}
public static ICertificatePal FromFile(string fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
{
// If we can't open the file, fail right away.
using (SafeBioHandle fileBio = Interop.Crypto.BioNewFile(fileName, "rb"))
{
Interop.Crypto.CheckValidOpenSslHandle(fileBio);
return FromBio(fileBio, password);
}
}
private static ICertificatePal FromBio(SafeBioHandle bio, SafePasswordHandle password)
{
int bioPosition = Interop.Crypto.BioTell(bio);
Debug.Assert(bioPosition >= 0);
ICertificatePal certPal;
if (TryReadX509Pem(bio, out certPal))
{
return certPal;
}
// Rewind, try again.
RewindBio(bio, bioPosition);
if (TryReadX509Der(bio, out certPal))
{
return certPal;
}
// Rewind, try again.
RewindBio(bio, bioPosition);
if (PkcsFormatReader.TryReadPkcs7Pem(bio, out certPal))
{
return certPal;
}
// Rewind, try again.
RewindBio(bio, bioPosition);
if (PkcsFormatReader.TryReadPkcs7Der(bio, out certPal))
{
return certPal;
}
// Rewind, try again.
RewindBio(bio, bioPosition);
// Capture the exception so in case of failure, the call to BioSeek does not override it.
Exception openSslException;
if (PkcsFormatReader.TryReadPkcs12(bio, password, out certPal, out openSslException))
{
return certPal;
}
// Since we aren't going to finish reading, leaving the buffer where it was when we got
// it seems better than leaving it in some arbitrary other position.
//
// Use BioSeek directly for the last seek attempt, because any failure here should instead
// report the already created (but not yet thrown) exception.
if (Interop.Crypto.BioSeek(bio, bioPosition) < 0)
{
Interop.Crypto.ErrClearError();
}
Debug.Assert(openSslException != null);
throw openSslException;
}
internal static void RewindBio(SafeBioHandle bio, int bioPosition)
{
int ret = Interop.Crypto.BioSeek(bio, bioPosition);
if (ret < 0)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
}
internal static bool TryReadX509Der(byte[] rawData, out ICertificatePal certPal)
{
SafeX509Handle certHandle = Interop.Crypto.DecodeX509(rawData, rawData.Length);
if (certHandle.IsInvalid)
{
certHandle.Dispose();
certPal = null;
Interop.Crypto.ErrClearError();
return false;
}
certPal = new OpenSslX509CertificateReader(certHandle);
return true;
}
internal static bool TryReadX509Pem(SafeBioHandle bio, out ICertificatePal certPal)
{
SafeX509Handle cert = Interop.Crypto.PemReadX509FromBioAux(bio);
if (cert.IsInvalid)
{
cert.Dispose();
certPal = null;
Interop.Crypto.ErrClearError();
return false;
}
certPal = new OpenSslX509CertificateReader(cert);
return true;
}
internal static bool TryReadX509PemNoAux(SafeBioHandle bio, out ICertificatePal certPal)
{
SafeX509Handle cert = Interop.Crypto.PemReadX509FromBio(bio);
if (cert.IsInvalid)
{
cert.Dispose();
certPal = null;
Interop.Crypto.ErrClearError();
return false;
}
certPal = new OpenSslX509CertificateReader(cert);
return true;
}
internal static bool TryReadX509Pem(byte[] rawData, out ICertificatePal certPal)
{
using (SafeBioHandle bio = Interop.Crypto.CreateMemoryBio())
{
Interop.Crypto.CheckValidOpenSslHandle(bio);
if (Interop.Crypto.BioWrite(bio, rawData, rawData.Length) != rawData.Length)
{
Interop.Crypto.ErrClearError();
}
return TryReadX509Pem(bio, out certPal);
}
}
internal static bool TryReadX509Der(SafeBioHandle bio, out ICertificatePal fromBio)
{
SafeX509Handle cert = Interop.Crypto.ReadX509AsDerFromBio(bio);
if (cert.IsInvalid)
{
cert.Dispose();
fromBio = null;
Interop.Crypto.ErrClearError();
return false;
}
fromBio = new OpenSslX509CertificateReader(cert);
return true;
}
internal OpenSslX509CertificateReader(SafeX509Handle handle)
{
// X509_check_purpose has the effect of populating the sha1_hash value,
// and other "initialize" type things.
bool init = Interop.Crypto.X509CheckPurpose(handle, -1, 0);
if (!init)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
_cert = handle;
}
public bool HasPrivateKey
{
get { return _privateKey != null; }
}
public IntPtr Handle
{
get { return _cert == null ? IntPtr.Zero : _cert.DangerousGetHandle(); }
}
internal SafeX509Handle SafeHandle
{
get { return _cert; }
}
public string Issuer => IssuerName.Name;
public string Subject => SubjectName.Name;
public string LegacyIssuer => IssuerName.Decode(X500DistinguishedNameFlags.None);
public string LegacySubject => SubjectName.Decode(X500DistinguishedNameFlags.None);
public byte[] Thumbprint
{
get
{
return Interop.Crypto.GetX509Thumbprint(_cert);
}
}
public string KeyAlgorithm
{
get
{
IntPtr oidPtr = Interop.Crypto.GetX509PublicKeyAlgorithm(_cert);
return Interop.Crypto.GetOidValue(oidPtr);
}
}
public byte[] KeyAlgorithmParameters
{
get
{
return Interop.Crypto.GetX509PublicKeyParameterBytes(_cert);
}
}
public byte[] PublicKeyValue
{
get
{
IntPtr keyBytesPtr = Interop.Crypto.GetX509PublicKeyBytes(_cert);
return Interop.Crypto.GetAsn1StringBytes(keyBytesPtr);
}
}
public byte[] SerialNumber
{
get
{
using (SafeSharedAsn1IntegerHandle serialNumber = Interop.Crypto.X509GetSerialNumber(_cert))
{
return Interop.Crypto.GetAsn1IntegerBytes(serialNumber);
}
}
}
public string SignatureAlgorithm
{
get
{
IntPtr oidPtr = Interop.Crypto.GetX509SignatureAlgorithm(_cert);
return Interop.Crypto.GetOidValue(oidPtr);
}
}
public DateTime NotAfter
{
get
{
return ExtractValidityDateTime(Interop.Crypto.GetX509NotAfter(_cert));
}
}
public DateTime NotBefore
{
get
{
return ExtractValidityDateTime(Interop.Crypto.GetX509NotBefore(_cert));
}
}
public byte[] RawData
{
get
{
return Interop.Crypto.OpenSslEncode(
x => Interop.Crypto.GetX509DerSize(x),
(x, buf) => Interop.Crypto.EncodeX509(x, buf),
_cert);
}
}
public int Version
{
get
{
int version = Interop.Crypto.GetX509Version(_cert);
if (version < 0)
{
throw new CryptographicException();
}
// The file encoding is v1(0), v2(1), v3(2).
// The .NET answers are 1, 2, 3.
return version + 1;
}
}
public bool Archived
{
get { return false; }
set
{
throw new PlatformNotSupportedException(
SR.Format(SR.Cryptography_Unix_X509_PropertyNotSettable, "Archived"));
}
}
public string FriendlyName
{
get { return ""; }
set
{
throw new PlatformNotSupportedException(
SR.Format(SR.Cryptography_Unix_X509_PropertyNotSettable, "FriendlyName"));
}
}
public X500DistinguishedName SubjectName
{
get
{
if (_subjectName == null)
{
_subjectName = Interop.Crypto.LoadX500Name(Interop.Crypto.X509GetSubjectName(_cert));
}
return _subjectName;
}
}
public X500DistinguishedName IssuerName
{
get
{
if (_issuerName == null)
{
_issuerName = Interop.Crypto.LoadX500Name(Interop.Crypto.X509GetIssuerName(_cert));
}
return _issuerName;
}
}
public IEnumerable<X509Extension> Extensions
{
get
{
int extensionCount = Interop.Crypto.X509GetExtCount(_cert);
X509Extension[] extensions = new X509Extension[extensionCount];
for (int i = 0; i < extensionCount; i++)
{
IntPtr ext = Interop.Crypto.X509GetExt(_cert, i);
Interop.Crypto.CheckValidOpenSslHandle(ext);
IntPtr oidPtr = Interop.Crypto.X509ExtensionGetOid(ext);
Interop.Crypto.CheckValidOpenSslHandle(oidPtr);
string oidValue = Interop.Crypto.GetOidValue(oidPtr);
Oid oid = new Oid(oidValue);
IntPtr dataPtr = Interop.Crypto.X509ExtensionGetData(ext);
Interop.Crypto.CheckValidOpenSslHandle(dataPtr);
byte[] extData = Interop.Crypto.GetAsn1StringBytes(dataPtr);
bool critical = Interop.Crypto.X509ExtensionGetCritical(ext);
extensions[i] = new X509Extension(oid, extData, critical);
}
return extensions;
}
}
internal static ArraySegment<byte> FindFirstExtension(SafeX509Handle cert, string oidValue)
{
int nid = Interop.Crypto.ResolveRequiredNid(oidValue);
using (SafeSharedAsn1OctetStringHandle data = Interop.Crypto.X509FindExtensionData(cert, nid))
{
if (data.IsInvalid)
{
return default;
}
return Interop.Crypto.RentAsn1StringBytes(data.DangerousGetHandle());
}
}
internal void SetPrivateKey(SafeEvpPKeyHandle privateKey)
{
_privateKey = privateKey;
}
internal SafeEvpPKeyHandle PrivateKeyHandle
{
get { return _privateKey; }
}
public RSA GetRSAPrivateKey()
{
if (_privateKey == null || _privateKey.IsInvalid)
{
return null;
}
return new RSAOpenSsl(_privateKey);
}
public DSA GetDSAPrivateKey()
{
if (_privateKey == null || _privateKey.IsInvalid)
{
return null;
}
return new DSAOpenSsl(_privateKey);
}
public ECDsa GetECDsaPublicKey()
{
using (SafeEvpPKeyHandle publicKeyHandle = Interop.Crypto.GetX509EvpPublicKey(_cert))
{
Interop.Crypto.CheckValidOpenSslHandle(publicKeyHandle);
return new ECDsaOpenSsl(publicKeyHandle);
}
}
public ECDsa GetECDsaPrivateKey()
{
if (_privateKey == null || _privateKey.IsInvalid)
{
return null;
}
return new ECDsaOpenSsl(_privateKey);
}
private ICertificatePal CopyWithPrivateKey(SafeEvpPKeyHandle privateKey)
{
// This could be X509Duplicate for a full clone, but since OpenSSL certificates
// are functionally immutable (unlike Windows ones) an UpRef is sufficient.
SafeX509Handle certHandle = Interop.Crypto.X509UpRef(_cert);
OpenSslX509CertificateReader duplicate = new OpenSslX509CertificateReader(certHandle);
duplicate.SetPrivateKey(privateKey);
return duplicate;
}
public ICertificatePal CopyWithPrivateKey(DSA privateKey)
{
DSAOpenSsl typedKey = privateKey as DSAOpenSsl;
if (typedKey != null)
{
return CopyWithPrivateKey((SafeEvpPKeyHandle)typedKey.DuplicateKeyHandle());
}
DSAParameters dsaParameters = privateKey.ExportParameters(true);
using (PinAndClear.Track(dsaParameters.X))
using (typedKey = new DSAOpenSsl(dsaParameters))
{
return CopyWithPrivateKey((SafeEvpPKeyHandle)typedKey.DuplicateKeyHandle());
}
}
public ICertificatePal CopyWithPrivateKey(ECDsa privateKey)
{
ECDsaOpenSsl typedKey = privateKey as ECDsaOpenSsl;
if (typedKey != null)
{
return CopyWithPrivateKey((SafeEvpPKeyHandle)typedKey.DuplicateKeyHandle());
}
ECParameters ecParameters = privateKey.ExportParameters(true);
using (PinAndClear.Track(ecParameters.D))
using (typedKey = new ECDsaOpenSsl())
{
typedKey.ImportParameters(ecParameters);
return CopyWithPrivateKey((SafeEvpPKeyHandle)typedKey.DuplicateKeyHandle());
}
}
public ICertificatePal CopyWithPrivateKey(RSA privateKey)
{
RSAOpenSsl typedKey = privateKey as RSAOpenSsl;
if (typedKey != null)
{
return CopyWithPrivateKey((SafeEvpPKeyHandle)typedKey.DuplicateKeyHandle());
}
RSAParameters rsaParameters = privateKey.ExportParameters(true);
using (PinAndClear.Track(rsaParameters.D))
using (PinAndClear.Track(rsaParameters.P))
using (PinAndClear.Track(rsaParameters.Q))
using (PinAndClear.Track(rsaParameters.DP))
using (PinAndClear.Track(rsaParameters.DQ))
using (PinAndClear.Track(rsaParameters.InverseQ))
using (typedKey = new RSAOpenSsl(rsaParameters))
{
return CopyWithPrivateKey((SafeEvpPKeyHandle)typedKey.DuplicateKeyHandle());
}
}
public string GetNameInfo(X509NameType nameType, bool forIssuer)
{
using (SafeBioHandle bioHandle = Interop.Crypto.GetX509NameInfo(_cert, (int)nameType, forIssuer))
{
if (bioHandle.IsInvalid)
{
return "";
}
int bioSize = Interop.Crypto.GetMemoryBioSize(bioHandle);
// Ensure space for the trailing \0
var buf = new byte[bioSize + 1];
int read = Interop.Crypto.BioGets(bioHandle, buf, buf.Length);
if (read < 0)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
return Encoding.UTF8.GetString(buf, 0, read);
}
}
public void AppendPrivateKeyInfo(StringBuilder sb)
{
if (!HasPrivateKey)
{
return;
}
// There's nothing really to say about the key, just acknowledge there is one.
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("[Private Key]");
}
public void Dispose()
{
if (_privateKey != null)
{
_privateKey.Dispose();
_privateKey = null;
}
if (_cert != null)
{
_cert.Dispose();
_cert = null;
}
}
internal OpenSslX509CertificateReader DuplicateHandles()
{
SafeX509Handle certHandle = Interop.Crypto.X509UpRef(_cert);
OpenSslX509CertificateReader duplicate = new OpenSslX509CertificateReader(certHandle);
if (_privateKey != null)
{
SafeEvpPKeyHandle keyHandle = _privateKey.DuplicateHandle();
duplicate.SetPrivateKey(keyHandle);
}
return duplicate;
}
internal static DateTime ExtractValidityDateTime(IntPtr validityDatePtr)
{
byte[] bytes = Interop.Crypto.GetAsn1StringBytes(validityDatePtr);
// RFC 5280 (X509v3 - https://tools.ietf.org/html/rfc5280)
// states that the validity times are either UTCTime:YYMMDDHHMMSSZ (13 bytes)
// or GeneralizedTime:YYYYMMDDHHMMSSZ (15 bytes).
// Technically, both UTCTime and GeneralizedTime can have more complicated
// representations, but X509 restricts them to only the one form each.
//
// Furthermore, the UTCTime year values are to be interpreted as 1950-2049.
//
// No mention is made in RFC 5280 of different rules for v1 or v2 certificates.
Debug.Assert(bytes != null);
Debug.Assert(
bytes.Length == 13 || bytes.Length == 15,
"DateTime value should be UTCTime (13 bytes) or GeneralizedTime (15 bytes)");
Debug.Assert(
bytes[bytes.Length - 1] == 'Z',
"DateTime value should end with Z marker");
if (bytes == null || bytes.Length < 1 || bytes[bytes.Length - 1] != 'Z')
{
throw new CryptographicException();
}
string dateString = Encoding.ASCII.GetString(bytes);
if (s_validityDateTimeFormatInfo == null)
{
DateTimeFormatInfo validityFormatInfo =
(DateTimeFormatInfo)CultureInfo.InvariantCulture.DateTimeFormat.Clone();
// Two-digit years are 1950-2049
validityFormatInfo.Calendar.TwoDigitYearMax = 2049;
s_validityDateTimeFormatInfo = validityFormatInfo;
}
if (bytes.Length == 13)
{
DateTime utcTime;
if (!DateTime.TryParseExact(
dateString,
"yyMMddHHmmss'Z'",
s_validityDateTimeFormatInfo,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
out utcTime))
{
throw new CryptographicException();
}
return utcTime.ToLocalTime();
}
if (bytes.Length == 15)
{
DateTime generalizedTime;
if (!DateTime.TryParseExact(
dateString,
"yyyyMMddHHmmss'Z'",
s_validityDateTimeFormatInfo,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
out generalizedTime))
{
throw new CryptographicException();
}
return generalizedTime.ToLocalTime();
}
throw new CryptographicException();
}
public byte[] Export(X509ContentType contentType, SafePasswordHandle password)
{
using (IExportPal storePal = StorePal.FromCertificate(this))
{
return storePal.Export (contentType, password);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
namespace Umbraco.Core
{
/// <summary>
/// A utility class for type checking, this provides internal caching so that calls to these methods will be faster
/// than doing a manual type check in c#
/// </summary>
internal static class TypeHelper
{
private static readonly ConcurrentDictionary<Tuple<Type, bool, bool, bool>, PropertyInfo[]> GetPropertiesCache
= new ConcurrentDictionary<Tuple<Type, bool, bool, bool>, PropertyInfo[]>();
private static readonly ConcurrentDictionary<Type, FieldInfo[]> GetFieldsCache
= new ConcurrentDictionary<Type, FieldInfo[]>();
private static readonly Assembly[] EmptyAssemblies = new Assembly[0];
/// <summary>
/// Based on a type we'll check if it is IEnumerable{T} (or similar) and if so we'll return a List{T}, this will also deal with array types and return List{T} for those too.
/// If it cannot be done, null is returned.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
internal static IList CreateGenericEnumerableFromObject(object obj)
{
var type = obj.GetType();
if (type.IsGenericType)
{
var genericTypeDef = type.GetGenericTypeDefinition();
if (genericTypeDef == typeof(IEnumerable<>)
|| genericTypeDef == typeof(ICollection<>)
|| genericTypeDef == typeof(Collection<>)
|| genericTypeDef == typeof(IList<>)
|| genericTypeDef == typeof(List<>)
//this will occur when Linq is used and we get the odd WhereIterator or DistinctIterators since those are special iterator types
|| obj is IEnumerable)
{
//if it is a IEnumerable<>, IList<T> or ICollection<> we'll use a List<>
var genericType = typeof(List<>).MakeGenericType(type.GetGenericArguments());
//pass in obj to fill the list
return (IList)Activator.CreateInstance(genericType, obj);
}
}
if (type.IsArray)
{
//if its an array, we'll use a List<>
var genericType = typeof(List<>).MakeGenericType(type.GetElementType());
//pass in obj to fill the list
return (IList)Activator.CreateInstance(genericType, obj);
}
return null;
}
/// <summary>
/// Checks if the method is actually overriding a base method
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
public static bool IsOverride(MethodInfo m)
{
return m.GetBaseDefinition().DeclaringType != m.DeclaringType;
}
/// <summary>
/// Find all assembly references that are referencing the assignTypeFrom Type's assembly found in the assemblyList
/// </summary>
/// <param name="assembly">The referenced assembly.</param>
/// <param name="assemblies">A list of assemblies.</param>
/// <returns></returns>
/// <remarks>
/// If the assembly of the assignTypeFrom Type is in the App_Code assembly, then we return nothing since things cannot
/// reference that assembly, same with the global.asax assembly.
/// </remarks>
public static Assembly[] GetReferencingAssemblies(Assembly assembly, IEnumerable<Assembly> assemblies)
{
if (assembly.IsAppCodeAssembly() || assembly.IsGlobalAsaxAssembly())
return EmptyAssemblies;
// find all assembly references that are referencing the current type's assembly since we
// should only be scanning those assemblies because any other assembly will definitely not
// contain sub type's of the one we're currently looking for
var name = assembly.GetName().Name;
return assemblies.Where(x => x == assembly || HasReference(x, name)).ToArray();
}
/// <summary>
/// Determines if an assembly references another assembly.
/// </summary>
/// <param name="assembly"></param>
/// <param name="name"></param>
/// <returns></returns>
public static bool HasReference(Assembly assembly, string name)
{
// ReSharper disable once LoopCanBeConvertedToQuery - no!
foreach (var a in assembly.GetReferencedAssemblies())
{
if (string.Equals(a.Name, name, StringComparison.Ordinal)) return true;
}
return false;
}
/// <summary>
/// Returns true if the type is a class and is not static
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static bool IsNonStaticClass(Type t)
{
return t.IsClass && IsStaticClass(t) == false;
}
/// <summary>
/// Returns true if the type is a static class
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
/// <remarks>
/// In IL a static class is abstract and sealed
/// see: http://stackoverflow.com/questions/1175888/determine-if-a-type-is-static
/// </remarks>
public static bool IsStaticClass(Type type)
{
return type.IsAbstract && type.IsSealed;
}
/// <summary>
/// Finds a lowest base class amongst a collection of types
/// </summary>
/// <param name="types"></param>
/// <returns></returns>
/// <remarks>
/// The term 'lowest' refers to the most base class of the type collection.
/// If a base type is not found amongst the type collection then an invalid attempt is returned.
/// </remarks>
public static Attempt<Type> GetLowestBaseType(params Type[] types)
{
if (types.Length == 0)
return Attempt<Type>.Fail();
if (types.Length == 1)
return Attempt.Succeed(types[0]);
foreach (var curr in types)
{
var others = types.Except(new[] {curr});
//is the curr type a common denominator for all others ?
var isBase = others.All(curr.IsAssignableFrom);
//if this type is the base for all others
if (isBase)
{
return Attempt.Succeed(curr);
}
}
return Attempt<Type>.Fail();
}
/// <summary>
/// Determines whether the type <paramref name="implementation"/> is assignable from the specified implementation,
/// and caches the result across the application using a <see cref="ConcurrentDictionary{TKey,TValue}"/>.
/// </summary>
/// <param name="contract">The type of the contract.</param>
/// <param name="implementation">The implementation.</param>
/// <returns>
/// <c>true</c> if [is type assignable from] [the specified contract]; otherwise, <c>false</c>.
/// </returns>
public static bool IsTypeAssignableFrom(Type contract, Type implementation)
{
return contract.IsAssignableFrom(implementation);
}
/// <summary>
/// Determines whether the type <paramref name="implementation"/> is assignable from the specified implementation <typeparamref name="TContract"/>,
/// and caches the result across the application using a <see cref="ConcurrentDictionary{TKey,TValue}"/>.
/// </summary>
/// <typeparam name="TContract">The type of the contract.</typeparam>
/// <param name="implementation">The implementation.</param>
public static bool IsTypeAssignableFrom<TContract>(Type implementation)
{
return IsTypeAssignableFrom(typeof(TContract), implementation);
}
/// <summary>
/// Determines whether the object instance <paramref name="implementation"/> is assignable from the specified implementation <typeparamref name="TContract"/>,
/// and caches the result across the application using a <see cref="ConcurrentDictionary{TKey,TValue}"/>.
/// </summary>
/// <typeparam name="TContract">The type of the contract.</typeparam>
/// <param name="implementation">The implementation.</param>
public static bool IsTypeAssignableFrom<TContract>(object implementation)
{
if (implementation == null) throw new ArgumentNullException("implementation");
return IsTypeAssignableFrom<TContract>(implementation.GetType());
}
/// <summary>
/// A method to determine whether <paramref name="implementation"/> represents a value type.
/// </summary>
/// <param name="implementation">The implementation.</param>
public static bool IsValueType(Type implementation)
{
return implementation.IsValueType || implementation.IsPrimitive;
}
/// <summary>
/// A method to determine whether <paramref name="implementation"/> is an implied value type (<see cref="Type.IsValueType"/>, <see cref="Type.IsEnum"/> or a string).
/// </summary>
/// <param name="implementation">The implementation.</param>
public static bool IsImplicitValueType(Type implementation)
{
return IsValueType(implementation) || implementation.IsEnum || implementation == typeof (string);
}
/// <summary>
/// Returns (and caches) a PropertyInfo from a type
/// </summary>
/// <param name="type"></param>
/// <param name="name"></param>
/// <param name="mustRead"></param>
/// <param name="mustWrite"></param>
/// <param name="includeIndexed"></param>
/// <param name="caseSensitive"> </param>
/// <returns></returns>
public static PropertyInfo GetProperty(Type type, string name,
bool mustRead = true,
bool mustWrite = true,
bool includeIndexed = false,
bool caseSensitive = true)
{
return CachedDiscoverableProperties(type, mustRead, mustWrite, includeIndexed)
.FirstOrDefault(x => caseSensitive ? (x.Name == name) : x.Name.InvariantEquals(name));
}
/// <summary>
/// Gets (and caches) <see cref="FieldInfo"/> discoverable in the current <see cref="AppDomain"/> for a given <paramref name="type"/>.
/// </summary>
/// <param name="type">The source.</param>
/// <returns></returns>
public static FieldInfo[] CachedDiscoverableFields(Type type)
{
return GetFieldsCache.GetOrAdd(
type,
x => type
.GetFields(BindingFlags.Public | BindingFlags.Instance)
.Where(y => y.IsInitOnly == false)
.ToArray());
}
/// <summary>
/// Gets (and caches) <see cref="PropertyInfo"/> discoverable in the current <see cref="AppDomain"/> for a given <paramref name="type"/>.
/// </summary>
/// <param name="type">The source.</param>
/// <param name="mustRead">true if the properties discovered are readable</param>
/// <param name="mustWrite">true if the properties discovered are writable</param>
/// <param name="includeIndexed">true if the properties discovered are indexable</param>
/// <returns></returns>
public static PropertyInfo[] CachedDiscoverableProperties(Type type, bool mustRead = true, bool mustWrite = true, bool includeIndexed = false)
{
return GetPropertiesCache.GetOrAdd(
new Tuple<Type, bool, bool, bool>(type, mustRead, mustWrite, includeIndexed),
x => type
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(y => (mustRead == false || y.CanRead)
&& (mustWrite == false || y.CanWrite)
&& (includeIndexed || y.GetIndexParameters().Any() == false))
.ToArray());
}
#region Match Type
//TODO: Need to determine if these methods should replace/combine/merge etc with IsTypeAssignableFrom, IsAssignableFromGeneric
// readings:
// http://stackoverflow.com/questions/2033912/c-sharp-variance-problem-assigning-listderived-as-listbase
// http://stackoverflow.com/questions/2208043/generic-variance-in-c-sharp-4-0
// http://stackoverflow.com/questions/8401738/c-sharp-casting-generics-covariance-and-contravariance
// http://stackoverflow.com/questions/1827425/how-to-check-programatically-if-a-type-is-a-struct-or-a-class
// http://stackoverflow.com/questions/74616/how-to-detect-if-type-is-another-generic-type/1075059#1075059
private static bool MatchGeneric(Type implementation, Type contract, IDictionary<string, Type> bindings)
{
// trying to match eg List<int> with List<T>
// or List<List<List<int>>> with List<ListList<T>>>
// classes are NOT invariant so List<string> does not match List<object>
if (implementation.IsGenericType == false) return false;
// must have the same generic type definition
var implDef = implementation.GetGenericTypeDefinition();
var contDef = contract.GetGenericTypeDefinition();
if (implDef != contDef) return false;
// must have the same number of generic arguments
var implArgs = implementation.GetGenericArguments();
var contArgs = contract.GetGenericArguments();
if (implArgs.Length != contArgs.Length) return false;
// generic arguments must match
// in insta we should have actual types (eg int, string...)
// in typea we can have generic parameters (eg <T>)
for (var i = 0; i < implArgs.Length; i++)
{
const bool variance = false; // classes are NOT invariant
if (MatchType(implArgs[i], contArgs[i], bindings, variance) == false)
return false;
}
return true;
}
public static bool MatchType(Type implementation, Type contract)
{
return MatchType(implementation, contract, new Dictionary<string, Type>());
}
internal static bool MatchType(Type implementation, Type contract, IDictionary<string, Type> bindings, bool variance = true)
{
if (contract.IsGenericType)
{
// eg type is List<int> or List<T>
// if we have variance then List<int> can match IList<T>
// if we don't have variance it can't - must have exact type
// try to match implementation against contract
if (MatchGeneric(implementation, contract, bindings)) return true;
// if no variance, fail
if (variance == false) return false;
// try to match an ancestor of implementation against contract
var t = implementation.BaseType;
while (t != null)
{
if (MatchGeneric(t, contract, bindings)) return true;
t = t.BaseType;
}
// try to match an interface of implementation against contract
return implementation.GetInterfaces().Any(i => MatchGeneric(i, contract, bindings));
}
if (contract.IsGenericParameter)
{
// eg <T>
if (bindings.ContainsKey(contract.Name))
{
// already bound: ensure it's compatible
return bindings[contract.Name] == implementation;
}
// not already bound: bind
bindings[contract.Name] = implementation;
return true;
}
// not a generic type, not a generic parameter
// so normal class or interface
// about primitive types, value types, etc:
// http://stackoverflow.com/questions/1827425/how-to-check-programatically-if-a-type-is-a-struct-or-a-class
// if it's a primitive type... it needs to be ==
if (implementation == contract) return true;
if (contract.IsClass && implementation.IsClass && implementation.IsSubclassOf(contract)) return true;
if (contract.IsInterface && implementation.GetInterfaces().Contains(contract)) return true;
return false;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLoption = Interop.Http.CURLoption;
using CurlProtocols = Interop.Http.CurlProtocols;
using CURLProxyType = Interop.Http.curl_proxytype;
using SafeCurlHandle = Interop.Http.SafeCurlHandle;
using SafeCurlSListHandle = Interop.Http.SafeCurlSListHandle;
using SafeCallbackHandle = Interop.Http.SafeCallbackHandle;
using SeekCallback = Interop.Http.SeekCallback;
using ReadWriteCallback = Interop.Http.ReadWriteCallback;
using ReadWriteFunction = Interop.Http.ReadWriteFunction;
using SslCtxCallback = Interop.Http.SslCtxCallback;
using DebugCallback = Interop.Http.DebugCallback;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
/// <summary>Provides all of the state associated with a single request/response, referred to as an "easy" request in libcurl parlance.</summary>
private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage>
{
internal readonly CurlHandler _handler;
internal readonly HttpRequestMessage _requestMessage;
internal readonly CurlResponseMessage _responseMessage;
internal readonly CancellationToken _cancellationToken;
internal readonly HttpContentAsyncStream _requestContentStream;
internal SafeCurlHandle _easyHandle;
private SafeCurlSListHandle _requestHeaders;
internal MultiAgent _associatedMultiAgent;
internal SendTransferState _sendTransferState;
internal StrongToWeakReference<EasyRequest> _selfStrongToWeakReference;
private SafeCallbackHandle _callbackHandle;
public EasyRequest(CurlHandler handler, HttpRequestMessage requestMessage, CancellationToken cancellationToken) :
base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_handler = handler;
_requestMessage = requestMessage;
_cancellationToken = cancellationToken;
if (requestMessage.Content != null)
{
_requestContentStream = new HttpContentAsyncStream(this);
}
_responseMessage = new CurlResponseMessage(this);
}
/// <summary>
/// Initialize the underlying libcurl support for this EasyRequest.
/// This is separated out of the constructor so that we can take into account
/// any additional configuration needed based on the request message
/// after the EasyRequest is configured and so that error handling
/// can be better handled in the caller.
/// </summary>
internal void InitializeCurl()
{
// Create the underlying easy handle
SafeCurlHandle easyHandle = Interop.Http.EasyCreate();
if (easyHandle.IsInvalid)
{
throw new OutOfMemoryException();
}
_easyHandle = easyHandle;
// Configure the handle
SetUrl();
SetMultithreading();
SetTimeouts();
SetRedirection();
SetVerb();
SetVersion();
SetDecompressionOptions();
SetProxyOptions(_requestMessage.RequestUri);
SetCredentialsOptions(_handler.GetCredentials(_requestMessage.RequestUri));
SetCookieOption(_requestMessage.RequestUri);
SetRequestHeaders();
SetSslOptions();
}
public void EnsureResponseMessagePublished()
{
// If the response message hasn't been published yet, do any final processing of it before it is.
if (!Task.IsCompleted)
{
EventSourceTrace("Publishing response message");
// On Windows, if the response was automatically decompressed, Content-Encoding and Content-Length
// headers are removed from the response. Do the same thing here.
DecompressionMethods dm = _handler.AutomaticDecompression;
if (dm != DecompressionMethods.None)
{
HttpContentHeaders contentHeaders = _responseMessage.Content.Headers;
IEnumerable<string> encodings;
if (contentHeaders.TryGetValues(HttpKnownHeaderNames.ContentEncoding, out encodings))
{
foreach (string encoding in encodings)
{
if (((dm & DecompressionMethods.GZip) != 0 && string.Equals(encoding, EncodingNameGzip, StringComparison.OrdinalIgnoreCase)) ||
((dm & DecompressionMethods.Deflate) != 0 && string.Equals(encoding, EncodingNameDeflate, StringComparison.OrdinalIgnoreCase)))
{
contentHeaders.Remove(HttpKnownHeaderNames.ContentEncoding);
contentHeaders.Remove(HttpKnownHeaderNames.ContentLength);
break;
}
}
}
}
}
// Now ensure it's published.
bool completedTask = TrySetResult(_responseMessage);
Debug.Assert(completedTask || Task.Status == TaskStatus.RanToCompletion,
"If the task was already completed, it should have been completed successfully; " +
"we shouldn't be completing as successful after already completing as failed.");
// If we successfully transitioned it to be completed, we also handed off lifetime ownership
// of the response to the owner of the task. Transition our reference on the EasyRequest
// to be weak instead of strong, so that we don't forcibly keep it alive.
if (completedTask)
{
Debug.Assert(_selfStrongToWeakReference != null, "Expected non-null wrapper");
_selfStrongToWeakReference.MakeWeak();
}
}
public void FailRequestAndCleanup(Exception error)
{
FailRequest(error);
Cleanup();
}
public void FailRequest(Exception error)
{
Debug.Assert(error != null, "Expected non-null exception");
EventSourceTrace("Failing request: {0}", error);
var oce = error as OperationCanceledException;
if (oce != null)
{
TrySetCanceled(oce.CancellationToken);
}
else
{
if (error is IOException || error is CurlException || error == null)
{
error = CreateHttpRequestException(error);
}
TrySetException(error);
}
// There's not much we can reasonably assert here about the result of TrySet*.
// It's possible that the task wasn't yet completed (e.g. a failure while initiating the request),
// it's possible that the task was already completed as success (e.g. a failure sending back the response),
// and it's possible that the task was already completed as failure (e.g. we handled the exception and
// faulted the task, but then tried to fault it again while finishing processing in the main loop).
// Make sure the exception is available on the response stream so that it's propagated
// from any attempts to read from the stream.
_responseMessage.ResponseStream.SignalComplete(error);
}
public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up
{
_responseMessage.ResponseStream.SignalComplete(); // No more callbacks so no more data
// Don't dispose of the ResponseMessage.ResponseStream as it may still be in use
// by code reading data stored in the stream.
// Dispose of the input content stream if there was one. Nothing should be using it any more.
_requestContentStream?.Dispose();
// Dispose of the underlying easy handle. We're no longer processing it.
_easyHandle?.Dispose();
// Dispose of the request headers if we had any. We had to keep this handle
// alive as long as the easy handle was using it. We didn't need to do any
// ref counting on the safe handle, though, as the only processing happens
// in Process, which ensures the handle will be rooted while libcurl is
// doing any processing that assumes it's valid.
_requestHeaders?.Dispose();
_callbackHandle?.Dispose();
}
private void SetUrl()
{
Uri requestUri = _requestMessage.RequestUri;
long scopeId;
if (IsLinkLocal(requestUri, out scopeId))
{
// Uri.AbsoluteUri doesn't include the ScopeId/ZoneID, so if it is link-local,
// we separately pass the scope to libcurl.
EventSourceTrace("ScopeId: {0}", scopeId);
SetCurlOption(CURLoption.CURLOPT_ADDRESS_SCOPE, scopeId);
}
EventSourceTrace("Url: {0}", requestUri);
SetCurlOption(CURLoption.CURLOPT_URL, requestUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, (long)(CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS));
}
private static bool IsLinkLocal(Uri url, out long scopeId)
{
IPAddress ip;
if (IPAddress.TryParse(url.DnsSafeHost, out ip) && ip.IsIPv6LinkLocal)
{
scopeId = ip.ScopeId;
return true;
}
scopeId = 0;
return false;
}
private void SetMultithreading()
{
SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L);
}
private void SetTimeouts()
{
// Set timeout limit on the connect phase.
SetCurlOption(CURLoption.CURLOPT_CONNECTTIMEOUT_MS, int.MaxValue);
// Override the default DNS cache timeout. libcurl defaults to a 1 minute
// timeout, but we extend that to match the Windows timeout of 10 minutes.
const int DnsCacheTimeoutSeconds = 10 * 60;
SetCurlOption(CURLoption.CURLOPT_DNS_CACHE_TIMEOUT, DnsCacheTimeoutSeconds);
}
private void SetRedirection()
{
if (!_handler._automaticRedirection)
{
return;
}
SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L);
CurlProtocols redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ?
CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https
CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https
SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, (long)redirectProtocols);
SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections);
EventSourceTrace("Max automatic redirections: {0}", _handler._maxAutomaticRedirections);
}
/// <summary>
/// When a Location header is received along with a 3xx status code, it's an indication
/// that we're likely to redirect. Prepare the easy handle in case we do.
/// </summary>
internal void SetPossibleRedirectForLocationHeader(string location)
{
// Reset cookies in case we redirect. Below we'll set new cookies for the
// new location if we have any.
if (_handler._useCookie)
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero);
}
// Parse the location string into a relative or absolute Uri, then combine that
// with the current request Uri to get the new location.
var updatedCredentials = default(KeyValuePair<NetworkCredential, CURLAUTH>);
Uri newUri;
if (Uri.TryCreate(_requestMessage.RequestUri, location.Trim(), out newUri))
{
// Just as with WinHttpHandler, for security reasons, we drop the server credential if it is
// anything other than a CredentialCache. We allow credentials in a CredentialCache since they
// are specifically tied to URIs.
updatedCredentials = GetCredentials(newUri, _handler.Credentials as CredentialCache, s_orderedAuthTypes);
// Reset proxy - it is possible that the proxy has different credentials for the new URI
SetProxyOptions(newUri);
// Set up new cookies
if (_handler._useCookie)
{
SetCookieOption(newUri);
}
}
// Set up the new credentials, either for the new Uri if we were able to get it,
// or to empty creds if we couldn't.
SetCredentialsOptions(updatedCredentials);
// Set the headers again. This is a workaround for libcurl's limitation in handling
// headers with empty values.
SetRequestHeaders();
}
private void SetContentLength(CURLoption lengthOption)
{
Debug.Assert(lengthOption == CURLoption.CURLOPT_POSTFIELDSIZE || lengthOption == CURLoption.CURLOPT_INFILESIZE);
if (_requestMessage.Content == null)
{
// Tell libcurl there's no data to be sent.
SetCurlOption(lengthOption, 0L);
return;
}
long? contentLengthOpt = _requestMessage.Content.Headers.ContentLength;
if (contentLengthOpt != null)
{
long contentLength = contentLengthOpt.GetValueOrDefault();
if (contentLength <= int.MaxValue)
{
// Tell libcurl how much data we expect to send.
SetCurlOption(lengthOption, contentLength);
}
else
{
// Similarly, tell libcurl how much data we expect to send. However,
// as the amount is larger than a 32-bit value, switch to the "_LARGE"
// equivalent libcurl options.
SetCurlOption(
lengthOption == CURLoption.CURLOPT_INFILESIZE ? CURLoption.CURLOPT_INFILESIZE_LARGE : CURLoption.CURLOPT_POSTFIELDSIZE_LARGE,
contentLength);
}
return;
}
// There is content but we couldn't determine its size. Don't set anything.
}
private void SetVerb()
{
EventSourceTrace<string>("Verb: {0}", _requestMessage.Method.Method);
if (_requestMessage.Method == HttpMethod.Put)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
SetContentLength(CURLoption.CURLOPT_INFILESIZE);
}
else if (_requestMessage.Method == HttpMethod.Head)
{
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else if (_requestMessage.Method == HttpMethod.Post)
{
SetCurlOption(CURLoption.CURLOPT_POST, 1L);
SetContentLength(CURLoption.CURLOPT_POSTFIELDSIZE);
}
else if (_requestMessage.Method == HttpMethod.Trace)
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
if (_requestMessage.Content != null)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
SetContentLength(CURLoption.CURLOPT_INFILESIZE);
}
}
}
private void SetVersion()
{
Version v = _requestMessage.Version;
if (v != null)
{
// Try to use the requested version, if a known version was explicitly requested.
// If an unknown version was requested, we simply use libcurl's default.
var curlVersion =
(v.Major == 1 && v.Minor == 1) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_1 :
(v.Major == 1 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_0 :
(v.Major == 2 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_2_0 :
Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE;
if (curlVersion != Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE)
{
// Ask libcurl to use the specified version if possible.
CURLcode c = Interop.Http.EasySetOptionLong(_easyHandle, CURLoption.CURLOPT_HTTP_VERSION, (long)curlVersion);
if (c == CURLcode.CURLE_OK)
{
// Success. The requested version will be used.
EventSourceTrace("HTTP version: {0}", v);
}
else if (c == CURLcode.CURLE_UNSUPPORTED_PROTOCOL)
{
// The requested version is unsupported. Fall back to using the default version chosen by libcurl.
EventSourceTrace("Unsupported protocol: {0}", v);
}
else
{
// Some other error. Fail.
ThrowIfCURLEError(c);
}
}
}
}
private void SetDecompressionOptions()
{
if (!_handler.SupportsAutomaticDecompression)
{
return;
}
DecompressionMethods autoDecompression = _handler.AutomaticDecompression;
bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0;
bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0;
if (gzip || deflate)
{
string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate :
gzip ? EncodingNameGzip :
EncodingNameDeflate;
SetCurlOption(CURLoption.CURLOPT_ACCEPT_ENCODING, encoding);
EventSourceTrace<string>("Encoding: {0}", encoding);
}
}
internal void SetProxyOptions(Uri requestUri)
{
if (!_handler._useProxy)
{
// Explicitly disable the use of a proxy. This will prevent libcurl from using
// any proxy, including ones set via environment variable.
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
EventSourceTrace("UseProxy false, disabling proxy");
return;
}
if (_handler.Proxy == null)
{
// UseProxy was true, but Proxy was null. Let libcurl do its default handling,
// which includes checking the http_proxy environment variable.
EventSourceTrace("UseProxy true, Proxy null, using default proxy");
// Since that proxy set in an environment variable might require a username and password,
// use the default proxy credentials if there are any. Currently only NetworkCredentials
// are used, as we can't query by the proxy Uri, since we don't know it.
SetProxyCredentials(_handler.DefaultProxyCredentials as NetworkCredential);
return;
}
// Custom proxy specified.
Uri proxyUri;
try
{
// Should we bypass a proxy for this URI?
if (_handler.Proxy.IsBypassed(requestUri))
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
EventSourceTrace("Proxy's IsBypassed returned true, bypassing proxy");
return;
}
// Get the proxy Uri for this request.
proxyUri = _handler.Proxy.GetProxy(requestUri);
if (proxyUri == null)
{
EventSourceTrace("GetProxy returned null, using default.");
return;
}
}
catch (PlatformNotSupportedException)
{
// WebRequest.DefaultWebProxy throws PlatformNotSupportedException,
// in which case we should use the default rather than the custom proxy.
EventSourceTrace("PlatformNotSupportedException from proxy, using default");
return;
}
// Configure libcurl with the gathered proxy information
// uri.AbsoluteUri/ToString() omit IPv6 scope IDs. SerializationInfoString ensures these details
// are included, but does not properly handle international hosts. As a workaround we check whether
// the host is a link-local IP address, and based on that either return the SerializationInfoString
// or the AbsoluteUri. (When setting the request Uri itself, we instead use CURLOPT_ADDRESS_SCOPE to
// set the scope id and the url separately, avoiding these issues and supporting versions of libcurl
// prior to v7.37 that don't support parsing scope IDs out of the url's host. As similar feature
// doesn't exist for proxies.)
IPAddress ip;
string proxyUrl = IPAddress.TryParse(proxyUri.DnsSafeHost, out ip) && ip.IsIPv6LinkLocal ?
proxyUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped) :
proxyUri.AbsoluteUri;
EventSourceTrace<string>("Proxy: {0}", proxyUrl);
SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, (long)CURLProxyType.CURLPROXY_HTTP);
SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUrl);
SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port);
KeyValuePair<NetworkCredential, CURLAUTH> credentialScheme = GetCredentials(
proxyUri, _handler.Proxy.Credentials, s_orderedAuthTypes);
SetProxyCredentials(credentialScheme.Key);
}
private void SetProxyCredentials(NetworkCredential credentials)
{
if (credentials == CredentialCache.DefaultCredentials)
{
// No "default credentials" on Unix; nop just like UseDefaultCredentials.
EventSourceTrace("DefaultCredentials set for proxy. Skipping.");
}
else if (credentials != null)
{
if (string.IsNullOrEmpty(credentials.UserName))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "UserName");
}
// Unlike normal credentials, proxy credentials are URL decoded by libcurl, so we URL encode
// them in order to allow, for example, a colon in the username.
string credentialText = string.IsNullOrEmpty(credentials.Domain) ?
string.Format("{0}:{1}", WebUtility.UrlEncode(credentials.UserName), WebUtility.UrlEncode(credentials.Password)) :
string.Format("{2}\\{0}:{1}", WebUtility.UrlEncode(credentials.UserName), WebUtility.UrlEncode(credentials.Password), WebUtility.UrlEncode(credentials.Domain));
EventSourceTrace("Proxy credentials set.");
SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText);
}
}
internal void SetCredentialsOptions(KeyValuePair<NetworkCredential, CURLAUTH> credentialSchemePair)
{
if (credentialSchemePair.Key == null)
{
EventSourceTrace("Credentials cleared.");
SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero);
SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero);
return;
}
NetworkCredential credentials = credentialSchemePair.Key;
CURLAUTH authScheme = credentialSchemePair.Value;
string userName = string.IsNullOrEmpty(credentials.Domain) ?
credentials.UserName :
string.Format("{0}\\{1}", credentials.Domain, credentials.UserName);
SetCurlOption(CURLoption.CURLOPT_USERNAME, userName);
SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, (long)authScheme);
if (credentials.Password != null)
{
SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password);
}
EventSourceTrace("Credentials set.");
}
internal void SetCookieOption(Uri uri)
{
if (!_handler._useCookie)
{
return;
}
string cookieValues = _handler.CookieContainer.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues);
EventSourceTrace<string>("Cookies: {0}", cookieValues);
}
}
internal void SetRequestHeaders()
{
var slist = new SafeCurlSListHandle();
// Add content request headers
if (_requestMessage.Content != null)
{
SetChunkedModeForSend(_requestMessage);
_requestMessage.Content.Headers.Remove(HttpKnownHeaderNames.ContentLength); // avoid overriding libcurl's handling via INFILESIZE/POSTFIELDSIZE
AddRequestHeaders(_requestMessage.Content.Headers, slist);
if (_requestMessage.Content.Headers.ContentType == null)
{
// Remove the Content-Type header libcurl adds by default.
ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoContentType));
}
}
// Add request headers
AddRequestHeaders(_requestMessage.Headers, slist);
// Since libcurl always adds a Transfer-Encoding header, we need to explicitly block
// it if caller specifically does not want to set the header
if (_requestMessage.Headers.TransferEncodingChunked.HasValue &&
!_requestMessage.Headers.TransferEncodingChunked.Value)
{
ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoTransferEncoding));
}
if (!slist.IsInvalid)
{
SafeCurlSListHandle prevList = _requestHeaders;
_requestHeaders = slist;
SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist);
prevList?.Dispose();
}
else
{
slist.Dispose();
}
}
private void SetSslOptions()
{
// SSL Options should be set regardless of the type of the original request,
// in case an http->https redirection occurs.
//
// While this does slow down the theoretical best path of the request the code
// to decide that we need to register the callback is more complicated than, and
// potentially more expensive than, just always setting the callback.
SslProvider.SetSslOptions(this, _handler.ClientCertificateOptions);
}
internal void SetCurlCallbacks(
IntPtr easyGCHandle,
ReadWriteCallback receiveHeadersCallback,
ReadWriteCallback sendCallback,
SeekCallback seekCallback,
ReadWriteCallback receiveBodyCallback,
DebugCallback debugCallback)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
// Add callback for processing headers
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Header,
receiveHeadersCallback,
easyGCHandle,
ref _callbackHandle);
// If we're sending data as part of the request, add callbacks for sending request data
if (_requestMessage.Content != null)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Read,
sendCallback,
easyGCHandle,
ref _callbackHandle);
Interop.Http.RegisterSeekCallback(
_easyHandle,
seekCallback,
easyGCHandle,
ref _callbackHandle);
}
// If we're expecting any data in response, add a callback for receiving body data
if (_requestMessage.Method != HttpMethod.Head)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Write,
receiveBodyCallback,
easyGCHandle,
ref _callbackHandle);
}
if (EventSourceTracingEnabled)
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
CURLcode curlResult = Interop.Http.RegisterDebugCallback(
_easyHandle,
debugCallback,
easyGCHandle,
ref _callbackHandle);
if (curlResult != CURLcode.CURLE_OK)
{
EventSourceTrace("Failed to register debug callback.");
}
}
}
internal CURLcode SetSslCtxCallback(SslCtxCallback callback, IntPtr userPointer)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
CURLcode result = Interop.Http.RegisterSslCtxCallback(_easyHandle, callback, userPointer, ref _callbackHandle);
return result;
}
private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSListHandle handle)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
{
string headerValue = headers.GetHeaderString(header.Key);
string headerKeyAndValue = string.IsNullOrEmpty(headerValue) ?
header.Key + ";" : // semicolon used by libcurl to denote empty value that should be sent
header.Key + ": " + headerValue;
ThrowOOMIfFalse(Interop.Http.SListAppend(handle, headerKeyAndValue));
}
}
internal void SetCurlOption(CURLoption option, string value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionString(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, long value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionLong(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, IntPtr value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, SafeHandle value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
private static void ThrowOOMIfFalse(bool appendResult)
{
if (!appendResult)
throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_OUT_OF_MEMORY, isMulti: false));
}
internal sealed class SendTransferState
{
internal readonly byte[] _buffer;
internal int _offset;
internal int _count;
internal Task<int> _task;
internal SendTransferState(int bufferLength)
{
Debug.Assert(bufferLength > 0 && bufferLength <= MaxRequestBufferSize, $"Expected 0 < bufferLength <= {MaxRequestBufferSize}, got {bufferLength}");
_buffer = new byte[bufferLength];
}
internal void SetTaskOffsetCount(Task<int> task, int offset, int count)
{
Debug.Assert(offset >= 0, "Offset should never be negative");
Debug.Assert(count >= 0, "Count should never be negative");
Debug.Assert(offset <= count, "Offset should never be greater than count");
_task = task;
_offset = offset;
_count = count;
}
}
internal void StoreLastEffectiveUri()
{
IntPtr urlCharPtr; // do not free; will point to libcurl private memory
CURLcode urlResult = Interop.Http.EasyGetInfoPointer(_easyHandle, Interop.Http.CURLINFO.CURLINFO_EFFECTIVE_URL, out urlCharPtr);
if (urlResult == CURLcode.CURLE_OK && urlCharPtr != IntPtr.Zero)
{
string url = Marshal.PtrToStringAnsi(urlCharPtr);
Uri finalUri;
if (Uri.TryCreate(url, UriKind.Absolute, out finalUri))
{
_requestMessage.RequestUri = finalUri;
return;
}
}
Debug.Fail("Expected to be able to get the last effective Uri from libcurl");
}
private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(formatMessage, arg0, easy: this, memberName: memberName);
}
private void EventSourceTrace(string message, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(message, easy: this, memberName: memberName);
}
}
}
}
| |
// 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.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Transforms;
using osu.Framework.Utils;
using osu.Framework.Timing;
using osuTK;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.Drawables
{
public class TestSceneTransformRewinding : FrameworkTestScene
{
private const double interval = 250;
private const int interval_count = 4;
private static double intervalAt(int sequence) => interval * sequence;
private ManualClock manualClock;
private FramedClock manualFramedClock;
[SetUp]
public void SetUp() => Schedule(() =>
{
Clear();
manualClock = new ManualClock();
manualFramedClock = new FramedClock(manualClock);
});
[Test]
public void BasicScale()
{
boxTest(box =>
{
box.Scale = Vector2.One;
box.ScaleTo(0, interval * 4);
});
checkAtTime(250, box => Precision.AlmostEquals(box.Scale.X, 0.75f));
checkAtTime(500, box => Precision.AlmostEquals(box.Scale.X, 0.5f));
checkAtTime(750, box => Precision.AlmostEquals(box.Scale.X, 0.25f));
checkAtTime(1000, box => Precision.AlmostEquals(box.Scale.X, 0f));
checkAtTime(500, box => Precision.AlmostEquals(box.Scale.X, 0.5f));
checkAtTime(250, box => Precision.AlmostEquals(box.Scale.X, 0.75f));
AddAssert("check transform count", () => box.Transforms.Count() == 1);
}
[Test]
public void ScaleSequence()
{
boxTest(box =>
{
box.Scale = Vector2.One;
box.ScaleTo(0.75f, interval).Then()
.ScaleTo(0.5f, interval).Then()
.ScaleTo(0.25f, interval).Then()
.ScaleTo(0, interval);
});
int i = 0;
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.75f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.5f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.25f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0f));
checkAtTime(interval * (i -= 2), box => Precision.AlmostEquals(box.Scale.X, 0.5f));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.75f));
AddAssert("check transform count", () => box.Transforms.Count() == 4);
}
[Test]
public void BasicMovement()
{
boxTest(box =>
{
box.Scale = new Vector2(0.25f);
box.Anchor = Anchor.TopLeft;
box.Origin = Anchor.TopLeft;
box.MoveTo(new Vector2(0.75f, 0), interval).Then()
.MoveTo(new Vector2(0.75f, 0.75f), interval).Then()
.MoveTo(new Vector2(0, 0.75f), interval).Then()
.MoveTo(new Vector2(0), interval);
});
int i = 0;
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.X, 0.75f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Y, 0.75f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.X, 0f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Y, 0f));
checkAtTime(interval * (i -= 2), box => Precision.AlmostEquals(box.Y, 0.75f));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.X, 0.75f));
AddAssert("check transform count", () => box.Transforms.Count() == 4);
}
[Test]
public void MoveSequence()
{
boxTest(box =>
{
box.Scale = new Vector2(0.25f);
box.Anchor = Anchor.TopLeft;
box.Origin = Anchor.TopLeft;
box.ScaleTo(0.5f, interval).MoveTo(new Vector2(0.5f), interval).Then()
.ScaleTo(0.1f, interval).MoveTo(new Vector2(0, 0.75f), interval).Then()
.ScaleTo(1f, interval).MoveTo(new Vector2(0, 0), interval).Then()
.FadeTo(0, interval);
});
int i = 0;
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.X, 0.5f) && Precision.AlmostEquals(box.Scale.X, 0.5f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Y, 0.75f) && Precision.AlmostEquals(box.Scale.X, 0.1f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.X, 0f));
checkAtTime(interval * (i += 2), box => Precision.AlmostEquals(box.Alpha, 0f));
checkAtTime(interval * (i - 2), box => Precision.AlmostEquals(box.Alpha, 1f));
AddAssert("check transform count", () => box.Transforms.Count() == 7);
}
[Test]
public void MoveCancelSequence()
{
boxTest(box =>
{
box.Scale = new Vector2(0.25f);
box.Anchor = Anchor.TopLeft;
box.Origin = Anchor.TopLeft;
box.ScaleTo(0.5f, interval).Then().ScaleTo(1, interval);
Scheduler.AddDelayed(() => { box.ScaleTo(new Vector2(0.1f), interval); }, interval / 2);
});
int i = 0;
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Scale.X, 0.25f));
checkAtTime(interval * ++i, box => !Precision.AlmostEquals(box.Scale.X, 0.5f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.1f));
AddAssert("check transform count", () => box.Transforms.Count() == 2);
}
[Test]
public void SameTypeInType()
{
boxTest(box =>
{
box.ScaleTo(0.5f, interval * 4);
box.Delay(interval * 2).ScaleTo(1, interval);
});
int i = 0;
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Scale.X, 0.25f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.3125f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.375f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 1));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.375f));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.3125f));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.25f));
AddAssert("check transform count", () => box.Transforms.Count() == 2);
}
[Test]
public void SameTypeInPartialOverlap()
{
boxTest(box =>
{
box.ScaleTo(0.5f, interval * 2);
box.Delay(interval).ScaleTo(1, interval * 2);
});
int i = 0;
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Scale.X, 0.25f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.375f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.6875f));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 1));
checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 1));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 1));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.6875f));
checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.375f));
AddAssert("check transform count", () => box.Transforms.Count() == 2);
}
[Test]
public void StartInMiddleOfSequence()
{
boxTest(box =>
{
box.Alpha = 0;
box.Delay(interval * 2).FadeInFromZero(interval);
box.ScaleTo(0.9f, interval * 4);
}, 750);
checkAtTime(interval * 3, box => Precision.AlmostEquals(box.Alpha, 1));
checkAtTime(interval * 4, box => Precision.AlmostEquals(box.Alpha, 1) && Precision.AlmostEquals(box.Scale.X, 0.9f));
checkAtTime(interval * 2, box => Precision.AlmostEquals(box.Alpha, 0) && Precision.AlmostEquals(box.Scale.X, 0.575f));
AddAssert("check transform count", () => box.Transforms.Count() == 3);
}
[Test]
public void RewindBetweenDisparateValues()
{
boxTest(box =>
{
box.Alpha = 0;
});
// move forward to future point in time before adding transforms.
checkAtTime(interval * 4, _ => true);
AddStep("add transforms", () =>
{
using (box.BeginAbsoluteSequence(0))
{
box.FadeOutFromOne(interval);
box.Delay(interval * 3).FadeOutFromOne(interval);
// FadeOutFromOne adds extra transforms which disallow testing this scenario, so we remove them.
box.RemoveTransform(box.Transforms.ElementAt(2));
box.RemoveTransform(box.Transforms.ElementAt(0));
}
});
checkAtTime(0, box => Precision.AlmostEquals(box.Alpha, 1));
checkAtTime(interval * 1, box => Precision.AlmostEquals(box.Alpha, 0));
checkAtTime(interval * 2, box => Precision.AlmostEquals(box.Alpha, 0));
checkAtTime(interval * 3, box => Precision.AlmostEquals(box.Alpha, 1));
checkAtTime(interval * 4, box => Precision.AlmostEquals(box.Alpha, 0));
// importantly, this should be 0 not 1, reading from the EndValue of the first FadeOutFromOne transform.
checkAtTime(interval * 2, box => Precision.AlmostEquals(box.Alpha, 0));
}
[Test]
public void AddPastTransformFromFutureWhenNotInHierarchy()
{
AddStep("seek clock to 1000", () => manualClock.CurrentTime = interval * 4);
AddStep("create box", () =>
{
box = createBox();
box.Clock = manualFramedClock;
box.RemoveCompletedTransforms = false;
manualFramedClock.ProcessFrame();
using (box.BeginAbsoluteSequence(0))
box.Delay(interval * 2).FadeOut(interval);
});
AddStep("seek clock to 0", () => manualClock.CurrentTime = 0);
AddStep("add box", () =>
{
Add(new AnimationContainer
{
Child = box,
ExaminableDrawable = box,
});
});
checkAtTime(interval * 2, box => Precision.AlmostEquals(box.Alpha, 1));
checkAtTime(interval * 3, box => Precision.AlmostEquals(box.Alpha, 0));
}
[Test]
public void AddPastTransformFromFuture()
{
boxTest(box =>
{
box.Alpha = 0;
});
// move forward to future point in time before adding transforms.
checkAtTime(interval * 4, _ => true);
AddStep("add transforms", () =>
{
using (box.BeginAbsoluteSequence(0))
{
box.FadeOutFromOne(interval);
box.Delay(interval * 3).FadeInFromZero(interval);
// FadeOutFromOne adds extra transforms which disallow testing this scenario, so we remove them.
box.RemoveTransform(box.Transforms.ElementAt(2));
box.RemoveTransform(box.Transforms.ElementAt(0));
}
});
AddStep("add one more transform in the middle", () =>
{
using (box.BeginAbsoluteSequence(interval * 2))
box.FadeIn(interval * 0.5);
});
checkAtTime(interval * 2, box => Precision.AlmostEquals(box.Alpha, 0));
checkAtTime(interval * 2.5, box => Precision.AlmostEquals(box.Alpha, 1));
}
[Test]
public void LoopSequence()
{
boxTest(box => { box.RotateTo(0).RotateTo(90, interval).Loop(); });
const int count = 4;
for (int i = 0; i <= count; i++)
{
if (i > 0) checkAtTime(interval * i - 1, box => Precision.AlmostEquals(box.Rotation, 90f, 1));
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Rotation, 0));
}
AddAssert("check transform count", () => box.Transforms.Count() == 10);
for (int i = count; i >= 0; i--)
{
if (i > 0) checkAtTime(interval * i - 1, box => Precision.AlmostEquals(box.Rotation, 90f, 1));
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Rotation, 0));
}
}
[Test]
public void StartInMiddleOfLoopSequence()
{
boxTest(box => { box.RotateTo(0).RotateTo(90, interval).Loop(); }, 750);
checkAtTime(750, box => Precision.AlmostEquals(box.Rotation, 0f));
AddAssert("check transform count", () => box.Transforms.Count() == 8);
const int count = 4;
for (int i = 0; i <= count; i++)
{
if (i > 0) checkAtTime(interval * i - 1, box => Precision.AlmostEquals(box.Rotation, 90f, 1));
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Rotation, 0));
}
AddAssert("check transform count", () => box.Transforms.Count() == 10);
for (int i = count; i >= 0; i--)
{
if (i > 0) checkAtTime(interval * i - 1, box => Precision.AlmostEquals(box.Rotation, 90f, 1));
checkAtTime(interval * i, box => Precision.AlmostEquals(box.Rotation, 0));
}
}
[Test]
public void TestSimultaneousTransformsOutOfOrder()
{
boxTest(box =>
{
using (box.BeginAbsoluteSequence(0))
{
box.MoveToX(0.5f, 4 * interval);
box.Delay(interval).MoveToY(0.5f, 2 * interval);
}
});
checkAtTime(0, box => Precision.AlmostEquals(box.Position, new Vector2(0)));
checkAtTime(interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.125f, 0)));
checkAtTime(2 * interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.25f, 0.25f)));
checkAtTime(3 * interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.375f, 0.5f)));
checkAtTime(4 * interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.5f)));
checkAtTime(3 * interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.375f, 0.5f)));
checkAtTime(2 * interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.25f, 0.25f)));
checkAtTime(interval, box => Precision.AlmostEquals(box.Position, new Vector2(0.125f, 0)));
checkAtTime(0, box => Precision.AlmostEquals(box.Position, new Vector2(0)));
}
[Test]
public void TestMultipleTransformTargets()
{
boxTest(box =>
{
box.Delay(500).MoveTo(new Vector2(0, 0.25f), 500);
box.MoveToY(0.5f, 250);
});
checkAtTime(double.MinValue, box => box.Y == 0);
checkAtTime(0, box => box.Y == 0);
checkAtTime(250, box => box.Y == 0.5f);
checkAtTime(750, box => box.Y == 0.375f);
checkAtTime(1000, box => box.Y == 0.25f);
checkAtTime(1500, box => box.Y == 0.25f);
checkAtTime(1250, box => box.Y == 0.25f);
checkAtTime(750, box => box.Y == 0.375f);
}
private Box box;
private void checkAtTime(double time, Func<Box, bool> assert)
{
AddAssert($"check at time {time}", () =>
{
manualClock.CurrentTime = time;
box.Clock = manualFramedClock;
box.UpdateSubTree();
return assert(box);
});
}
private void boxTest(Action<Box> action, int startTime = 0)
{
AddStep("add box", () =>
{
Add(new AnimationContainer(startTime)
{
Child = box = createBox(),
ExaminableDrawable = box,
});
action(box);
});
}
private static Box createBox()
{
return new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
RelativePositionAxes = Axes.Both,
Scale = new Vector2(0.25f),
};
}
private class AnimationContainer : Container
{
public override bool RemoveCompletedTransforms => false;
protected override Container<Drawable> Content => content;
private readonly Container content;
private readonly SpriteText minTimeText;
private readonly SpriteText currentTimeText;
private readonly SpriteText maxTimeText;
private readonly Tick seekingTick;
private readonly WrappingTimeContainer wrapping;
public Box ExaminableDrawable;
private readonly FlowContainer<DrawableTransform> transforms;
public AnimationContainer(int startTime = 0)
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
InternalChild = wrapping = new WrappingTimeContainer(startTime)
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Container
{
FillMode = FillMode.Fit,
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(0.6f),
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.DarkGray,
},
content = new Container
{
RelativeSizeAxes = Axes.Both,
Masking = true,
},
}
},
transforms = new FillFlowContainer<DrawableTransform>
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Spacing = Vector2.One,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Width = 0.2f,
},
new Container
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.8f, 0.1f),
Children = new Drawable[]
{
minTimeText = new SpriteText
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.TopLeft,
},
currentTimeText = new SpriteText
{
RelativePositionAxes = Axes.X,
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomCentre,
Y = -10,
},
maxTimeText = new SpriteText
{
Anchor = Anchor.BottomRight,
Origin = Anchor.TopRight,
},
seekingTick = new Tick(0, false),
new Tick(0),
new Tick(1),
new Tick(2),
new Tick(3),
new Tick(4),
}
}
}
};
}
private List<Transform> displayedTransforms;
protected override void Update()
{
base.Update();
double time = wrapping.Time.Current;
minTimeText.Text = wrapping.MinTime.ToString("n0");
currentTimeText.Text = time.ToString("n0");
seekingTick.X = currentTimeText.X = (float)(time / (wrapping.MaxTime - wrapping.MinTime));
maxTimeText.Text = wrapping.MaxTime.ToString("n0");
maxTimeText.Colour = time > wrapping.MaxTime ? Color4.Gray : wrapping.Time.Elapsed > 0 ? Color4.Blue : Color4.Red;
minTimeText.Colour = time < wrapping.MinTime ? Color4.Gray : content.Time.Elapsed > 0 ? Color4.Blue : Color4.Red;
if (displayedTransforms == null || !ExaminableDrawable.Transforms.SequenceEqual(displayedTransforms))
{
transforms.Clear();
foreach (var t in ExaminableDrawable.Transforms)
transforms.Add(new DrawableTransform(t));
displayedTransforms = new List<Transform>(ExaminableDrawable.Transforms);
}
}
private class DrawableTransform : CompositeDrawable
{
private readonly Transform transform;
private readonly Box applied;
private readonly Box appliedToEnd;
private readonly SpriteText text;
private const float height = 15;
public DrawableTransform(Transform transform)
{
this.transform = transform;
RelativeSizeAxes = Axes.X;
Height = height;
InternalChildren = new Drawable[]
{
applied = new Box { Size = new Vector2(height) },
appliedToEnd = new Box { X = height + 2, Size = new Vector2(height) },
text = new SpriteText { X = (height + 2) * 2, Font = new FontUsage(size: height) },
};
}
protected override void Update()
{
base.Update();
applied.Colour = transform.Applied ? Color4.Green : Color4.Red;
appliedToEnd.Colour = transform.AppliedToEnd ? Color4.Green : Color4.Red;
text.Text = transform.ToString();
}
}
private class Tick : Box
{
private readonly int tick;
private readonly bool colouring;
public Tick(int tick, bool colouring = true)
{
this.tick = tick;
this.colouring = colouring;
Anchor = Anchor.BottomLeft;
Origin = Anchor.BottomCentre;
Size = new Vector2(1, 10);
Colour = Color4.White;
RelativePositionAxes = Axes.X;
X = (float)tick / interval_count;
}
protected override void Update()
{
base.Update();
if (colouring)
Colour = Time.Current > tick * interval ? Color4.Yellow : Color4.White;
}
}
}
private class WrappingTimeContainer : Container
{
// Padding, in milliseconds, at each end of maxima of the clock time
private const double time_padding = 50;
public double MinTime => clock.MinTime + time_padding;
public double MaxTime => clock.MaxTime - time_padding;
private readonly ReversibleClock clock;
public WrappingTimeContainer(double startTime)
{
clock = new ReversibleClock(startTime);
}
[BackgroundDependencyLoader]
private void load()
{
// Replace the game clock, but keep it as a reference
clock.SetSource(Clock);
Clock = clock;
}
protected override void LoadComplete()
{
base.LoadComplete();
clock.MinTime = -time_padding;
clock.MaxTime = intervalAt(interval_count) + time_padding;
}
private class ReversibleClock : IFrameBasedClock
{
private readonly double startTime;
public double MinTime;
public double MaxTime = 1000;
private OffsetClock offsetClock;
private IFrameBasedClock trackingClock;
private bool reversed;
public ReversibleClock(double startTime)
{
this.startTime = startTime;
}
public void SetSource(IFrameBasedClock trackingClock)
{
this.trackingClock = trackingClock;
offsetClock = new OffsetClock(trackingClock) { Offset = -trackingClock.CurrentTime + startTime };
}
public double CurrentTime { get; private set; }
public double Rate => offsetClock.Rate;
public bool IsRunning => offsetClock.IsRunning;
public double ElapsedFrameTime => (reversed ? -1 : 1) * trackingClock.ElapsedFrameTime;
public double FramesPerSecond => trackingClock.FramesPerSecond;
public FrameTimeInfo TimeInfo => new FrameTimeInfo { Current = CurrentTime, Elapsed = ElapsedFrameTime };
public void ProcessFrame()
{
// There are two iterations, when iteration % 2 == 0 : not reversed
int iteration = (int)(offsetClock.CurrentTime / (MaxTime - MinTime));
reversed = iteration % 2 == 1;
double iterationTime = offsetClock.CurrentTime % (MaxTime - MinTime);
if (reversed)
CurrentTime = MaxTime - iterationTime;
else
CurrentTime = MinTime + iterationTime;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Web;
using Umbraco.Core.Logging;
using umbraco.cms.businesslogic.template;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.macro;
using Umbraco.Core.IO;
namespace umbraco.cms.businesslogic.packager
{
public class CreatedPackage
{
public static CreatedPackage GetById(int id)
{
var pack = new CreatedPackage();
pack.Data = data.Package(id, IOHelper.MapPath(Settings.CreatedPackagesSettings));
return pack;
}
public static CreatedPackage MakeNew(string name)
{
var pack = new CreatedPackage();
pack.Data = data.MakeNew(name, IOHelper.MapPath(Settings.CreatedPackagesSettings));
var e = new NewEventArgs();
pack.OnNew(e);
return pack;
}
public void Save()
{
var e = new SaveEventArgs();
FireBeforeSave(e);
if (!e.Cancel)
{
data.Save(this.Data, IOHelper.MapPath(Settings.CreatedPackagesSettings));
FireAfterSave(e);
}
}
public void Delete()
{
var e = new DeleteEventArgs();
FireBeforeDelete(e);
if (!e.Cancel)
{
data.Delete(this.Data.Id, IOHelper.MapPath(Settings.CreatedPackagesSettings));
FireAfterDelete(e);
}
}
public PackageInstance Data { get; set; }
public static List<CreatedPackage> GetAllCreatedPackages()
{
var val = new List<CreatedPackage>();
foreach (var pack in data.GetAllPackages(IOHelper.MapPath(Settings.CreatedPackagesSettings)))
{
var crPack = new CreatedPackage();
crPack.Data = pack;
val.Add(crPack);
}
return val;
}
private static XmlDocument _packageManifest;
private static void CreatePackageManifest()
{
_packageManifest = new XmlDocument();
var xmldecl = _packageManifest.CreateXmlDeclaration("1.0", "UTF-8", "no");
_packageManifest.AppendChild(xmldecl);
//root node
XmlNode umbPackage = _packageManifest.CreateElement("umbPackage");
_packageManifest.AppendChild(umbPackage);
//Files node
umbPackage.AppendChild(_packageManifest.CreateElement("files"));
}
private static void AppendElement(XmlNode node)
{
var root = _packageManifest.SelectSingleNode("/umbPackage");
root.AppendChild(node);
}
public void Publish()
{
var package = this;
var pack = package.Data;
try
{
var e = new PublishEventArgs();
package.FireBeforePublish(e);
if (e.Cancel == false)
{
var outInt = 0;
//Path checking...
var localPath = IOHelper.MapPath(SystemDirectories.Media + "/" + pack.Folder);
if (Directory.Exists(localPath) == false)
Directory.CreateDirectory(localPath);
//Init package file...
CreatePackageManifest();
//Info section..
AppendElement(utill.PackageInfo(pack, _packageManifest));
//Documents...
var contentNodeId = 0;
if (string.IsNullOrEmpty(pack.ContentNodeId) == false && int.TryParse(pack.ContentNodeId, out contentNodeId))
{
XmlNode documents = _packageManifest.CreateElement("Documents");
XmlNode documentSet = _packageManifest.CreateElement("DocumentSet");
XmlAttribute importMode = _packageManifest.CreateAttribute("importMode", "");
importMode.Value = "root";
documentSet.Attributes.Append(importMode);
documents.AppendChild(documentSet);
//load content from umbraco.
var umbDocument = new Document(contentNodeId);
documentSet.AppendChild(umbDocument.ToXml(_packageManifest, pack.ContentLoadChildNodes));
AppendElement(documents);
}
//Document types..
var dtl = new List<DocumentType>();
var docTypes = _packageManifest.CreateElement("DocumentTypes");
foreach (var dtId in pack.Documenttypes)
{
if (int.TryParse(dtId, out outInt))
{
DocumentType docT = new DocumentType(outInt);
AddDocumentType(docT, ref dtl);
}
}
foreach (DocumentType d in dtl)
{
docTypes.AppendChild(d.ToXml(_packageManifest));
}
AppendElement(docTypes);
//Templates
var templates = _packageManifest.CreateElement("Templates");
foreach (var templateId in pack.Templates)
{
if (int.TryParse(templateId, out outInt))
{
var t = new Template(outInt);
templates.AppendChild(t.ToXml(_packageManifest));
}
}
AppendElement(templates);
//Stylesheets
var stylesheets = _packageManifest.CreateElement("Stylesheets");
foreach (var ssId in pack.Stylesheets)
{
if (int.TryParse(ssId, out outInt))
{
var s = new StyleSheet(outInt);
stylesheets.AppendChild(s.ToXml(_packageManifest));
}
}
AppendElement(stylesheets);
//Macros
var macros = _packageManifest.CreateElement("Macros");
foreach (var macroId in pack.Macros)
{
if (int.TryParse(macroId, out outInt))
{
macros.AppendChild(utill.Macro(int.Parse(macroId), true, localPath, _packageManifest));
}
}
AppendElement(macros);
//Dictionary Items
var dictionaryItems = _packageManifest.CreateElement("DictionaryItems");
foreach (var dictionaryId in pack.DictionaryItems)
{
if (int.TryParse(dictionaryId, out outInt))
{
var di = new Dictionary.DictionaryItem(outInt);
dictionaryItems.AppendChild(di.ToXml(_packageManifest));
}
}
AppendElement(dictionaryItems);
//Languages
var languages = _packageManifest.CreateElement("Languages");
foreach (var langId in pack.Languages)
{
if (int.TryParse(langId, out outInt))
{
var lang = new language.Language(outInt);
languages.AppendChild(lang.ToXml(_packageManifest));
}
}
AppendElement(languages);
//Datatypes
var dataTypes = _packageManifest.CreateElement("DataTypes");
foreach (var dtId in pack.DataTypes)
{
if (int.TryParse(dtId, out outInt))
{
datatype.DataTypeDefinition dtd = new datatype.DataTypeDefinition(outInt);
dataTypes.AppendChild(dtd.ToXml(_packageManifest));
}
}
AppendElement(dataTypes);
//Files
foreach (var fileName in pack.Files)
{
utill.AppendFileToManifest(fileName, localPath, _packageManifest);
}
//Load control on install...
if (string.IsNullOrEmpty(pack.LoadControl) == false)
{
XmlNode control = _packageManifest.CreateElement("control");
control.InnerText = pack.LoadControl;
utill.AppendFileToManifest(pack.LoadControl, localPath, _packageManifest);
AppendElement(control);
}
//Actions
if (string.IsNullOrEmpty(pack.Actions) == false)
{
try
{
var xdActions = new XmlDocument();
xdActions.LoadXml("<Actions>" + pack.Actions + "</Actions>");
var actions = xdActions.DocumentElement.SelectSingleNode(".");
if (actions != null)
{
actions = _packageManifest.ImportNode(actions, true).Clone();
AppendElement(actions);
}
}
catch { }
}
var manifestFileName = localPath + "/package.xml";
if (File.Exists(manifestFileName))
File.Delete(manifestFileName);
_packageManifest.Save(manifestFileName);
_packageManifest = null;
//string packPath = Settings.PackagerRoot.Replace(System.IO.Path.DirectorySeparatorChar.ToString(), "/") + "/" + pack.Name.Replace(' ', '_') + "_" + pack.Version.Replace(' ', '_') + "." + Settings.PackageFileExtension;
// check if there's a packages directory below media
var packagesDirectory = SystemDirectories.Media + "/created-packages";
if (Directory.Exists(IOHelper.MapPath(packagesDirectory)) == false)
{
Directory.CreateDirectory(IOHelper.MapPath(packagesDirectory));
}
var packPath = packagesDirectory + "/" + (pack.Name + "_" + pack.Version).Replace(' ', '_') + "." + Settings.PackageFileExtension;
utill.ZipPackage(localPath, IOHelper.MapPath(packPath));
pack.PackagePath = packPath;
if (pack.PackageGuid.Trim() == "")
pack.PackageGuid = Guid.NewGuid().ToString();
package.Save();
//Clean up..
File.Delete(localPath + "/package.xml");
Directory.Delete(localPath, true);
package.FireAfterPublish(e);
}
}
catch (Exception ex)
{
LogHelper.Error<CreatedPackage>("An error occurred", ex);
}
}
private void AddDocumentType(DocumentType dt, ref List<DocumentType> dtl)
{
if (dt.MasterContentType != 0)
{
//first add masters
var mDocT = new DocumentType(dt.MasterContentType);
AddDocumentType(mDocT, ref dtl);
}
if (dtl.Contains(dt) == false)
{
dtl.Add(dt);
}
}
//EVENTS
public delegate void SaveEventHandler(CreatedPackage sender, SaveEventArgs e);
public delegate void NewEventHandler(CreatedPackage sender, NewEventArgs e);
public delegate void PublishEventHandler(CreatedPackage sender, PublishEventArgs e);
public delegate void DeleteEventHandler(CreatedPackage sender, DeleteEventArgs e);
/// <summary>
/// Occurs when a macro is saved.
/// </summary>
public static event SaveEventHandler BeforeSave;
protected virtual void FireBeforeSave(SaveEventArgs e)
{
if (BeforeSave != null)
BeforeSave(this, e);
}
public static event SaveEventHandler AfterSave;
protected virtual void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
AfterSave(this, e);
}
public static event NewEventHandler New;
protected virtual void OnNew(NewEventArgs e)
{
if (New != null)
New(this, e);
}
public static event DeleteEventHandler BeforeDelete;
protected virtual void FireBeforeDelete(DeleteEventArgs e)
{
if (BeforeDelete != null)
BeforeDelete(this, e);
}
public static event DeleteEventHandler AfterDelete;
protected virtual void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
AfterDelete(this, e);
}
public static event PublishEventHandler BeforePublish;
protected virtual void FireBeforePublish(PublishEventArgs e)
{
if (BeforePublish != null)
BeforePublish(this, e);
}
public static event PublishEventHandler AfterPublish;
protected virtual void FireAfterPublish(PublishEventArgs e)
{
if (AfterPublish != null)
AfterPublish(this, e);
}
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using NUnit.Framework;
namespace NUnit.TestData.TestFixtureData
{
/// <summary>
/// Classes used for testing NUnit
/// </summary>
[TestFixture]
public class NoDefaultCtorFixture
{
public NoDefaultCtorFixture(int index) { }
[Test]
public void OneTest() { }
}
[TestFixture(7,3)]
public class FixtureWithArgsSupplied
{
public FixtureWithArgsSupplied(int x, int y) { }
[Test]
public void OneTest() { }
}
[TestFixture]
public class BadCtorFixture
{
BadCtorFixture()
{
throw new Exception();
}
[Test] public void OneTest()
{}
}
public class FixtureWithoutTestFixtureAttribute
{
[Test]
public void SomeTest() { }
}
#if NET_2_0
public static class StaticFixtureWithoutTestFixtureAttribute
{
[Test]
public static void StaticTest() { }
}
#endif
[TestFixture]
public class MultipleSetUpAttributes
{
[SetUp]
public void Init1()
{}
[SetUp]
public void Init2()
{}
[Test] public void OneTest()
{}
}
[TestFixture]
public class MultipleTearDownAttributes
{
[TearDown]
public void Destroy1()
{}
[TearDown]
public void Destroy2()
{}
[Test] public void OneTest()
{}
}
[TestFixture]
[Ignore("testing ignore a fixture")]
public class IgnoredFixture
{
[Test]
public void Success()
{}
}
[TestFixture]
public class OuterClass
{
[TestFixture]
public class NestedTestFixture
{
[TestFixture]
public class DoublyNestedTestFixture
{
[Test]
public void Test()
{
}
}
}
}
[TestFixture]
public abstract class AbstractTestFixture
{
[TearDown]
public void Destroy1()
{}
[Test]
public void SomeTest()
{}
}
public class DerivedFromAbstractTestFixture : AbstractTestFixture
{
}
[TestFixture]
public class BaseClassTestFixture
{
[Test]
public void Success() { }
}
public abstract class AbstractDerivedTestFixture : BaseClassTestFixture
{
}
public class DerivedFromAbstractDerivedTestFixture : AbstractDerivedTestFixture
{
}
[TestFixture]
public abstract class AbstractBaseFixtureWithAttribute
{
}
[TestFixture]
public abstract class AbstractDerivedFixtureWithSecondAttribute
: AbstractBaseFixtureWithAttribute
{
}
public class DoubleDerivedClassWithTwoInheritedAttributes
: AbstractDerivedFixtureWithSecondAttribute
{
}
[TestFixture]
public class MultipleFixtureSetUpAttributes
{
[TestFixtureSetUp]
public void Init1()
{}
[TestFixtureSetUp]
public void Init2()
{}
[Test] public void OneTest()
{}
}
[TestFixture]
public class MultipleFixtureTearDownAttributes
{
[TestFixtureTearDown]
public void Destroy1()
{}
[TestFixtureTearDown]
public void Destroy2()
{}
[Test] public void OneTest()
{}
}
// Base class used to ensure following classes
// all have at least one test
public class OneTestBase
{
[Test] public void OneTest() { }
}
[TestFixture]
public class PrivateSetUp : OneTestBase
{
[SetUp]
private void Setup() {}
}
[TestFixture]
public class ProtectedSetUp : OneTestBase
{
[SetUp]
protected void Setup() {}
}
[TestFixture]
public class StaticSetUp : OneTestBase
{
[SetUp]
public static void Setup() {}
}
[TestFixture]
public class SetUpWithReturnValue : OneTestBase
{
[SetUp]
public int Setup() { return 0; }
}
[TestFixture]
public class SetUpWithParameters : OneTestBase
{
[SetUp]
public void Setup(int j) { }
}
[TestFixture]
public class PrivateTearDown : OneTestBase
{
[TearDown]
private void Teardown() {}
}
[TestFixture]
public class ProtectedTearDown : OneTestBase
{
[TearDown]
protected void Teardown() {}
}
[TestFixture]
public class StaticTearDown : OneTestBase
{
[SetUp]
public static void TearDown() {}
}
[TestFixture]
public class TearDownWithReturnValue : OneTestBase
{
[TearDown]
public int Teardown() { return 0; }
}
[TestFixture]
public class TearDownWithParameters : OneTestBase
{
[TearDown]
public void Teardown(int j) { }
}
[TestFixture]
public class PrivateFixtureSetUp : OneTestBase
{
[TestFixtureSetUp]
private void Setup() {}
}
[TestFixture]
public class ProtectedFixtureSetUp : OneTestBase
{
[TestFixtureSetUp]
protected void Setup() {}
}
[TestFixture]
public class StaticFixtureSetUp : OneTestBase
{
[TestFixtureSetUp]
public static void Setup() {}
}
[TestFixture]
public class FixtureSetUpWithReturnValue : OneTestBase
{
[TestFixtureSetUp]
public int Setup() { return 0; }
}
[TestFixture]
public class FixtureSetUpWithParameters : OneTestBase
{
[SetUp]
public void Setup(int j) { }
}
[TestFixture]
public class PrivateFixtureTearDown : OneTestBase
{
[TestFixtureTearDown]
private void Teardown() {}
}
[TestFixture]
public class ProtectedFixtureTearDown : OneTestBase
{
[TestFixtureTearDown]
protected void Teardown() {}
}
[TestFixture]
public class StaticFixtureTearDown : OneTestBase
{
[TestFixtureTearDown]
public static void Teardown() {}
}
[TestFixture]
public class FixtureTearDownWithReturnValue : OneTestBase
{
[TestFixtureTearDown]
public int Teardown() { return 0; }
}
[TestFixture]
public class FixtureTearDownWithParameters : OneTestBase
{
[TestFixtureTearDown]
public void Teardown(int j) { }
}
#if NET_2_0
[TestFixture(typeof(int))]
[TestFixture(typeof(string))]
public class GenericFixtureWithProperArgsProvided<T>
{
[Test]
public void SomeTest() { }
}
public class GenericFixtureWithNoTestFixtureAttribute<T>
{
[Test]
public void SomeTest() { }
}
[TestFixture]
public class GenericFixtureWithNoArgsProvided<T>
{
[Test]
public void SomeTest() { }
}
[TestFixture]
public abstract class AbstractFixtureBase
{
[Test]
public void SomeTest() { }
}
public class GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided<T> : AbstractFixtureBase
{
}
[TestFixture(typeof(int))]
[TestFixture(typeof(string))]
public class GenericFixtureDerivedFromAbstractFixtureWithArgsProvided<T> : AbstractFixtureBase
{
}
#endif
}
| |
using System;
using System.Collections.Generic;
using System.Data.Services.Common;
using System.Linq;
using System.Runtime.Versioning;
using NuGet.Server.Infrastructure;
namespace NuGet.Server.DataServices
{
[DataServiceKey("Id", "Version")]
[EntityPropertyMapping("Id", SyndicationItemProperty.Title, SyndicationTextContentKind.Plaintext, keepInContent: false)]
[EntityPropertyMapping("Authors", SyndicationItemProperty.AuthorName, SyndicationTextContentKind.Plaintext, keepInContent: false)]
[EntityPropertyMapping("LastUpdated", SyndicationItemProperty.Updated, SyndicationTextContentKind.Plaintext, keepInContent: false)]
[EntityPropertyMapping("Summary", SyndicationItemProperty.Summary, SyndicationTextContentKind.Plaintext, keepInContent: false)]
[HasStream]
public class Package
{
public Package(IPackage package, DerivedPackageData derivedData)
{
Id = package.Id;
Version = package.Version.ToString();
IsPrerelease = !String.IsNullOrEmpty(package.Version.SpecialVersion);
Title = package.Title;
Authors = String.Join(",", package.Authors);
Owners = String.Join(",", package.Owners);
if (package.IconUrl != null)
{
IconUrl = package.IconUrl.GetComponents(UriComponents.HttpRequestUrl, UriFormat.Unescaped);
}
if (package.LicenseUrl != null)
{
LicenseUrl = package.LicenseUrl.GetComponents(UriComponents.HttpRequestUrl, UriFormat.Unescaped);
}
if (package.ProjectUrl != null)
{
ProjectUrl = package.ProjectUrl.GetComponents(UriComponents.HttpRequestUrl, UriFormat.Unescaped);
}
RequireLicenseAcceptance = package.RequireLicenseAcceptance;
DevelopmentDependency = package.DevelopmentDependency;
Description = package.Description;
Summary = package.Summary;
ReleaseNotes = package.ReleaseNotes;
Tags = package.Tags;
Dependencies = String.Join("|", package.DependencySets.SelectMany(ConvertDependencySetToStrings));
PackageHash = derivedData.PackageHash;
PackageHashAlgorithm = "SHA512";
PackageSize = derivedData.PackageSize;
LastUpdated = derivedData.LastUpdated.UtcDateTime;
Published = derivedData.Created.UtcDateTime;
IsAbsoluteLatestVersion = package.IsAbsoluteLatestVersion;
IsLatestVersion = package.IsLatestVersion;
Path = derivedData.Path;
FullPath = derivedData.FullPath;
MinClientVersion = package.MinClientVersion == null ? null : package.MinClientVersion.ToString();
Listed = package.Listed;
}
internal string FullPath
{
get;
set;
}
internal string Path
{
get;
set;
}
public string Id
{
get;
set;
}
public string Version
{
get;
set;
}
public bool IsPrerelease
{
get;
private set;
}
public string Title
{
get;
set;
}
public string Authors
{
get;
set;
}
public string Owners
{
get;
set;
}
public string IconUrl
{
get;
set;
}
public string LicenseUrl
{
get;
set;
}
public string ProjectUrl
{
get;
set;
}
public int DownloadCount
{
get;
set;
}
public bool RequireLicenseAcceptance
{
get;
set;
}
public bool DevelopmentDependency
{
get;
set;
}
public string Description
{
get;
set;
}
public string Summary
{
get;
set;
}
public string ReleaseNotes
{
get;
set;
}
public DateTime Published
{
get;
set;
}
public DateTime LastUpdated
{
get;
set;
}
public string Dependencies
{
get;
set;
}
public string PackageHash
{
get;
set;
}
public string PackageHashAlgorithm
{
get;
set;
}
public long PackageSize
{
get;
set;
}
public string Copyright
{
get;
set;
}
public string Tags
{
get;
set;
}
public bool IsAbsoluteLatestVersion
{
get;
set;
}
public bool IsLatestVersion
{
get;
set;
}
public bool Listed
{
get;
set;
}
public int VersionDownloadCount
{
get;
set;
}
public string MinClientVersion
{
get;
set;
}
private IEnumerable<string> ConvertDependencySetToStrings(PackageDependencySet dependencySet)
{
if (dependencySet.Dependencies.Count == 0)
{
if (dependencySet.TargetFramework != null)
{
// if this Dependency set is empty, we still need to send down one string of the form "::<target framework>",
// so that the client can reconstruct an empty group.
return new string[] { String.Format("::{0}", VersionUtility.GetShortFrameworkName(dependencySet.TargetFramework)) };
}
}
else
{
return dependencySet.Dependencies.Select(dependency => ConvertDependency(dependency, dependencySet.TargetFramework));
}
return new string[0];
}
private string ConvertDependency(PackageDependency packageDependency, FrameworkName targetFramework)
{
if (targetFramework == null)
{
if (packageDependency.VersionSpec == null)
{
return packageDependency.Id;
}
else
{
return String.Format("{0}:{1}", packageDependency.Id, packageDependency.VersionSpec);
}
}
else
{
return String.Format("{0}:{1}:{2}", packageDependency.Id, packageDependency.VersionSpec, VersionUtility.GetShortFrameworkName(targetFramework));
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmPricingMatrix
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmPricingMatrix() : base()
{
Load += frmPricingMatrix_Load;
KeyPress += frmPricingMatrix_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdPrint;
public System.Windows.Forms.Button cmdPrint {
get { return withEventsField_cmdPrint; }
set {
if (withEventsField_cmdPrint != null) {
withEventsField_cmdPrint.Click -= cmdPrint_Click;
}
withEventsField_cmdPrint = value;
if (withEventsField_cmdPrint != null) {
withEventsField_cmdPrint.Click += cmdPrint_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_Command1;
public System.Windows.Forms.Button Command1 {
get { return withEventsField_Command1; }
set {
if (withEventsField_Command1 != null) {
withEventsField_Command1.Click -= Command1_Click;
}
withEventsField_Command1 = value;
if (withEventsField_Command1 != null) {
withEventsField_Command1.Click += Command1_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.TextBox _txtUnit_7;
public System.Windows.Forms.TextBox _txtCase_7;
public System.Windows.Forms.TextBox _txtUnit_8;
public System.Windows.Forms.TextBox _txtCase_8;
public System.Windows.Forms.TextBox _txtUnit_6;
public System.Windows.Forms.TextBox _txtCase_6;
public System.Windows.Forms.TextBox _txtUnit_5;
public System.Windows.Forms.TextBox _txtCase_5;
public System.Windows.Forms.TextBox _txtUnit_4;
public System.Windows.Forms.TextBox _txtCase_4;
public System.Windows.Forms.TextBox _txtUnit_3;
public System.Windows.Forms.TextBox _txtCase_3;
public System.Windows.Forms.TextBox _txtUnit_2;
public System.Windows.Forms.TextBox _txtCase_2;
public System.Windows.Forms.TextBox _txtCase_1;
public System.Windows.Forms.TextBox _txtUnit_1;
public System.Windows.Forms.Label _lblPricingGroup_8;
public System.Windows.Forms.Label _lblPricingGroup_7;
public System.Windows.Forms.Label _lblPricingGroup_6;
public System.Windows.Forms.Label _lblPricingGroup_5;
public System.Windows.Forms.Label _lblPricingGroup_4;
public System.Windows.Forms.Label _lblPricingGroup_3;
public System.Windows.Forms.Label _lblPricingGroup_2;
public System.Windows.Forms.Label _lblPricingGroup_1;
public System.Windows.Forms.Label _lbl_5;
public System.Windows.Forms.Label _lbl_2;
private System.Windows.Forms.Label withEventsField_lblHeading;
public System.Windows.Forms.Label lblHeading {
get { return withEventsField_lblHeading; }
set {
if (withEventsField_lblHeading != null) {
withEventsField_lblHeading.Click -= lblHeading_Click;
}
withEventsField_lblHeading = value;
if (withEventsField_lblHeading != null) {
withEventsField_lblHeading.Click += lblHeading_Click;
}
}
}
public System.Windows.Forms.GroupBox _frmDetails_0;
private System.Windows.Forms.TextBox withEventsField_txtEdit;
public System.Windows.Forms.TextBox txtEdit {
get { return withEventsField_txtEdit; }
set {
if (withEventsField_txtEdit != null) {
withEventsField_txtEdit.Enter -= txtEdit_Enter;
withEventsField_txtEdit.KeyDown -= txtEdit_KeyDown;
withEventsField_txtEdit.KeyPress -= txtEdit_KeyPress;
}
withEventsField_txtEdit = value;
if (withEventsField_txtEdit != null) {
withEventsField_txtEdit.Enter += txtEdit_Enter;
withEventsField_txtEdit.KeyDown += txtEdit_KeyDown;
withEventsField_txtEdit.KeyPress += txtEdit_KeyPress;
}
}
}
private myDataGridView withEventsField_gridItem;
public myDataGridView gridItem {
get { return withEventsField_gridItem; }
set {
if (withEventsField_gridItem != null) {
withEventsField_gridItem.Enter -= gridItem_Enter;
withEventsField_gridItem.KeyPress -= gridItem_KeyPress;
}
withEventsField_gridItem = value;
if (withEventsField_gridItem != null) {
withEventsField_gridItem.Enter += gridItem_Enter;
withEventsField_gridItem.KeyPress += gridItem_KeyPress;
}
}
}
public System.Windows.Forms.Label lblColorChanged;
public System.Windows.Forms.Label _lblColorFixed_1;
public System.Windows.Forms.Label _lblColorFixed_0;
public System.Windows.Forms.Label _lblcolor_1;
public System.Windows.Forms.Label _lblcolor_0;
//Public WithEvents frmDetails As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblColorFixed As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblPricingGroup As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblcolor As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents txtCase As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
//Public WithEvents txtUnit As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPricingMatrix));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.picButtons = new System.Windows.Forms.Panel();
this.cmdPrint = new System.Windows.Forms.Button();
this.Command1 = new System.Windows.Forms.Button();
this.cmdExit = new System.Windows.Forms.Button();
this._frmDetails_0 = new System.Windows.Forms.GroupBox();
this._txtUnit_7 = new System.Windows.Forms.TextBox();
this._txtCase_7 = new System.Windows.Forms.TextBox();
this._txtUnit_8 = new System.Windows.Forms.TextBox();
this._txtCase_8 = new System.Windows.Forms.TextBox();
this._txtUnit_6 = new System.Windows.Forms.TextBox();
this._txtCase_6 = new System.Windows.Forms.TextBox();
this._txtUnit_5 = new System.Windows.Forms.TextBox();
this._txtCase_5 = new System.Windows.Forms.TextBox();
this._txtUnit_4 = new System.Windows.Forms.TextBox();
this._txtCase_4 = new System.Windows.Forms.TextBox();
this._txtUnit_3 = new System.Windows.Forms.TextBox();
this._txtCase_3 = new System.Windows.Forms.TextBox();
this._txtUnit_2 = new System.Windows.Forms.TextBox();
this._txtCase_2 = new System.Windows.Forms.TextBox();
this._txtCase_1 = new System.Windows.Forms.TextBox();
this._txtUnit_1 = new System.Windows.Forms.TextBox();
this._lblPricingGroup_8 = new System.Windows.Forms.Label();
this._lblPricingGroup_7 = new System.Windows.Forms.Label();
this._lblPricingGroup_6 = new System.Windows.Forms.Label();
this._lblPricingGroup_5 = new System.Windows.Forms.Label();
this._lblPricingGroup_4 = new System.Windows.Forms.Label();
this._lblPricingGroup_3 = new System.Windows.Forms.Label();
this._lblPricingGroup_2 = new System.Windows.Forms.Label();
this._lblPricingGroup_1 = new System.Windows.Forms.Label();
this._lbl_5 = new System.Windows.Forms.Label();
this._lbl_2 = new System.Windows.Forms.Label();
this.lblHeading = new System.Windows.Forms.Label();
this.txtEdit = new System.Windows.Forms.TextBox();
this.gridItem = new myDataGridView();
this.lblColorChanged = new System.Windows.Forms.Label();
this._lblColorFixed_1 = new System.Windows.Forms.Label();
this._lblColorFixed_0 = new System.Windows.Forms.Label();
this._lblcolor_1 = new System.Windows.Forms.Label();
this._lblcolor_0 = new System.Windows.Forms.Label();
//Me.frmDetails = New Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray(components)
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.lblColorFixed = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.lblPricingGroup = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.lblcolor = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.txtCase = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components)
//Me.txtUnit = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components)
this.picButtons.SuspendLayout();
this._frmDetails_0.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.gridItem).BeginInit();
//CType(Me.frmDetails, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lblColorFixed, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lblPricingGroup, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lblcolor, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.txtCase, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.txtUnit, System.ComponentModel.ISupportInitialize).BeginInit()
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Text = "Detailed Pricing Matrices";
this.ClientSize = new System.Drawing.Size(543, 525);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = true;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmPricingMatrix";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(543, 39);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 35;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdPrint.Text = "&Print";
this.cmdPrint.Size = new System.Drawing.Size(73, 29);
this.cmdPrint.Location = new System.Drawing.Point(368, 3);
this.cmdPrint.TabIndex = 38;
this.cmdPrint.TabStop = false;
this.cmdPrint.BackColor = System.Drawing.SystemColors.Control;
this.cmdPrint.CausesValidation = true;
this.cmdPrint.Enabled = true;
this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPrint.Name = "cmdPrint";
this.Command1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.Command1.Text = "Command1";
this.Command1.Size = new System.Drawing.Size(97, 25);
this.Command1.Location = new System.Drawing.Point(16, 8);
this.Command1.TabIndex = 37;
this.Command1.Visible = false;
this.Command1.BackColor = System.Drawing.SystemColors.Control;
this.Command1.CausesValidation = true;
this.Command1.Enabled = true;
this.Command1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Command1.Cursor = System.Windows.Forms.Cursors.Default;
this.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Command1.TabStop = true;
this.Command1.Name = "Command1";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Size = new System.Drawing.Size(73, 29);
this.cmdExit.Location = new System.Drawing.Point(462, 3);
this.cmdExit.TabIndex = 36;
this.cmdExit.TabStop = false;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Name = "cmdExit";
this._frmDetails_0.Text = "Frame1";
this._frmDetails_0.Size = new System.Drawing.Size(532, 88);
this._frmDetails_0.Location = new System.Drawing.Point(0, 48);
this._frmDetails_0.TabIndex = 2;
this._frmDetails_0.BackColor = System.Drawing.SystemColors.Control;
this._frmDetails_0.Enabled = true;
this._frmDetails_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._frmDetails_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._frmDetails_0.Visible = true;
this._frmDetails_0.Padding = new System.Windows.Forms.Padding(0);
this._frmDetails_0.Name = "_frmDetails_0";
this._txtUnit_7.AutoSize = false;
this._txtUnit_7.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtUnit_7.Enabled = false;
this._txtUnit_7.Size = new System.Drawing.Size(46, 19);
this._txtUnit_7.Location = new System.Drawing.Point(405, 39);
this._txtUnit_7.TabIndex = 18;
this._txtUnit_7.Text = "0.00";
this._txtUnit_7.AcceptsReturn = true;
this._txtUnit_7.BackColor = System.Drawing.SystemColors.Window;
this._txtUnit_7.CausesValidation = true;
this._txtUnit_7.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtUnit_7.HideSelection = true;
this._txtUnit_7.ReadOnly = false;
this._txtUnit_7.MaxLength = 0;
this._txtUnit_7.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtUnit_7.Multiline = false;
this._txtUnit_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtUnit_7.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtUnit_7.TabStop = true;
this._txtUnit_7.Visible = true;
this._txtUnit_7.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtUnit_7.Name = "_txtUnit_7";
this._txtCase_7.AutoSize = false;
this._txtCase_7.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtCase_7.Enabled = false;
this._txtCase_7.Size = new System.Drawing.Size(46, 19);
this._txtCase_7.Location = new System.Drawing.Point(405, 57);
this._txtCase_7.TabIndex = 17;
this._txtCase_7.Text = "0.00";
this._txtCase_7.AcceptsReturn = true;
this._txtCase_7.BackColor = System.Drawing.SystemColors.Window;
this._txtCase_7.CausesValidation = true;
this._txtCase_7.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtCase_7.HideSelection = true;
this._txtCase_7.ReadOnly = false;
this._txtCase_7.MaxLength = 0;
this._txtCase_7.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtCase_7.Multiline = false;
this._txtCase_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtCase_7.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtCase_7.TabStop = true;
this._txtCase_7.Visible = true;
this._txtCase_7.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtCase_7.Name = "_txtCase_7";
this._txtUnit_8.AutoSize = false;
this._txtUnit_8.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtUnit_8.Enabled = false;
this._txtUnit_8.Size = new System.Drawing.Size(46, 19);
this._txtUnit_8.Location = new System.Drawing.Point(453, 39);
this._txtUnit_8.TabIndex = 16;
this._txtUnit_8.Text = "0.00";
this._txtUnit_8.AcceptsReturn = true;
this._txtUnit_8.BackColor = System.Drawing.SystemColors.Window;
this._txtUnit_8.CausesValidation = true;
this._txtUnit_8.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtUnit_8.HideSelection = true;
this._txtUnit_8.ReadOnly = false;
this._txtUnit_8.MaxLength = 0;
this._txtUnit_8.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtUnit_8.Multiline = false;
this._txtUnit_8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtUnit_8.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtUnit_8.TabStop = true;
this._txtUnit_8.Visible = true;
this._txtUnit_8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtUnit_8.Name = "_txtUnit_8";
this._txtCase_8.AutoSize = false;
this._txtCase_8.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtCase_8.Enabled = false;
this._txtCase_8.Size = new System.Drawing.Size(46, 19);
this._txtCase_8.Location = new System.Drawing.Point(453, 57);
this._txtCase_8.TabIndex = 15;
this._txtCase_8.Text = "0.00";
this._txtCase_8.AcceptsReturn = true;
this._txtCase_8.BackColor = System.Drawing.SystemColors.Window;
this._txtCase_8.CausesValidation = true;
this._txtCase_8.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtCase_8.HideSelection = true;
this._txtCase_8.ReadOnly = false;
this._txtCase_8.MaxLength = 0;
this._txtCase_8.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtCase_8.Multiline = false;
this._txtCase_8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtCase_8.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtCase_8.TabStop = true;
this._txtCase_8.Visible = true;
this._txtCase_8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtCase_8.Name = "_txtCase_8";
this._txtUnit_6.AutoSize = false;
this._txtUnit_6.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtUnit_6.Enabled = false;
this._txtUnit_6.Size = new System.Drawing.Size(46, 19);
this._txtUnit_6.Location = new System.Drawing.Point(357, 39);
this._txtUnit_6.TabIndex = 14;
this._txtUnit_6.Text = "0.00";
this._txtUnit_6.AcceptsReturn = true;
this._txtUnit_6.BackColor = System.Drawing.SystemColors.Window;
this._txtUnit_6.CausesValidation = true;
this._txtUnit_6.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtUnit_6.HideSelection = true;
this._txtUnit_6.ReadOnly = false;
this._txtUnit_6.MaxLength = 0;
this._txtUnit_6.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtUnit_6.Multiline = false;
this._txtUnit_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtUnit_6.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtUnit_6.TabStop = true;
this._txtUnit_6.Visible = true;
this._txtUnit_6.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtUnit_6.Name = "_txtUnit_6";
this._txtCase_6.AutoSize = false;
this._txtCase_6.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtCase_6.Enabled = false;
this._txtCase_6.Size = new System.Drawing.Size(46, 19);
this._txtCase_6.Location = new System.Drawing.Point(357, 57);
this._txtCase_6.TabIndex = 13;
this._txtCase_6.Text = "0.00";
this._txtCase_6.AcceptsReturn = true;
this._txtCase_6.BackColor = System.Drawing.SystemColors.Window;
this._txtCase_6.CausesValidation = true;
this._txtCase_6.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtCase_6.HideSelection = true;
this._txtCase_6.ReadOnly = false;
this._txtCase_6.MaxLength = 0;
this._txtCase_6.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtCase_6.Multiline = false;
this._txtCase_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtCase_6.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtCase_6.TabStop = true;
this._txtCase_6.Visible = true;
this._txtCase_6.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtCase_6.Name = "_txtCase_6";
this._txtUnit_5.AutoSize = false;
this._txtUnit_5.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtUnit_5.Enabled = false;
this._txtUnit_5.Size = new System.Drawing.Size(46, 19);
this._txtUnit_5.Location = new System.Drawing.Point(309, 39);
this._txtUnit_5.TabIndex = 12;
this._txtUnit_5.Text = "0.00";
this._txtUnit_5.AcceptsReturn = true;
this._txtUnit_5.BackColor = System.Drawing.SystemColors.Window;
this._txtUnit_5.CausesValidation = true;
this._txtUnit_5.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtUnit_5.HideSelection = true;
this._txtUnit_5.ReadOnly = false;
this._txtUnit_5.MaxLength = 0;
this._txtUnit_5.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtUnit_5.Multiline = false;
this._txtUnit_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtUnit_5.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtUnit_5.TabStop = true;
this._txtUnit_5.Visible = true;
this._txtUnit_5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtUnit_5.Name = "_txtUnit_5";
this._txtCase_5.AutoSize = false;
this._txtCase_5.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtCase_5.Enabled = false;
this._txtCase_5.Size = new System.Drawing.Size(46, 19);
this._txtCase_5.Location = new System.Drawing.Point(309, 57);
this._txtCase_5.TabIndex = 11;
this._txtCase_5.Text = "0.00";
this._txtCase_5.AcceptsReturn = true;
this._txtCase_5.BackColor = System.Drawing.SystemColors.Window;
this._txtCase_5.CausesValidation = true;
this._txtCase_5.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtCase_5.HideSelection = true;
this._txtCase_5.ReadOnly = false;
this._txtCase_5.MaxLength = 0;
this._txtCase_5.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtCase_5.Multiline = false;
this._txtCase_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtCase_5.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtCase_5.TabStop = true;
this._txtCase_5.Visible = true;
this._txtCase_5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtCase_5.Name = "_txtCase_5";
this._txtUnit_4.AutoSize = false;
this._txtUnit_4.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtUnit_4.Enabled = false;
this._txtUnit_4.Size = new System.Drawing.Size(46, 19);
this._txtUnit_4.Location = new System.Drawing.Point(261, 39);
this._txtUnit_4.TabIndex = 10;
this._txtUnit_4.Text = "0.00";
this._txtUnit_4.AcceptsReturn = true;
this._txtUnit_4.BackColor = System.Drawing.SystemColors.Window;
this._txtUnit_4.CausesValidation = true;
this._txtUnit_4.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtUnit_4.HideSelection = true;
this._txtUnit_4.ReadOnly = false;
this._txtUnit_4.MaxLength = 0;
this._txtUnit_4.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtUnit_4.Multiline = false;
this._txtUnit_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtUnit_4.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtUnit_4.TabStop = true;
this._txtUnit_4.Visible = true;
this._txtUnit_4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtUnit_4.Name = "_txtUnit_4";
this._txtCase_4.AutoSize = false;
this._txtCase_4.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtCase_4.Enabled = false;
this._txtCase_4.Size = new System.Drawing.Size(46, 19);
this._txtCase_4.Location = new System.Drawing.Point(261, 57);
this._txtCase_4.TabIndex = 9;
this._txtCase_4.Text = "0.00";
this._txtCase_4.AcceptsReturn = true;
this._txtCase_4.BackColor = System.Drawing.SystemColors.Window;
this._txtCase_4.CausesValidation = true;
this._txtCase_4.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtCase_4.HideSelection = true;
this._txtCase_4.ReadOnly = false;
this._txtCase_4.MaxLength = 0;
this._txtCase_4.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtCase_4.Multiline = false;
this._txtCase_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtCase_4.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtCase_4.TabStop = true;
this._txtCase_4.Visible = true;
this._txtCase_4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtCase_4.Name = "_txtCase_4";
this._txtUnit_3.AutoSize = false;
this._txtUnit_3.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtUnit_3.Enabled = false;
this._txtUnit_3.Size = new System.Drawing.Size(46, 19);
this._txtUnit_3.Location = new System.Drawing.Point(213, 39);
this._txtUnit_3.TabIndex = 8;
this._txtUnit_3.Text = "0.00";
this._txtUnit_3.AcceptsReturn = true;
this._txtUnit_3.BackColor = System.Drawing.SystemColors.Window;
this._txtUnit_3.CausesValidation = true;
this._txtUnit_3.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtUnit_3.HideSelection = true;
this._txtUnit_3.ReadOnly = false;
this._txtUnit_3.MaxLength = 0;
this._txtUnit_3.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtUnit_3.Multiline = false;
this._txtUnit_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtUnit_3.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtUnit_3.TabStop = true;
this._txtUnit_3.Visible = true;
this._txtUnit_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtUnit_3.Name = "_txtUnit_3";
this._txtCase_3.AutoSize = false;
this._txtCase_3.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtCase_3.Enabled = false;
this._txtCase_3.Size = new System.Drawing.Size(46, 19);
this._txtCase_3.Location = new System.Drawing.Point(213, 57);
this._txtCase_3.TabIndex = 7;
this._txtCase_3.Text = "0.00";
this._txtCase_3.AcceptsReturn = true;
this._txtCase_3.BackColor = System.Drawing.SystemColors.Window;
this._txtCase_3.CausesValidation = true;
this._txtCase_3.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtCase_3.HideSelection = true;
this._txtCase_3.ReadOnly = false;
this._txtCase_3.MaxLength = 0;
this._txtCase_3.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtCase_3.Multiline = false;
this._txtCase_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtCase_3.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtCase_3.TabStop = true;
this._txtCase_3.Visible = true;
this._txtCase_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtCase_3.Name = "_txtCase_3";
this._txtUnit_2.AutoSize = false;
this._txtUnit_2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtUnit_2.Enabled = false;
this._txtUnit_2.Size = new System.Drawing.Size(46, 19);
this._txtUnit_2.Location = new System.Drawing.Point(165, 39);
this._txtUnit_2.TabIndex = 6;
this._txtUnit_2.Text = "0.00";
this._txtUnit_2.AcceptsReturn = true;
this._txtUnit_2.BackColor = System.Drawing.SystemColors.Window;
this._txtUnit_2.CausesValidation = true;
this._txtUnit_2.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtUnit_2.HideSelection = true;
this._txtUnit_2.ReadOnly = false;
this._txtUnit_2.MaxLength = 0;
this._txtUnit_2.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtUnit_2.Multiline = false;
this._txtUnit_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtUnit_2.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtUnit_2.TabStop = true;
this._txtUnit_2.Visible = true;
this._txtUnit_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtUnit_2.Name = "_txtUnit_2";
this._txtCase_2.AutoSize = false;
this._txtCase_2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtCase_2.Enabled = false;
this._txtCase_2.Size = new System.Drawing.Size(46, 19);
this._txtCase_2.Location = new System.Drawing.Point(165, 57);
this._txtCase_2.TabIndex = 5;
this._txtCase_2.Text = "0.00";
this._txtCase_2.AcceptsReturn = true;
this._txtCase_2.BackColor = System.Drawing.SystemColors.Window;
this._txtCase_2.CausesValidation = true;
this._txtCase_2.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtCase_2.HideSelection = true;
this._txtCase_2.ReadOnly = false;
this._txtCase_2.MaxLength = 0;
this._txtCase_2.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtCase_2.Multiline = false;
this._txtCase_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtCase_2.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtCase_2.TabStop = true;
this._txtCase_2.Visible = true;
this._txtCase_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtCase_2.Name = "_txtCase_2";
this._txtCase_1.AutoSize = false;
this._txtCase_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtCase_1.Enabled = false;
this._txtCase_1.Size = new System.Drawing.Size(46, 19);
this._txtCase_1.Location = new System.Drawing.Point(117, 57);
this._txtCase_1.TabIndex = 4;
this._txtCase_1.Text = "0.00";
this._txtCase_1.AcceptsReturn = true;
this._txtCase_1.BackColor = System.Drawing.SystemColors.Window;
this._txtCase_1.CausesValidation = true;
this._txtCase_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtCase_1.HideSelection = true;
this._txtCase_1.ReadOnly = false;
this._txtCase_1.MaxLength = 0;
this._txtCase_1.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtCase_1.Multiline = false;
this._txtCase_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtCase_1.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtCase_1.TabStop = true;
this._txtCase_1.Visible = true;
this._txtCase_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtCase_1.Name = "_txtCase_1";
this._txtUnit_1.AutoSize = false;
this._txtUnit_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtUnit_1.Enabled = false;
this._txtUnit_1.Size = new System.Drawing.Size(46, 19);
this._txtUnit_1.Location = new System.Drawing.Point(117, 39);
this._txtUnit_1.TabIndex = 3;
this._txtUnit_1.Text = "0.00";
this._txtUnit_1.AcceptsReturn = true;
this._txtUnit_1.BackColor = System.Drawing.SystemColors.Window;
this._txtUnit_1.CausesValidation = true;
this._txtUnit_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtUnit_1.HideSelection = true;
this._txtUnit_1.ReadOnly = false;
this._txtUnit_1.MaxLength = 0;
this._txtUnit_1.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtUnit_1.Multiline = false;
this._txtUnit_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtUnit_1.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtUnit_1.TabStop = true;
this._txtUnit_1.Visible = true;
this._txtUnit_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtUnit_1.Name = "_txtUnit_1";
this._lblPricingGroup_8.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this._lblPricingGroup_8.BackColor = System.Drawing.Color.Transparent;
this._lblPricingGroup_8.Text = "CG8";
this._lblPricingGroup_8.Size = new System.Drawing.Size(46, 13);
this._lblPricingGroup_8.Location = new System.Drawing.Point(451, 24);
this._lblPricingGroup_8.TabIndex = 29;
this._lblPricingGroup_8.Enabled = true;
this._lblPricingGroup_8.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblPricingGroup_8.Cursor = System.Windows.Forms.Cursors.Default;
this._lblPricingGroup_8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblPricingGroup_8.UseMnemonic = true;
this._lblPricingGroup_8.Visible = true;
this._lblPricingGroup_8.AutoSize = false;
this._lblPricingGroup_8.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblPricingGroup_8.Name = "_lblPricingGroup_8";
this._lblPricingGroup_7.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this._lblPricingGroup_7.BackColor = System.Drawing.Color.Transparent;
this._lblPricingGroup_7.Text = "CG7";
this._lblPricingGroup_7.Size = new System.Drawing.Size(46, 13);
this._lblPricingGroup_7.Location = new System.Drawing.Point(405, 24);
this._lblPricingGroup_7.TabIndex = 28;
this._lblPricingGroup_7.Enabled = true;
this._lblPricingGroup_7.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblPricingGroup_7.Cursor = System.Windows.Forms.Cursors.Default;
this._lblPricingGroup_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblPricingGroup_7.UseMnemonic = true;
this._lblPricingGroup_7.Visible = true;
this._lblPricingGroup_7.AutoSize = false;
this._lblPricingGroup_7.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblPricingGroup_7.Name = "_lblPricingGroup_7";
this._lblPricingGroup_6.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this._lblPricingGroup_6.BackColor = System.Drawing.Color.Transparent;
this._lblPricingGroup_6.Text = "CG6";
this._lblPricingGroup_6.Size = new System.Drawing.Size(46, 13);
this._lblPricingGroup_6.Location = new System.Drawing.Point(356, 24);
this._lblPricingGroup_6.TabIndex = 27;
this._lblPricingGroup_6.Enabled = true;
this._lblPricingGroup_6.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblPricingGroup_6.Cursor = System.Windows.Forms.Cursors.Default;
this._lblPricingGroup_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblPricingGroup_6.UseMnemonic = true;
this._lblPricingGroup_6.Visible = true;
this._lblPricingGroup_6.AutoSize = false;
this._lblPricingGroup_6.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblPricingGroup_6.Name = "_lblPricingGroup_6";
this._lblPricingGroup_5.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this._lblPricingGroup_5.BackColor = System.Drawing.Color.Transparent;
this._lblPricingGroup_5.Text = "CG5";
this._lblPricingGroup_5.Size = new System.Drawing.Size(46, 13);
this._lblPricingGroup_5.Location = new System.Drawing.Point(309, 24);
this._lblPricingGroup_5.TabIndex = 26;
this._lblPricingGroup_5.Enabled = true;
this._lblPricingGroup_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblPricingGroup_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lblPricingGroup_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblPricingGroup_5.UseMnemonic = true;
this._lblPricingGroup_5.Visible = true;
this._lblPricingGroup_5.AutoSize = false;
this._lblPricingGroup_5.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblPricingGroup_5.Name = "_lblPricingGroup_5";
this._lblPricingGroup_4.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this._lblPricingGroup_4.BackColor = System.Drawing.Color.Transparent;
this._lblPricingGroup_4.Text = "CG4";
this._lblPricingGroup_4.Size = new System.Drawing.Size(46, 13);
this._lblPricingGroup_4.Location = new System.Drawing.Point(261, 24);
this._lblPricingGroup_4.TabIndex = 25;
this._lblPricingGroup_4.Enabled = true;
this._lblPricingGroup_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblPricingGroup_4.Cursor = System.Windows.Forms.Cursors.Default;
this._lblPricingGroup_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblPricingGroup_4.UseMnemonic = true;
this._lblPricingGroup_4.Visible = true;
this._lblPricingGroup_4.AutoSize = false;
this._lblPricingGroup_4.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblPricingGroup_4.Name = "_lblPricingGroup_4";
this._lblPricingGroup_3.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this._lblPricingGroup_3.BackColor = System.Drawing.Color.Transparent;
this._lblPricingGroup_3.Text = "CG3";
this._lblPricingGroup_3.Size = new System.Drawing.Size(46, 13);
this._lblPricingGroup_3.Location = new System.Drawing.Point(213, 24);
this._lblPricingGroup_3.TabIndex = 24;
this._lblPricingGroup_3.Enabled = true;
this._lblPricingGroup_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblPricingGroup_3.Cursor = System.Windows.Forms.Cursors.Default;
this._lblPricingGroup_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblPricingGroup_3.UseMnemonic = true;
this._lblPricingGroup_3.Visible = true;
this._lblPricingGroup_3.AutoSize = false;
this._lblPricingGroup_3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblPricingGroup_3.Name = "_lblPricingGroup_3";
this._lblPricingGroup_2.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this._lblPricingGroup_2.BackColor = System.Drawing.Color.Transparent;
this._lblPricingGroup_2.Text = "CG2";
this._lblPricingGroup_2.Size = new System.Drawing.Size(46, 13);
this._lblPricingGroup_2.Location = new System.Drawing.Point(165, 24);
this._lblPricingGroup_2.TabIndex = 23;
this._lblPricingGroup_2.Enabled = true;
this._lblPricingGroup_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblPricingGroup_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lblPricingGroup_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblPricingGroup_2.UseMnemonic = true;
this._lblPricingGroup_2.Visible = true;
this._lblPricingGroup_2.AutoSize = false;
this._lblPricingGroup_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblPricingGroup_2.Name = "_lblPricingGroup_2";
this._lblPricingGroup_1.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this._lblPricingGroup_1.BackColor = System.Drawing.Color.Transparent;
this._lblPricingGroup_1.Text = "CG1";
this._lblPricingGroup_1.Size = new System.Drawing.Size(46, 13);
this._lblPricingGroup_1.Location = new System.Drawing.Point(120, 24);
this._lblPricingGroup_1.TabIndex = 22;
this._lblPricingGroup_1.Enabled = true;
this._lblPricingGroup_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblPricingGroup_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lblPricingGroup_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblPricingGroup_1.UseMnemonic = true;
this._lblPricingGroup_1.Visible = true;
this._lblPricingGroup_1.AutoSize = false;
this._lblPricingGroup_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblPricingGroup_1.Name = "_lblPricingGroup_1";
this._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lbl_5.Text = "Case/Carton Markup :";
this._lbl_5.Size = new System.Drawing.Size(105, 13);
this._lbl_5.Location = new System.Drawing.Point(7, 60);
this._lbl_5.TabIndex = 21;
this._lbl_5.BackColor = System.Drawing.SystemColors.Control;
this._lbl_5.Enabled = true;
this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_5.UseMnemonic = true;
this._lbl_5.Visible = true;
this._lbl_5.AutoSize = true;
this._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_5.Name = "_lbl_5";
this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lbl_2.Text = "Unit Markup :";
this._lbl_2.Size = new System.Drawing.Size(64, 13);
this._lbl_2.Location = new System.Drawing.Point(48, 42);
this._lbl_2.TabIndex = 20;
this._lbl_2.BackColor = System.Drawing.SystemColors.Control;
this._lbl_2.Enabled = true;
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.UseMnemonic = true;
this._lbl_2.Visible = true;
this._lbl_2.AutoSize = true;
this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_2.Name = "_lbl_2";
this.lblHeading.BackColor = System.Drawing.Color.FromArgb(128, 128, 255);
this.lblHeading.Text = "Default Pricing Matrix for each Channel.";
this.lblHeading.ForeColor = System.Drawing.Color.White;
this.lblHeading.Size = new System.Drawing.Size(526, 15);
this.lblHeading.Location = new System.Drawing.Point(3, 0);
this.lblHeading.TabIndex = 19;
this.lblHeading.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblHeading.Enabled = true;
this.lblHeading.Cursor = System.Windows.Forms.Cursors.Default;
this.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblHeading.UseMnemonic = true;
this.lblHeading.Visible = true;
this.lblHeading.AutoSize = false;
this.lblHeading.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.lblHeading.Name = "lblHeading";
this.txtEdit.AutoSize = false;
this.txtEdit.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.txtEdit.BackColor = System.Drawing.Color.FromArgb(255, 255, 192);
this.txtEdit.Size = new System.Drawing.Size(55, 16);
this.txtEdit.Location = new System.Drawing.Point(186, 321);
this.txtEdit.TabIndex = 1;
this.txtEdit.Tag = "0.00";
this.txtEdit.Text = "0.00";
this.txtEdit.AcceptsReturn = true;
this.txtEdit.CausesValidation = true;
this.txtEdit.Enabled = true;
this.txtEdit.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtEdit.HideSelection = true;
this.txtEdit.ReadOnly = false;
this.txtEdit.MaxLength = 0;
this.txtEdit.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtEdit.Multiline = false;
this.txtEdit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtEdit.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtEdit.TabStop = true;
this.txtEdit.Visible = true;
this.txtEdit.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.txtEdit.Name = "txtEdit";
//gridItem.OcxState = CType(resources.GetObject("gridItem.OcxState"), System.Windows.Forms.AxHost.State)
this.gridItem.Size = new System.Drawing.Size(529, 354);
this.gridItem.Location = new System.Drawing.Point(3, 144);
this.gridItem.TabIndex = 0;
this.gridItem.Name = "gridItem";
this.lblColorChanged.BackColor = System.Drawing.Color.FromArgb(255, 224, 192);
this.lblColorChanged.Text = "Label1";
this.lblColorChanged.Size = new System.Drawing.Size(82, 34);
this.lblColorChanged.Location = new System.Drawing.Point(561, 246);
this.lblColorChanged.TabIndex = 34;
this.lblColorChanged.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblColorChanged.Enabled = true;
this.lblColorChanged.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblColorChanged.Cursor = System.Windows.Forms.Cursors.Default;
this.lblColorChanged.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblColorChanged.UseMnemonic = true;
this.lblColorChanged.Visible = true;
this.lblColorChanged.AutoSize = false;
this.lblColorChanged.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblColorChanged.Name = "lblColorChanged";
this._lblColorFixed_1.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this._lblColorFixed_1.Text = "Label1";
this._lblColorFixed_1.Size = new System.Drawing.Size(67, 13);
this._lblColorFixed_1.Location = new System.Drawing.Point(546, 156);
this._lblColorFixed_1.TabIndex = 33;
this._lblColorFixed_1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblColorFixed_1.Enabled = true;
this._lblColorFixed_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblColorFixed_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lblColorFixed_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblColorFixed_1.UseMnemonic = true;
this._lblColorFixed_1.Visible = true;
this._lblColorFixed_1.AutoSize = false;
this._lblColorFixed_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblColorFixed_1.Name = "_lblColorFixed_1";
this._lblColorFixed_0.BackColor = System.Drawing.Color.FromArgb(192, 192, 192);
this._lblColorFixed_0.Text = "Label1";
this._lblColorFixed_0.Size = new System.Drawing.Size(67, 13);
this._lblColorFixed_0.Location = new System.Drawing.Point(552, 138);
this._lblColorFixed_0.TabIndex = 32;
this._lblColorFixed_0.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblColorFixed_0.Enabled = true;
this._lblColorFixed_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblColorFixed_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lblColorFixed_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblColorFixed_0.UseMnemonic = true;
this._lblColorFixed_0.Visible = true;
this._lblColorFixed_0.AutoSize = false;
this._lblColorFixed_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblColorFixed_0.Name = "_lblColorFixed_0";
this._lblcolor_1.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this._lblcolor_1.Text = "Label1";
this._lblcolor_1.Size = new System.Drawing.Size(70, 19);
this._lblcolor_1.Location = new System.Drawing.Point(570, 204);
this._lblcolor_1.TabIndex = 31;
this._lblcolor_1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblcolor_1.Enabled = true;
this._lblcolor_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblcolor_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lblcolor_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblcolor_1.UseMnemonic = true;
this._lblcolor_1.Visible = true;
this._lblcolor_1.AutoSize = false;
this._lblcolor_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblcolor_1.Name = "_lblcolor_1";
this._lblcolor_0.BackColor = System.Drawing.Color.FromArgb(192, 192, 192);
this._lblcolor_0.Text = "Label1";
this._lblcolor_0.Size = new System.Drawing.Size(70, 19);
this._lblcolor_0.Location = new System.Drawing.Point(570, 186);
this._lblcolor_0.TabIndex = 30;
this._lblcolor_0.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblcolor_0.Enabled = true;
this._lblcolor_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblcolor_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lblcolor_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblcolor_0.UseMnemonic = true;
this._lblcolor_0.Visible = true;
this._lblcolor_0.AutoSize = false;
this._lblcolor_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblcolor_0.Name = "_lblcolor_0";
this.Controls.Add(picButtons);
this.Controls.Add(_frmDetails_0);
this.Controls.Add(txtEdit);
this.Controls.Add(gridItem);
this.Controls.Add(lblColorChanged);
this.Controls.Add(_lblColorFixed_1);
this.Controls.Add(_lblColorFixed_0);
this.Controls.Add(_lblcolor_1);
this.Controls.Add(_lblcolor_0);
this.picButtons.Controls.Add(cmdPrint);
this.picButtons.Controls.Add(Command1);
this.picButtons.Controls.Add(cmdExit);
this._frmDetails_0.Controls.Add(_txtUnit_7);
this._frmDetails_0.Controls.Add(_txtCase_7);
this._frmDetails_0.Controls.Add(_txtUnit_8);
this._frmDetails_0.Controls.Add(_txtCase_8);
this._frmDetails_0.Controls.Add(_txtUnit_6);
this._frmDetails_0.Controls.Add(_txtCase_6);
this._frmDetails_0.Controls.Add(_txtUnit_5);
this._frmDetails_0.Controls.Add(_txtCase_5);
this._frmDetails_0.Controls.Add(_txtUnit_4);
this._frmDetails_0.Controls.Add(_txtCase_4);
this._frmDetails_0.Controls.Add(_txtUnit_3);
this._frmDetails_0.Controls.Add(_txtCase_3);
this._frmDetails_0.Controls.Add(_txtUnit_2);
this._frmDetails_0.Controls.Add(_txtCase_2);
this._frmDetails_0.Controls.Add(_txtCase_1);
this._frmDetails_0.Controls.Add(_txtUnit_1);
this._frmDetails_0.Controls.Add(_lblPricingGroup_8);
this._frmDetails_0.Controls.Add(_lblPricingGroup_7);
this._frmDetails_0.Controls.Add(_lblPricingGroup_6);
this._frmDetails_0.Controls.Add(_lblPricingGroup_5);
this._frmDetails_0.Controls.Add(_lblPricingGroup_4);
this._frmDetails_0.Controls.Add(_lblPricingGroup_3);
this._frmDetails_0.Controls.Add(_lblPricingGroup_2);
this._frmDetails_0.Controls.Add(_lblPricingGroup_1);
this._frmDetails_0.Controls.Add(_lbl_5);
this._frmDetails_0.Controls.Add(_lbl_2);
this._frmDetails_0.Controls.Add(lblHeading);
//Me.frmDetails.SetIndex(_frmDetails_0, CType(0, Short))
//Me.lbl.SetIndex(_lbl_5, CType(5, Short))
//Me.lbl.SetIndex(_lbl_2, CType(2, Short))
//Me.lblColorFixed.SetIndex(_lblColorFixed_1, CType(1, Short))
//Me.lblColorFixed.SetIndex(_lblColorFixed_0, CType(0, Short))
//Me.lblPricingGroup.SetIndex(_lblPricingGroup_8, CType(8, Short))
//Me.lblPricingGroup.SetIndex(_lblPricingGroup_7, CType(7, Short))
//Me.lblPricingGroup.SetIndex(_lblPricingGroup_6, CType(6, Short))
//Me.lblPricingGroup.SetIndex(_lblPricingGroup_5, CType(5, Short))
//Me.lblPricingGroup.SetIndex(_lblPricingGroup_4, CType(4, Short))
//Me.lblPricingGroup.SetIndex(_lblPricingGroup_3, CType(3, Short))
//Me.lblPricingGroup.SetIndex(_lblPricingGroup_2, CType(2, Short))
//Me.lblPricingGroup.SetIndex(_lblPricingGroup_1, CType(1, Short))
//Me.lblcolor.SetIndex(_lblcolor_1, CType(1, Short))
//Me.lblcolor.SetIndex(_lblcolor_0, CType(0, Short))
//Me.txtCase.SetIndex(_txtCase_7, CType(7, Short))
//Me.txtCase.SetIndex(_txtCase_8, CType(8, Short))
//Me.txtCase.SetIndex(_txtCase_6, CType(6, Short))
//Me.txtCase.SetIndex(_txtCase_5, CType(5, Short))
//Me.txtCase.SetIndex(_txtCase_4, CType(4, Short))
//Me.txtCase.SetIndex(_txtCase_3, CType(3, Short))
//Me.txtCase.SetIndex(_txtCase_2, CType(2, Short))
//Me.txtCase.SetIndex(_txtCase_1, CType(1, Short))
//Me.txtUnit.SetIndex(_txtUnit_7, CType(7, Short))
//Me.txtUnit.SetIndex(_txtUnit_8, CType(8, Short))
//Me.txtUnit.SetIndex(_txtUnit_6, CType(6, Short))
//Me.txtUnit.SetIndex(_txtUnit_5, CType(5, Short))
//Me.txtUnit.SetIndex(_txtUnit_4, CType(4, Short))
//Me.txtUnit.SetIndex(_txtUnit_3, CType(3, Short))
//Me.txtUnit.SetIndex(_txtUnit_2, CType(2, Short))
//Me.txtUnit.SetIndex(_txtUnit_1, CType(1, Short))
//CType(Me.txtUnit, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.txtCase, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lblcolor, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lblPricingGroup, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lblColorFixed, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.frmDetails, System.ComponentModel.ISupportInitialize).EndInit()
((System.ComponentModel.ISupportInitialize)this.gridItem).EndInit();
this.picButtons.ResumeLayout(false);
this._frmDetails_0.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#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.Binary;
using System.Buffers;
using System.Buffers.Pools;
using System.Collections.Generic;
using System.Collections.Sequences;
using System.Globalization;
using System.IO.Pipelines.Testing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Pipelines.Text.Primitives;
using Xunit;
using System.Text.Formatting;
namespace System.IO.Pipelines.Tests
{
public class ReadableBufferFacts
{
[Fact]
public void EmptyIsCorrect()
{
var buffer = BufferUtilities.CreateBuffer(0, 0);
Assert.Equal(0, buffer.Length);
Assert.True(buffer.IsEmpty);
}
[Fact]
public async Task TestIndexOfWorksForAllLocations()
{
using (var factory = new PipeFactory())
{
var readerWriter = factory.Create();
const int Size = 5 * 4032; // multiple blocks
// populate with a pile of dummy data
byte[] data = new byte[512];
for (int i = 0; i < data.Length; i++) data[i] = 42;
int totalBytes = 0;
var writeBuffer = readerWriter.Writer.Alloc();
for (int i = 0; i < Size / data.Length; i++)
{
writeBuffer.Write(data);
totalBytes += data.Length;
}
await writeBuffer.FlushAsync();
// now read it back
var result = await readerWriter.Reader.ReadAsync();
var readBuffer = result.Buffer;
Assert.False(readBuffer.IsSingleSpan);
Assert.Equal(totalBytes, readBuffer.Length);
TestIndexOfWorksForAllLocations(ref readBuffer, 42);
}
}
[Fact]
public async Task EqualsDetectsDeltaForAllLocations()
{
using (var factory = new PipeFactory())
{
var readerWriter = factory.Create();
// populate with dummy data
const int DataSize = 10000;
byte[] data = new byte[DataSize];
var rand = new Random(12345);
rand.NextBytes(data);
var writeBuffer = readerWriter.Writer.Alloc();
writeBuffer.Write(data);
await writeBuffer.FlushAsync();
// now read it back
var result = await readerWriter.Reader.ReadAsync();
var readBuffer = result.Buffer;
Assert.False(readBuffer.IsSingleSpan);
Assert.Equal(data.Length, readBuffer.Length);
// check the entire buffer
EqualsDetectsDeltaForAllLocations(readBuffer, data, 0, data.Length);
// check the first 32 sub-lengths
for (int i = 0; i <= 32; i++)
{
var slice = readBuffer.Slice(0, i);
EqualsDetectsDeltaForAllLocations(slice, data, 0, i);
}
// check the last 32 sub-lengths
for (int i = 0; i <= 32; i++)
{
var slice = readBuffer.Slice(data.Length - i, i);
EqualsDetectsDeltaForAllLocations(slice, data, data.Length - i, i);
}
}
}
private void EqualsDetectsDeltaForAllLocations(ReadableBuffer slice, byte[] expected, int offset, int length)
{
Assert.Equal(length, slice.Length);
Assert.True(slice.EqualsTo(new Span<byte>(expected, offset, length)));
// change one byte in buffer, for every position
for (int i = 0; i < length; i++)
{
expected[offset + i] ^= 42;
Assert.False(slice.EqualsTo(new Span<byte>(expected, offset, length)));
expected[offset + i] ^= 42;
}
}
[Fact]
public async Task GetUInt64GivesExpectedValues()
{
using (var factory = new PipeFactory())
{
var readerWriter = factory.Create();
var writeBuffer = readerWriter.Writer.Alloc();
writeBuffer.Ensure(50);
writeBuffer.Advance(50); // not even going to pretend to write data here - we're going to cheat
await writeBuffer.FlushAsync(); // by overwriting the buffer in-situ
// now read it back
var result = await readerWriter.Reader.ReadAsync();
var readBuffer = result.Buffer;
ReadUInt64GivesExpectedValues(ref readBuffer);
}
}
[Theory]
[InlineData(" hello", "hello")]
[InlineData(" hello", "hello")]
[InlineData("\r\n hello", "hello")]
[InlineData("\rhe llo", "he llo")]
[InlineData("\thell o ", "hell o ")]
public async Task TrimStartTrimsWhitespaceAtStart(string input, string expected)
{
using (var readerWriter = new PipeFactory())
{
var connection = readerWriter.Create();
var writeBuffer = connection.Writer.Alloc();
var bytes = Encoding.ASCII.GetBytes(input);
writeBuffer.Write(bytes);
await writeBuffer.FlushAsync();
var result = await connection.Reader.ReadAsync();
var buffer = result.Buffer;
var trimmed = buffer.TrimStart();
var outputBytes = trimmed.ToArray();
Assert.Equal(expected, Encoding.ASCII.GetString(outputBytes));
}
}
[Theory]
[InlineData("hello ", "hello")]
[InlineData("hello ", "hello")]
[InlineData("hello \r\n", "hello")]
[InlineData("he llo\r", "he llo")]
[InlineData(" hell o\t", " hell o")]
public async Task TrimEndTrimsWhitespaceAtEnd(string input, string expected)
{
using (var factory = new PipeFactory())
{
var readerWriter = factory.Create();
var writeBuffer = readerWriter.Writer.Alloc();
var bytes = Encoding.ASCII.GetBytes(input);
writeBuffer.Write(bytes);
await writeBuffer.FlushAsync();
var result = await readerWriter.Reader.ReadAsync();
var buffer = result.Buffer;
var trimmed = buffer.TrimEnd();
var outputBytes = trimmed.ToArray();
Assert.Equal(expected, Encoding.ASCII.GetString(outputBytes));
}
}
[Theory]
[InlineData("foo\rbar\r\n", "\r\n", "foo\rbar")]
[InlineData("foo\rbar\r\n", "\rbar", "foo")]
[InlineData("/pathpath/", "path/", "/path")]
[InlineData("hellzhello", "hell", null)]
public async Task TrySliceToSpan(string input, string sliceTo, string expected)
{
var sliceToBytes = Encoding.UTF8.GetBytes(sliceTo);
using (var factory = new PipeFactory())
{
var readerWriter = factory.Create();
var writeBuffer = readerWriter.Writer.Alloc();
var bytes = Encoding.UTF8.GetBytes(input);
writeBuffer.Write(bytes);
await writeBuffer.FlushAsync();
var result = await readerWriter.Reader.ReadAsync();
var buffer = result.Buffer;
ReadableBuffer slice;
ReadCursor cursor;
Assert.True(buffer.TrySliceTo(sliceToBytes, out slice, out cursor));
Assert.Equal(expected, slice.GetUtf8String());
}
}
private unsafe void TestIndexOfWorksForAllLocations(ref ReadableBuffer readBuffer, byte emptyValue)
{
byte huntValue = (byte)~emptyValue;
var handles = new List<BufferHandle>();
// we're going to fully index the final locations of the buffer, so that we
// can mutate etc in constant time
var addresses = BuildPointerIndex(ref readBuffer, handles);
// check it isn't there to start with
ReadableBuffer slice;
ReadCursor cursor;
var found = readBuffer.TrySliceTo(huntValue, out slice, out cursor);
Assert.False(found);
// correctness test all values
for (int i = 0; i < readBuffer.Length; i++)
{
*addresses[i] = huntValue;
found = readBuffer.TrySliceTo(huntValue, out slice, out cursor);
*addresses[i] = emptyValue;
Assert.True(found);
var remaining = readBuffer.Slice(cursor);
var handle = remaining.First.Retain(pin: true);
Assert.True(handle.PinnedPointer != null);
Assert.True((byte*)handle.PinnedPointer == addresses[i]);
handle.Dispose();
}
// free up memory handles
foreach (var handle in handles)
{
handle.Dispose();
}
handles.Clear();
}
private static unsafe byte*[] BuildPointerIndex(ref ReadableBuffer readBuffer, List<BufferHandle> handles)
{
byte*[] addresses = new byte*[readBuffer.Length];
int index = 0;
foreach (var memory in readBuffer)
{
var handle = memory.Retain(pin: true);
handles.Add(handle);
var ptr = (byte*)handle.PinnedPointer;
for (int i = 0; i < memory.Length; i++)
{
addresses[index++] = ptr++;
}
}
return addresses;
}
private unsafe void ReadUInt64GivesExpectedValues(ref ReadableBuffer readBuffer)
{
Assert.True(readBuffer.IsSingleSpan);
for (ulong i = 0; i < 1024; i++)
{
TestValue(ref readBuffer, i);
}
TestValue(ref readBuffer, ulong.MinValue);
TestValue(ref readBuffer, ulong.MaxValue);
var rand = new Random(41234);
// low numbers
for (int i = 0; i < 10000; i++)
{
TestValue(ref readBuffer, (ulong)rand.Next());
}
// wider range of numbers
for (int i = 0; i < 10000; i++)
{
ulong x = (ulong)rand.Next(), y = (ulong)rand.Next();
TestValue(ref readBuffer, (x << 32) | y);
TestValue(ref readBuffer, (y << 32) | x);
}
}
private unsafe void TestValue(ref ReadableBuffer readBuffer, ulong value)
{
fixed (byte* ptr = &readBuffer.First.Span.DangerousGetPinnableReference())
{
Assert.True(ptr != null);
string s = value.ToString(CultureInfo.InvariantCulture);
int written;
fixed (char* c = s)
{
written = Encoding.ASCII.GetBytes(c, s.Length, ptr, readBuffer.Length);
}
var slice = readBuffer.Slice(0, written);
Assert.Equal(value, slice.GetUInt64());
}
}
[Theory]
[InlineData("abc,def,ghi", ',')]
[InlineData("a;b;c;d", ';')]
[InlineData("a;b;c;d", ',')]
[InlineData("", ',')]
public async Task Split(string input, char delimiter)
{
// note: different expectation to string.Split; empty has 0 outputs
var expected = input == "" ? new string[0] : input.Split(delimiter);
using (var factory = new PipeFactory())
{
var readerWriter = factory.Create();
var output = readerWriter.Writer.Alloc();
output.Append(input, SymbolTable.InvariantUtf8);
var readable = output.AsReadableBuffer();
// via struct API
var iter = readable.Split((byte)delimiter);
Assert.Equal(expected.Length, iter.Count());
int i = 0;
foreach (var item in iter)
{
Assert.Equal(expected[i++], item.GetUtf8String());
}
Assert.Equal(expected.Length, i);
// via objects/LINQ etc
IEnumerable<ReadableBuffer> asObject = iter;
Assert.Equal(expected.Length, asObject.Count());
i = 0;
foreach (var item in asObject)
{
Assert.Equal(expected[i++], item.GetUtf8String());
}
Assert.Equal(expected.Length, i);
await output.FlushAsync();
}
}
[Fact]
public void ReadTWorksAgainstSimpleBuffers()
{
var readable = BufferUtilities.CreateBuffer(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 });
var span = readable.First.Span;
Assert.True(readable.IsSingleSpan);
Assert.Equal(span.Read<byte>(), readable.ReadLittleEndian<byte>());
Assert.Equal(span.Read<sbyte>(), readable.ReadLittleEndian<sbyte>());
Assert.Equal(span.Read<short>(), readable.ReadLittleEndian<short>());
Assert.Equal(span.Read<ushort>(), readable.ReadLittleEndian<ushort>());
Assert.Equal(span.Read<int>(), readable.ReadLittleEndian<int>());
Assert.Equal(span.Read<uint>(), readable.ReadLittleEndian<uint>());
Assert.Equal(span.Read<long>(), readable.ReadLittleEndian<long>());
Assert.Equal(span.Read<ulong>(), readable.ReadLittleEndian<ulong>());
Assert.Equal(span.Read<float>(), readable.ReadLittleEndian<float>());
Assert.Equal(span.Read<double>(), readable.ReadLittleEndian<double>());
}
[Fact]
public void ReadTWorksAgainstMultipleBuffers()
{
var readable = BufferUtilities.CreateBuffer(new byte[] { 0, 1, 2 }, new byte[] { 3, 4, 5 }, new byte[] { 6, 7, 9 });
Assert.Equal(9, readable.Length);
int spanCount = 0;
foreach (var _ in readable)
{
spanCount++;
}
Assert.Equal(3, spanCount);
Assert.False(readable.IsSingleSpan);
Span<byte> span = readable.ToArray();
Assert.Equal(span.Read<byte>(), readable.ReadLittleEndian<byte>());
Assert.Equal(span.Read<sbyte>(), readable.ReadLittleEndian<sbyte>());
Assert.Equal(span.Read<short>(), readable.ReadLittleEndian<short>());
Assert.Equal(span.Read<ushort>(), readable.ReadLittleEndian<ushort>());
Assert.Equal(span.Read<int>(), readable.ReadLittleEndian<int>());
Assert.Equal(span.Read<uint>(), readable.ReadLittleEndian<uint>());
Assert.Equal(span.Read<long>(), readable.ReadLittleEndian<long>());
Assert.Equal(span.Read<ulong>(), readable.ReadLittleEndian<ulong>());
Assert.Equal(span.Read<float>(), readable.ReadLittleEndian<float>());
Assert.Equal(span.Read<double>(), readable.ReadLittleEndian<double>());
}
[Fact]
public async Task CopyToAsync()
{
using (var factory = new PipeFactory())
{
var readerWriter = factory.Create();
var output = readerWriter.Writer.Alloc();
output.Append("Hello World", SymbolTable.InvariantUtf8);
await output.FlushAsync();
var ms = new MemoryStream();
var result = await readerWriter.Reader.ReadAsync();
var rb = result.Buffer;
await rb.CopyToAsync(ms);
ms.Position = 0;
Assert.Equal(11, rb.Length);
Assert.Equal(11, ms.Length);
Assert.Equal(rb.ToArray(), ms.ToArray());
Assert.Equal("Hello World", Encoding.ASCII.GetString(ms.ToArray()));
}
}
[Fact]
public async Task CopyToAsyncNativeMemory()
{
using (var factory = new PipeFactory(NativeBufferPool.Shared))
{
var readerWriter = factory.Create();
var output = readerWriter.Writer.Alloc();
output.Append("Hello World", SymbolTable.InvariantUtf8);
await output.FlushAsync();
var ms = new MemoryStream();
var result = await readerWriter.Reader.ReadAsync();
var rb = result.Buffer;
await rb.CopyToAsync(ms);
ms.Position = 0;
Assert.Equal(11, rb.Length);
Assert.Equal(11, ms.Length);
Assert.Equal(rb.ToArray(), ms.ToArray());
Assert.Equal("Hello World", Encoding.ASCII.GetString(ms.ToArray()));
}
}
[Fact]
public void CanUseArrayBasedReadableBuffers()
{
var data = Encoding.ASCII.GetBytes("***abc|def|ghijk****"); // note sthe padding here - verifying that it is omitted correctly
var buffer = ReadableBuffer.Create(data, 3, data.Length - 7);
Assert.Equal(13, buffer.Length);
var split = buffer.Split((byte)'|');
Assert.Equal(3, split.Count());
using (var iter = split.GetEnumerator())
{
Assert.True(iter.MoveNext());
var current = iter.Current;
Assert.Equal("abc", current.GetAsciiString());
using (var preserved = iter.Current.Preserve())
{
Assert.Equal("abc", preserved.Buffer.GetAsciiString());
}
Assert.True(iter.MoveNext());
current = iter.Current;
Assert.Equal("def", current.GetAsciiString());
using (var preserved = iter.Current.Preserve())
{
Assert.Equal("def", preserved.Buffer.GetAsciiString());
}
Assert.True(iter.MoveNext());
current = iter.Current;
Assert.Equal("ghijk", current.GetAsciiString());
using (var preserved = iter.Current.Preserve())
{
Assert.Equal("ghijk", preserved.Buffer.GetAsciiString());
}
Assert.False(iter.MoveNext());
}
}
[Fact]
public void CanUseOwnedBufferBasedReadableBuffers()
{
var data = Encoding.ASCII.GetBytes("***abc|def|ghijk****"); // note sthe padding here - verifying that it is omitted correctly
OwnedBuffer<byte> owned = data;
var buffer = ReadableBuffer.Create(owned, 3, data.Length - 7);
Assert.Equal(13, buffer.Length);
var split = buffer.Split((byte)'|');
Assert.Equal(3, split.Count());
using (var iter = split.GetEnumerator())
{
Assert.True(iter.MoveNext());
var current = iter.Current;
Assert.Equal("abc", current.GetAsciiString());
using (var preserved = iter.Current.Preserve())
{
Assert.Equal("abc", preserved.Buffer.GetAsciiString());
}
Assert.True(iter.MoveNext());
current = iter.Current;
Assert.Equal("def", current.GetAsciiString());
using (var preserved = iter.Current.Preserve())
{
Assert.Equal("def", preserved.Buffer.GetAsciiString());
}
Assert.True(iter.MoveNext());
current = iter.Current;
Assert.Equal("ghijk", current.GetAsciiString());
using (var preserved = iter.Current.Preserve())
{
Assert.Equal("ghijk", preserved.Buffer.GetAsciiString());
}
Assert.False(iter.MoveNext());
}
}
[Fact]
public void ReadableBufferSequenceWorks()
{
using (var factory = new PipeFactory())
{
var readerWriter = factory.Create();
var output = readerWriter.Writer.Alloc();
{
// empty buffer
var readable = output.AsReadableBuffer() as ISequence<ReadOnlyBuffer<byte>>;
var position = Position.First;
ReadOnlyBuffer<byte> memory;
int spanCount = 0;
while (readable.TryGet(ref position, out memory))
{
spanCount++;
Assert.Equal(0, memory.Length);
}
Assert.Equal(1, spanCount);
}
{
var readable = BufferUtilities.CreateBuffer(new byte[] { 1 }, new byte[] { 2, 2 }, new byte[] { 3, 3, 3 }) as ISequence<ReadOnlyBuffer<byte>>;
var position = Position.First;
ReadOnlyBuffer<byte> memory;
int spanCount = 0;
while (readable.TryGet(ref position, out memory))
{
spanCount++;
Assert.Equal(spanCount, memory.Length);
}
Assert.Equal(3, spanCount);
}
}
}
[Theory]
[MemberData(nameof(OutOfRangeSliceCases))]
public void ReadableBufferDoesNotAllowSlicingOutOfRange(Action<ReadableBuffer> fail)
{
foreach (var p in Size100ReadableBuffers)
{
var buffer = (ReadableBuffer) p[0];
var ex = Assert.Throws<InvalidOperationException>(() => fail(buffer));
}
}
[Theory]
[MemberData(nameof(Size100ReadableBuffers))]
public void ReadableBufferMove_MovesReadCursor(ReadableBuffer buffer)
{
var cursor = buffer.Move(buffer.Start, 65);
Assert.Equal(buffer.Slice(65).Start, cursor);
}
[Theory]
[MemberData(nameof(Size100ReadableBuffers))]
public void ReadableBufferMove_ChecksBounds(ReadableBuffer buffer)
{
Assert.Throws<InvalidOperationException>(() => buffer.Move(buffer.Start, 101));
}
[Fact]
public void ReadableBufferMove_DoesNotAlowNegative()
{
var data = new byte[20];
var buffer = ReadableBuffer.Create(data);
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Move(buffer.Start, -1));
}
[Fact]
public void ReadCursorSeekChecksEndIfNotTrustingEnd()
{
var buffer = BufferUtilities.CreateBuffer(1, 1, 1);
var buffer2 = BufferUtilities.CreateBuffer(1, 1, 1);
Assert.Throws<InvalidOperationException>(() => buffer.Start.Seek(2, buffer2.End, true));
}
[Fact]
public void ReadCursorSeekDoesNotCheckEndIfTrustingEnd()
{
var buffer = BufferUtilities.CreateBuffer(1, 1, 1);
var buffer2 = BufferUtilities.CreateBuffer(1, 1, 1);
buffer.Start.Seek(2, buffer2.End, false);
}
public static TheoryData<ReadableBuffer> Size100ReadableBuffers
{
get
{
return new TheoryData<ReadableBuffer>()
{
BufferUtilities.CreateBuffer(100),
BufferUtilities.CreateBuffer(50, 50),
BufferUtilities.CreateBuffer(33, 33, 34)
};
}
}
public static TheoryData<Action<ReadableBuffer>> OutOfRangeSliceCases
{
get
{
return new TheoryData<Action<ReadableBuffer>>()
{
b => b.Slice(101),
b => b.Slice(0, 101),
b => b.Slice(b.Start, 101),
b => b.Slice(0, 70).Slice(b.End, b.End),
b => b.Slice(0, 70).Slice(b.Start, b.End),
b => b.Slice(0, 70).Slice(0, b.End),
b => b.Slice(70, b.Start)
};
}
}
}
}
| |
namespace Ioke.Lang {
using System.Collections;
using System.Collections.Generic;
using Ioke.Lang.Util;
public class DefinitionsBehavior {
public static void Init(IokeObject obj) {
Runtime runtime = obj.runtime;
obj.Kind = "DefaultBehavior Definitions";
obj.RegisterMethod(runtime.NewNativeMethod("expects any number of unevaluated arguments. if no arguments at all are given, will just return nil. creates a new method based on the arguments. this method will be evaluated using the context of the object it's called on, and thus the definition can not refer to the outside scope where the method is defined. (there are other ways of achieving this). all arguments except the last one is expected to be names of arguments that will be used in the method. there will possible be additions to the format of arguments later on - including named parameters and optional arguments. the actual code is the last argument given.",
new NativeMethod("method", DefaultArgumentsDefinition.builder()
.WithOptionalPositionalUnevaluated("documentation")
.WithRestUnevaluated("argumentsAndBody")
.Arguments,
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
var args = message.Arguments;
if(args.Count == 0) {
Message mx = new Message(context.runtime, "nil", null, false);
mx.File = Message.GetFile(message);
mx.Line = Message.GetLine(message);
mx.Position = Message.GetPosition(message);
IokeObject mmx = context.runtime.CreateMessage(mx);
return runtime.NewMethod(null, runtime.DefaultMethod, new DefaultMethod(context, DefaultArgumentsDefinition.Empty(), mmx));
}
string doc = null;
int start = 0;
if(args.Count > 1 && ((IokeObject)Message.GetArguments(message)[0]).Name.Equals("internal:createText")) {
start++;
string s = (string)((IokeObject)args[0]).Arguments[0];
doc = s;
}
DefaultArgumentsDefinition def = DefaultArgumentsDefinition.CreateFrom(args, start, args.Count-1, message, on, context);
return runtime.NewMethod(doc, runtime.DefaultMethod, new DefaultMethod(context, def, (IokeObject)args[args.Count-1]));
})));
obj.RegisterMethod(runtime.NewNativeMethod("expects one code argument, optionally preceeded by a documentation string. will create a new DefaultMacro based on the code and return it.",
new NativeMethod("macro", DefaultArgumentsDefinition.builder()
.WithOptionalPositionalUnevaluated("documentation")
.WithOptionalPositionalUnevaluated("body")
.Arguments,
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
var args = message.Arguments;
if(args.Count == 0) {
Message mx = new Message(context.runtime, "nil", null, false);
mx.File = Message.GetFile(message);
mx.Line = Message.GetLine(message);
mx.Position = Message.GetPosition(message);
IokeObject mmx = context.runtime.CreateMessage(mx);
return runtime.NewMacro(null, runtime.DefaultMacro, new DefaultMacro(context, mmx));
}
string doc = null;
int start = 0;
if(args.Count > 1 && ((IokeObject)Message.GetArguments(message)[0]).Name.Equals("internal:createText")) {
start++;
string s = (string)(((IokeObject)args[0]).Arguments[0]);
doc = s;
}
return runtime.NewMacro(doc, runtime.DefaultMacro, new DefaultMacro(context, (IokeObject)args[start]));
})));
obj.RegisterMethod(runtime.NewNativeMethod("creates a new lexical block that can be executed at will, while retaining a reference to the lexical closure it was created in. it will always update variables if they exist. there is currently no way of introducing shadowing variables in the local context. new variables can be created though, just like in a method. a lexical block mimics LexicalBlock, and can take arguments. at the moment these are restricted to required arguments, but support for the same argument types as DefaultMethod will come.",
new NativeMethod("fn", DefaultArgumentsDefinition.builder()
.WithOptionalPositionalUnevaluated("documentation")
.WithRestUnevaluated("argumentsAndBody")
.Arguments,
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
var args = message.Arguments;
if(args.Count == 0) {
return runtime.NewLexicalBlock(null, runtime.LexicalBlock, new LexicalBlock(context, DefaultArgumentsDefinition.Empty(), method.runtime.nilMessage));
}
string doc = null;
int start = 0;
if(args.Count > 1 && ((IokeObject)Message.GetArguments(message)[0]).Name.Equals("internal:createText")) {
start++;
string s = ((string)((IokeObject)args[0]).Arguments[0]);
doc = s;
}
IokeObject code = IokeObject.As(args[args.Count-1], context);
DefaultArgumentsDefinition def = DefaultArgumentsDefinition.CreateFrom(args, start, args.Count-1, message, on, context);
return runtime.NewLexicalBlock(doc, runtime.LexicalBlock, new LexicalBlock(context, def, code));
})));
obj.RegisterMethod(runtime.NewNativeMethod("creates a new lexical block that can be executed at will, while retaining a reference to the lexical closure it was created in. it will always update variables if they exist. there is currently no way of introducing shadowing variables in the local context. new variables can be created though, just like in a method. a lexical block mimics LexicalBlock, and can take arguments. at the moment these are restricted to required arguments, but support for the same argument types as DefaultMethod will come. same as fn()",
new NativeMethod("\u028E", DefaultArgumentsDefinition.builder()
.WithOptionalPositionalUnevaluated("documentation")
.WithRestUnevaluated("argumentsAndBody")
.Arguments,
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
var args = message.Arguments;
if(args.Count == 0) {
return runtime.NewLexicalBlock(null, runtime.LexicalBlock, new LexicalBlock(context, DefaultArgumentsDefinition.Empty(), method.runtime.nilMessage));
}
string doc = null;
int start = 0;
if(args.Count > 1 && ((IokeObject)Message.GetArguments(message)[0]).Name.Equals("internal:createText")) {
start++;
string s = ((string)((IokeObject)args[0]).Arguments[0]);
doc = s;
}
IokeObject code = IokeObject.As(args[args.Count-1], context);
DefaultArgumentsDefinition def = DefaultArgumentsDefinition.CreateFrom(args, start, args.Count-1, message, on, context);
return runtime.NewLexicalBlock(doc, runtime.LexicalBlock, new LexicalBlock(context, def, code));
})));
obj.RegisterMethod(runtime.NewNativeMethod("expects one code argument, optionally preceeded by a documentation string. will create a new LexicalMacro based on the code and return it.",
new NativeMethod("lecro", DefaultArgumentsDefinition.builder()
.WithOptionalPositionalUnevaluated("documentation")
.WithOptionalPositionalUnevaluated("body")
.Arguments,
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
var args = message.Arguments;
if(args.Count == 0) {
Message mx = new Message(context.runtime, "nil", null, false);
mx.File = Message.GetFile(message);
mx.Line = Message.GetLine(message);
mx.Position = Message.GetPosition(message);
IokeObject mmx = context.runtime.CreateMessage(mx);
return runtime.NewMacro(null, runtime.LexicalMacro, new LexicalMacro(context, mmx));
}
string doc = null;
int start = 0;
if(args.Count > 1 && ((IokeObject)Message.GetArguments(message)[0]).Name.Equals("internal:createText")) {
start++;
string s = ((string)((IokeObject)args[0]).Arguments[0]);
doc = s;
}
return runtime.NewMacro(doc, runtime.LexicalMacro, new LexicalMacro(context, (IokeObject)args[start]));
})));
obj.RegisterMethod(runtime.NewNativeMethod("expects one code argument, optionally preceeded by a documentation string. will create a new DefaultSyntax based on the code and return it.",
new NativeMethod("syntax", DefaultArgumentsDefinition.builder()
.WithOptionalPositionalUnevaluated("documentation")
.WithOptionalPositionalUnevaluated("body")
.Arguments,
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
var args = message.Arguments;
if(args.Count == 0) {
Message mx = new Message(context.runtime, "nil", null, false);
mx.File = Message.GetFile(message);
mx.Line = Message.GetLine(message);
mx.Position = Message.GetPosition(message);
IokeObject mmx = context.runtime.CreateMessage(mx);
return runtime.NewMacro(null, runtime.DefaultSyntax, new DefaultSyntax(context, mmx));
}
string doc = null;
int start = 0;
if(args.Count > 1 && ((IokeObject)Message.GetArguments(message)[0]).Name.Equals("internal:createText")) {
start++;
string s = (string)((IokeObject)args[0]).Arguments[0];
doc = s;
}
return runtime.NewMacro(doc, runtime.DefaultSyntax, new DefaultSyntax(context, (IokeObject)args[start]));
})));
obj.RegisterMethod(runtime.NewNativeMethod("Takes two evaluated text or symbol arguments that name the method to alias, and the new name to give it. returns the receiver.",
new NativeMethod("aliasMethod", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("oldName")
.WithRequiredPositional("newName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string fromName = Text.GetText(((Message)IokeObject.dataOf(runtime.asText)).SendTo(runtime.asText, context, args[0]));
string toName = Text.GetText(((Message)IokeObject.dataOf(runtime.asText)).SendTo(runtime.asText, context, args[1]));
IokeObject.As(on, context).AliasMethod(fromName, toName, message, context);
return on;
})));
}
}
}
| |
// 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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace VstsBuildsApi
{
public class VstsBuildClient
{
private string _collectionIdentifier;
private string _credentials;
private static readonly string[] s_InstanceIdentifiableField = new string[] { "_links",
"authoredBy",
"comment",
"createdDate",
"id",
"path",
"revision",
"uri",
"url"
};
/// <summary>
/// Constructor
/// </summary>
/// <param name="collectionIdentifier">collection identifer for build definitions</param>
/// <param name="credentials">credentials used for basic rest api authentication</param>
public VstsBuildClient(string collectionIdentifier, string credentials)
{
if(string.IsNullOrWhiteSpace(collectionIdentifier))
{
throw new Exception("Required parameter (collectionIdentifier) cannot be null or white space.");
}
if(!Uri.IsWellFormedUriString(collectionIdentifier, UriKind.Relative))
{
throw new Exception(string.Format("collectionIdentifier '{0}' contains invalid characters. collectionIdentifier must contain only valid uri characters.", collectionIdentifier));
}
_collectionIdentifier = collectionIdentifier;
_credentials = credentials;
}
/// <summary>
/// Load a local build definition, combine the uniqueIdentifier with the definition name,
/// check VSTS for a matching definition name, if present, update that definition with the
/// local build definition, otherwise create a new definition.
/// </summary>
/// <param name="stream">Stream to a VSTS build definition</param>
/// <returns>Created or updated build Id</returns>
public async Task<string> CreateOrUpdateDefinitionAsync(Stream stream)
{
JObject definition = GetDefinition(stream);
return await CreateOrUpdateDefinitionAsync(definition).ConfigureAwait(false);
}
/// <summary>
/// Load a local build definition, combine the uniqueIdentifier with the definition name,
/// check VSTS for a matching definition name, if present, update that definition with the
/// local build definition, otherwise create a new definition.
/// </summary>
/// <param name="definition">VSTS build definition JSON object</param>
/// <returns>Created or updated build definition id</returns>
private async Task<string> CreateOrUpdateDefinitionAsync(JObject definition)
{
var key = _collectionIdentifier + "_" + definition["name"].ToString();
definition["name"] = key;
IReadOnlyList<JObject> vstsDefinitions = await VstsRetrieveDefinitionsListByNameAndPathAsync(definition).ConfigureAwait(false);
if (vstsDefinitions.Count == 0)
{
/* Create */
JObject vstsDefinition = await VstsCreateDefinitionAsync(definition).ConfigureAwait(false);
return vstsDefinition["id"].ToString();
}
else if(vstsDefinitions.Count == 1)
{
JObject vstsDefinition = await VstsRetrieveDefinitionByIdAsync(vstsDefinitions[0]).ConfigureAwait(false);
/* Update */
if (!IsDefinitionContentSubsetEquivalent(definition, vstsDefinition))
{
foreach(var fieldName in s_InstanceIdentifiableField)
{
definition[fieldName] = vstsDefinition[fieldName];
}
vstsDefinition = await VstsUpdateDefinitionAsync(definition).ConfigureAwait(false);
}
return vstsDefinition["id"].ToString();
}
else
{
throw new Exception(string.Format("Obtained multiple {0} definitions with the same 'name' ({1}) and 'path' ({2}) properties. This should not be possible.", vstsDefinitions.Count, vstsDefinitions[0]["name"].ToString(), vstsDefinitions[0]["path"].ToString()));
}
}
private JObject GetDefinition(Stream stream)
{
using (StreamReader streamReader = new StreamReader(stream))
using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
{
return (JObject)JToken.ReadFrom(jsonReader);
}
}
/// <summary>
/// Update VSTS Build Definition
/// </summary>
/// <returns>updated definitions id</returns>
private async Task<JObject> VstsUpdateDefinitionAsync(JObject definition)
{
string requestUri = $"DefaultCollection/{VstsBuildsApiBase(definition)}/_apis/build/definitions/{definition["id"].ToString()}?api-version=2.0";
HttpContent content = new StringContent(JsonConvert.SerializeObject(definition), System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await GetClient(GetVstsBuildsApiUrl(definition)).PutAsync(requestUri, content);
ProcessResponseStatusCode(response);
return JObject.Parse(await response.Content.ReadAsStringAsync());
}
/// <summary>
/// Create VSTS Build Definition
/// </summary>
private async Task<JObject> VstsCreateDefinitionAsync(JObject definition)
{
/* Remove definition instance identifiable information */
RemoveIdentifiableInformation(definition);
string requestUri = $"DefaultCollection/{VstsBuildsApiBase(definition)}/_apis/build/definitions?api-version=2.0";
HttpContent content = new StringContent(JsonConvert.SerializeObject(definition), Encoding.UTF8, "application/json");
HttpResponseMessage response = await GetClient(GetVstsBuildsApiUrl(definition)).PostAsync(requestUri, content);
ProcessResponseStatusCode(response);
return JObject.Parse(await response.Content.ReadAsStringAsync());
}
/// <summary>
/// Retrieve a VSTS Build Definition by name and VSTS folder path
/// </summary>
private async Task<JObject> VstsRetrieveDefinitionByIdAsync(JObject definition)
{
string requestUri = $"DefaultCollection/{VstsBuildsApiBase(definition)}/_apis/build/definitions/{definition["id"].ToString()}?api-version=2.0";
HttpResponseMessage response = await GetClient(GetVstsBuildsApiUrl(definition)).GetAsync(requestUri);
ProcessResponseStatusCode(response);
return JObject.Parse(await response.Content.ReadAsStringAsync());
}
/// <summary>
/// Retrieve a VSTS Build Definition by name and VSTS folder path
/// </summary>
private async Task<IReadOnlyList<JObject>> VstsRetrieveDefinitionsListByNameAndPathAsync(JObject definition)
{
string requestUri = $"DefaultCollection/{VstsBuildsApiBase(definition)}/_apis/build/definitions?api-version=2.0&name={definition["name"].ToString()}";
HttpResponseMessage response = await GetClient(GetVstsBuildsApiUrl(definition)).GetAsync(requestUri);
ProcessResponseStatusCode(response);
string json = await response.Content.ReadAsStringAsync();
JObject definitionsJObject = JObject.Parse(json);
List<JObject> definitions = new List<JObject>();
if (int.Parse(definitionsJObject["count"].Value<string>()) > 0)
{
var children = definitionsJObject["value"].Children();
foreach(var childDefinition in children)
{
JObject childObject = (JObject)childDefinition;
if (definition["quality"].ToString() == "definition" &&
definition["path"].ToString() == childObject["path"].ToString())
{
definitions.Add(childObject);
}
}
}
return definitions;
}
private string VstsBuildsApiBase(JObject definition)
{
return definition["project"]["name"].ToString();
}
private string GetVstsBuildsApiUrl(JObject definition)
{
return definition["project"]["url"].ToString();
}
private HttpClient GetClient(string url)
{
HttpClient client = new HttpClient();
Uri uri = new Uri(url);
client.BaseAddress = new Uri(string.Format("{0}://{1}/", uri.Scheme, uri.Authority));
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials);
return client;
}
// This method performs similar functionality as HttpResponseMessage.EnsureSuccessStatusCode(), but is more strict about
// what "success" is because we can not properly handle "non-authoratative" responses which are reported as "success".
private void ProcessResponseStatusCode(HttpResponseMessage response)
{
if(response.StatusCode == System.Net.HttpStatusCode.OK)
{
return;
}
throw new HttpRequestException(string.Format("Response code {0} received from {1} is not a valid response.", response.StatusCode, response.RequestMessage.RequestUri));
}
/// <summary>
/// Validates that definition1 is a content equivalent subset of definition2
/// </summary>
private static bool IsDefinitionContentSubsetEquivalent(JObject definition1, JObject definition2)
{
JObject clonedDefinition1 = (JObject)definition1.DeepClone();
JObject clonedDefinition2 = (JObject)definition2.DeepClone();
RemoveIdentifiableInformation(clonedDefinition1, clonedDefinition2);
// Compare only the child tokens present in the first definition to the corresponding contents of the second definition
// The second definition may contain additional tokens which we don't care about.
foreach(var childToken in clonedDefinition1.Children())
{
if(!JToken.DeepEquals(childToken.First, clonedDefinition2[childToken.Path]))
{
return false;
}
}
return true;
}
private static void RemoveIdentifiableInformation(params JObject[] jObjects)
{
foreach(var fieldName in s_InstanceIdentifiableField)
{
RemoveJObjectToken(fieldName, jObjects);
}
}
private static void RemoveJObjectToken(string tokenName, params JObject[] jObjects)
{
foreach(var jObject in jObjects)
{
jObject.Remove(tokenName);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace FSharpWebSite.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Logging;
using Microsoft.Isam.Esent.Interop;
using Rhino.Queues.Model;
using Rhino.Queues.Protocol;
namespace Rhino.Queues.Storage
{
using Utils;
public class GlobalActions : AbstractActions
{
private readonly QueueManagerConfiguration configuration;
private readonly ILog logger = LogManager.GetLogger(typeof(GlobalActions));
public GlobalActions(JET_INSTANCE instance, ColumnsInformation columnsInformation, string database, Guid instanceId, QueueManagerConfiguration configuration)
: base(instance, columnsInformation, database, instanceId)
{
this.configuration = configuration;
}
public void CreateQueueIfDoesNotExists(string queueName)
{
Api.MakeKey(session, queues, queueName, Encoding.Unicode, MakeKeyGrbit.NewKey);
if (Api.TrySeek(session, queues, SeekGrbit.SeekEQ))
return;
new QueueSchemaCreator(session, dbid, queueName).Create();
using (var updateQueue = new Update(session, queues, JET_prep.Insert))
{
Api.SetColumn(session, queues, ColumnsInformation.QueuesColumns["name"], queueName, Encoding.Unicode);
Api.SetColumn(session, queues, ColumnsInformation.QueuesColumns["created_at"], DateTime.Now.ToOADate());
updateQueue.Save();
}
}
public void RegisterRecoveryInformation(Guid transactionId, byte[] information)
{
using (var update = new Update(session, recovery, JET_prep.Insert))
{
Api.SetColumn(session, recovery, ColumnsInformation.RecoveryColumns["tx_id"], transactionId.ToByteArray());
Api.SetColumn(session, recovery, ColumnsInformation.RecoveryColumns["recovery_info"], information);
update.Save();
}
}
public void DeleteRecoveryInformation(Guid transactionId)
{
Api.MakeKey(session, recovery, transactionId.ToByteArray(), MakeKeyGrbit.NewKey);
if (Api.TrySeek(session, recovery, SeekGrbit.SeekEQ) == false)
return;
Api.JetDelete(session, recovery);
}
public IEnumerable<byte[]> GetRecoveryInformation()
{
Api.MoveBeforeFirst(session, recovery);
while (Api.TryMoveNext(session, recovery))
{
yield return Api.RetrieveColumn(session, recovery, ColumnsInformation.RecoveryColumns["recovery_info"]);
}
}
public void RegisterUpdateToReverse(Guid txId, MessageBookmark bookmark, MessageStatus statusToRestore, string subQueue)
{
Api.JetSetCurrentIndex(session, txs, "by_bookmark");
var actualBookmark = bookmark.Bookmark.Take(bookmark.Size).ToArray();
Api.MakeKey(session, txs, bookmark.Size, MakeKeyGrbit.NewKey);
Api.MakeKey(session, txs, actualBookmark, MakeKeyGrbit.None);
if(Api.TrySeek(session, txs, SeekGrbit.SeekEQ))
{
Api.JetDelete(session, txs);
}
using (var update = new Update(session, txs, JET_prep.Insert))
{
Api.SetColumn(session, txs, ColumnsInformation.TxsColumns["tx_id"], txId.ToByteArray());
Api.SetColumn(session, txs, ColumnsInformation.TxsColumns["bookmark_size"], bookmark.Size);
Api.SetColumn(session, txs, ColumnsInformation.TxsColumns["bookmark_data"], actualBookmark);
Api.SetColumn(session, txs, ColumnsInformation.TxsColumns["value_to_restore"], (int)statusToRestore);
Api.SetColumn(session, txs, ColumnsInformation.TxsColumns["queue"], bookmark.QueueName, Encoding.Unicode);
Api.SetColumn(session, txs, ColumnsInformation.TxsColumns["subqueue"], subQueue, Encoding.Unicode);
update.Save();
}
}
public void RemoveReversalsMoveCompletedMessagesAndFinishSubQueueMove(Guid transactionId)
{
Api.JetSetCurrentIndex(session, txs, "by_tx_id");
Api.MakeKey(session, txs, transactionId.ToByteArray(), MakeKeyGrbit.NewKey);
if (Api.TrySeek(session, txs, SeekGrbit.SeekEQ) == false)
return;
Api.MakeKey(session, txs, transactionId.ToByteArray(), MakeKeyGrbit.NewKey);
try
{
Api.JetSetIndexRange(session, txs, SetIndexRangeGrbit.RangeInclusive | SetIndexRangeGrbit.RangeUpperLimit);
}
catch (EsentErrorException e)
{
if (e.Error != JET_err.NoCurrentRecord)
throw;
return;
}
do
{
var queue = Api.RetrieveColumnAsString(session, txs, ColumnsInformation.TxsColumns["queue"], Encoding.Unicode);
var bookmarkData = Api.RetrieveColumn(session, txs, ColumnsInformation.TxsColumns["bookmark_data"]);
var bookmarkSize = Api.RetrieveColumnAsInt32(session, txs, ColumnsInformation.TxsColumns["bookmark_size"]).Value;
var actions = GetQueue(queue);
var bookmark = new MessageBookmark
{
Bookmark = bookmarkData,
QueueName = queue,
Size = bookmarkSize
};
switch (actions.GetMessageStatus(bookmark))
{
case MessageStatus.SubqueueChanged:
case MessageStatus.EnqueueWait:
actions.SetMessageStatus(bookmark, MessageStatus.ReadyToDeliver);
break;
default:
if (configuration.EnableProcessedMessageHistory)
actions.MoveToHistory(bookmark);
else
actions.Delete(bookmark);
break;
}
Api.JetDelete(session, txs);
} while (Api.TryMoveNext(session, txs));
}
public Guid RegisterToSend(Endpoint destination, string queue, string subQueue, MessagePayload payload, Guid transactionId)
{
var bookmark = new MessageBookmark();
var msgId = GuidCombGenerator.Generate();
using (var update = new Update(session, outgoing, JET_prep.Insert))
{
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["msg_id"], msgId.ToByteArray());
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["tx_id"], transactionId.ToByteArray());
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["address"], destination.Host, Encoding.Unicode);
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["port"], destination.Port);
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["time_to_send"], DateTime.Now.ToOADate());
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["sent_at"], DateTime.Now.ToOADate());
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["send_status"], (int)OutgoingMessageStatus.NotReady);
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["queue"], queue, Encoding.Unicode);
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["subqueue"], subQueue, Encoding.Unicode);
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["headers"], payload.Headers.ToQueryString(),
Encoding.Unicode);
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["data"], payload.Data);
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["number_of_retries"], 1);
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["size_of_data"], payload.Data.Length);
if (payload.DeliverBy != null)
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["deliver_by"], payload.DeliverBy.Value.ToOADate());
if (payload.MaxAttempts != null)
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["max_attempts"], payload.MaxAttempts.Value);
update.Save(bookmark.Bookmark, bookmark.Size, out bookmark.Size);
}
Api.JetGotoBookmark(session, outgoing, bookmark.Bookmark, bookmark.Size);
logger.DebugFormat("Created output message '{0}' for 'rhino.queues://{1}:{2}/{3}/{4}' as NotReady",
msgId,
destination.Host,
destination.Port,
queue,
subQueue
);
return msgId;
}
public void MarkAsReadyToSend(Guid transactionId)
{
Api.JetSetCurrentIndex(session, outgoing, "by_tx_id");
Api.MakeKey(session, outgoing, transactionId.ToByteArray(), MakeKeyGrbit.NewKey);
if (Api.TrySeek(session, outgoing, SeekGrbit.SeekEQ) == false)
return;
Api.MakeKey(session, outgoing, transactionId.ToByteArray(), MakeKeyGrbit.NewKey);
try
{
Api.JetSetIndexRange(session, outgoing,
SetIndexRangeGrbit.RangeInclusive | SetIndexRangeGrbit.RangeUpperLimit);
}
catch (EsentErrorException e)
{
if (e.Error!=JET_err.NoCurrentRecord)
throw;
return;
}
do
{
using (var update = new Update(session, outgoing, JET_prep.Replace))
{
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["send_status"], (int)OutgoingMessageStatus.Ready);
update.Save();
}
logger.DebugFormat("Marking output message {0} as Ready",
new Guid(Api.RetrieveColumn(session, outgoing, ColumnsInformation.OutgoingColumns["msg_id"])));
} while (Api.TryMoveNext(session, outgoing));
}
public void DeleteMessageToSend(Guid transactionId)
{
Api.JetSetCurrentIndex(session, outgoing, "by_tx_id");
Api.MakeKey(session, outgoing, transactionId.ToByteArray(), MakeKeyGrbit.NewKey);
if (Api.TrySeek(session, outgoing, SeekGrbit.SeekEQ) == false)
return;
Api.MakeKey(session, outgoing, transactionId.ToByteArray(), MakeKeyGrbit.NewKey);
try
{
Api.JetSetIndexRange(session, outgoing,
SetIndexRangeGrbit.RangeInclusive | SetIndexRangeGrbit.RangeUpperLimit);
}
catch (EsentErrorException e)
{
if (e.Error!=JET_err.NoCurrentRecord)
throw;
return;
}
do
{
logger.DebugFormat("Deleting output message {0}",
new Guid(Api.RetrieveColumn(session, outgoing, ColumnsInformation.OutgoingColumns["msg_id"])));
Api.JetDelete(session, outgoing);
} while (Api.TryMoveNext(session, outgoing));
}
public void MarkAllOutgoingInFlightMessagesAsReadyToSend()
{
Api.MoveBeforeFirst(session, outgoing);
while (Api.TryMoveNext(session, outgoing))
{
var status = (OutgoingMessageStatus)Api.RetrieveColumnAsInt32(session, outgoing, ColumnsInformation.OutgoingColumns["send_status"]).Value;
if (status != OutgoingMessageStatus.InFlight)
continue;
using (var update = new Update(session, outgoing, JET_prep.Replace))
{
Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["send_status"], (int)OutgoingMessageStatus.Ready);
update.Save();
}
}
}
public void MarkAllProcessedMessagesWithTransactionsNotRegisterForRecoveryAsReadyToDeliver()
{
var txsWithRecovery = new HashSet<Guid>();
Api.MoveBeforeFirst(session, recovery);
while (Api.TryMoveNext(session, recovery))
{
var idAsBytes = Api.RetrieveColumn(session, recovery, ColumnsInformation.RecoveryColumns["tx_id"]);
txsWithRecovery.Add(new Guid(idAsBytes));
}
var txsWithoutRecovery = new HashSet<Guid>();
Api.MoveBeforeFirst(session, txs);
while (Api.TryMoveNext(session, txs))
{
var idAsBytes = Api.RetrieveColumn(session, txs, ColumnsInformation.RecoveryColumns["tx_id"]);
txsWithoutRecovery.Add(new Guid(idAsBytes));
}
foreach (var txId in txsWithoutRecovery)
{
if (txsWithRecovery.Contains(txId))
continue;
ReverseAllFrom(txId);
}
}
public void ReverseAllFrom(Guid transactionId)
{
Api.JetSetCurrentIndex(session, txs, "by_tx_id");
Api.MakeKey(session, txs, transactionId.ToByteArray(), MakeKeyGrbit.NewKey);
if (Api.TrySeek(session, txs, SeekGrbit.SeekEQ) == false)
return;
Api.MakeKey(session, txs, transactionId.ToByteArray(), MakeKeyGrbit.NewKey);
try
{
Api.JetSetIndexRange(session, txs, SetIndexRangeGrbit.RangeUpperLimit | SetIndexRangeGrbit.RangeInclusive);
}
catch (EsentErrorException e)
{
if (e.Error != JET_err.NoCurrentRecord)
throw;
return;
}
do
{
var bytes = Api.RetrieveColumn(session, txs, ColumnsInformation.TxsColumns["bookmark_data"]);
var size = Api.RetrieveColumnAsInt32(session, txs, ColumnsInformation.TxsColumns["bookmark_size"]).Value;
var oldStatus = (MessageStatus)Api.RetrieveColumnAsInt32(session, txs, ColumnsInformation.TxsColumns["value_to_restore"]).Value;
var queue = Api.RetrieveColumnAsString(session, txs, ColumnsInformation.TxsColumns["queue"]);
var subqueue = Api.RetrieveColumnAsString(session, txs, ColumnsInformation.TxsColumns["subqueue"]);
var bookmark = new MessageBookmark
{
QueueName = queue,
Bookmark = bytes,
Size = size
};
var actions = GetQueue(queue);
var newStatus = actions.GetMessageStatus(bookmark);
switch (newStatus)
{
case MessageStatus.SubqueueChanged:
actions.SetMessageStatus(bookmark, MessageStatus.ReadyToDeliver, subqueue);
break;
case MessageStatus.EnqueueWait:
actions.Delete(bookmark);
break;
default:
actions.SetMessageStatus(bookmark, oldStatus);
break;
}
} while (Api.TryMoveNext(session, txs));
}
public string[] GetAllQueuesNames()
{
var names = new List<string>();
Api.MoveBeforeFirst(session, queues);
while (Api.TryMoveNext(session, queues))
{
names.Add(Api.RetrieveColumnAsString(session, queues, ColumnsInformation.QueuesColumns["name"]));
}
return names.ToArray();
}
public MessageBookmark GetSentMessageBookmarkAtPosition(int positionFromNewestSentMessage)
{
Api.MoveAfterLast(session, outgoingHistory);
try
{
Api.JetMove(session, outgoingHistory, -positionFromNewestSentMessage, MoveGrbit.None);
}
catch (EsentErrorException e)
{
if (e.Error == JET_err.NoCurrentRecord)
return null;
throw;
}
var bookmark = new MessageBookmark();
Api.JetGetBookmark(session, outgoingHistory, bookmark.Bookmark, bookmark.Size, out bookmark.Size);
return bookmark;
}
public IEnumerable<PersistentMessageToSend> GetSentMessages(int? batchSize = null)
{
Api.MoveBeforeFirst(session, outgoingHistory);
int count = 0;
while (Api.TryMoveNext(session, outgoingHistory) && count++ != batchSize)
{
var address = Api.RetrieveColumnAsString(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns["address"]);
var port = Api.RetrieveColumnAsInt32(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns["port"]).Value;
var bookmark = new MessageBookmark();
Api.JetGetBookmark(session, outgoingHistory, bookmark.Bookmark, bookmark.Size, out bookmark.Size);
yield return new PersistentMessageToSend
{
Id = new MessageId
{
SourceInstanceId = instanceId,
MessageIdentifier = new Guid(Api.RetrieveColumn(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns["msg_id"]))
},
OutgoingStatus = (OutgoingMessageStatus)Api.RetrieveColumnAsInt32(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns["send_status"]).Value,
Endpoint = new Endpoint(address, port),
Queue = Api.RetrieveColumnAsString(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns["queue"], Encoding.Unicode),
SubQueue = Api.RetrieveColumnAsString(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns["subqueue"], Encoding.Unicode),
SentAt = DateTime.FromOADate(Api.RetrieveColumnAsDouble(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns["sent_at"]).Value),
Data = Api.RetrieveColumn(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns["data"]),
Bookmark = bookmark
};
}
}
public void DeleteMessageToSendHistoric(MessageBookmark bookmark)
{
Api.JetGotoBookmark(session, outgoingHistory, bookmark.Bookmark, bookmark.Size);
Api.JetDelete(session, outgoingHistory);
}
public int GetNumberOfMessages(string queueName)
{
Api.JetSetCurrentIndex(session, queues, "pk");
Api.MakeKey(session, queues, queueName, Encoding.Unicode, MakeKeyGrbit.NewKey);
if (Api.TrySeek(session, queues, SeekGrbit.SeekEQ) == false)
return -1;
var bytes = new byte[4];
var zero = BitConverter.GetBytes(0);
int actual;
Api.JetEscrowUpdate(session, queues, ColumnsInformation.QueuesColumns["number_of_messages"],
zero, zero.Length, bytes, bytes.Length, out actual, EscrowUpdateGrbit.None);
return BitConverter.ToInt32(bytes, 0);
}
public IEnumerable<MessageId> GetAlreadyReceivedMessageIds()
{
Api.MoveBeforeFirst(session, recveivedMsgs);
while(Api.TryMoveNext(session, recveivedMsgs))
{
yield return new MessageId
{
SourceInstanceId = new Guid(Api.RetrieveColumn(session, recveivedMsgs, ColumnsInformation.RecveivedMsgsColumns["instance_id"])),
MessageIdentifier = new Guid(Api.RetrieveColumn(session, recveivedMsgs, ColumnsInformation.RecveivedMsgsColumns["msg_id"])),
};
}
}
public void MarkReceived(MessageId id)
{
using(var update = new Update(session, recveivedMsgs, JET_prep.Insert))
{
Api.SetColumn(session, recveivedMsgs, ColumnsInformation.RecveivedMsgsColumns["instance_id"], id.SourceInstanceId.ToByteArray());
Api.SetColumn(session, recveivedMsgs, ColumnsInformation.RecveivedMsgsColumns["msg_id"], id.MessageIdentifier.ToByteArray());
update.Save();
}
}
public IEnumerable<MessageId> DeleteOldestReceivedMessageIds(int numberOfItemsToKeep, int numberOfItemsToDelete)
{
Api.MoveAfterLast(session, recveivedMsgs);
try
{
Api.JetMove(session, recveivedMsgs, -numberOfItemsToKeep, MoveGrbit.None);
}
catch (EsentErrorException e)
{
if (e.Error == JET_err.NoCurrentRecord)
yield break;
throw;
}
while(Api.TryMovePrevious(session, recveivedMsgs) && numberOfItemsToDelete-- > 0)
{
yield return new MessageId
{
SourceInstanceId = new Guid(Api.RetrieveColumn(session, recveivedMsgs, ColumnsInformation.RecveivedMsgsColumns["instance_id"])),
MessageIdentifier = new Guid(Api.RetrieveColumn(session, recveivedMsgs, ColumnsInformation.RecveivedMsgsColumns["msg_id"])),
};
Api.JetDelete(session, recveivedMsgs);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Collections.ObjectModel
{
[Serializable]
[DebuggerTypeProxy(typeof(ICollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Collection<T> : IList<T>, IList, IReadOnlyList<T>
{
private IList<T> items; // Do not rename (binary serialization)
[NonSerialized]
private Object _syncRoot;
public Collection()
{
items = new List<T>();
}
public Collection(IList<T> list)
{
if (list == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
}
items = list;
}
public int Count
{
get { return items.Count; }
}
protected IList<T> Items
{
get { return items; }
}
public T this[int index]
{
get { return items[index]; }
set
{
if (items.IsReadOnly)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
if (index < 0 || index >= items.Count)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
SetItem(index, value);
}
}
public void Add(T item)
{
if (items.IsReadOnly)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
int index = items.Count;
InsertItem(index, item);
}
public void Clear()
{
if (items.IsReadOnly)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
ClearItems();
}
public void CopyTo(T[] array, int index)
{
items.CopyTo(array, index);
}
public bool Contains(T item)
{
return items.Contains(item);
}
public IEnumerator<T> GetEnumerator()
{
return items.GetEnumerator();
}
public int IndexOf(T item)
{
return items.IndexOf(item);
}
public void Insert(int index, T item)
{
if (items.IsReadOnly)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
if (index < 0 || index > items.Count)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);
}
InsertItem(index, item);
}
public bool Remove(T item)
{
if (items.IsReadOnly)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
int index = items.IndexOf(item);
if (index < 0) return false;
RemoveItem(index);
return true;
}
public void RemoveAt(int index)
{
if (items.IsReadOnly)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
if (index < 0 || index >= items.Count)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
RemoveItem(index);
}
protected virtual void ClearItems()
{
items.Clear();
}
protected virtual void InsertItem(int index, T item)
{
items.Insert(index, item);
}
protected virtual void RemoveItem(int index)
{
items.RemoveAt(index);
}
protected virtual void SetItem(int index, T item)
{
items[index] = item;
}
bool ICollection<T>.IsReadOnly
{
get
{
return items.IsReadOnly;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)items).GetEnumerator();
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
ICollection c = items as ICollection;
if (c != null)
{
_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
return _syncRoot;
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
T[] tArray = array as T[];
if (tArray != null)
{
items.CopyTo(tArray, index);
}
else
{
//
// Catch the obvious case assignment will fail.
// We can't find all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType)))
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
//
// We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
//
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = items.Count;
try
{
for (int i = 0; i < count; i++)
{
objects[index++] = items[i];
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
object IList.this[int index]
{
get { return items[index]; }
set
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
try
{
this[index] = (T)value;
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
}
}
}
bool IList.IsReadOnly
{
get
{
return items.IsReadOnly;
}
}
bool IList.IsFixedSize
{
get
{
// There is no IList<T>.IsFixedSize, so we must assume that only
// readonly collections are fixed size, if our internal item
// collection does not implement IList. Note that Array implements
// IList, and therefore T[] and U[] will be fixed-size.
IList list = items as IList;
if (list != null)
{
return list.IsFixedSize;
}
return items.IsReadOnly;
}
}
int IList.Add(object value)
{
if (items.IsReadOnly)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
try
{
Add((T)value);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
}
return this.Count - 1;
}
bool IList.Contains(object value)
{
if (IsCompatibleObject(value))
{
return Contains((T)value);
}
return false;
}
int IList.IndexOf(object value)
{
if (IsCompatibleObject(value))
{
return IndexOf((T)value);
}
return -1;
}
void IList.Insert(int index, object value)
{
if (items.IsReadOnly)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
try
{
Insert(index, (T)value);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
}
}
void IList.Remove(object value)
{
if (items.IsReadOnly)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
if (IsCompatibleObject(value))
{
Remove((T)value);
}
}
private static bool IsCompatibleObject(object value)
{
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightLogicalInt641()
{
var test = new ImmUnaryOpTest__ShiftRightLogicalInt641();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalInt641
{
private struct TestStruct
{
public Vector256<Int64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt641 testClass)
{
var result = Avx2.ShiftRightLogical(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static Int64[] _data = new Int64[Op1ElementCount];
private static Vector256<Int64> _clsVar;
private Vector256<Int64> _fld;
private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable;
static ImmUnaryOpTest__ShiftRightLogicalInt641()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
}
public ImmUnaryOpTest__ShiftRightLogicalInt641()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftRightLogical(
Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftRightLogical(
Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftRightLogical(
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftRightLogical(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogicalInt641();
var result = Avx2.ShiftRightLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftRightLogical(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftRightLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int64> firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((long)(firstOp[0] >> 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((long)(firstOp[i] >> 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<Int64>(Vector256<Int64><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
#region Usings
using System;
using System.Diagnostics;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using PowerShellTools.Common.ServiceManagement.DebuggingContract;
using PowerShellTools.Common.Debugging;
using PowerShellTools.Common.Logging;
#endregion
namespace PowerShellTools.DebugEngine
{
// This class implements IDebugProgramNode2.
// This interface represents a program that can be debugged.
// A debug engine (DE) or a custom port supplier implements this interface to represent a program that can be debugged.
public class ScriptProgramNode : IDebugProgramNode2, IDebugProgram2, IDebugProgramNodeAttach2, IDebugEngineProgram2, IDebugThread2, IEnumDebugThreads2, IDebugModule3
{
private static readonly ILog Log = LogManager.GetLogger(typeof (ScriptProgramNode));
public ScriptDebugProcess Process { get; set; }
public ScriptDebugger Debugger
{
get;
set;
}
public Guid Id { get; set; }
/// <summary>
/// This is either the file name or the contents of the script. IsFile determines which it is.
/// TODO: Rename.
/// </summary>
public string FileName { get; set; }
/// <summary>
/// Arguments that will be passed to the script.
/// </summary>
public string Arguments { get; set; }
/// <summary>
/// Whether or not this program node represents a file or a command being debugged.
/// </summary>
public bool IsFile { get; set; }
/// <summary>
/// Whether or not this program node represents a runspace that is being debugged that has been
/// attached to.
/// </summary>
public bool IsAttachedProgram { get; set; }
/// <summary>
/// Whether or not this program node represents a runspace on a remote machine.
/// </summary>
public bool IsRemoteProgram { get; set; }
public ScriptProgramNode(ScriptDebugProcess process)
{
Id = Guid.NewGuid();
this.Process = process;
}
#region IDebugProgramNode2 Members
public int GetHostName(enum_GETHOSTNAME_TYPE dwHostNameType, out string pbstrHostName)
{
Log.Debug("ScriptProgramNode: Entering GetHostName");
pbstrHostName = null;
return VSConstants.E_NOTIMPL;
}
// Gets the name and identifier of the DE running this program.
int IDebugProgramNode2.GetEngineInfo(out string engineName, out Guid engineGuid)
{
Log.Debug("ScriptProgramNode: Entering GetEngineInfo");
engineName = ResourceStrings.EngineName;
engineGuid = new Guid(Engine.Id);
return VSConstants.S_OK;
}
// Gets the system process identifier for the process hosting a program.
int IDebugProgramNode2.GetHostPid(AD_PROCESS_ID[] pHostProcessId)
{
Log.Debug("ScriptProgramNode: Entering GetHostPid");
// Return the process id of the debugged process
pHostProcessId[0].ProcessIdType = (uint)enum_AD_PROCESS_ID.AD_PROCESS_ID_GUID;
pHostProcessId[0].guidProcessId = Process.Id;
return VSConstants.S_OK;
}
// Gets the name of a program.
int IDebugProgramNode2.GetProgramName(out string programName)
{
Log.Debug("ScriptProgramNode: Entering GetProgramName");
// Since we are using default transport and don't want to customize the process name, this method doesn't need
// to be implemented.
programName = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region Deprecated interface methods
// These methods are not called by the Visual Studio debugger, so they don't need to be implemented
int IDebugProgramNode2.Attach_V7(IDebugProgram2 pMDMProgram, IDebugEventCallback2 pCallback, uint dwReason)
{
Debug.Fail("This function is not called by the debugger");
return VSConstants.E_NOTIMPL;
}
int IDebugProgramNode2.DetachDebugger_V7()
{
Debug.Fail("This function is not called by the debugger");
return VSConstants.E_NOTIMPL;
}
int IDebugProgramNode2.GetHostMachineName_V7(out string hostMachineName)
{
Debug.Fail("This function is not called by the debugger");
hostMachineName = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region Implementation of IDebugProgram2
public int WriteDump(enum_DUMPTYPE DUMPTYPE, string pszDumpUrl)
{
Log.Debug("Program: WriteDump");
return VSConstants.E_NOTIMPL;
}
public int EnumThreads(out IEnumDebugThreads2 ppEnum)
{
Log.Debug("ScriptProgramNode: Entering EnumThreads");
ppEnum = this;
return VSConstants.S_OK;
}
public int GetName(out string pbstrName)
{
Log.Debug("ScriptProgramNode: Entering GetName");
pbstrName = "PowerShell Script";
return VSConstants.S_OK;
}
public int GetProcess(out IDebugProcess2 ppProcess)
{
Log.Debug("ScriptProgramNode: Entering GetProcess");
ppProcess = Process;
return VSConstants.S_OK;
}
public int Terminate()
{
Log.Debug("ScriptProgramNode: Entering Terminate");
return VSConstants.S_OK;
}
public int Attach(IDebugEventCallback2 pCallback)
{
Log.Debug("ScriptProgramNode: Entering Attach");
return VSConstants.S_OK;
}
public int CanDetach()
{
Log.Debug("ScriptProgramNode: Entering CanDetach");
return VSConstants.S_OK;
}
public int Detach()
{
Log.Debug("ScriptProgramNode: Entering Detach");
DebugScenario scenario = Debugger.DebuggingService.GetDebugScenario();
bool result = (scenario == DebugScenario.Local);
if (scenario == DebugScenario.LocalAttach)
{
result = Debugger.DebuggingService.DetachFromRunspace();
}
else if (scenario == DebugScenario.RemoteAttach)
{
result = Debugger.DebuggingService.DetachFromRemoteRunspace();
}
if (!result)
{
// try as hard as we can to detach/cleanup the mess for the length of CleanupRetryTimeout
TimeSpan retryTimeSpan = TimeSpan.FromMilliseconds(DebugEngineConstants.CleanupRetryTimeout);
Stopwatch timeElapsed = Stopwatch.StartNew();
while (timeElapsed.Elapsed < retryTimeSpan && !result)
{
result = (Debugger.DebuggingService.CleanupAttach() == DebugScenario.Local);
}
}
if (result)
{
Debugger.DebuggerFinished();
Debugger.RefreshPrompt();
}
return result ? VSConstants.S_OK : VSConstants.S_FALSE;
}
public int GetProgramId(out Guid pguidProgramId)
{
Log.Debug(String.Format("ScriptProgramNode: Entering GetProgramId {0}", Id));
pguidProgramId = Id;
return VSConstants.S_OK;
}
public int GetDebugProperty(out IDebugProperty2 ppProperty)
{
Log.Debug("ScriptProgramNode: Entering GetDebugProperty");
ppProperty = null;
return VSConstants.E_NOTIMPL;
}
public int Execute()
{
Log.Debug("ScriptProgramNode: Entering Execute");
Debugger.Continue();
return VSConstants.S_OK;
}
public int Continue(IDebugThread2 pThread)
{
Log.Debug("ScriptProgramNode: Entering Continue");
Debugger.Continue();
return VSConstants.S_OK;
}
public int Step(IDebugThread2 pThread, enum_STEPKIND sk, enum_STEPUNIT Step)
{
Log.Debug("ScriptProgramNode: Entering Step");
switch(sk)
{
case enum_STEPKIND.STEP_OVER:
Debugger.StepOver();
break;
case enum_STEPKIND.STEP_INTO:
Debugger.StepInto();
break;
case enum_STEPKIND.STEP_OUT:
Debugger.StepOut();
break;
}
return VSConstants.S_OK;
}
public int CauseBreak()
{
Log.Debug("ScriptProgramNode: Entering CauseBreak");
//TODO: Debugger.DebuggerManager.BreakDebug();
return VSConstants.S_OK;
}
public int GetEngineInfo(out string pbstrEngine, out Guid pguidEngine)
{
Log.Debug("ScriptProgramNode: Entering GetEngineInfo");
pbstrEngine = ResourceStrings.EngineName;
pguidEngine = Guid.Parse(Engine.Id);
return VSConstants.S_OK;
}
public int EnumCodeContexts(IDebugDocumentPosition2 pDocPos, out IEnumDebugCodeContexts2 ppEnum)
{
Log.Debug("Program: EnumCodeContexts");
ppEnum = null;
return VSConstants.E_NOTIMPL;
}
public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes)
{
Log.Debug("Program: GetMemoryBytes");
ppMemoryBytes = null;
return VSConstants.E_NOTIMPL;
}
public int GetDisassemblyStream(enum_DISASSEMBLY_STREAM_SCOPE dwScope, IDebugCodeContext2 pCodeContext, out IDebugDisassemblyStream2 ppDisassemblyStream)
{
Log.Debug("Program: GetDisassemblyStream");
ppDisassemblyStream = null;
return VSConstants.E_NOTIMPL;
}
public int EnumModules(out IEnumDebugModules2 ppEnum)
{
Log.Debug("Program: EnumModules");
ppEnum = null;
return VSConstants.E_NOTIMPL;
}
public int GetENCUpdate(out object ppUpdate)
{
Log.Debug("Program: GetENCUpdate");
ppUpdate = null;
return VSConstants.E_NOTIMPL;
}
public int EnumCodePaths(string pszHint, IDebugCodeContext2 pStart, IDebugStackFrame2 pFrame, int fSource, out IEnumCodePaths2 ppEnum, out IDebugCodeContext2 ppSafety)
{
Log.Debug("Program: EnumCodePaths");
ppEnum = null;
ppSafety = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region Implementation of IDebugProgramNodeAttach2
public int OnAttach(ref Guid guidProgramId)
{
Log.Debug("ScriptProgramNode: Entering OnAttach");
return VSConstants.S_OK;
}
#endregion
#region Implementation of IDebugEngineProgram2
public int Stop()
{
Log.Debug("Program: Stop");
Debugger.Stop();
return VSConstants.S_OK;
}
public int WatchForThreadStep(IDebugProgram2 pOriginatingProgram, uint dwTid, int fWatch, uint dwFrame)
{
Log.Debug("Program: WatchForThreadStep");
return VSConstants.S_OK;
}
public int WatchForExpressionEvaluationOnThread(IDebugProgram2 pOriginatingProgram, uint dwTid, uint dwEvalFlags, IDebugEventCallback2 pExprCallback, int fWatch)
{
Log.Debug("Program: WatchForExpressionEvaluationOnThread");
return VSConstants.S_OK;
}
#endregion
#region Implementation of IDebugThread2
public int EnumFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, out IEnumDebugFrameInfo2 ppEnum)
{
Log.Debug("Thread: EnumFrameInfo");
ppEnum = new ScriptStackFrameCollection(Debugger.CallStack, this);
return VSConstants.S_OK;
}
public int SetThreadName(string pszName)
{
Log.Debug("Thread: SetThreadName");
return VSConstants.E_NOTIMPL;
}
public int GetProgram(out IDebugProgram2 ppProgram)
{
Log.Debug("Thread: GetProgram");
ppProgram = this;
return VSConstants.S_OK;
}
public int CanSetNextStatement(IDebugStackFrame2 pStackFrame, IDebugCodeContext2 pCodeContext)
{
Log.Debug("Thread: CanSetNextStatement");
return VSConstants.S_OK;
}
public int SetNextStatement(IDebugStackFrame2 pStackFrame, IDebugCodeContext2 pCodeContext)
{
Log.Debug("Thread: SetNextStatement");
return VSConstants.S_OK;
}
public int GetThreadId(out uint pdwThreadId)
{
Log.Debug("Thread: GetThreadId");
pdwThreadId = 0;
return VSConstants.S_OK;
}
public int Suspend(out uint pdwSuspendCount)
{
Log.Debug("Thread: Suspend");
pdwSuspendCount = 0;
return VSConstants.S_OK;
}
public int Resume(out uint pdwSuspendCount)
{
Log.Debug("Thread: Resume");
pdwSuspendCount = 0;
return VSConstants.E_NOTIMPL;
}
public int GetThreadProperties(enum_THREADPROPERTY_FIELDS dwFields, THREADPROPERTIES[] ptp)
{
Log.Debug("Thread: GetThreadProperties");
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_ID) != 0)
{
ptp[0].dwThreadId = 0;
ptp[0].dwFields |= enum_THREADPROPERTY_FIELDS.TPF_ID;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_NAME) != 0)
{
ptp[0].bstrName = "Thread";
ptp[0].dwFields |= enum_THREADPROPERTY_FIELDS.TPF_NAME;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_STATE) != 0)
{
ptp[0].dwThreadState = (int)enum_THREADSTATE.THREADSTATE_STOPPED;
ptp[0].dwFields |= enum_THREADPROPERTY_FIELDS.TPF_STATE;
}
return VSConstants.S_OK;
}
public int GetLogicalThread(IDebugStackFrame2 pStackFrame, out IDebugLogicalThread2 ppLogicalThread)
{
Log.Debug("Thread: GetLogicalThread");
ppLogicalThread = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region Implementation of IEnumDebugThreads2
public int Next(uint celt, IDebugThread2[] rgelt, ref uint pceltFetched)
{
rgelt[0] = this;
pceltFetched = 1;
return VSConstants.S_OK;
}
public int Skip(uint celt)
{
return VSConstants.E_NOTIMPL;
}
public int Reset()
{
return VSConstants.S_OK;
}
public int Clone(out IEnumDebugThreads2 ppEnum)
{
ppEnum = null;
return VSConstants.E_NOTIMPL;
}
public int GetCount(out uint pcelt)
{
pcelt = 1;
return VSConstants.S_OK;
}
#endregion
#region Implementation of IDebugModule2
public int GetInfo(enum_MODULE_INFO_FIELDS dwFields, MODULE_INFO[] pinfo)
{
Log.Debug("ScriptProgramNode: IDebugModule2.GetInfo");
if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_NAME) != 0)
{
pinfo[0].m_bstrName = FileName;
pinfo[0].dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_NAME;
}
if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_FLAGS) != 0)
{
pinfo[0].m_dwModuleFlags = enum_MODULE_FLAGS.MODULE_FLAG_SYMBOLS;
pinfo[0].dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_FLAGS;
}
if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_URLSYMBOLLOCATION) != 0)
{
pinfo[0].m_bstrUrlSymbolLocation = @".\";
pinfo[0].dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_URLSYMBOLLOCATION;
}
return VSConstants.S_OK;
}
public int ReloadSymbols_Deprecated(string pszUrlToSymbols, out string pbstrDebugMessage)
{
throw new NotImplementedException();
}
#endregion
#region Implementation of IDebugModule3
public int GetSymbolInfo(enum_SYMBOL_SEARCH_INFO_FIELDS dwFields, MODULE_SYMBOL_SEARCH_INFO[] pinfo)
{
// This engine only supports loading symbols at the location specified in the binary's symbol path location in the PE file and
// does so only for the primary exe of the debuggee.
// Therefore, it only displays if the symbols were loaded or not. If symbols were loaded, that path is added.
pinfo[0] = new MODULE_SYMBOL_SEARCH_INFO();
pinfo[0].dwValidFields = 1; // SSIF_VERBOSE_SEARCH_INFO;
string symbolPath = "Symbols Loaded - " + FileName;
pinfo[0].bstrVerboseSearchInfo = symbolPath;
return VSConstants.S_OK;
}
public int LoadSymbols()
{
return VSConstants.E_NOTIMPL;
}
public int IsUserCode(out int pfUser)
{
pfUser = 1;
return VSConstants.S_OK;
}
public int SetJustMyCodeState(int fIsUserCode)
{
return VSConstants.E_NOTIMPL;
}
#endregion
}
}
| |
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using ReaderException = com.google.zxing.ReaderException;
using DecoderResult = com.google.zxing.common.DecoderResult;
namespace com.google.zxing.pdf417.decoder
{
/// <summary> <p>This class contains the methods for decoding the PDF417 codewords.</p>
///
/// </summary>
/// <author> SITA Lab (kevin.osullivan@sita.aero)
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
sealed class DecodedBitStreamParser
{
private const int TEXT_COMPACTION_MODE_LATCH = 900;
private const int BYTE_COMPACTION_MODE_LATCH = 901;
private const int NUMERIC_COMPACTION_MODE_LATCH = 902;
private const int BYTE_COMPACTION_MODE_LATCH_6 = 924;
private const int BEGIN_MACRO_PDF417_CONTROL_BLOCK = 928;
private const int BEGIN_MACRO_PDF417_OPTIONAL_FIELD = 923;
private const int MACRO_PDF417_TERMINATOR = 922;
private const int MODE_SHIFT_TO_BYTE_COMPACTION_MODE = 913;
private const int MAX_NUMERIC_CODEWORDS = 15;
private const int ALPHA = 0;
private const int LOWER = 1;
private const int MIXED = 2;
private const int PUNCT = 3;
private const int PUNCT_SHIFT = 4;
private const int PL = 25;
private const int LL = 27;
private const int AS = 27;
private const int ML = 28;
private const int AL = 28;
private const int PS = 29;
private const int PAL = 29;
//UPGRADE_NOTE: Final was removed from the declaration of 'PUNCT_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private static readonly char[] PUNCT_CHARS = new char[]{';', '<', '>', '@', '[', (char) (92), '}', '_', (char) (96), '~', '!', (char) (13), (char) (9), ',', ':', (char) (10), '-', '.', '$', '/', (char) (34), '|', '*', '(', ')', '?', '{', '}', (char) (39)};
//UPGRADE_NOTE: Final was removed from the declaration of 'MIXED_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private static readonly char[] MIXED_CHARS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '&', (char) (13), (char) (9), ',', ':', '#', '-', '.', '$', '/', '+', '%', '*', '=', '^'};
// Table containing values for the exponent of 900.
// This is used in the numeric compaction decode algorithm.
//UPGRADE_NOTE: Final was removed from the declaration of 'EXP900'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private static readonly System.String[] EXP900 = new System.String[]{"000000000000000000000000000000000000000000001", "000000000000000000000000000000000000000000900", "000000000000000000000000000000000000000810000", "000000000000000000000000000000000000729000000", "000000000000000000000000000000000656100000000", "000000000000000000000000000000590490000000000", "000000000000000000000000000531441000000000000", "000000000000000000000000478296900000000000000", "000000000000000000000430467210000000000000000", "000000000000000000387420489000000000000000000", "000000000000000348678440100000000000000000000", "000000000000313810596090000000000000000000000", "000000000282429536481000000000000000000000000", "000000254186582832900000000000000000000000000", "000228767924549610000000000000000000000000000", "205891132094649000000000000000000000000000000"};
private DecodedBitStreamParser()
{
}
internal static DecoderResult decode(int[] codewords)
{
System.Text.StringBuilder result = new System.Text.StringBuilder(100);
// Get compaction mode
int codeIndex = 1;
int code = codewords[codeIndex++];
while (codeIndex < codewords[0])
{
switch (code)
{
case TEXT_COMPACTION_MODE_LATCH: {
codeIndex = textCompaction(codewords, codeIndex, result);
break;
}
case BYTE_COMPACTION_MODE_LATCH: {
codeIndex = byteCompaction(code, codewords, codeIndex, result);
break;
}
case NUMERIC_COMPACTION_MODE_LATCH: {
codeIndex = numericCompaction(codewords, codeIndex, result);
break;
}
case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: {
codeIndex = byteCompaction(code, codewords, codeIndex, result);
break;
}
case BYTE_COMPACTION_MODE_LATCH_6: {
codeIndex = byteCompaction(code, codewords, codeIndex, result);
break;
}
default: {
// Default to text compaction. During testing numerous barcodes
// appeared to be missing the starting mode. In these cases defaulting
// to text compaction seems to work.
codeIndex--;
codeIndex = textCompaction(codewords, codeIndex, result);
break;
}
}
if (codeIndex < codewords.Length)
{
code = codewords[codeIndex++];
}
else
{
throw ReaderException.Instance;
}
}
return new DecoderResult(null, result.ToString(), null, null);
}
/// <summary> Text Compaction mode (see 5.4.1.5) permits all printable ASCII characters to be
/// encoded, i.e. values 32 - 126 inclusive in accordance with ISO/IEC 646 (IRV), as
/// well as selected control characters.
///
/// </summary>
/// <param name="codewords">The array of codewords (data + error)
/// </param>
/// <param name="codeIndex">The current index into the codeword array.
/// </param>
/// <param name="result"> The decoded data is appended to the result.
/// </param>
/// <returns> The next index into the codeword array.
/// </returns>
private static int textCompaction(int[] codewords, int codeIndex, System.Text.StringBuilder result)
{
// 2 character per codeword
int[] textCompactionData = new int[codewords[0] << 1];
// Used to hold the byte compaction value if there is a mode shift
int[] byteCompactionData = new int[codewords[0] << 1];
int index = 0;
bool end = false;
while ((codeIndex < codewords[0]) && !end)
{
int code = codewords[codeIndex++];
if (code < TEXT_COMPACTION_MODE_LATCH)
{
textCompactionData[index] = code / 30;
textCompactionData[index + 1] = code % 30;
index += 2;
}
else
{
switch (code)
{
case TEXT_COMPACTION_MODE_LATCH: {
codeIndex--;
end = true;
break;
}
case BYTE_COMPACTION_MODE_LATCH: {
codeIndex--;
end = true;
break;
}
case NUMERIC_COMPACTION_MODE_LATCH: {
codeIndex--;
end = true;
break;
}
case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: {
// The Mode Shift codeword 913 shall cause a temporary
// switch from Text Compaction mode to Byte Compaction mode.
// This switch shall be in effect for only the next codeword,
// after which the mode shall revert to the prevailing sub-mode
// of the Text Compaction mode. Codeword 913 is only available
// in Text Compaction mode; its use is described in 5.4.2.4.
textCompactionData[index] = MODE_SHIFT_TO_BYTE_COMPACTION_MODE;
byteCompactionData[index] = code; //Integer.toHexString(code);
index++;
break;
}
case BYTE_COMPACTION_MODE_LATCH_6: {
codeIndex--;
end = true;
break;
}
}
}
}
decodeTextCompaction(textCompactionData, byteCompactionData, index, result);
return codeIndex;
}
/// <summary> The Text Compaction mode includes all the printable ASCII characters
/// (i.e. values from 32 to 126) and three ASCII control characters: HT or tab
/// (ASCII value 9), LF or line feed (ASCII value 10), and CR or carriage
/// return (ASCII value 13). The Text Compaction mode also includes various latch
/// and shift characters which are used exclusively within the mode. The Text
/// Compaction mode encodes up to 2 characters per codeword. The compaction rules
/// for converting data into PDF417 codewords are defined in 5.4.2.2. The sub-mode
/// switches are defined in 5.4.2.3.
///
/// </summary>
/// <param name="textCompactionData">The text compaction data.
/// </param>
/// <param name="byteCompactionData">The byte compaction data if there
/// was a mode shift.
/// </param>
/// <param name="length"> The size of the text compaction and byte compaction data.
/// </param>
/// <param name="result"> The decoded data is appended to the result.
/// </param>
private static void decodeTextCompaction(int[] textCompactionData, int[] byteCompactionData, int length, System.Text.StringBuilder result)
{
// Beginning from an initial state of the Alpha sub-mode
// The default compaction mode for PDF417 in effect at the start of each symbol shall always be Text
// Compaction mode Alpha sub-mode (uppercase alphabetic). A latch codeword from another mode to the Text
// Compaction mode shall always switch to the Text Compaction Alpha sub-mode.
int subMode = ALPHA;
int priorToShiftMode = ALPHA;
int i = 0;
while (i < length)
{
int subModeCh = textCompactionData[i];
char ch = (char) (0);
switch (subMode)
{
case ALPHA:
// Alpha (uppercase alphabetic)
if (subModeCh < 26)
{
// Upper case Alpha Character
ch = (char) ('A' + subModeCh);
}
else
{
if (subModeCh == 26)
{
ch = ' ';
}
else if (subModeCh == LL)
{
subMode = LOWER;
}
else if (subModeCh == ML)
{
subMode = MIXED;
}
else if (subModeCh == PS)
{
// Shift to punctuation
priorToShiftMode = subMode;
subMode = PUNCT_SHIFT;
}
else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE)
{
result.Append((char) byteCompactionData[i]);
}
}
break;
case LOWER:
// Lower (lowercase alphabetic)
if (subModeCh < 26)
{
ch = (char) ('a' + subModeCh);
}
else
{
if (subModeCh == 26)
{
ch = ' ';
}
else if (subModeCh == AL)
{
subMode = ALPHA;
}
else if (subModeCh == ML)
{
subMode = MIXED;
}
else if (subModeCh == PS)
{
// Shift to punctuation
priorToShiftMode = subMode;
subMode = PUNCT_SHIFT;
}
else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE)
{
result.Append((char) byteCompactionData[i]);
}
}
break;
case MIXED:
// Mixed (numeric and some punctuation)
if (subModeCh < PL)
{
ch = MIXED_CHARS[subModeCh];
}
else
{
if (subModeCh == PL)
{
subMode = PUNCT;
}
else if (subModeCh == 26)
{
ch = ' ';
}
else if (subModeCh == AS)
{
//mode_change = true;
}
else if (subModeCh == AL)
{
subMode = ALPHA;
}
else if (subModeCh == PS)
{
// Shift to punctuation
priorToShiftMode = subMode;
subMode = PUNCT_SHIFT;
}
else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE)
{
result.Append((char) byteCompactionData[i]);
}
}
break;
case PUNCT:
// Punctuation
if (subModeCh < PS)
{
ch = PUNCT_CHARS[subModeCh];
}
else
{
if (subModeCh == PAL)
{
subMode = ALPHA;
}
else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE)
{
result.Append((char) byteCompactionData[i]);
}
}
break;
case PUNCT_SHIFT:
// Restore sub-mode
subMode = priorToShiftMode;
if (subModeCh < PS)
{
ch = PUNCT_CHARS[subModeCh];
}
else
{
if (subModeCh == PAL)
{
subMode = ALPHA;
}
}
break;
}
if (ch != 0)
{
// Append decoded character to result
result.Append(ch);
}
i++;
}
}
/// <summary> Byte Compaction mode (see 5.4.3) permits all 256 possible 8-bit byte values to be encoded.
/// This includes all ASCII characters value 0 to 127 inclusive and provides for international
/// character set support.
///
/// </summary>
/// <param name="mode"> The byte compaction mode i.e. 901 or 924
/// </param>
/// <param name="codewords">The array of codewords (data + error)
/// </param>
/// <param name="codeIndex">The current index into the codeword array.
/// </param>
/// <param name="result"> The decoded data is appended to the result.
/// </param>
/// <returns> The next index into the codeword array.
/// </returns>
private static int byteCompaction(int mode, int[] codewords, int codeIndex, System.Text.StringBuilder result)
{
if (mode == BYTE_COMPACTION_MODE_LATCH)
{
// Total number of Byte Compaction characters to be encoded
// is not a multiple of 6
int count = 0;
long value_Renamed = 0;
char[] decodedData = new char[6];
int[] byteCompactedCodewords = new int[6];
bool end = false;
while ((codeIndex < codewords[0]) && !end)
{
int code = codewords[codeIndex++];
if (code < TEXT_COMPACTION_MODE_LATCH)
{
byteCompactedCodewords[count] = code;
count++;
// Base 900
value_Renamed *= 900;
value_Renamed += code;
}
else
{
if ((code == TEXT_COMPACTION_MODE_LATCH) || (code == BYTE_COMPACTION_MODE_LATCH) || (code == NUMERIC_COMPACTION_MODE_LATCH) || (code == BYTE_COMPACTION_MODE_LATCH_6) || (code == BEGIN_MACRO_PDF417_CONTROL_BLOCK) || (code == BEGIN_MACRO_PDF417_OPTIONAL_FIELD) || (code == MACRO_PDF417_TERMINATOR))
{
}
codeIndex--;
end = true;
}
if ((count % 5 == 0) && (count > 0))
{
// Decode every 5 codewords
// Convert to Base 256
for (int j = 0; j < 6; ++j)
{
decodedData[5 - j] = (char) (value_Renamed % 256);
value_Renamed >>= 8;
}
result.Append(decodedData);
count = 0;
}
}
// If Byte Compaction mode is invoked with codeword 901,
// the final group of codewords is interpreted directly
// as one byte per codeword, without compaction.
for (int i = ((count / 5) * 5); i < count; i++)
{
result.Append((char) byteCompactedCodewords[i]);
}
}
else if (mode == BYTE_COMPACTION_MODE_LATCH_6)
{
// Total number of Byte Compaction characters to be encoded
// is an integer multiple of 6
int count = 0;
long value_Renamed = 0;
bool end = false;
while ((codeIndex < codewords[0]) && !end)
{
int code = codewords[codeIndex++];
if (code < TEXT_COMPACTION_MODE_LATCH)
{
count += 1;
// Base 900
value_Renamed *= 900;
value_Renamed += code;
}
else
{
if ((code == TEXT_COMPACTION_MODE_LATCH) || (code == BYTE_COMPACTION_MODE_LATCH) || (code == NUMERIC_COMPACTION_MODE_LATCH) || (code == BYTE_COMPACTION_MODE_LATCH_6) || (code == BEGIN_MACRO_PDF417_CONTROL_BLOCK) || (code == BEGIN_MACRO_PDF417_OPTIONAL_FIELD) || (code == MACRO_PDF417_TERMINATOR))
{
}
codeIndex--;
end = true;
}
if ((count % 5 == 0) && (count > 0))
{
// Decode every 5 codewords
// Convert to Base 256
char[] decodedData = new char[6];
for (int j = 0; j < 6; ++j)
{
decodedData[5 - j] = (char) (value_Renamed % 256);
value_Renamed >>= 8;
}
result.Append(decodedData);
}
}
}
return codeIndex;
}
/// <summary> Numeric Compaction mode (see 5.4.4) permits efficient encoding of numeric data strings.
///
/// </summary>
/// <param name="codewords">The array of codewords (data + error)
/// </param>
/// <param name="codeIndex">The current index into the codeword array.
/// </param>
/// <param name="result"> The decoded data is appended to the result.
/// </param>
/// <returns> The next index into the codeword array.
/// </returns>
private static int numericCompaction(int[] codewords, int codeIndex, System.Text.StringBuilder result)
{
int count = 0;
bool end = false;
int[] numericCodewords = new int[MAX_NUMERIC_CODEWORDS];
while ((codeIndex < codewords.Length) && !end)
{
int code = codewords[codeIndex++];
if (code < TEXT_COMPACTION_MODE_LATCH)
{
numericCodewords[count] = code;
count++;
}
else
{
if ((code == TEXT_COMPACTION_MODE_LATCH) || (code == BYTE_COMPACTION_MODE_LATCH) || (code == BYTE_COMPACTION_MODE_LATCH_6) || (code == BEGIN_MACRO_PDF417_CONTROL_BLOCK) || (code == BEGIN_MACRO_PDF417_OPTIONAL_FIELD) || (code == MACRO_PDF417_TERMINATOR))
{
}
codeIndex--;
end = true;
}
if ((count % MAX_NUMERIC_CODEWORDS) == 0 || code == NUMERIC_COMPACTION_MODE_LATCH)
{
// Re-invoking Numeric Compaction mode (by using codeword 902
// while in Numeric Compaction mode) serves to terminate the
// current Numeric Compaction mode grouping as described in 5.4.4.2,
// and then to start a new one grouping.
System.String s = decodeBase900toBase10(numericCodewords, count);
result.Append(s);
count = 0;
}
}
return codeIndex;
}
/// <summary> Convert a list of Numeric Compacted codewords from Base 900 to Base 10.
///
/// </summary>
/// <param name="codewords">The array of codewords
/// </param>
/// <param name="count"> The number of codewords
/// </param>
/// <returns> The decoded string representing the Numeric data.
/// </returns>
/*
EXAMPLE
Encode the fifteen digit numeric string 000213298174000
Prefix the numeric string with a 1 and set the initial value of
t = 1 000 213 298 174 000
Calculate codeword 0
d0 = 1 000 213 298 174 000 mod 900 = 200
t = 1 000 213 298 174 000 div 900 = 1 111 348 109 082
Calculate codeword 1
d1 = 1 111 348 109 082 mod 900 = 282
t = 1 111 348 109 082 div 900 = 1 234 831 232
Calculate codeword 2
d2 = 1 234 831 232 mod 900 = 632
t = 1 234 831 232 div 900 = 1 372 034
Calculate codeword 3
d3 = 1 372 034 mod 900 = 434
t = 1 372 034 div 900 = 1 524
Calculate codeword 4
d4 = 1 524 mod 900 = 624
t = 1 524 div 900 = 1
Calculate codeword 5
d5 = 1 mod 900 = 1
t = 1 div 900 = 0
Codeword sequence is: 1, 624, 434, 632, 282, 200
Decode the above codewords involves
1 x 900 power of 5 + 624 x 900 power of 4 + 434 x 900 power of 3 +
632 x 900 power of 2 + 282 x 900 power of 1 + 200 x 900 power of 0 = 1000213298174000
Remove leading 1 => Result is 000213298174000
As there are huge numbers involved here we must use fake out the maths using string
tokens for the numbers.
BigDecimal is not supported by J2ME.
*/
private static System.String decodeBase900toBase10(int[] codewords, int count)
{
System.Text.StringBuilder accum = null;
for (int i = 0; i < count; i++)
{
System.Text.StringBuilder value_Renamed = multiply(EXP900[count - i - 1], codewords[i]);
if (accum == null)
{
// First time in accum=0
accum = value_Renamed;
}
else
{
accum = add(accum.ToString(), value_Renamed.ToString());
}
}
System.String result = null;
// Remove leading '1' which was inserted to preserve
// leading zeros
for (int i = 0; i < accum.Length; i++)
{
if (accum[i] == '1')
{
//result = accum.substring(i + 1);
result = accum.ToString().Substring(i + 1);
break;
}
}
if (result == null)
{
// No leading 1 => just write the converted number.
result = accum.ToString();
}
return result;
}
/// <summary> Multiplies two String numbers
///
/// </summary>
/// <param name="value1">Any number represented as a string.
/// </param>
/// <param name="value2">A number <= 999.
/// </param>
/// <returns> the result of value1 * value2.
/// </returns>
private static System.Text.StringBuilder multiply(System.String value1, int value2)
{
System.Text.StringBuilder result = new System.Text.StringBuilder(value1.Length);
for (int i = 0; i < value1.Length; i++)
{
// Put zeros into the result.
result.Append('0');
}
int hundreds = value2 / 100;
int tens = (value2 / 10) % 10;
int ones = value2 % 10;
// Multiply by ones
for (int j = 0; j < ones; j++)
{
result = add(result.ToString(), value1);
}
// Multiply by tens
for (int j = 0; j < tens; j++)
{
result = add(result.ToString(), (value1 + '0').Substring(1));
}
// Multiply by hundreds
for (int j = 0; j < hundreds; j++)
{
result = add(result.ToString(), (value1 + "00").Substring(2));
}
return result;
}
/// <summary> Add two numbers which are represented as strings.
///
/// </summary>
/// <param name="value1">
/// </param>
/// <param name="value2">
/// </param>
/// <returns> the result of value1 + value2
/// </returns>
private static System.Text.StringBuilder add(System.String value1, System.String value2)
{
System.Text.StringBuilder temp1 = new System.Text.StringBuilder(5);
System.Text.StringBuilder temp2 = new System.Text.StringBuilder(5);
System.Text.StringBuilder result = new System.Text.StringBuilder(value1.Length);
for (int i = 0; i < value1.Length; i++)
{
// Put zeros into the result.
result.Append('0');
}
int carry = 0;
for (int i = value1.Length - 3; i > - 1; i -= 3)
{
temp1.Length = 0;
temp1.Append(value1[i]);
temp1.Append(value1[i + 1]);
temp1.Append(value1[i + 2]);
temp2.Length = 0;
temp2.Append(value2[i]);
temp2.Append(value2[i + 1]);
temp2.Append(value2[i + 2]);
int intValue1 = System.Int32.Parse(temp1.ToString());
int intValue2 = System.Int32.Parse(temp2.ToString());
int sumval = (intValue1 + intValue2 + carry) % 1000;
carry = (intValue1 + intValue2 + carry) / 1000;
result[i + 2] = (char) ((sumval % 10) + '0');
result[i + 1] = (char) (((sumval / 10) % 10) + '0');
result[i] = (char) ((sumval / 100) + '0');
}
return result;
}
/*
private static String decodeBase900toBase10(int codewords[], int count) {
BigInteger accum = BigInteger.valueOf(0);
BigInteger value = null;
for (int i = 0; i < count; i++) {
value = BigInteger.valueOf(900).pow(count - i - 1);
value = value.multiply(BigInteger.valueOf(codewords[i]));
accum = accum.add(value);
}
if (debug) System.out.println("Big Integer " + accum);
String result = accum.toString().substring(1);
return result;
}
*/
}
}
| |
// Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
using AppBrix.Logging.Contracts;
using AppBrix.Logging.Events;
using AppBrix.Tests;
using FluentAssertions;
using System;
using Xunit;
namespace AppBrix.Logging.Tests.Config;
public sealed class LoggingConfigTests : TestsBase
{
#region Setup and cleanup
public LoggingConfigTests() : base(TestUtils.CreateTestApp<LoggingModule>()) => this.app.Start();
#endregion
#region Tests
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestErrorLevelConfig()
{
var message = "Test message";
var errorCalled = false;
var warningCalled = false;
var infoCalled = false;
var debugCalled = false;
var traceCalled = false;
this.app.ConfigService.GetLoggingConfig().LogLevel = LogLevel.Error;
this.app.GetEventHub().Subscribe<ILogEntry>(x =>
{
switch (x.Level)
{
case LogLevel.Trace:
traceCalled = true;
break;
case LogLevel.Debug:
debugCalled = true;
break;
case LogLevel.Info:
infoCalled = true;
break;
case LogLevel.Warning:
warningCalled = true;
break;
case LogLevel.Error:
errorCalled = true;
break;
default:
throw new NotSupportedException(x.Level.ToString());
}
});
this.app.GetLogHub().Error(message);
this.app.GetLogHub().Warning(message);
this.app.GetLogHub().Info(message);
this.app.GetLogHub().Debug(message);
this.app.GetLogHub().Trace(message);
errorCalled.Should().BeTrue("the error event should have been called");
warningCalled.Should().BeFalse("the warning event should not have been called");
infoCalled.Should().BeFalse("the info event should not have been called");
debugCalled.Should().BeFalse("the debug event should not have been called");
traceCalled.Should().BeFalse("the trace event should not have been called");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestWarningLevelConfig()
{
var message = "Test message";
var errorCalled = false;
var warningCalled = false;
var infoCalled = false;
var debugCalled = false;
var traceCalled = false;
this.app.ConfigService.GetLoggingConfig().LogLevel = LogLevel.Warning;
this.app.GetEventHub().Subscribe<ILogEntry>(x =>
{
switch (x.Level)
{
case LogLevel.Trace:
traceCalled = true;
break;
case LogLevel.Debug:
debugCalled = true;
break;
case LogLevel.Info:
infoCalled = true;
break;
case LogLevel.Warning:
warningCalled = true;
break;
case LogLevel.Error:
errorCalled = true;
break;
default:
throw new NotSupportedException(x.Level.ToString());
}
});
this.app.GetLogHub().Error(message);
this.app.GetLogHub().Warning(message);
this.app.GetLogHub().Info(message);
this.app.GetLogHub().Debug(message);
this.app.GetLogHub().Trace(message);
errorCalled.Should().BeTrue("the error event should have been called");
warningCalled.Should().BeTrue("the warning event should have been called");
infoCalled.Should().BeFalse("the info event should not have been called");
debugCalled.Should().BeFalse("the debug event should not have been called");
traceCalled.Should().BeFalse("the trace event should not have been called");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestInfoLevelConfig()
{
var message = "Test message";
var errorCalled = false;
var warningCalled = false;
var infoCalled = false;
var debugCalled = false;
var traceCalled = false;
this.app.ConfigService.GetLoggingConfig().LogLevel = LogLevel.Info;
this.app.GetEventHub().Subscribe<ILogEntry>(x =>
{
switch (x.Level)
{
case LogLevel.Trace:
traceCalled = true;
break;
case LogLevel.Debug:
debugCalled = true;
break;
case LogLevel.Info:
infoCalled = true;
break;
case LogLevel.Warning:
warningCalled = true;
break;
case LogLevel.Error:
errorCalled = true;
break;
default:
throw new NotSupportedException(x.Level.ToString());
}
});
this.app.GetLogHub().Error(message);
this.app.GetLogHub().Warning(message);
this.app.GetLogHub().Info(message);
this.app.GetLogHub().Debug(message);
this.app.GetLogHub().Trace(message);
errorCalled.Should().BeTrue("the error event should have been called");
warningCalled.Should().BeTrue("the warning event should have been called");
infoCalled.Should().BeTrue("the info event should have been called");
debugCalled.Should().BeFalse("the debug event should not have been called");
traceCalled.Should().BeFalse("the trace event should not have been called");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestDebugLevelConfig()
{
var message = "Test message";
var errorCalled = false;
var warningCalled = false;
var infoCalled = false;
var debugCalled = false;
var traceCalled = false;
this.app.ConfigService.GetLoggingConfig().LogLevel = LogLevel.Debug;
this.app.GetEventHub().Subscribe<ILogEntry>(x =>
{
switch (x.Level)
{
case LogLevel.Trace:
traceCalled = true;
break;
case LogLevel.Debug:
debugCalled = true;
break;
case LogLevel.Info:
infoCalled = true;
break;
case LogLevel.Warning:
warningCalled = true;
break;
case LogLevel.Error:
errorCalled = true;
break;
default:
throw new NotSupportedException(x.Level.ToString());
}
});
this.app.GetLogHub().Error(message);
this.app.GetLogHub().Warning(message);
this.app.GetLogHub().Info(message);
this.app.GetLogHub().Debug(message);
this.app.GetLogHub().Trace(message);
errorCalled.Should().BeTrue("the error event should have been called");
warningCalled.Should().BeTrue("the warning event should have been called");
infoCalled.Should().BeTrue("the info event should have been called");
debugCalled.Should().BeTrue("the debug event should have been called");
traceCalled.Should().BeFalse("the trace event should not have been called");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestTraceLevelConfig()
{
var message = "Test message";
var errorCalled = false;
var warningCalled = false;
var infoCalled = false;
var debugCalled = false;
var traceCalled = false;
this.app.ConfigService.GetLoggingConfig().LogLevel = LogLevel.Trace;
this.app.GetEventHub().Subscribe<ILogEntry>(x =>
{
switch (x.Level)
{
case LogLevel.Trace:
traceCalled = true;
break;
case LogLevel.Debug:
debugCalled = true;
break;
case LogLevel.Info:
infoCalled = true;
break;
case LogLevel.Warning:
warningCalled = true;
break;
case LogLevel.Error:
errorCalled = true;
break;
default:
throw new NotSupportedException(x.Level.ToString());
}
});
this.app.GetLogHub().Error(message);
this.app.GetLogHub().Warning(message);
this.app.GetLogHub().Info(message);
this.app.GetLogHub().Debug(message);
this.app.GetLogHub().Trace(message);
errorCalled.Should().BeTrue("the error event should have been called");
warningCalled.Should().BeTrue("the warning event should have been called");
infoCalled.Should().BeTrue("the info event should have been called");
debugCalled.Should().BeTrue("the debug event should have been called");
traceCalled.Should().BeTrue("the trace event should have been called");
}
#endregion
}
| |
// ------------------------------------------------------------------------------
// 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.
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 ReferenceAttachmentRequest.
/// </summary>
public partial class ReferenceAttachmentRequest : BaseRequest, IReferenceAttachmentRequest
{
/// <summary>
/// Constructs a new ReferenceAttachmentRequest.
/// </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 ReferenceAttachmentRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified ReferenceAttachment using POST.
/// </summary>
/// <param name="referenceAttachmentToCreate">The ReferenceAttachment to create.</param>
/// <returns>The created ReferenceAttachment.</returns>
public System.Threading.Tasks.Task<ReferenceAttachment> CreateAsync(ReferenceAttachment referenceAttachmentToCreate)
{
return this.CreateAsync(referenceAttachmentToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified ReferenceAttachment using POST.
/// </summary>
/// <param name="referenceAttachmentToCreate">The ReferenceAttachment to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ReferenceAttachment.</returns>
public async System.Threading.Tasks.Task<ReferenceAttachment> CreateAsync(ReferenceAttachment referenceAttachmentToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<ReferenceAttachment>(referenceAttachmentToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified ReferenceAttachment.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified ReferenceAttachment.
/// </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<ReferenceAttachment>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified ReferenceAttachment.
/// </summary>
/// <returns>The ReferenceAttachment.</returns>
public System.Threading.Tasks.Task<ReferenceAttachment> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified ReferenceAttachment.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The ReferenceAttachment.</returns>
public async System.Threading.Tasks.Task<ReferenceAttachment> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<ReferenceAttachment>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified ReferenceAttachment using PATCH.
/// </summary>
/// <param name="referenceAttachmentToUpdate">The ReferenceAttachment to update.</param>
/// <returns>The updated ReferenceAttachment.</returns>
public System.Threading.Tasks.Task<ReferenceAttachment> UpdateAsync(ReferenceAttachment referenceAttachmentToUpdate)
{
return this.UpdateAsync(referenceAttachmentToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified ReferenceAttachment using PATCH.
/// </summary>
/// <param name="referenceAttachmentToUpdate">The ReferenceAttachment to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated ReferenceAttachment.</returns>
public async System.Threading.Tasks.Task<ReferenceAttachment> UpdateAsync(ReferenceAttachment referenceAttachmentToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<ReferenceAttachment>(referenceAttachmentToUpdate, 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 IReferenceAttachmentRequest 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 IReferenceAttachmentRequest Expand(Expression<Func<ReferenceAttachment, 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 IReferenceAttachmentRequest 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 IReferenceAttachmentRequest Select(Expression<Func<ReferenceAttachment, 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="referenceAttachmentToInitialize">The <see cref="ReferenceAttachment"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(ReferenceAttachment referenceAttachmentToInitialize)
{
}
}
}
| |
// 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 Fixtures.Azure.AcceptanceTestsAzureParameterGrouping
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ParameterGroupingOperations operations.
/// </summary>
internal partial class ParameterGroupingOperations : Microsoft.Rest.IServiceOperations<AutoRestParameterGroupingTestService>, IParameterGroupingOperations
{
/// <summary>
/// Initializes a new instance of the ParameterGroupingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ParameterGroupingOperations(AutoRestParameterGroupingTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestParameterGroupingTestService
/// </summary>
public AutoRestParameterGroupingTestService Client { get; private set; }
/// <summary>
/// Post a bunch of required parameters grouped
/// </summary>
/// <param name='parameterGroupingPostRequiredParameters'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostRequiredWithHttpMessagesAsync(ParameterGroupingPostRequiredParametersInner parameterGroupingPostRequiredParameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (parameterGroupingPostRequiredParameters == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameterGroupingPostRequiredParameters");
}
if (parameterGroupingPostRequiredParameters != null)
{
parameterGroupingPostRequiredParameters.Validate();
}
int body = default(int);
if (parameterGroupingPostRequiredParameters != null)
{
body = parameterGroupingPostRequiredParameters.Body;
}
string customHeader = default(string);
if (parameterGroupingPostRequiredParameters != null)
{
customHeader = parameterGroupingPostRequiredParameters.CustomHeader;
}
int? query = default(int?);
if (parameterGroupingPostRequiredParameters != null)
{
query = parameterGroupingPostRequiredParameters.Query;
}
string path = default(string);
if (parameterGroupingPostRequiredParameters != null)
{
path = parameterGroupingPostRequiredParameters.Path;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("customHeader", customHeader);
tracingParameters.Add("query", query);
tracingParameters.Add("path", path);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostRequired", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postRequired/{path}").ToString();
_url = _url.Replace("{path}", System.Uri.EscapeDataString(path));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (query != null)
{
_queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeader != null)
{
if (_httpRequest.Headers.Contains("customHeader"))
{
_httpRequest.Headers.Remove("customHeader");
}
_httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader);
}
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;
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.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)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_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)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post a bunch of optional parameters grouped
/// </summary>
/// <param name='parameterGroupingPostOptionalParameters'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostOptionalWithHttpMessagesAsync(ParameterGroupingPostOptionalParametersInner parameterGroupingPostOptionalParameters = default(ParameterGroupingPostOptionalParametersInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
string customHeader = default(string);
if (parameterGroupingPostOptionalParameters != null)
{
customHeader = parameterGroupingPostOptionalParameters.CustomHeader;
}
int? query = default(int?);
if (parameterGroupingPostOptionalParameters != null)
{
query = parameterGroupingPostOptionalParameters.Query;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("customHeader", customHeader);
tracingParameters.Add("query", query);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostOptional", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postOptional").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (query != null)
{
_queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeader != null)
{
if (_httpRequest.Headers.Contains("customHeader"))
{
_httpRequest.Headers.Remove("customHeader");
}
_httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_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)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post parameters from multiple different parameter groups
/// </summary>
/// <param name='firstParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='parameterGroupingPostMultiParamGroupsSecondParamGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostMultiParamGroupsWithHttpMessagesAsync(FirstParameterGroupInner firstParameterGroup = default(FirstParameterGroupInner), ParameterGroupingPostMultiParamGroupsSecondParamGroupInner parameterGroupingPostMultiParamGroupsSecondParamGroup = default(ParameterGroupingPostMultiParamGroupsSecondParamGroupInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
string headerOne = default(string);
if (firstParameterGroup != null)
{
headerOne = firstParameterGroup.HeaderOne;
}
int? queryOne = default(int?);
if (firstParameterGroup != null)
{
queryOne = firstParameterGroup.QueryOne;
}
string headerTwo = default(string);
if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null)
{
headerTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.HeaderTwo;
}
int? queryTwo = default(int?);
if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null)
{
queryTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.QueryTwo;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("headerOne", headerOne);
tracingParameters.Add("queryOne", queryOne);
tracingParameters.Add("headerTwo", headerTwo);
tracingParameters.Add("queryTwo", queryTwo);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostMultiParamGroups", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postMultipleParameterGroups").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (queryOne != null)
{
_queryParameters.Add(string.Format("query-one={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryOne, this.Client.SerializationSettings).Trim('"'))));
}
if (queryTwo != null)
{
_queryParameters.Add(string.Format("query-two={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryTwo, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (headerOne != null)
{
if (_httpRequest.Headers.Contains("header-one"))
{
_httpRequest.Headers.Remove("header-one");
}
_httpRequest.Headers.TryAddWithoutValidation("header-one", headerOne);
}
if (headerTwo != null)
{
if (_httpRequest.Headers.Contains("header-two"))
{
_httpRequest.Headers.Remove("header-two");
}
_httpRequest.Headers.TryAddWithoutValidation("header-two", headerTwo);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_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)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post parameters with a shared parameter group object
/// </summary>
/// <param name='firstParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostSharedParameterGroupObjectWithHttpMessagesAsync(FirstParameterGroupInner firstParameterGroup = default(FirstParameterGroupInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
string headerOne = default(string);
if (firstParameterGroup != null)
{
headerOne = firstParameterGroup.HeaderOne;
}
int? queryOne = default(int?);
if (firstParameterGroup != null)
{
queryOne = firstParameterGroup.QueryOne;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("headerOne", headerOne);
tracingParameters.Add("queryOne", queryOne);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostSharedParameterGroupObject", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/sharedParameterGroupObject").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (queryOne != null)
{
_queryParameters.Add(string.Format("query-one={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryOne, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (headerOne != null)
{
if (_httpRequest.Headers.Contains("header-one"))
{
_httpRequest.Headers.Remove("header-one");
}
_httpRequest.Headers.TryAddWithoutValidation("header-one", headerOne);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_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)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="HealthMonitoringSection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Configuration {
using System;
using System.Xml;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using System.ComponentModel;
using System.Web.Hosting;
using System.Web.Util;
using System.Web.Configuration;
using System.Web.Management;
using System.Web.Compilation;
using System.Security.Permissions;
/*
<!--
healthMonitoring attributes:
heartbeatInterval="[seconds]" - A non-negative integer in seconds that details how often the WebHeartbeatEvent is raised
by each application domain. Zero means no heart beat event is fired.
-->
<healthMonitoring
enabled="true"
heartbeatInterval="0">
<bufferModes>
<add name="Critical Notification"
maxBufferSize="100"
maxFlushSize="20"
urgentFlushThreshold="1"
regularFlushInterval="Infinite"
urgentFlushInterval="00:01:00"
maxBufferThreads="1"
/>
<add name="Notification"
maxBufferSize="300"
maxFlushSize="20"
urgentFlushThreshold="1"
regularFlushInterval="Infinite"
urgentFlushInterval="00:01:00"
maxBufferThreads="1"
/>
<add name="Analysis"
maxBufferSize="1000"
maxFlushSize="100"
urgentFlushThreshold="100"
regularFlushInterval="00:05:00"
urgentFlushInterval="00:01:00"
maxBufferThreads="1"
/>
<add name="Logging"
maxBufferSize="1000"
maxFlushSize="200"
urgentFlushThreshold="800"
regularFlushInterval="00:30:00"
urgentFlushInterval="00:05:00"
maxBufferThreads="1"
/>
</bufferModes>
<!--
providers attributes:
name - Friendly name of the provider.
type - A class that implements IProvider. The value is a fully qualified reference to an assembly.
Other name/value pairs - Additional name value pairs may be present. It is the responsibility of the provider to
understand those values.
-->
<providers>
<!--
<add name="SqlWebEventProvider"
type="System.Web.Management.SqlWebEventProvider,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%"
connectionStringName="Name corresponding to the entry in <connectionStrings> section where the connection string for the provider is specified"
maxEventDetailsLength="Maximum number of characters allowed to be logged in the Details column in the SQL table. Default is no limit."
buffer="true|false (default is false)"
bufferMode="name of the buffer mode to use if buffer is set to true"
/>
<add name="SimpleMailWebEventProvider"
type="System.Web.Management.SimpleMailWebEventProvider,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%"
from="sender address"
to="semi-colon separated to addresses"
cc="semi-colon separated cc addresses"
bcc="semi-colon separated bcc addresses"
priority="High|Normal|Low (default is Normal)"
bodyHeader="Text added at the top of a message (optional)"
bodyFooter="Text added at the bottom of a message (optional)"
subjectPrefix="Text added at the beginning of the subject (optional)"
buffer="true|false (default is true)"
bufferMode="name of the buffer mode to use if buffer is set to true"
maxEventLength="Maximum number of characters allowed for each event in a message (optional) (default is 8K characters)"
maxEventsPerMessage="Maximum number of events allowed for in each message (optional) (default is 50)"
maxMessagesPerNotification="Maximum number of messages allowed for each notification (optional) (default is 10)"
/>
<add name="TemplatedMailWebEventProvider"
type="System.Web.Management.TemplatedMailWebEventProvider,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%"
from="sender address"
to="semi-colon separated to addresses"
cc="semi-colon separated cc addresses"
bcc="semi-colon separated bcc addresses"
priority="High|Normal|Low (default is Normal)"
subjectPrefix="Text added at the beginning of the subject (optional)"
template="The template page (.aspx) that will be used to create the message body for each notification"
detailedTemplateErrors="true|false (default is false)"
buffer="true|false (default is true)"
bufferMode="name of the buffer mode to use if buffer is set to true"
maxEventsPerMessage="Maximum number of events allowed for in each message (optional) (default is 50)"
maxMessagesPerNotification="Maximum number of messages allowed for each notification (optional) (default is 100)"
/>
-->
<add name="EventLogProvider"
type="System.Web.Management.EventLogWebEventProvider,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%"
/>
<add name="SqlWebEventProvider"
type="System.Web.Management.SqlWebEventProvider,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%"
connectionStringName="LocalSqlServer"
maxEventDetailsLength="1073741823"
buffer="false"
bufferMode="Notification"
/>
<add name="WmiWebEventProvider"
type="System.Web.Management.WmiWebEventProvider,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%"
/>
</providers>
<!--
eventMappings attributes:
name - The friendly name of the event class.
type - The type of the event class. This can be the type of a parent class.
startEventCode - The starting event code range. Default is 0.
endEventCode - The ending event code range. Default is Int32.MaxValue.
-->
<eventMappings>
<add name="All Events"
type="System.Web.Management.WebBaseEvent,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%" />
<add name="Heartbeats"
type="System.Web.Management.WebHeartbeatEvent,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%" />
<add name="Application Lifetime Events"
type="System.Web.Management.WebApplicationLifetimeEvent,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%" />
<add name="Request Processing Events"
type="System.Web.Management.WebRequestEvent,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%" />
<add name="All Errors"
type="System.Web.Management.WebBaseErrorEvent,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%" />
<add name="Infrastructure Errors"
type="System.Web.Management.WebErrorEvent,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%" />
<add name="Request Processing Errors"
type="System.Web.Management.WebRequestErrorEvent,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%" />
<add name="All Audits"
type="System.Web.Management.WebAuditEvent,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%" />
<add name="Failure Audits"
type="System.Web.Management.WebFailureAuditEvent,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%" />
<add name="Success Audits"
type="System.Web.Management.WebSuccessAuditEvent,System.Web,Version=%ASSEMBLY_VERSION%,Culture=neutral,PublicKeyToken=%MICROSOFT_PUBLICKEY%" />
</eventMappings>
<!--
profiles attributes:
The scope of the following attributes is per application domain.
minInstances="[number]" - It is the minimum number of occurences of each event before it's fired.
E.g. a value of 5 means that ASP.NET will not fire the event until the 5th
instance of the event is raised. A value of 0 is invalid. Default is 1.
maxLimit="[Infinite|number]" - It is the threshold after which events stop being fired. E.g. a value
of 10 means ASP.NET will stop firing the event after the 10th events
have been raised. Default is Infinite.
minInterval="[Infinite|HH:MM:SS]" - It is a time interval that details the minimum duration between firing two events
of the same type. E.g. A value of "00:01:00" means at most one event of a given
type will be thrown per minute. 00:00:00 means there is no minimum interval.
Default is 00:00:00.
custom="[type]" - It is the type of a custom class that implements System.Web.Management.IWebEventCustomEvaluator.
-->
<profiles>
<add name="Default"
minInstances="1"
maxLimit="Infinite"
minInterval="00:01:00"
/>
<add name="Critical"
minInstances="1"
maxLimit="Infinite"
minInterval="00:00:00"
/>
</profiles>
<!--
rules attributes:
<rules>
<add
name="stinrg" The name of the rule.
eventName="string" The name of the event type, as specified in <healthEventNames>.
profile="string" (Optional) The name of the profile for the event type, as specified in <healthProfiles>.
provider="provider" The name of the provider to be used by the event type.
The same <healthProfiles> attributes can also be specified to override specific settings in the profile.
/>
<remove Remove an entry
name="string" /> Name of the entry
<clear/> Remove all entries
</rules>
-->
<rules>
<add name="All Errors Default"
eventName="All Errors"
provider="EventLogProvider"
profile="Default"
minInterval="00:01:00" />
<add name="Failure Audits Default"
eventName="Failure Audits"
provider="EventLogProvider"
profile="Default"
minInterval="00:01:00" />
</rules>
</healthMonitoring>
*/
public sealed class HealthMonitoringSection : ConfigurationSection {
const int MAX_HEARTBEAT_VALUE = Int32.MaxValue / 1000; // in sec; this value will be converted to ms and passed to Timer ctor, which takes a ms param
const bool DEFAULT_HEALTH_MONITORING_ENABLED = true;
const int DEFAULT_HEARTBEATINTERVAL = 0; // This was Zero in Machine.config and 60 in here
private static ConfigurationPropertyCollection _properties;
private static readonly ConfigurationProperty _propHeartbeatInterval =
new ConfigurationProperty("heartbeatInterval",
typeof(TimeSpan),
TimeSpan.FromSeconds((long)DEFAULT_HEARTBEATINTERVAL),
StdValidatorsAndConverters.TimeSpanSecondsConverter,
new TimeSpanValidator(TimeSpan.Zero, TimeSpan.FromSeconds(MAX_HEARTBEAT_VALUE)),
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propEnabled =
new ConfigurationProperty("enabled",
typeof(bool),
DEFAULT_HEALTH_MONITORING_ENABLED,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propBufferModes =
new ConfigurationProperty("bufferModes",
typeof(BufferModesCollection),
null,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propProviders =
new ConfigurationProperty("providers",
typeof(ProviderSettingsCollection),
null,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propProfileSettingsCollection =
new ConfigurationProperty("profiles",
typeof(ProfileSettingsCollection),
null,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propRuleSettingsCollection =
new ConfigurationProperty("rules",
typeof(RuleSettingsCollection),
null,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propEventMappingSettingsCollection =
new ConfigurationProperty("eventMappings",
typeof(EventMappingSettingsCollection),
null,
ConfigurationPropertyOptions.None);
static HealthMonitoringSection() {
// Property initialization
_properties = new ConfigurationPropertyCollection();
_properties.Add(_propHeartbeatInterval);
_properties.Add(_propEnabled);
_properties.Add(_propBufferModes);
_properties.Add(_propProviders);
_properties.Add(_propProfileSettingsCollection);
_properties.Add(_propRuleSettingsCollection);
_properties.Add(_propEventMappingSettingsCollection);
}
public HealthMonitoringSection() {
}
protected override ConfigurationPropertyCollection Properties {
get {
return _properties;
}
}
[ConfigurationProperty("heartbeatInterval", DefaultValue = "00:00:00" /* DEFAULT_HEARTBEATINTERVAL */)]
[TypeConverter(typeof(TimeSpanSecondsConverter))]
[TimeSpanValidator(MinValueString = "00:00:00", MaxValueString = "24.20:31:23")]
public TimeSpan HeartbeatInterval {
get {
return (TimeSpan)base[_propHeartbeatInterval];
}
set {
base[_propHeartbeatInterval] = value;
}
}
[ConfigurationProperty("enabled", DefaultValue = DEFAULT_HEALTH_MONITORING_ENABLED)]
public bool Enabled {
get {
return (bool)base[_propEnabled];
}
set {
base[_propEnabled] = value;
}
}
[ConfigurationProperty("bufferModes")]
public BufferModesCollection BufferModes {
get {
return (BufferModesCollection)base[_propBufferModes];
}
}
[ConfigurationProperty("providers")]
public ProviderSettingsCollection Providers {
get {
return (ProviderSettingsCollection)base[_propProviders];
}
}
[ConfigurationProperty("profiles")]
public ProfileSettingsCollection Profiles {
get {
return (ProfileSettingsCollection)base[_propProfileSettingsCollection];
}
}
[ConfigurationProperty("rules")]
public RuleSettingsCollection Rules {
get {
return (RuleSettingsCollection)base[_propRuleSettingsCollection];
}
}
[ConfigurationProperty("eventMappings")]
public EventMappingSettingsCollection EventMappings {
get {
return (EventMappingSettingsCollection)base[_propEventMappingSettingsCollection];
}
}
} // class HealthMonitoringSection
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using EPiServer;
using EPiServer.Configuration;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Filters;
using EPiServer.Logging;
using EPiServer.ServiceLocation;
using EPiServer.Web;
namespace EPiBootstrapArea.SampleWeb.Business.ContentProviders
{
/// <summary>
/// Used to clone a part of the page tree
/// </summary>
/// <remarks>The current implementation only supports cloning of <see cref="PageData"/> content</remarks>
/// <code>
/// // Example of programmatically registering a cloned content provider
///
/// var rootPageOfContentToClone = new PageReference(10);
///
/// var pageWhereClonedContentShouldAppear = new PageReference(20);
///
/// var provider = new ClonedContentProvider(rootPageOfContentToClone, pageWhereClonedContentShouldAppear);
///
/// var providerManager = ServiceLocator.Current.GetInstance<IContentProviderManager>();
///
/// providerManager.ProviderMap.AddProvider(provider);
/// </code>
public class ClonedContentProvider : ContentProvider, IPageCriteriaQueryService
{
private static readonly ILogger Logger = LogManager.GetLogger();
private readonly NameValueCollection _parameters = new NameValueCollection(1);
public ClonedContentProvider(PageReference cloneRoot, PageReference entryRoot) : this(cloneRoot, entryRoot, null) { }
public ClonedContentProvider(PageReference cloneRoot, PageReference entryRoot, CategoryList categoryFilter)
{
if (cloneRoot.CompareToIgnoreWorkID(entryRoot))
{
throw new NotSupportedException("Entry root and clone root cannot be set to the same content reference");
}
if (ServiceLocator.Current.GetInstance<IContentLoader>().GetChildren<IContent>(entryRoot).Any())
{
throw new NotSupportedException("Unable to create ClonedContentProvider, the EntryRoot property must point to leaf content (without children)");
}
CloneRoot = cloneRoot;
EntryRoot = entryRoot;
Category = categoryFilter;
// Set the entry point parameter
Parameters.Add(ContentProviderElement.EntryPointString, EntryRoot.ID.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Clones a page to make it appear to come from where the content provider is attached
/// </summary>
private PageData ClonePage(PageData originalPage)
{
if (originalPage == null)
{
throw new ArgumentNullException("originalPage", "No page to clone specified");
}
Logger.Debug("Cloning page {0}...", originalPage.PageLink);
var clone = originalPage.CreateWritableClone();
// If original page was under the clone root, we make it appear to be under the entry root instead
if (originalPage.ParentLink.CompareToIgnoreWorkID(CloneRoot))
{
clone.ParentLink = EntryRoot;
}
// All pages but the entry root should appear to come from this content provider
if (!clone.PageLink.CompareToIgnoreWorkID(EntryRoot))
{
clone.ContentLink.ProviderName = ProviderKey;
}
// Unless the parent is the entry root, it should appear to come from this content provider
if (!clone.ParentLink.CompareToIgnoreWorkID(EntryRoot))
{
var parentLinkClone = clone.ParentLink.CreateWritableClone();
parentLinkClone.ProviderName = ProviderKey;
clone.ParentLink = parentLinkClone;
}
// This is integral to map the cloned page to this content provider
clone.LinkURL = ConstructContentUri(originalPage.PageTypeID, clone.ContentLink, clone.ContentGuid).ToString();
return clone;
}
/// <summary>
/// Filters out content references to content that does not match current category filters, if any
/// </summary>
/// <param name="contentReferences"></param>
/// <returns></returns>
private IList<T> FilterByCategory<T>(IEnumerable<T> contentReferences)
{
if (Category == null || !Category.Any())
{
return contentReferences.ToList();
}
// Filter by category if a category filter has been set
var filteredChildren = new List<T>();
foreach (var contentReference in contentReferences)
{
ICategorizable content = null;
if (contentReference is ContentReference)
{
content = (contentReference as ContentReference).Get<IContent>() as ICategorizable;
} else if (typeof(T) == typeof(GetChildrenReferenceResult))
{
content = (contentReference as GetChildrenReferenceResult).ContentLink.Get<IContent>() as ICategorizable;
}
if (content != null)
{
var atLeastOneMatchingCategory = content.Category.Any(c => Category.Contains(c));
if (atLeastOneMatchingCategory)
{
filteredChildren.Add(contentReference);
}
}
else // Non-categorizable content will also be included
{
filteredChildren.Add(contentReference);
}
}
return filteredChildren;
}
protected override IContent LoadContent(ContentReference contentLink, ILanguageSelector languageSelector)
{
if (ContentReference.IsNullOrEmpty(contentLink) || contentLink.ID == 0)
{
throw new ArgumentNullException("contentLink");
}
if (contentLink.WorkID > 0)
{
return ContentStore.LoadVersion(contentLink, -1);
}
var languageBranchRepository = ServiceLocator.Current.GetInstance<ILanguageBranchRepository>();
LanguageBranch langBr = null;
if (languageSelector.Language != null)
{
langBr = languageBranchRepository.Load(languageSelector.Language);
}
if (contentLink.GetPublishedOrLatest)
{
return ContentStore.LoadVersion(contentLink, langBr != null ? langBr.ID : -1);
}
// Get published version of Content
var originalContent = ContentStore.Load(contentLink, langBr != null ? langBr.ID : -1);
var page = originalContent as PageData;
if (page == null)
{
throw new NotSupportedException("Only cloning of pages is supported");
}
return ClonePage(page);
}
protected override ContentResolveResult ResolveContent(ContentReference contentLink)
{
var contentData = ContentCoreDataLoader.Service.Load(contentLink.ID);
// All pages but the entry root should appear to come from this content provider
if (!contentLink.CompareToIgnoreWorkID(EntryRoot))
{
contentData.ContentReference.ProviderName = ProviderKey;
}
var result = CreateContentResolveResult(contentData);
if (!result.ContentLink.CompareToIgnoreWorkID(EntryRoot))
{
result.ContentLink.ProviderName = ProviderKey;
}
return result;
}
protected override Uri ConstructContentUri(int contentTypeId, ContentReference contentLink, Guid contentGuid)
{
if (!contentLink.CompareToIgnoreWorkID(EntryRoot))
{
contentLink.ProviderName = ProviderKey;
}
return base.ConstructContentUri(contentTypeId, contentLink, contentGuid);
}
protected override IList<GetChildrenReferenceResult> LoadChildrenReferencesAndTypes(ContentReference contentLink, string languageID, out bool languageSpecific)
{
// If retrieving children for the entry point, we retrieve pages from the clone root
contentLink = contentLink.CompareToIgnoreWorkID(EntryRoot) ? CloneRoot : contentLink;
FilterSortOrder sortOrder;
var children = ContentStore.LoadChildrenReferencesAndTypes(contentLink.ID, languageID, out sortOrder);
languageSpecific = sortOrder == FilterSortOrder.Alphabetical;
foreach (var contentReference in children.Where(contentReference => !contentReference.ContentLink.CompareToIgnoreWorkID(EntryRoot)))
{
contentReference.ContentLink.ProviderName = ProviderKey;
}
return FilterByCategory <GetChildrenReferenceResult>(children);
}
protected override IEnumerable<IContent> LoadContents(IList<ContentReference> contentReferences, ILanguageSelector selector)
{
return contentReferences
.Select(contentReference => ClonePage(ContentLoader.Get<PageData>(contentReference.ToReferenceWithoutVersion())))
.Cast<IContent>()
.ToList();
}
protected override void SetCacheSettings(IContent content, CacheSettings cacheSettings)
{
// Make the cache of this content provider depend on the original content
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(content.ContentLink.ID)));
}
protected override void SetCacheSettings(ContentReference contentReference, IEnumerable<GetChildrenReferenceResult> children, CacheSettings cacheSettings)
{
// Make the cache of this content provider depend on the original content
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(contentReference.ID)));
foreach (var child in children)
{
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(child.ContentLink.ID)));
}
}
public override IList<ContentReference> GetDescendentReferences(ContentReference contentLink)
{
// If retrieving children for the entry point, we retrieve pages from the clone root
contentLink = contentLink.CompareToIgnoreWorkID(EntryRoot) ? CloneRoot : contentLink;
var descendents = ContentStore.ListAll(contentLink);
foreach (var contentReference in descendents.Where(contentReference => !contentReference.CompareToIgnoreWorkID(EntryRoot)))
{
contentReference.ProviderName = ProviderKey;
}
return FilterByCategory<ContentReference>(descendents);
}
public PageDataCollection FindAllPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias, string languageBranch, ILanguageSelector selector)
{
// Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
if (pageLink.CompareToIgnoreWorkID(EntryRoot))
{
pageLink = CloneRoot;
}
else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName)) // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
{
pageLink = new PageReference(pageLink.ID);
}
var pages = PageQueryService.FindAllPagesWithCriteria(pageLink, criterias, languageBranch, selector);
// Return cloned search result set
return new PageDataCollection(pages.Select(ClonePage));
}
public PageDataCollection FindPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias, string languageBranch, ILanguageSelector selector)
{
// Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
if (pageLink.CompareToIgnoreWorkID(EntryRoot))
{
pageLink = CloneRoot;
}
else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName)) // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
{
pageLink = new PageReference(pageLink.ID);
}
var pages = PageQueryService.FindPagesWithCriteria(pageLink, criterias, languageBranch, selector);
// Return cloned search result set
return new PageDataCollection(pages.Select(ClonePage));
}
/// <summary>
/// Gets the content store used to get original content
/// </summary>
protected virtual ContentStore ContentStore
{
get { return ServiceLocator.Current.GetInstance<ContentStore>(); }
}
/// <summary>
/// Gets the content loader used to get content
/// </summary>
protected virtual IContentLoader ContentLoader
{
get { return ServiceLocator.Current.GetInstance<IContentLoader>(); }
}
/// <summary>
/// Gets the service used to query for pages using criterias
/// </summary>
protected virtual IPageCriteriaQueryService PageQueryService
{
get { return ServiceLocator.Current.GetInstance<IPageCriteriaQueryService>(); }
}
/// <summary>
/// Content that should be cloned at the entry point
/// </summary>
public PageReference CloneRoot { get; protected set; }
/// <summary>
/// Gets the page where the cloned content will appear
/// </summary>
public PageReference EntryRoot { get; protected set; }
/// <summary>
/// Gets the category filters used for this content provider
/// </summary>
/// <remarks>If set, pages not matching at least one of these categories will be excluded from this content provider</remarks>
public CategoryList Category { get; protected set; }
/// <summary>
/// Gets a unique key for this content provider instance
/// </summary>
public override string ProviderKey
{
get
{
return string.Format("ClonedContent-{0}-{1}", CloneRoot.ID, EntryRoot.ID);
}
}
/// <summary>
/// Gets capabilities indicating no content editing can be performed through this provider
/// </summary>
public override ContentProviderCapabilities ProviderCapabilities { get { return ContentProviderCapabilities.Search; } }
/// <summary>
/// Gets configuration parameters for this content provider instance
/// </summary>
public override NameValueCollection Parameters { get { return _parameters; } }
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Avalonia.Platform;
using Avalonia.Platform.Interop;
using Avalonia.Utilities;
namespace Avalonia.Shared.PlatformSupport
{
static class StandardRuntimePlatformServices
{
public static void Register(Assembly assembly = null)
{
var standardPlatform = new StandardRuntimePlatform();
AssetLoader.RegisterResUriParsers();
AvaloniaLocator.CurrentMutable
.Bind<IRuntimePlatform>().ToConstant(standardPlatform)
.Bind<IAssetLoader>().ToConstant(new AssetLoader(assembly))
.Bind<IDynamicLibraryLoader>().ToConstant(
#if __IOS__
new IOSLoader()
#else
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? (IDynamicLibraryLoader)new Win32Loader()
: new UnixLoader()
#endif
);
}
}
internal partial class StandardRuntimePlatform : IRuntimePlatform
{
public IDisposable StartSystemTimer(TimeSpan interval, Action tick)
{
return new Timer(_ => tick(), null, interval, interval);
}
public IUnmanagedBlob AllocBlob(int size) => new UnmanagedBlob(this, size);
class UnmanagedBlob : IUnmanagedBlob
{
private readonly StandardRuntimePlatform _plat;
private IntPtr _address;
private readonly object _lock = new object();
#if DEBUG
private static readonly List<string> Backtraces = new List<string>();
private static Thread GCThread;
private readonly string _backtrace;
private static readonly object _btlock = new object();
class GCThreadDetector
{
~GCThreadDetector()
{
GCThread = Thread.CurrentThread;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void Spawn() => new GCThreadDetector();
static UnmanagedBlob()
{
Spawn();
GC.WaitForPendingFinalizers();
}
#endif
public UnmanagedBlob(StandardRuntimePlatform plat, int size)
{
if (size <= 0)
throw new ArgumentException("Positive number required", nameof(size));
_plat = plat;
_address = plat.Alloc(size);
GC.AddMemoryPressure(size);
Size = size;
#if DEBUG
_backtrace = Environment.StackTrace;
lock (_btlock)
Backtraces.Add(_backtrace);
#endif
}
void DoDispose()
{
lock (_lock)
{
if (!IsDisposed)
{
#if DEBUG
lock (_btlock)
Backtraces.Remove(_backtrace);
#endif
_plat?.Free(_address, Size);
GC.RemoveMemoryPressure(Size);
IsDisposed = true;
_address = IntPtr.Zero;
Size = 0;
}
}
}
public void Dispose()
{
#if DEBUG
if (Thread.CurrentThread.ManagedThreadId == GCThread?.ManagedThreadId)
{
lock (_lock)
{
if (!IsDisposed)
{
Console.Error.WriteLine("Native blob disposal from finalizer thread\nBacktrace: "
+ Environment.StackTrace
+ "\n\nBlob created by " + _backtrace);
}
}
}
#endif
DoDispose();
GC.SuppressFinalize(this);
}
~UnmanagedBlob()
{
#if DEBUG
Console.Error.WriteLine("Undisposed native blob created by " + _backtrace);
#endif
DoDispose();
}
public IntPtr Address => IsDisposed ? throw new ObjectDisposedException("UnmanagedBlob") : _address;
public int Size { get; private set; }
public bool IsDisposed { get; private set; }
}
#if NET461 || NETCOREAPP2_0
[DllImport("libc", SetLastError = true)]
private static extern IntPtr mmap(IntPtr addr, IntPtr length, int prot, int flags, int fd, IntPtr offset);
[DllImport("libc", SetLastError = true)]
private static extern int munmap(IntPtr addr, IntPtr length);
[DllImport("libc", SetLastError = true)]
private static extern long sysconf(int name);
private bool? _useMmap;
private bool UseMmap
=> _useMmap ?? ((_useMmap = GetRuntimeInfo().OperatingSystem == OperatingSystemType.Linux)).Value;
IntPtr Alloc(int size)
{
if (UseMmap)
{
var rv = mmap(IntPtr.Zero, new IntPtr(size), 3, 0x22, -1, IntPtr.Zero);
if (rv.ToInt64() == -1 || (ulong) rv.ToInt64() == 0xffffffff)
{
var errno = Marshal.GetLastWin32Error();
throw new Exception("Unable to allocate memory: " + errno);
}
return rv;
}
else
return Marshal.AllocHGlobal(size);
}
void Free(IntPtr ptr, int len)
{
if (UseMmap)
{
if (munmap(ptr, new IntPtr(len)) == -1)
{
var errno = Marshal.GetLastWin32Error();
throw new Exception("Unable to free memory: " + errno);
}
}
else
Marshal.FreeHGlobal(ptr);
}
#else
IntPtr Alloc(int size) => Marshal.AllocHGlobal(size);
void Free(IntPtr ptr, int len) => Marshal.FreeHGlobal(ptr);
#endif
}
internal class IOSLoader : IDynamicLibraryLoader
{
IntPtr IDynamicLibraryLoader.LoadLibrary(string dll)
{
throw new PlatformNotSupportedException();
}
IntPtr IDynamicLibraryLoader.GetProcAddress(IntPtr dll, string proc, bool optional)
{
throw new PlatformNotSupportedException();
}
}
public class AssetLoader : IAssetLoader
{
private const string AvaloniaResourceName = "!AvaloniaResources";
private static readonly Dictionary<string, AssemblyDescriptor> AssemblyNameCache
= new Dictionary<string, AssemblyDescriptor>();
private AssemblyDescriptor _defaultResmAssembly;
/// <summary>
/// Initializes a new instance of the <see cref="AssetLoader"/> class.
/// </summary>
/// <param name="assembly">
/// The default assembly from which to load resm: assets for which no assembly is specified.
/// </param>
public AssetLoader(Assembly assembly = null)
{
if (assembly == null)
assembly = Assembly.GetEntryAssembly();
if (assembly != null)
_defaultResmAssembly = new AssemblyDescriptor(assembly);
}
/// <summary>
/// Sets the default assembly from which to load assets for which no assembly is specified.
/// </summary>
/// <param name="assembly">The default assembly.</param>
public void SetDefaultAssembly(Assembly assembly)
{
_defaultResmAssembly = new AssemblyDescriptor(assembly);
}
/// <summary>
/// Checks if an asset with the specified URI exists.
/// </summary>
/// <param name="uri">The URI.</param>
/// <param name="baseUri">
/// A base URI to use if <paramref name="uri"/> is relative.
/// </param>
/// <returns>True if the asset could be found; otherwise false.</returns>
public bool Exists(Uri uri, Uri baseUri = null)
{
return GetAsset(uri, baseUri) != null;
}
/// <summary>
/// Opens the asset with the requested URI.
/// </summary>
/// <param name="uri">The URI.</param>
/// <param name="baseUri">
/// A base URI to use if <paramref name="uri"/> is relative.
/// </param>
/// <returns>A stream containing the asset contents.</returns>
/// <exception cref="FileNotFoundException">
/// The asset could not be found.
/// </exception>
public Stream Open(Uri uri, Uri baseUri = null) => OpenAndGetAssembly(uri, baseUri).Item1;
/// <summary>
/// Opens the asset with the requested URI and returns the asset stream and the
/// assembly containing the asset.
/// </summary>
/// <param name="uri">The URI.</param>
/// <param name="baseUri">
/// A base URI to use if <paramref name="uri"/> is relative.
/// </param>
/// <returns>
/// The stream containing the resource contents together with the assembly.
/// </returns>
/// <exception cref="FileNotFoundException">
/// The asset could not be found.
/// </exception>
public (Stream stream, Assembly assembly) OpenAndGetAssembly(Uri uri, Uri baseUri = null)
{
var asset = GetAsset(uri, baseUri);
if (asset == null)
{
throw new FileNotFoundException($"The resource {uri} could not be found.");
}
return (asset.GetStream(), asset.Assembly);
}
public Assembly GetAssembly(Uri uri, Uri baseUri)
{
if (!uri.IsAbsoluteUri && baseUri != null)
uri = new Uri(baseUri, uri);
return GetAssembly(uri).Assembly;
}
/// <summary>
/// Gets all assets of a folder and subfolders that match specified uri.
/// </summary>
/// <param name="uri">The URI.</param>
/// <param name="baseUri">Base URI that is used if <paramref name="uri"/> is relative.</param>
/// <returns>All matching assets as a tuple of the absolute path to the asset and the assembly containing the asset</returns>
public IEnumerable<Uri> GetAssets(Uri uri, Uri baseUri)
{
if (uri.IsAbsoluteUri && uri.Scheme == "resm")
{
var assembly = GetAssembly(uri);
return assembly?.Resources.Where(x => x.Key.Contains(uri.AbsolutePath))
.Select(x =>new Uri($"resm:{x.Key}?assembly={assembly.Name}")) ??
Enumerable.Empty<Uri>();
}
uri = EnsureAbsolute(uri, baseUri);
if (uri.Scheme == "avares")
{
var (asm, path) = GetResAsmAndPath(uri);
if (asm == null)
{
throw new ArgumentException(
"No default assembly, entry assembly or explicit assembly specified; " +
"don't know where to look up for the resource, try specifying assembly explicitly.");
}
if (asm?.AvaloniaResources == null)
return Enumerable.Empty<Uri>();
path = path.TrimEnd('/') + '/';
return asm.AvaloniaResources.Where(r => r.Key.StartsWith(path))
.Select(x => new Uri($"avares://{asm.Name}{x.Key}"));
}
return Enumerable.Empty<Uri>();
}
private Uri EnsureAbsolute(Uri uri, Uri baseUri)
{
if (uri.IsAbsoluteUri)
return uri;
if(baseUri == null)
throw new ArgumentException($"Relative uri {uri} without base url");
if (!baseUri.IsAbsoluteUri)
throw new ArgumentException($"Base uri {baseUri} is relative");
if (baseUri.Scheme == "resm")
throw new ArgumentException(
$"Relative uris for 'resm' scheme aren't supported; {baseUri} uses resm");
return new Uri(baseUri, uri);
}
private IAssetDescriptor GetAsset(Uri uri, Uri baseUri)
{
if (uri.IsAbsoluteUri && uri.Scheme == "resm")
{
var asm = GetAssembly(uri) ?? GetAssembly(baseUri) ?? _defaultResmAssembly;
if (asm == null)
{
throw new ArgumentException(
"No default assembly, entry assembly or explicit assembly specified; " +
"don't know where to look up for the resource, try specifying assembly explicitly.");
}
IAssetDescriptor rv;
var resourceKey = uri.AbsolutePath;
asm.Resources.TryGetValue(resourceKey, out rv);
return rv;
}
uri = EnsureAbsolute(uri, baseUri);
if (uri.Scheme == "avares")
{
var (asm, path) = GetResAsmAndPath(uri);
if (asm.AvaloniaResources == null)
return null;
asm.AvaloniaResources.TryGetValue(path, out var desc);
return desc;
}
throw new ArgumentException($"Unsupported url type: " + uri.Scheme, nameof(uri));
}
private (AssemblyDescriptor asm, string path) GetResAsmAndPath(Uri uri)
{
var asm = GetAssembly(uri.Authority);
return (asm, uri.AbsolutePath);
}
private AssemblyDescriptor GetAssembly(Uri uri)
{
if (uri != null)
{
if (!uri.IsAbsoluteUri)
return null;
if (uri.Scheme == "avares")
return GetResAsmAndPath(uri).asm;
if (uri.Scheme == "resm")
{
var qs = ParseQueryString(uri);
string assemblyName;
if (qs.TryGetValue("assembly", out assemblyName))
{
return GetAssembly(assemblyName);
}
}
}
return null;
}
private AssemblyDescriptor GetAssembly(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
AssemblyDescriptor rv;
if (!AssemblyNameCache.TryGetValue(name, out rv))
{
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
var match = loadedAssemblies.FirstOrDefault(a => a.GetName().Name == name);
if (match != null)
{
AssemblyNameCache[name] = rv = new AssemblyDescriptor(match);
}
else
{
// iOS does not support loading assemblies dynamically!
//
#if __IOS__
throw new InvalidOperationException(
$"Assembly {name} needs to be referenced and explicitly loaded before loading resources");
#else
name = Uri.UnescapeDataString(name);
AssemblyNameCache[name] = rv = new AssemblyDescriptor(Assembly.Load(name));
#endif
}
}
return rv;
}
private Dictionary<string, string> ParseQueryString(Uri uri)
{
return uri.Query.TrimStart('?')
.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Split('='))
.ToDictionary(p => p[0], p => p[1]);
}
private interface IAssetDescriptor
{
Stream GetStream();
Assembly Assembly { get; }
}
private class AssemblyResourceDescriptor : IAssetDescriptor
{
private readonly Assembly _asm;
private readonly string _name;
public AssemblyResourceDescriptor(Assembly asm, string name)
{
_asm = asm;
_name = name;
}
public Stream GetStream()
{
return _asm.GetManifestResourceStream(_name);
}
public Assembly Assembly => _asm;
}
private class AvaloniaResourceDescriptor : IAssetDescriptor
{
private readonly int _offset;
private readonly int _length;
public Assembly Assembly { get; }
public AvaloniaResourceDescriptor(Assembly asm, int offset, int length)
{
_offset = offset;
_length = length;
Assembly = asm;
}
public Stream GetStream()
{
return new SlicedStream(Assembly.GetManifestResourceStream(AvaloniaResourceName), _offset, _length);
}
}
class SlicedStream : Stream
{
private readonly Stream _baseStream;
private readonly int _from;
public SlicedStream(Stream baseStream, int from, int length)
{
Length = length;
_baseStream = baseStream;
_from = from;
_baseStream.Position = from;
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
return _baseStream.Read(buffer, offset, (int)Math.Min(count, Length - Position));
}
public override long Seek(long offset, SeekOrigin origin)
{
if (origin == SeekOrigin.Begin)
Position = offset;
if (origin == SeekOrigin.End)
Position = _from + Length + offset;
if (origin == SeekOrigin.Current)
Position = Position + offset;
return Position;
}
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override bool CanRead => true;
public override bool CanSeek => _baseStream.CanRead;
public override bool CanWrite => false;
public override long Length { get; }
public override long Position
{
get => _baseStream.Position - _from;
set => _baseStream.Position = value + _from;
}
protected override void Dispose(bool disposing)
{
if (disposing)
_baseStream.Dispose();
}
public override void Close() => _baseStream.Close();
}
private class AssemblyDescriptor
{
public AssemblyDescriptor(Assembly assembly)
{
Assembly = assembly;
if (assembly != null)
{
Resources = assembly.GetManifestResourceNames()
.ToDictionary(n => n, n => (IAssetDescriptor)new AssemblyResourceDescriptor(assembly, n));
Name = assembly.GetName().Name;
using (var resources = assembly.GetManifestResourceStream(AvaloniaResourceName))
{
if (resources != null)
{
Resources.Remove(AvaloniaResourceName);
var indexLength = new BinaryReader(resources).ReadInt32();
var index = AvaloniaResourcesIndexReaderWriter.Read(new SlicedStream(resources, 4, indexLength));
var baseOffset = indexLength + 4;
AvaloniaResources = index.ToDictionary(r => "/" + r.Path.TrimStart('/'), r => (IAssetDescriptor)
new AvaloniaResourceDescriptor(assembly, baseOffset + r.Offset, r.Size));
}
}
}
}
public Assembly Assembly { get; }
public Dictionary<string, IAssetDescriptor> Resources { get; }
public Dictionary<string, IAssetDescriptor> AvaloniaResources { get; }
public string Name { get; }
}
public static void RegisterResUriParsers()
{
if (!UriParser.IsKnownScheme("avares"))
UriParser.Register(new GenericUriParser(
GenericUriParserOptions.GenericAuthority |
GenericUriParserOptions.NoUserInfo |
GenericUriParserOptions.NoPort |
GenericUriParserOptions.NoQuery |
GenericUriParserOptions.NoFragment), "avares", -1);
}
}
}
| |
using Aspose.Email.Live.Demos.UI.Helpers;
using Aspose.Email.Live.Demos.UI.Models;
using Aspose.Email.Storage.Mbox;
using Aspose.Email.Storage.Pst;
using Aspose.Words;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Linq;
namespace Aspose.Email.Live.Demos.UI.Services.Email
{
public partial class EmailService
{
public void Parse(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
var ext = Path.GetExtension(shortResourceNameWithExtension);
switch (ext.ToLowerInvariant())
{
case ".eml":
case ".msg": ParseEmlOrMsg(input, shortResourceNameWithExtension, handler); break;
case ".mbox": ParseMbox(input, shortResourceNameWithExtension, handler); break;
case ".ost":
case ".pst": ParseOstOrPst(input, shortResourceNameWithExtension, handler); break;
default:
throw new NotSupportedException($"Input type not supported {ext?.ToUpperInvariant()}");
}
}
public FileDataResult ParseFileData(Stream input)
{
var result = new FileDataResult();
using (var mail = MapiHelper.GetMapiMessageFromStream(input))
{
result.Html = mail.BodyHtml;
// May there are only 3 attachments if the Aspose.Email license has expired
// Renew the license to fix it
if (mail.Attachments != null)
result.Attachments = mail.Attachments.Select(x => new FileAttachment()
{
Name = x.FileName,
Size = x.BinaryData?.Length.ToString() ?? "---",
Source = x.BinaryData,
Type = GetFileTypeByExtension(Path.GetExtension(x.FileName)),
Extension = Path.GetExtension(x.FileName)?.ToLowerInvariant()
}).ToArray();
}
return result;
}
private string GetFileTypeByExtension(string extension)
{
switch (extension?.ToLowerInvariant())
{
case ".eml": return "Mail Message";
case ".msg": return "Mail Message";
case ".mbox": return "Message Box";
case ".ost": return "Open Storage";
case ".pst": return "Personal Storage";
case ".pdf": return "Pdf";
case ".pptx": return "Presentation";
case ".ppt": return "Presentation";
case ".odt": return "Document";
case ".ott": return "Document";
case ".dotx": return "Document";
case ".dotm": return "Document";
case ".docx": return "Document";
case ".docm": return "Document";
case ".doc": return "Document";
case ".rtf": return "Document";
case ".txt": return "Text";
case ".jpg": return "Image";
case ".jpeg": return "Image";
case ".png": return "Image";
case ".tiff": return "Image";
case ".bmp": return "Image";
case ".tga": return "Image";
case ".svg": return "Image";
case ".ico": return "Image";
case ".xls": return "Table";
default:
return "File";
}
}
public void ExtractAttachments(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
var ext = Path.GetExtension(shortResourceNameWithExtension);
switch (ext.ToLowerInvariant())
{
case ".eml":
case ".msg": ExtractAttachmentsFromEmlOrMsg(input, shortResourceNameWithExtension, handler); break;
case ".mbox": ExtractAttachmentsFromMbox(input, shortResourceNameWithExtension, handler); break;
case ".ost":
case ".pst": ExtractAttachmentsFromOstOrPst(input, shortResourceNameWithExtension, handler); break;
default:
throw new NotSupportedException($"Input type not supported {ext?.ToUpperInvariant()}");
}
}
void ParseEmlOrMsg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var mail = MapiHelper.GetMapiMessageFromStream(input))
{
if (mail.Body != null)
using (var output = handler.CreateOutputStream(Path.ChangeExtension(shortResourceNameWithExtension, ".txt")))
using (var writer = new StreamWriter(output))
writer.Write(mail.Body);
if (mail.BodyRtf != null)
using (var output = handler.CreateOutputStream(Path.ChangeExtension(shortResourceNameWithExtension, ".rtf")))
using (var writer = new StreamWriter(output))
writer.Write(mail.BodyRtf);
if (mail.BodyHtml != null)
using (var output = handler.CreateOutputStream(Path.ChangeExtension(shortResourceNameWithExtension, ".html")))
using (var writer = new StreamWriter(output))
writer.Write(mail.BodyHtml);
if (mail.Attachments != null)
foreach (var attachment in mail.Attachments)
{
using (var output = handler.CreateOutputStream(Path.GetFileName(attachment.LongFileName)))
attachment.Save(output);
}
}
}
void ParseMbox(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
Convert(input, shortResourceNameWithExtension, handler, ".msg");
}
void ParseOstOrPst(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
Convert(input, shortResourceNameWithExtension, handler, ".msg");
}
private void ExtractAttachmentsFromEmlOrMsg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var mail = MapiHelper.GetMapiMessageFromStream(input))
{
if (mail.Attachments != null)
foreach (var attachment in mail.Attachments)
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension+"_"+Path.GetFileName(attachment.LongFileName)))
attachment.Save(output);
}
}
}
private void ExtractAttachmentsFromMbox(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var reader = new MboxrdStorageReader(input, false))
{
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
{
var message = reader.ReadNextMessage();
foreach (var attachment in message.Attachments)
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_" + Path.GetFileName(attachment.Name)))
attachment.Save(output);
}
}
}
}
private void ExtractAttachmentsFromOstOrPst(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var personalStorage = PersonalStorage.FromStream(input))
{
HandleFolderAndSubfolders(mapiMessage =>
{
foreach (var attachment in mapiMessage.Attachments)
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_" + Path.GetFileName(attachment.LongFileName)))
attachment.Save(output);
}
}, personalStorage.RootFolder);
}
}
public void ExtractAttachmentsAsJpgImages(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
var ext = Path.GetExtension(shortResourceNameWithExtension);
switch (ext.ToLowerInvariant())
{
case ".eml":
case ".msg": ExtractAttachmentsAsJpgFromEmlOrMsg(input, shortResourceNameWithExtension, handler); break;
case ".mbox": ExtractAttachmentsAsJpgFromMbox(input, shortResourceNameWithExtension, handler); break;
case ".ost":
case ".pst": ExtractAttachmentsAsJpgFromOstOrPst(input, shortResourceNameWithExtension, handler); break;
default:
throw new NotSupportedException($"Input type not supported {ext?.ToUpperInvariant()}");
}
}
private void ExtractAttachmentsAsJpgFromEmlOrMsg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var mail = MapiHelper.GetMailMessageFromStream(input))
{
if (mail.Attachments != null)
{
foreach (var attachment in mail.Attachments)
{
var type = attachment.ContentType.MediaType;
START:
switch (type)
{
case "message/rfc822":
case "ost":
case "pst":
case "mbox":
case "eml":
case "msg":
{
var ms = new MemoryStream();
attachment.Save(ms);
ms.Position = 0;
var name = Path.GetFileName(attachment.Name);
if (attachment.ContentType.MediaType == "message/rfc822")
name += ".msg";
Convert(ms, name, handler, "jpg");
break;
}
case "png":
case "jpg":
case "jpeg":
case "tiff":
case "bmp":
case "svg":
{
using (var output = handler.CreateOutputStream(attachment.Name))
attachment.Save(output);
break;
}
case "application/vnd.ms-outlook":
case "application/octet-stream":
{
var extension = Path.GetExtension(attachment.ContentType.Name)?.ToLowerInvariant();
if (extension.IsNullOrWhiteSpace())
break;
else
{
type = extension.Substring(1);
goto START;
}
}
case "text/plain":
case "application/msword":
default:
{
try
{
var ms = new MemoryStream();
attachment.Save(ms);
ms.Position = 0;
var document = new Document(ms);
var saveOptions = new Aspose.Words.Saving.ImageSaveOptions(SaveFormat.Jpeg);
if (document.PageCount == 1)
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_" + attachment.Name, ".jpg"))
document.Save(output, saveOptions);
}
else
{
for (int i = 0; i < document.PageCount; i++)
{
saveOptions.PageSet = new Words.Saving.PageSet(i);
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_" + attachment.Name, ".jpg", i))
document.Save(output, saveOptions);
}
}
break;
}
catch (NotSupportedException ex)
{
Logger.LogError(ex, "Unsupported email attachment", "Parser", attachment.ContentType.MediaType);
break;
}
catch (Aspose.Words.UnsupportedFileFormatException ex)
{
Logger.LogError(ex, "Unsupported email attachment", "Parser", attachment.ContentType.MediaType);
break;
}
}
}
}
}
}
}
private void ExtractAttachmentsAsJpgFromMbox(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var reader = new MboxrdStorageReader(input, false))
{
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
{
var message = reader.ReadNextMessage();
foreach (var attachment in message.Attachments)
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_" + Path.GetFileName(attachment.Name)))
attachment.Save(output);
}
}
}
}
private void ExtractAttachmentsAsJpgFromOstOrPst(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var personalStorage = PersonalStorage.FromStream(input))
{
HandleFolderAndSubfolders(mapiMessage =>
{
foreach (var attachment in mapiMessage.Attachments)
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_" + Path.GetFileName(attachment.LongFileName)))
attachment.Save(output);
}
}, personalStorage.RootFolder);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Compute.Fluent
{
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Definition;
using Microsoft.Azure.Management.Graph.RBAC.Fluent;
using Microsoft.Azure.Management.Network.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions;
using Microsoft.Azure.Management.Storage.Fluent;
using Microsoft.Rest;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
internal partial class VirtualMachineScaleSetsImpl
{
/// <summary>
/// Shuts down the virtual machines in the scale set and releases the compute resources.
/// </summary>
/// <param name="groupName">The name of the resource group the virtual machine scale set is in.</param>
/// <param name="name">The name of the virtual machine scale set.</param>
/// <throws>CloudException thrown for an invalid response from the service.</throws>
/// <throws>IOException exception thrown from serialization/deserialization.</throws>
/// <throws>InterruptedException exception thrown when the operation is interrupted.</throws>
void Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSets.Deallocate(string groupName, string name)
{
this.Deallocate(groupName, name);
}
/// <summary>
/// Shuts down the virtual machines in the scale set and releases the compute resources asynchronously.
/// </summary>
/// <param name="groupName">The name of the resource group the virtual machine scale set is in.</param>
/// <param name="name">The name of the virtual machine scale set.</param>
/// <return>A representation of the deferred computation of this call.</return>
async Task Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSets.DeallocateAsync(string groupName, string name, CancellationToken cancellationToken)
{
await this.DeallocateAsync(groupName, name, cancellationToken);
}
/// <summary>
/// Begins a definition for a new resource.
/// This is the beginning of the builder pattern used to create top level resources
/// in Azure. The final method completing the definition and starting the actual resource creation
/// process in Azure is Creatable.create().
/// Note that the Creatable.create() method is
/// only available at the stage of the resource definition that has the minimum set of input
/// parameters specified. If you do not see Creatable.create() among the available methods, it
/// means you have not yet specified all the required input settings. Input settings generally begin
/// with the word "with", for example: <code>.withNewResourceGroup()</code> and return the next stage
/// of the resource definition, as an interface in the "fluent interface" style.
/// </summary>
/// <param name="name">The name of the new resource.</param>
/// <return>The first stage of the new resource definition.</return>
VirtualMachineScaleSet.Definition.IBlank Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsCreating<VirtualMachineScaleSet.Definition.IBlank>.Define(string name)
{
return this.Define(name);
}
/// <summary>
/// Powers off (stops) the virtual machines in the scale set.
/// </summary>
/// <param name="groupName">The name of the resource group the virtual machine scale set is in.</param>
/// <param name="name">The name of the virtual machine scale set.</param>
/// <throws>CloudException thrown for an invalid response from the service.</throws>
/// <throws>IOException exception thrown from serialization/deserialization.</throws>
/// <throws>InterruptedException exception thrown when the operation is interrupted.</throws>
void Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSets.PowerOff(string groupName, string name)
{
this.PowerOff(groupName, name);
}
/// <summary>
/// Powers off (stops) the virtual machines in the scale set asynchronously.
/// </summary>
/// <param name="groupName">The name of the resource group the virtual machine in the scale set is in.</param>
/// <param name="name">The name of the virtual machine scale set.</param>
/// <return>A representation of the deferred computation of this call.</return>
async Task Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSets.PowerOffAsync(string groupName, string name, CancellationToken cancellationToken)
{
await this.PowerOffAsync(groupName, name, cancellationToken);
}
/// <summary>
/// Re-images (updates the version of the installed operating system) the virtual machines in the scale set.
/// </summary>
/// <param name="groupName">The name of the resource group the virtual machine scale set is in.</param>
/// <param name="name">The name of the virtual machine scale set.</param>
/// <throws>CloudException thrown for an invalid response from the service.</throws>
/// <throws>IOException exception thrown from serialization/deserialization.</throws>
/// <throws>InterruptedException exception thrown when the operation is interrupted.</throws>
void Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSets.Reimage(string groupName, string name)
{
this.Reimage(groupName, name);
}
/// <summary>
/// Re-images (updates the version of the installed operating system) the virtual machines in the scale set asynchronously.
/// </summary>
/// <param name="groupName">The name of the resource group the virtual machine scale set is in.</param>
/// <param name="name">The name of the virtual machine scale set.</param>
/// <return>A representation of the deferred computation of this call.</return>
async Task Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSets.ReimageAsync(string groupName, string name, CancellationToken cancellationToken)
{
await this.ReimageAsync(groupName, name, cancellationToken);
}
/// <summary>
/// Restarts the virtual machines in the scale set.
/// </summary>
/// <param name="groupName">The name of the resource group the virtual machine scale set is in.</param>
/// <param name="name">The name of the virtual machine scale set.</param>
/// <throws>CloudException thrown for an invalid response from the service.</throws>
/// <throws>IOException exception thrown from serialization/deserialization.</throws>
/// <throws>InterruptedException exception thrown when the operation is interrupted.</throws>
void Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSets.Restart(string groupName, string name)
{
this.Restart(groupName, name);
}
/// <summary>
/// Restarts the virtual machines in the scale set asynchronously.
/// </summary>
/// <param name="groupName">The name of the resource group the virtual machine scale set is in.</param>
/// <param name="name">The virtual machine scale set name.</param>
/// <return>A representation of the deferred computation of this call.</return>
async Task Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSets.RestartAsync(string groupName, string name, CancellationToken cancellationToken)
{
await this.RestartAsync(groupName, name, cancellationToken);
}
/// <summary>
/// Run commands in a virtual machine instance in a scale set.
/// </summary>
/// <param name="groupName">The resource group name.</param>
/// <param name="scaleSetName">The virtual machine scale set name.</param>
/// <param name="vmId">The virtual machine instance id.</param>
/// <param name="inputCommand">Command input.</param>
/// <return>Result of execution.</return>
Models.RunCommandResultInner Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetsBeta.RunCommandInVMInstance(string groupName, string scaleSetName, string vmId, RunCommandInput inputCommand)
{
return this.RunCommandInVMInstance(groupName, scaleSetName, vmId, inputCommand);
}
/// <summary>
/// Run commands in a virtual machine instance in a scale set asynchronously.
/// </summary>
/// <param name="groupName">The resource group name.</param>
/// <param name="scaleSetName">The virtual machine scale set name.</param>
/// <param name="vmId">The virtual machine instance id.</param>
/// <param name="inputCommand">Command input.</param>
/// <return>Handle to the asynchronous execution.</return>
async Task<Models.RunCommandResultInner> Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetsBeta.RunCommandVMInstanceAsync(string groupName, string scaleSetName, string vmId, RunCommandInput inputCommand, CancellationToken cancellationToken)
{
return await this.RunCommandVMInstanceAsync(groupName, scaleSetName, vmId, inputCommand, cancellationToken);
}
/// <summary>
/// Run PowerShell script in a virtual machine instance in a scale set.
/// </summary>
/// <param name="groupName">The resource group name.</param>
/// <param name="scaleSetName">The virtual machine scale set name.</param>
/// <param name="vmId">The virtual machine instance id.</param>
/// <param name="scriptLines">PowerShell script lines.</param>
/// <param name="scriptParameters">Script parameters.</param>
/// <return>Result of PowerShell script execution.</return>
Models.RunCommandResultInner Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetsBeta.RunPowerShellScriptInVMInstance(string groupName, string scaleSetName, string vmId, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters)
{
return this.RunPowerShellScriptInVMInstance(groupName, scaleSetName, vmId, scriptLines, scriptParameters);
}
/// <summary>
/// Run PowerShell in a virtual machine instance in a scale set asynchronously.
/// </summary>
/// <param name="groupName">The resource group name.</param>
/// <param name="scaleSetName">The virtual machine scale set name.</param>
/// <param name="vmId">The virtual machine instance id.</param>
/// <param name="scriptLines">PowerShell script lines.</param>
/// <param name="scriptParameters">Script parameters.</param>
/// <return>Handle to the asynchronous execution.</return>
async Task<Models.RunCommandResultInner> Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetsBeta.RunPowerShellScriptInVMInstanceAsync(string groupName, string scaleSetName, string vmId, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters, CancellationToken cancellationToken)
{
return await this.RunPowerShellScriptInVMInstanceAsync(groupName, scaleSetName, vmId, scriptLines, scriptParameters, cancellationToken);
}
/// <summary>
/// Run shell script in a virtual machine instance in a scale set.
/// </summary>
/// <param name="groupName">The resource group name.</param>
/// <param name="scaleSetName">The virtual machine scale set name.</param>
/// <param name="vmId">The virtual machine instance id.</param>
/// <param name="scriptLines">Shell script lines.</param>
/// <param name="scriptParameters">Script parameters.</param>
/// <return>Result of shell script execution.</return>
Models.RunCommandResultInner Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetsBeta.RunShellScriptInVMInstance(string groupName, string scaleSetName, string vmId, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters)
{
return this.RunShellScriptInVMInstance(groupName, scaleSetName, vmId, scriptLines, scriptParameters);
}
/// <summary>
/// Run shell script in a virtual machine instance in a scale set asynchronously.
/// </summary>
/// <param name="groupName">The resource group name.</param>
/// <param name="scaleSetName">The virtual machine scale set name.</param>
/// <param name="vmId">The virtual machine instance id.</param>
/// <param name="scriptLines">Shell script lines.</param>
/// <param name="scriptParameters">Script parameters.</param>
/// <return>Handle to the asynchronous execution.</return>
async Task<Models.RunCommandResultInner> Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetsBeta.RunShellScriptInVMInstanceAsync(string groupName, string scaleSetName, string vmId, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters, CancellationToken cancellationToken)
{
return await this.RunShellScriptInVMInstanceAsync(groupName, scaleSetName, vmId, scriptLines, scriptParameters, cancellationToken);
}
/// <summary>
/// Starts the virtual machines in the scale set.
/// </summary>
/// <param name="groupName">The name of the resource group the virtual machine scale set is in.</param>
/// <param name="name">The name of the virtual machine scale set.</param>
/// <throws>CloudException thrown for an invalid response from the service.</throws>
/// <throws>IOException exception thrown from serialization/deserialization.</throws>
/// <throws>InterruptedException exception thrown when the operation is interrupted.</throws>
void Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSets.Start(string groupName, string name)
{
this.Start(groupName, name);
}
/// <summary>
/// Starts the virtual machines in the scale set asynchronously.
/// </summary>
/// <param name="groupName">The name of the resource group the virtual machine scale set is in.</param>
/// <param name="name">The name of the virtual machine scale set.</param>
/// <return>A representation of the deferred computation of this call.</return>
async Task Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSets.StartAsync(string groupName, string name, CancellationToken cancellationToken)
{
await this.StartAsync(groupName, name, cancellationToken);
}
}
}
| |
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Newtonsoft.Json.Linq;
using Orchard.ContentManagement;
using Orchard.Data;
using Orchard.DisplayManagement;
using Orchard.Forms.Services;
using Orchard.Localization;
using Orchard.Mvc;
using Orchard.Mvc.Extensions;
using Orchard.Security;
using Orchard.Themes;
using System;
using Orchard.Settings;
using Orchard.UI.Navigation;
using Orchard.UI.Notify;
using Orchard.Workflows.Models;
using Orchard.Workflows.Services;
using Orchard.Workflows.ViewModels;
namespace Orchard.Workflows.Controllers {
[ValidateInput(false)]
public class AdminController : Controller, IUpdateModel {
private readonly ISiteService _siteService;
private readonly IRepository<WorkflowDefinitionRecord> _workflowDefinitionRecords;
private readonly IRepository<WorkflowRecord> _workflowRecords;
private readonly IActivitiesManager _activitiesManager;
private readonly IFormManager _formManager;
public AdminController(
IOrchardServices services,
IShapeFactory shapeFactory,
ISiteService siteService,
IRepository<WorkflowDefinitionRecord> workflowDefinitionRecords,
IRepository<WorkflowRecord> workflowRecords,
IActivitiesManager activitiesManager,
IFormManager formManager
) {
_siteService = siteService;
_workflowDefinitionRecords = workflowDefinitionRecords;
_workflowRecords = workflowRecords;
_activitiesManager = activitiesManager;
_formManager = formManager;
Services = services;
T = NullLocalizer.Instance;
New = shapeFactory;
}
dynamic New { get; set; }
public IOrchardServices Services { get; set; }
public Localizer T { get; set; }
public ActionResult Index(AdminIndexOptions options, PagerParameters pagerParameters) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list workflows")))
return new HttpUnauthorizedResult();
var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);
// default options
if (options == null)
options = new AdminIndexOptions();
var queries = _workflowDefinitionRecords.Table;
switch (options.Filter) {
case WorkflowDefinitionFilter.All:
break;
default:
throw new ArgumentOutOfRangeException();
}
if (!String.IsNullOrWhiteSpace(options.Search)) {
queries = queries.Where(w => w.Name.Contains(options.Search));
}
var pagerShape = New.Pager(pager).TotalItemCount(queries.Count());
switch (options.Order) {
case WorkflowDefinitionOrder.Name:
queries = queries.OrderBy(u => u.Name);
break;
}
if (pager.GetStartIndex() > 0) {
queries = queries.Skip(pager.GetStartIndex());
}
if (pager.PageSize > 0) {
queries = queries.Take(pager.PageSize);
}
var results = queries.ToList();
var model = new AdminIndexViewModel {
WorkflowDefinitions = results.Select(x => new WorkflowDefinitionEntry {
WorkflowDefinitionRecord = x,
WokflowDefinitionId = x.Id,
Name = x.Name
}).ToList(),
Options = options,
Pager = pagerShape
};
// maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Filter", options.Filter);
routeData.Values.Add("Options.Search", options.Search);
routeData.Values.Add("Options.Order", options.Order);
pagerShape.RouteData(routeData);
return View(model);
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.BulkEdit")]
public ActionResult BulkEdit(AdminIndexOptions options, PagerParameters pagerParameters) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list workflows")))
return new HttpUnauthorizedResult();
var viewModel = new AdminIndexViewModel { WorkflowDefinitions = new List<WorkflowDefinitionEntry>(), Options = new AdminIndexOptions() };
if (!TryUpdateModel(viewModel)) {
return View(viewModel);
}
var checkedEntries = viewModel.WorkflowDefinitions.Where(t => t.IsChecked);
switch (options.BulkAction) {
case WorkflowDefinitionBulk.None:
break;
case WorkflowDefinitionBulk.Delete:
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage workflows")))
return new HttpUnauthorizedResult();
foreach (var entry in checkedEntries) {
var workflowDefinition = _workflowDefinitionRecords.Get(entry.WokflowDefinitionId);
if (workflowDefinition != null) {
_workflowDefinitionRecords.Delete(workflowDefinition);
Services.Notifier.Information(T("Workflow {0} deleted", workflowDefinition.Name));
}
}
break;
default:
throw new ArgumentOutOfRangeException();
}
return RedirectToAction("Index", new { page = pagerParameters.Page, pageSize = pagerParameters.PageSize });
}
public ActionResult List(int id) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list workflows")))
return new HttpUnauthorizedResult();
var contentItem = Services.ContentManager.Get(id, VersionOptions.Latest);
if (contentItem == null) {
return HttpNotFound();
}
var workflows = _workflowRecords.Table.Where(x => x.ContentItemRecord == contentItem.Record).ToList();
var viewModel = New.ViewModel(
ContentItem: contentItem,
Workflows: workflows
);
return View(viewModel);
}
public ActionResult EditProperties(int id = 0)
{
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows.")))
return new HttpUnauthorizedResult();
if (id == 0) {
return View();
}
else {
var workflowDefinition = _workflowDefinitionRecords.Get(id);
return View(new AdminEditViewModel { WorkflowDefinition = new WorkflowDefinitionViewModel { Name = workflowDefinition.Name, Id = workflowDefinition.Id } });
}
}
[HttpPost, ActionName("EditProperties")]
public ActionResult EditPropertiesPost(AdminEditViewModel adminEditViewModel, int id = 0) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows.")))
return new HttpUnauthorizedResult();
if (String.IsNullOrWhiteSpace(adminEditViewModel.WorkflowDefinition.Name)) {
ModelState.AddModelError("Name", T("The Name can't be empty.").Text);
}
if (!ModelState.IsValid) {
return View();
}
if (id == 0) {
var workflowDefinitionRecord = new WorkflowDefinitionRecord {
Name = adminEditViewModel.WorkflowDefinition.Name
};
_workflowDefinitionRecords.Create(workflowDefinitionRecord);
return RedirectToAction("Edit", new { workflowDefinitionRecord.Id });
}
else {
var workflowDefinition = _workflowDefinitionRecords.Get(id);
workflowDefinition.Name = adminEditViewModel.WorkflowDefinition.Name;
return RedirectToAction("Index");
}
}
public ActionResult Edit(int id, string localId, int? workflowId) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
// convert the workflow definition into its view model
var workflowDefinitionRecord = _workflowDefinitionRecords.Get(id);
var workflowDefinitionViewModel = CreateWorkflowDefinitionViewModel(workflowDefinitionRecord);
var workflow = workflowId.HasValue ? _workflowRecords.Get(workflowId.Value) : null;
var viewModel = new AdminEditViewModel {
LocalId = String.IsNullOrEmpty(localId) ? Guid.NewGuid().ToString() : localId,
IsLocal = !String.IsNullOrEmpty(localId),
WorkflowDefinition = workflowDefinitionViewModel,
AllActivities = _activitiesManager.GetActivities(),
Workflow = workflow
};
return View(viewModel);
}
[HttpPost]
public ActionResult Delete(int id) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage workflows")))
return new HttpUnauthorizedResult();
var workflowDefinition = _workflowDefinitionRecords.Get(id);
if (workflowDefinition != null) {
_workflowDefinitionRecords.Delete(workflowDefinition);
Services.Notifier.Information(T("Workflow {0} deleted", workflowDefinition.Name));
}
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult DeleteWorkflow(int id, string returnUrl) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage workflows")))
return new HttpUnauthorizedResult();
var workflow = _workflowRecords.Get(id);
if (workflow != null) {
_workflowRecords.Delete(workflow);
Services.Notifier.Information(T("Workflow deleted"));
}
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index"));
}
private WorkflowDefinitionViewModel CreateWorkflowDefinitionViewModel(WorkflowDefinitionRecord workflowDefinitionRecord) {
if (workflowDefinitionRecord == null) {
throw new ArgumentNullException("workflowDefinitionRecord");
}
var workflowDefinitionModel = new WorkflowDefinitionViewModel {
Id = workflowDefinitionRecord.Id,
Name = workflowDefinitionRecord.Name
};
dynamic workflow = new JObject();
workflow.Activities = new JArray(workflowDefinitionRecord.ActivityRecords.Select(x => {
dynamic activity = new JObject();
activity.Name = x.Name;
activity.Id = x.Id;
activity.ClientId = x.Name + "_" + x.Id;
activity.Left = x.X;
activity.Top = x.Y;
activity.Start = x.Start;
activity.State = FormParametersHelper.FromJsonString(x.State);
return activity;
}));
workflow.Connections = new JArray(workflowDefinitionRecord.TransitionRecords.Select(x => {
dynamic connection = new JObject();
connection.Id = x.Id;
connection.SourceId = x.SourceActivityRecord.Name + "_" + x.SourceActivityRecord.Id;
connection.TargetId = x.DestinationActivityRecord.Name + "_" + x.DestinationActivityRecord.Id;
connection.SourceEndpoint = x.SourceEndpoint;
return connection;
}));
workflowDefinitionModel.JsonData = FormParametersHelper.ToJsonString(workflow);
return workflowDefinitionModel;
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Save")]
public ActionResult EditPost(int id, string localId, string data) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
var workflowDefinitionRecord = _workflowDefinitionRecords.Get(id);
if (workflowDefinitionRecord == null) {
return HttpNotFound();
}
workflowDefinitionRecord.Enabled = true;
var state = FormParametersHelper.FromJsonString(data);
var activitiesIndex = new Dictionary<string, ActivityRecord>();
workflowDefinitionRecord.ActivityRecords.Clear();
foreach (var activity in state.Activities) {
ActivityRecord activityRecord;
workflowDefinitionRecord.ActivityRecords.Add(activityRecord = new ActivityRecord {
Name = activity.Name,
X = activity.Left,
Y = activity.Top,
Start = activity.Start,
State = FormParametersHelper.ToJsonString(activity.State),
WorkflowDefinitionRecord = workflowDefinitionRecord
});
activitiesIndex.Add((string)activity.ClientId, activityRecord);
}
workflowDefinitionRecord.TransitionRecords.Clear();
foreach (var connection in state.Connections) {
workflowDefinitionRecord.TransitionRecords.Add(new TransitionRecord {
SourceActivityRecord = activitiesIndex[(string)connection.SourceId],
DestinationActivityRecord = activitiesIndex[(string)connection.TargetId],
SourceEndpoint = connection.SourceEndpoint,
WorkflowDefinitionRecord = workflowDefinitionRecord
});
}
Services.Notifier.Information(T("Workflow saved successfully"));
return RedirectToAction("Edit", new { id, localId });
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Cancel")]
public ActionResult EditPostCancel() {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
return View();
}
[Themed(false)]
[HttpPost]
public ActionResult RenderActivity(ActivityViewModel model) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
var activity = _activitiesManager.GetActivityByName(model.Name);
if (activity == null) {
return HttpNotFound();
}
dynamic shape = New.Activity(activity);
if (model.State != null) {
var state = FormParametersHelper.ToDynamic(FormParametersHelper.ToString(model.State));
shape.State(state);
} else {
shape.State(FormParametersHelper.FromJsonString("{}"));
}
shape.Metadata.Alternates.Add("Activity__" + activity.Name);
return new ShapeResult(this, shape);
}
public ActionResult EditActivity(string localId, string clientId, ActivityViewModel model) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
var activity = _activitiesManager.GetActivityByName(model.Name);
if (activity == null) {
return HttpNotFound();
}
// build the form, and let external components alter it
var form = activity.Form == null ? null : _formManager.Build(activity.Form);
// form is bound on client side
var viewModel = New.ViewModel(LocalId: localId, ClientId: clientId, Form: form);
return View(viewModel);
}
[HttpPost, ActionName("EditActivity")]
[FormValueRequired("_submit.Save")]
public ActionResult EditActivityPost(int id, string localId, string name, string clientId, FormCollection formValues) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
var activity = _activitiesManager.GetActivityByName(name);
if (activity == null) {
return HttpNotFound();
}
// validating form values
_formManager.Validate(new ValidatingContext { FormName = activity.Form, ModelState = ModelState, ValueProvider = ValueProvider });
// stay on the page if there are validation errors
if (!ModelState.IsValid) {
// build the form, and let external components alter it
var form = activity.Form == null ? null : _formManager.Build(activity.Form);
// bind form with existing values.
_formManager.Bind(form, ValueProvider);
var viewModel = New.ViewModel(Id: id, LocalId: localId, Form: form);
return View(viewModel);
}
var model = new UpdatedActivityModel {
ClientId = clientId,
Data = HttpUtility.JavaScriptStringEncode(FormParametersHelper.ToJsonString(formValues))
};
TempData["UpdatedViewModel"] = model;
return RedirectToAction("Edit", new {
id,
localId
});
}
[HttpPost, ActionName("EditActivity")]
[FormValueRequired("_submit.Cancel")]
public ActionResult EditActivityPostCancel(int id, string localId, string name, string clientId, FormCollection formValues) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
return RedirectToAction("Edit", new { id, localId });
}
bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) {
return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
}
public void AddModelError(string key, LocalizedString errorMessage) {
ModelState.AddModelError(key, errorMessage.ToString());
}
}
}
| |
#if !BESTHTTP_DISABLE_SIGNALR
using System;
using System.Text;
using System.Collections.Generic;
using BestHTTP.Extensions;
using BestHTTP.SignalR.Hubs;
using BestHTTP.SignalR.Messages;
using BestHTTP.SignalR.Transports;
using BestHTTP.SignalR.JsonEncoders;
using BestHTTP.SignalR.Authentication;
using PlatformSupport.Collections.ObjectModel;
#if !NETFX_CORE
using PlatformSupport.Collections.Specialized;
#else
using System.Collections.Specialized;
#endif
namespace BestHTTP.SignalR
{
public delegate void OnNonHubMessageDelegate(Connection connection, object data);
public delegate void OnConnectedDelegate(Connection connection);
public delegate void OnClosedDelegate(Connection connection);
public delegate void OnErrorDelegate(Connection connection, string error);
public delegate void OnStateChanged(Connection connection, ConnectionStates oldState, ConnectionStates newState);
public delegate void OnPrepareRequestDelegate(Connection connection, HTTPRequest req, RequestTypes type);
/// <summary>
/// Interface to be able to hide internally used functions and properties.
/// </summary>
public interface IConnection
{
ProtocolVersions Protocol { get; }
NegotiationData NegotiationResult { get; }
IJsonEncoder JsonEncoder { get; set; }
void OnMessage(IServerMessage msg);
void TransportStarted();
void TransportReconnected();
void TransportAborted();
void Error(string reason);
Uri BuildUri(RequestTypes type);
Uri BuildUri(RequestTypes type, TransportBase transport);
HTTPRequest PrepareRequest(HTTPRequest req, RequestTypes type);
string ParseResponse(string responseStr);
}
/// <summary>
/// Supported versions of the SignalR protocol.
/// </summary>
public enum ProtocolVersions : byte
{
Protocol_2_0,
Protocol_2_1,
Protocol_2_2
}
/// <summary>
/// The main SignalR class. This is the entry point to connect to a SignalR service.
/// </summary>
public sealed class Connection : IHeartbeat, IConnection
{
#region Public Properties
/// <summary>
/// The default Json encode/decoder that will be used to encode/decode the event arguments.
/// </summary>
public static IJsonEncoder DefaultEncoder = new DefaultJsonEncoder();
/// <summary>
/// The base url endpoint where the SignalR service can be found.
/// </summary>
public Uri Uri { get; private set; }
/// <summary>
/// Current State of the SignalR connection.
/// </summary>
public ConnectionStates State
{
get { return _state; }
private set
{
ConnectionStates old = _state;
_state = value;
if (OnStateChanged != null)
OnStateChanged(this, old, _state);
}
}
private ConnectionStates _state;
/// <summary>
/// Result of the nogotiation request from the server.
/// </summary>
public NegotiationData NegotiationResult { get; private set; }
/// <summary>
/// The hubs that the client is connected to.
/// </summary>
public Hub[] Hubs { get; private set; }
/// <summary>
/// The transport that is used to send and receive messages.
/// </summary>
public TransportBase Transport { get; private set; }
/// <summary>
/// Additional query parameters that will be passed for the handsake uri. If the value is null, or an empty string it will be not appended to the query only the key.
/// <remarks>The keys and values must be escaped properly, as the plugin will not escape these. </remarks>
/// </summary>
public ObservableDictionary<string, string> AdditionalQueryParams
{
get { return additionalQueryParams; }
set
{
// Unsubscribe from previous dictionary's events
if (additionalQueryParams != null)
additionalQueryParams.CollectionChanged -= AdditionalQueryParams_CollectionChanged;
additionalQueryParams = value;
// Clear out the cached value
BuiltQueryParams = null;
// Subscribe to the collection changed event
if (value != null)
value.CollectionChanged += AdditionalQueryParams_CollectionChanged;
}
}
private ObservableDictionary<string, string> additionalQueryParams;
/// <summary>
/// If it's false, the parmateres in the AdditionalQueryParams will be passed for all http requests. Its default value is true.
/// </summary>
public bool QueryParamsOnlyForHandshake { get; set; }
/// <summary>
/// The Json encoder that will be used by the connection and the transport.
/// </summary>
public IJsonEncoder JsonEncoder { get; set; }
/// <summary>
/// An IAuthenticationProvider implementation that will be used to authenticate the connection.
/// </summary>
public IAuthenticationProvider AuthenticationProvider { get; set; }
#endregion
#region Public Events
/// <summary>
/// Called when the protocol is open for communication.
/// </summary>
public event OnConnectedDelegate OnConnected;
/// <summary>
/// Called when the connection is closed, and no further messages are sent or received.
/// </summary>
public event OnClosedDelegate OnClosed;
/// <summary>
/// Called when an error occures. If the connection is already Started, it will try to do a reconnect, otherwise it will close the connection.
/// </summary>
public event OnErrorDelegate OnError;
/// <summary>
/// This event called when a reconnection attempt are started. If fails to reconnect an OnError and OnClosed events are called.
/// </summary>
public event OnConnectedDelegate OnReconnecting;
/// <summary>
/// This event called when the reconnection attempt succeded.
/// </summary>
public event OnConnectedDelegate OnReconnected;
/// <summary>
/// Called every time when the connection's state changes.
/// </summary>
public event OnStateChanged OnStateChanged;
/// <summary>
/// It's called when a non-Hub message received. The data can be anything from primitive types to array of complex objects.
/// </summary>
public event OnNonHubMessageDelegate OnNonHubMessage;
/// <summary>
/// With this delegate all requests can be further customized.
/// </summary>
public OnPrepareRequestDelegate RequestPreparator { get; set; }
#endregion
#region Indexers
/// <summary>
/// Indexer property the access hubs by index.
/// </summary>
public Hub this[int idx] { get { return Hubs[idx] as Hub; } }
/// <summary>
/// Indexer property the access hubs by name.
/// </summary>
public Hub this[string hubName]
{
get
{
for (int i = 0; i < Hubs.Length; ++i)
{
Hub hub = Hubs[i] as Hub;
if (hub.Name.Equals(hubName, StringComparison.OrdinalIgnoreCase))
return hub;
}
return null;
}
}
/// <summary>
/// Current client protocol in use.
/// </summary>
public ProtocolVersions Protocol { get; private set; }
#endregion
#region Internals
/// <summary>
/// An object to be able maintain thread safety.
/// </summary>
internal object SyncRoot = new object();
/// <summary>
/// Unique ID for all message sent by the client.
/// </summary>
internal UInt64 ClientMessageCounter { get; set; }
#endregion
#region Privates
/// <summary>
/// Supported client protocol versions.
/// </summary>
private readonly string[] ClientProtocols = new string[] { "1.3", "1.4", "1.5" };
/// <summary>
/// A timestamp that will be sent with all request for easier debugging.
/// </summary>
private UInt32 Timestamp { get { return (UInt32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).Ticks; } }
/// <summary>
/// Request counter sent with all request for easier debugging.
/// </summary>
private UInt64 RequestCounter;
/// <summary>
/// Instance of the last received message. Used for its MessageId.
/// </summary>
private MultiMessage LastReceivedMessage;
/// <summary>
/// The GroupsToken sent by the server that stores what groups we are joined to.
/// We will send it with the reconnect request.
/// </summary>
private string GroupsToken;
/// <summary>
/// Received messages before the Start request finishes.
/// </summary>
private List<IServerMessage> BufferedMessages;
/// <summary>
/// When the last message received from the server. Used for reconnecting.
/// </summary>
private DateTime LastMessageReceivedAt;
/// <summary>
/// When we started to reconnect. When too much time passes without a successful reconnect, we will close the connection.
/// </summary>
private DateTime ReconnectStartedAt;
/// <summary>
/// True, if the reconnect process started.
/// </summary>
private bool ReconnectStarted;
/// <summary>
/// When the last ping request sent out.
/// </summary>
private DateTime LastPingSentAt;
/// <summary>
/// How mutch time we have to wait between two pings.
/// </summary>
private TimeSpan PingInterval;
/// <summary>
/// Reference to the ping request.
/// </summary>
private HTTPRequest PingRequest;
/// <summary>
/// When the transport started the connection process
/// </summary>
private DateTime? TransportConnectionStartedAt;
/// <summary>
/// Cached StringBuilder instance used in BuildUri
/// </summary>
private StringBuilder queryBuilder = new StringBuilder();
/// <summary>
/// Builds and returns with the connection data made from the hub names.
/// </summary>
private string ConnectionData
{
get
{
if (!string.IsNullOrEmpty(BuiltConnectionData))
return BuiltConnectionData;
StringBuilder sb = new StringBuilder("[", Hubs.Length * 4);
if (Hubs != null)
for (int i = 0; i < Hubs.Length; ++i)
{
sb.Append(@"{""Name"":""");
sb.Append(Hubs[i].Name);
sb.Append(@"""}");
if (i < Hubs.Length - 1)
sb.Append(",");
}
sb.Append("]");
return BuiltConnectionData = Uri.EscapeUriString(sb.ToString());
}
}
/// <summary>
/// The cached value of the result of the ConnectionData property call.
/// </summary>
private string BuiltConnectionData;
/// <summary>
/// Builds the keys and values from the AdditionalQueryParams to an key=value form. If AdditionalQueryParams is null or empty, it will return an empty string.
/// </summary>
private string QueryParams
{
get
{
if (AdditionalQueryParams == null || AdditionalQueryParams.Count == 0)
return string.Empty;
if (!string.IsNullOrEmpty(BuiltQueryParams))
return BuiltQueryParams;
StringBuilder sb = new StringBuilder(AdditionalQueryParams.Count * 4);
foreach (var kvp in AdditionalQueryParams)
{
sb.Append("&");
sb.Append(kvp.Key);
if (!string.IsNullOrEmpty(kvp.Value))
{
sb.Append("=");
sb.Append(Uri.EscapeDataString(kvp.Value));
}
}
return BuiltQueryParams = sb.ToString();
}
}
/// <summary>
/// The cached value of the result of the QueryParams property call.
/// </summary>
private string BuiltQueryParams;
private SupportedProtocols NextProtocolToTry;
#endregion
#region Constructors
public Connection(Uri uri, params string[] hubNames)
: this(uri)
{
if (hubNames != null && hubNames.Length > 0)
{
this.Hubs = new Hub[hubNames.Length];
for (int i = 0; i < hubNames.Length; ++i)
this.Hubs[i] = new Hub(hubNames[i], this);
}
}
public Connection(Uri uri, params Hub[] hubs)
:this(uri)
{
this.Hubs = hubs;
if (hubs != null)
for (int i = 0; i < hubs.Length; ++i)
(hubs[i] as IHub).Connection = this;
}
public Connection(Uri uri)
{
this.State = ConnectionStates.Initial;
this.Uri = uri;
this.JsonEncoder = Connection.DefaultEncoder;
this.PingInterval = TimeSpan.FromMinutes(5);
// Expected protocol
this.Protocol = ProtocolVersions.Protocol_2_2;
}
#endregion
#region Starting the protocol
/// <summary>
/// This function will start to authenticate if required, and the SignalR protocol negotiation.
/// </summary>
public void Open()
{
if (State != ConnectionStates.Initial && State != ConnectionStates.Closed)
return;
if (AuthenticationProvider != null && AuthenticationProvider.IsPreAuthRequired)
{
this.State = ConnectionStates.Authenticating;
AuthenticationProvider.OnAuthenticationSucceded += OnAuthenticationSucceded;
AuthenticationProvider.OnAuthenticationFailed += OnAuthenticationFailed;
// Start the authentication process
AuthenticationProvider.StartAuthentication();
}
else
StartImpl();
}
/// <summary>
/// Called when the authentication succeded.
/// </summary>
/// <param name="provider"></param>
private void OnAuthenticationSucceded(IAuthenticationProvider provider)
{
provider.OnAuthenticationSucceded -= OnAuthenticationSucceded;
StartImpl();
}
/// <summary>
/// Called when the authentication failed.
/// </summary>
private void OnAuthenticationFailed(IAuthenticationProvider provider, string reason)
{
provider.OnAuthenticationFailed -= OnAuthenticationFailed;
(this as IConnection).Error(reason);
}
/// <summary>
/// It's the real Start implementation. It will start the negotiation
/// </summary>
private void StartImpl()
{
this.State = ConnectionStates.Negotiating;
NegotiationResult = new NegotiationData(this);
NegotiationResult.OnReceived = OnNegotiationDataReceived;
NegotiationResult.OnError = OnNegotiationError;
NegotiationResult.Start();
}
#region Negotiation Event Handlers
/// <summary>
/// Protocol negotiation finished successfully.
/// </summary>
private void OnNegotiationDataReceived(NegotiationData data)
{
// Find out what supported protocol the server speak
int protocolIdx = -1;
for (int i = 0; i < ClientProtocols.Length && protocolIdx == -1; ++i)
if (data.ProtocolVersion == ClientProtocols[i])
protocolIdx = i;
// No supported protocol found? Try using the latest one.
if (protocolIdx == -1)
{
protocolIdx = (byte)ProtocolVersions.Protocol_2_2;
HTTPManager.Logger.Warning("SignalR Connection", "Unknown protocol version: " + data.ProtocolVersion);
}
this.Protocol = (ProtocolVersions)protocolIdx;
#if !BESTHTTP_DISABLE_WEBSOCKET
if (data.TryWebSockets)
{
Transport = new WebSocketTransport(this);
#if !BESTHTTP_DISABLE_SERVERSENT_EVENTS
NextProtocolToTry = SupportedProtocols.ServerSentEvents;
#else
NextProtocolToTry = SupportedProtocols.HTTP;
#endif
}
else
#endif
{
#if !BESTHTTP_DISABLE_SERVERSENT_EVENTS
Transport = new ServerSentEventsTransport(this);
// Long-Poll
NextProtocolToTry = SupportedProtocols.HTTP;
#else
Transport = new PollingTransport(this);
NextProtocolToTry = SupportedProtocols.Unknown;
#endif
}
this.State = ConnectionStates.Connecting;
TransportConnectionStartedAt = DateTime.UtcNow;
Transport.Connect();
}
/// <summary>
/// Protocol negotiation failed.
/// </summary>
private void OnNegotiationError(NegotiationData data, string error)
{
(this as IConnection).Error(error);
}
#endregion
#endregion
#region Public Interface
/// <summary>
/// Closes the connection and shuts down the transport.
/// </summary>
public void Close()
{
if (this.State == ConnectionStates.Closed)
return;
this.State = ConnectionStates.Closed;
//ReconnectStartedAt = null;
ReconnectStarted = false;
TransportConnectionStartedAt = null;
if (Transport != null)
{
Transport.Abort();
Transport = null;
}
NegotiationResult = null;
HTTPManager.Heartbeats.Unsubscribe(this);
LastReceivedMessage = null;
if (Hubs != null)
for (int i = 0; i < Hubs.Length; ++i)
(Hubs[i] as IHub).Close();
if (BufferedMessages != null)
{
BufferedMessages.Clear();
BufferedMessages = null;
}
if (OnClosed != null)
{
try
{
OnClosed(this);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("SignalR Connection", "OnClosed", ex);
}
}
}
/// <summary>
/// Initiates a reconnect to the SignalR server.
/// </summary>
public void Reconnect()
{
// Return if reconnect process already started.
if (ReconnectStarted)
return;
ReconnectStarted = true;
// Set ReconnectStartedAt only when the previous State is not Reconnecting,
// so we keep the first date&time when we started reconnecting
if (this.State != ConnectionStates.Reconnecting)
ReconnectStartedAt = DateTime.UtcNow;
this.State = ConnectionStates.Reconnecting;
HTTPManager.Logger.Warning("SignalR Connection", "Reconnecting");
Transport.Reconnect();
if (PingRequest != null)
PingRequest.Abort();
if (OnReconnecting != null)
{
try
{
OnReconnecting(this);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("SignalR Connection", "OnReconnecting", ex);
}
}
}
/// <summary>
/// Will encode the argument to a Json string using the Connection's JsonEncoder, then will send it to the server.
/// </summary>
/// <returns>True if the plugin was able to send out the message</returns>
public bool Send(object arg)
{
if (arg == null)
throw new ArgumentNullException("arg");
lock(SyncRoot)
{
if (this.State != ConnectionStates.Connected)
return false;
string json = JsonEncoder.Encode(arg);
if (string.IsNullOrEmpty(json))
HTTPManager.Logger.Error("SignalR Connection", "Failed to JSon encode the given argument. Please try to use an advanced JSon encoder(check the documentation how you can do it).");
else
Transport.Send(json);
}
return true;
}
/// <summary>
/// Sends the given json string to the server.
/// </summary>
/// <returns>True if the plugin was able to send out the message</returns>
public bool SendJson(string json)
{
if (json == null)
throw new ArgumentNullException("json");
lock(SyncRoot)
{
if (this.State != ConnectionStates.Connected)
return false;
Transport.Send(json);
}
return true;
}
#endregion
#region IManager Functions
/// <summary>
/// Called when we receive a message from the server
/// </summary>
void IConnection.OnMessage(IServerMessage msg)
{
if (this.State == ConnectionStates.Closed)
return;
// Store messages that we receive while we are connecting
if (this.State == ConnectionStates.Connecting)
{
if (BufferedMessages == null)
BufferedMessages = new List<IServerMessage>();
BufferedMessages.Add(msg);
return;
}
LastMessageReceivedAt = DateTime.UtcNow;
switch(msg.Type)
{
case MessageTypes.Multiple:
LastReceivedMessage = msg as MultiMessage;
// Not received in the reconnect process, so we can't rely on it
if (LastReceivedMessage.IsInitialization)
HTTPManager.Logger.Information("SignalR Connection", "OnMessage - Init");
if (LastReceivedMessage.GroupsToken != null)
GroupsToken = LastReceivedMessage.GroupsToken;
if (LastReceivedMessage.ShouldReconnect)
{
HTTPManager.Logger.Information("SignalR Connection", "OnMessage - Should Reconnect");
Reconnect();
// Should we return here not processing the messages that may come with it?
//return;
}
if (LastReceivedMessage.Data != null)
for (int i = 0; i < LastReceivedMessage.Data.Count; ++i)
(this as IConnection).OnMessage(LastReceivedMessage.Data[i]);
break;
case MessageTypes.MethodCall:
MethodCallMessage methodCall = msg as MethodCallMessage;
Hub hub = this[methodCall.Hub];
if (hub != null)
(hub as IHub).OnMethod(methodCall);
else
HTTPManager.Logger.Warning("SignalR Connection", string.Format("Hub \"{0}\" not found!", methodCall.Hub));
break;
case MessageTypes.Result:
case MessageTypes.Failure:
case MessageTypes.Progress:
UInt64 id = (msg as IHubMessage).InvocationId;
hub = FindHub(id);
if (hub != null)
(hub as IHub).OnMessage(msg);
else
HTTPManager.Logger.Warning("SignalR Connection", string.Format("No Hub found for Progress message! Id: {0}", id.ToString()));
break;
case MessageTypes.Data:
if (OnNonHubMessage != null)
OnNonHubMessage(this, (msg as DataMessage).Data);
break;
case MessageTypes.KeepAlive:
break;
default:
HTTPManager.Logger.Warning("SignalR Connection", "Unknown message type received: " + msg.Type.ToString());
break;
}
}
/// <summary>
/// Called from the transport implementations when the Start request finishes successfully.
/// </summary>
void IConnection.TransportStarted()
{
if (this.State != ConnectionStates.Connecting)
return;
InitOnStart();
if (OnConnected != null)
{
try
{
OnConnected(this);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("SignalR Connection", "OnOpened", ex);
}
}
// Deliver messages that we received before the /start request returned.
// This must be after the OnStarted call, to let the clients to subrscribe to these events.
if (BufferedMessages != null)
{
for (int i = 0; i < BufferedMessages.Count; ++i)
(this as IConnection).OnMessage(BufferedMessages[i]);
BufferedMessages.Clear();
BufferedMessages = null;
}
}
/// <summary>
/// Called when the transport sucessfully reconnected to the server.
/// </summary>
void IConnection.TransportReconnected()
{
if (this.State != ConnectionStates.Reconnecting)
return;
HTTPManager.Logger.Information("SignalR Connection", "Transport Reconnected");
InitOnStart();
if (OnReconnected != null)
{
try
{
OnReconnected(this);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("SignalR Connection", "OnReconnected", ex);
}
}
}
/// <summary>
/// Called from the transport implementation when the Abort request finishes successfully.
/// </summary>
void IConnection.TransportAborted()
{
Close();
}
/// <summary>
/// Called when an error occures. If the connection is in the Connected state, it will start the reconnect process, otherwise it will close the connection.
/// </summary>
void IConnection.Error(string reason)
{
// Not interested about errors we received after we already closed
if (this.State == ConnectionStates.Closed)
return;
HTTPManager.Logger.Error("SignalR Connection", reason);
//ReconnectStartedAt = null;
ReconnectStarted = false;
if (OnError != null)
OnError(this, reason);
if (this.State == ConnectionStates.Connected || this.State == ConnectionStates.Reconnecting)
Reconnect();
else
{
// Fall back if possible
if (this.State != ConnectionStates.Connecting || !TryFallbackTransport())
Close();
}
}
/// <summary>
/// Creates an Uri instance for the given request type.
/// </summary>
Uri IConnection.BuildUri(RequestTypes type)
{
return (this as IConnection).BuildUri(type, null);
}
/// <summary>
/// Creates an Uri instance from the given parameters.
/// </summary>
Uri IConnection.BuildUri(RequestTypes type, TransportBase transport)
{
lock (SyncRoot)
{
// make sure that the queryBuilder is reseted
queryBuilder.Length = 0;
UriBuilder uriBuilder = new UriBuilder(Uri);
if (!uriBuilder.Path.EndsWith("/"))
uriBuilder.Path += "/";
this.RequestCounter %= UInt64.MaxValue;
switch (type)
{
case RequestTypes.Negotiate:
uriBuilder.Path += "negotiate";
goto default;
case RequestTypes.Connect:
#if !BESTHTTP_DISABLE_WEBSOCKET
if (transport != null && transport.Type == TransportTypes.WebSocket)
uriBuilder.Scheme = HTTPProtocolFactory.IsSecureProtocol(Uri) ? "wss" : "ws";
#endif
uriBuilder.Path += "connect";
goto default;
case RequestTypes.Start:
uriBuilder.Path += "start";
goto default;
case RequestTypes.Poll:
uriBuilder.Path += "poll";
if (this.LastReceivedMessage != null)
{
queryBuilder.Append("messageId=");
queryBuilder.Append(this.LastReceivedMessage.MessageId);
}
goto default;
case RequestTypes.Send:
uriBuilder.Path += "send";
goto default;
case RequestTypes.Reconnect:
#if !BESTHTTP_DISABLE_WEBSOCKET
if (transport != null && transport.Type == TransportTypes.WebSocket)
uriBuilder.Scheme = HTTPProtocolFactory.IsSecureProtocol(Uri) ? "wss" : "ws";
#endif
uriBuilder.Path += "reconnect";
if (this.LastReceivedMessage != null)
{
queryBuilder.Append("messageId=");
queryBuilder.Append(this.LastReceivedMessage.MessageId);
}
if (!string.IsNullOrEmpty(GroupsToken))
{
if (queryBuilder.Length > 0)
queryBuilder.Append("&");
queryBuilder.Append("groupsToken=");
queryBuilder.Append(GroupsToken);
}
goto default;
case RequestTypes.Abort:
uriBuilder.Path += "abort";
goto default;
case RequestTypes.Ping:
uriBuilder.Path += "ping";
queryBuilder.Append("&tid=");
queryBuilder.Append(this.RequestCounter++.ToString());
queryBuilder.Append("&_=");
queryBuilder.Append(Timestamp.ToString());
break;
default:
if (queryBuilder.Length > 0)
queryBuilder.Append("&");
queryBuilder.Append("tid=");
queryBuilder.Append(this.RequestCounter++.ToString());
queryBuilder.Append("&_=");
queryBuilder.Append(Timestamp.ToString());
if (transport != null)
{
queryBuilder.Append("&transport=");
queryBuilder.Append(transport.Name);
}
queryBuilder.Append("&clientProtocol=");
queryBuilder.Append(ClientProtocols[(byte)Protocol]);
if (NegotiationResult != null && !string.IsNullOrEmpty(this.NegotiationResult.ConnectionToken))
{
queryBuilder.Append("&connectionToken=");
queryBuilder.Append(this.NegotiationResult.ConnectionToken);
}
if (this.Hubs != null && this.Hubs.Length > 0)
{
queryBuilder.Append("&connectionData=");
queryBuilder.Append(this.ConnectionData);
}
break;
}
// Query params are added to all uri
if (this.AdditionalQueryParams != null && this.AdditionalQueryParams.Count > 0)
queryBuilder.Append(this.QueryParams);
uriBuilder.Query = queryBuilder.ToString();
// reset the string builder
queryBuilder.Length = 0;
return uriBuilder.Uri;
}
}
/// <summary>
/// It's called on every request before sending it out to the server.
/// </summary>
HTTPRequest IConnection.PrepareRequest(HTTPRequest req, RequestTypes type)
{
if (req != null && AuthenticationProvider != null)
AuthenticationProvider.PrepareRequest(req, type);
if (RequestPreparator != null)
RequestPreparator(this, req, type);
return req;
}
/// <summary>
/// Will parse a "{ 'Response': 'xyz' }" object and returns with 'xyz'. If it fails to parse, or getting the 'Response' key, it will call the Error function.
/// </summary>
string IConnection.ParseResponse(string responseStr)
{
Dictionary<string, object> dic = JSON.Json.Decode(responseStr) as Dictionary<string, object>;
if (dic == null)
{
(this as IConnection).Error("Failed to parse Start response: " + responseStr);
return string.Empty;
}
object value;
if (!dic.TryGetValue("Response", out value) || value == null)
{
(this as IConnection).Error("No 'Response' key found in response: " + responseStr);
return string.Empty;
}
return value.ToString();
}
#endregion
#region IHeartbeat Implementation
/// <summary>
/// IHeartbeat implementation to manage timeouts.
/// </summary>
void IHeartbeat.OnHeartbeatUpdate(TimeSpan dif)
{
switch(this.State)
{
case ConnectionStates.Connected:
if (Transport.SupportsKeepAlive && NegotiationResult.KeepAliveTimeout != null && DateTime.UtcNow - LastMessageReceivedAt >= NegotiationResult.KeepAliveTimeout)
Reconnect();
if (PingRequest == null && DateTime.UtcNow - LastPingSentAt >= PingInterval)
Ping();
break;
default:
if (TransportConnectionStartedAt != null && DateTime.UtcNow - TransportConnectionStartedAt >= NegotiationResult.TransportConnectTimeout)
{
HTTPManager.Logger.Warning("SignalR Connection", "OnHeartbeatUpdate - Transport failed to connect in the given time!");
// Using the Error function here instead of Close() will enable us to try to do a transport fallback.
(this as IConnection).Error("Transport failed to connect in the given time!");
}
if (ReconnectStarted && DateTime.UtcNow - ReconnectStartedAt >= NegotiationResult.DisconnectTimeout)
{
HTTPManager.Logger.Warning("SignalR Connection", "OnHeartbeatUpdate - Failed to reconnect in the given time!");
Close();
}
break;
}
}
#endregion
#region Private Helper Functions
/// <summary>
/// Init function to set the connected states and set up other variables.
/// </summary>
private void InitOnStart()
{
this.State = ConnectionStates.Connected;
//ReconnectStartedAt = null;
ReconnectStarted = false;
TransportConnectionStartedAt = null;
LastPingSentAt = DateTime.UtcNow;
LastMessageReceivedAt = DateTime.UtcNow;
HTTPManager.Heartbeats.Subscribe(this);
}
/// <summary>
/// Find and return with a Hub that has the message id.
/// </summary>
private Hub FindHub(UInt64 msgId)
{
if (Hubs != null)
for (int i = 0; i < Hubs.Length; ++i)
if ((Hubs[i] as IHub).HasSentMessageId(msgId))
return Hubs[i];
return null;
}
/// <summary>
/// Try to fall back to next transport. If no more transport to try, it will return false.
/// </summary>
private bool TryFallbackTransport()
{
if (this.State == ConnectionStates.Connecting)
{
if (BufferedMessages != null)
BufferedMessages.Clear();
// stop the current transport
Transport.Stop();
Transport = null;
switch(NextProtocolToTry)
{
#if !BESTHTTP_DISABLE_SERVERSENT_EVENTS
case SupportedProtocols.ServerSentEvents:
Transport = new ServerSentEventsTransport(this);
NextProtocolToTry = SupportedProtocols.HTTP;
break;
#endif
case SupportedProtocols.HTTP:
Transport = new PollingTransport(this);
NextProtocolToTry = SupportedProtocols.Unknown;
break;
case SupportedProtocols.Unknown:
return false;
}
TransportConnectionStartedAt = DateTime.UtcNow;
Transport.Connect();
if (PingRequest != null)
PingRequest.Abort();
return true;
}
return false;
}
/// <summary>
/// This event will be called when the AdditonalQueryPrams dictionary changed. We have to reset the cached values.
/// </summary>
private void AdditionalQueryParams_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
BuiltQueryParams = null;
}
#endregion
#region Ping Implementation
/// <summary>
/// Sends a Ping request to the SignalR server.
/// </summary>
private void Ping()
{
HTTPManager.Logger.Information("SignalR Connection", "Sending Ping request.");
PingRequest = new HTTPRequest((this as IConnection).BuildUri(RequestTypes.Ping), OnPingRequestFinished);
PingRequest.ConnectTimeout = PingInterval;
PingRequest.Send();
LastPingSentAt = DateTime.UtcNow;
}
/// <summary>
/// Called when the Ping request finished.
/// </summary>
void OnPingRequestFinished(HTTPRequest req, HTTPResponse resp)
{
PingRequest = null;
string reason = string.Empty;
switch (req.State)
{
// The request finished without any problem.
case HTTPRequestStates.Finished:
if (resp.IsSuccess)
{
// Parse the response, and do nothing when we receive the "pong" response
string response = (this as IConnection).ParseResponse(resp.DataAsText);
if (response != "pong")
reason = "Wrong answer for ping request: " + response;
else
HTTPManager.Logger.Information("SignalR Connection", "Pong received.");
}
else
reason = string.Format("Ping - Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
resp.StatusCode,
resp.Message,
resp.DataAsText);
break;
// The request finished with an unexpected error. The request's Exception property may contain more info about the error.
case HTTPRequestStates.Error:
reason = "Ping - Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
break;
// Ceonnecting to the server is timed out.
case HTTPRequestStates.ConnectionTimedOut:
reason = "Ping - Connection Timed Out!";
break;
// The request didn't finished in the given time.
case HTTPRequestStates.TimedOut:
reason = "Ping - Processing the request Timed Out!";
break;
}
if (!string.IsNullOrEmpty(reason))
(this as IConnection).Error(reason);
}
#endregion
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Reflection;
using System.Text;
using Cvv.WebUtility.Core;
using Cvv.WebUtility.Core.Json;
using Cvv.WebUtility.Mini;
using Cvv.WebUtility.Mvc.Provider;
namespace Cvv.WebUtility.Mvc
{
public static class WebAppConfig
{
private static readonly object _locked = new object();
private static string _defaultLayout = "master";
private static string _defaultLanguageCode = "en-US";
private static string _defaultTheme = "Default";
private static string _extension;
private static string _appKey;
private static string _appSecret;
private static string _oAuthUri;
private static Type _sessionType;
private static Type _securityType;
private static ITimeProvider _timeProvider;
private static ILoggingProvider _loggingProvider;
private static ISecurityProvider _securityProvider;
private static IDeserializerProvider _deserializeProvider;
private static ISerializerProvider _serializeProvider;
private static ISessionSerializer _sessionSerializer;
private static IStringFilter _stringFilterProvider;
private static ISessionDataProvider _sessionDataProvider = new MiniSessionDataProvider();
private static ISessionLoggingProvider _sessionLoggingProvider = new MiniSessionLoggingProvider();
private static IVisitorProvider _visitorProvider = new MinimalVisitorProvider();
private static readonly string _version;
private static readonly int _templateCacheDuration;
private static readonly Encoding _templateFileEncoding;
private static Dictionary<string, ControllerClass> _controllerClasses = null;
private static readonly List<Assembly> _registeredAssemblies = new List<Assembly>();
private static readonly bool _enabledPermission = false;
private static readonly bool _enabledHttpCompress;
public static event Action<SessionBase> SessionCreated;
static WebAppConfig()
{
string appClassName = ConfigurationManager.AppSettings["WebAppClassName"];
_version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
_templateCacheDuration = Convert.ToInt32(ConfigurationManager.AppSettings["TemplateCacheDuration"]);
_templateFileEncoding = string.IsNullOrEmpty(ConfigurationManager.AppSettings["TemplateFileEncoding"]) ? Encoding.Default : Encoding.GetEncoding(ConfigurationManager.AppSettings["TemplateFileEncoding"]);
bool.TryParse(ConfigurationManager.AppSettings["EnabledHttpCompress"], out _enabledHttpCompress);
string enabledPermission = ConfigurationManager.AppSettings["EnabledPermission"];
string defaultLanguageCode = ConfigurationManager.AppSettings["DefaultLanguageCode"];
if (defaultLanguageCode != null && defaultLanguageCode.Length >= 2)
{
_defaultLanguageCode = defaultLanguageCode;
}
_extension = ConfigurationManager.AppSettings["Extension"] ?? string.Empty;
_appKey = ConfigurationManager.AppSettings["AppKey"];
_appSecret = ConfigurationManager.AppSettings["AppSecret"];
_oAuthUri = ConfigurationManager.AppSettings["OAuthUri"];
//if (string.IsNullOrEmpty(_appKey))
// throw new CException("AppKey not found, please check the Web.config's configuration/appSettings.");
//if (string.IsNullOrEmpty(_appSecret))
// throw new CException("AppSecret not found, please check the Web.config's configuration/appSettings.");
//if (string.IsNullOrEmpty(_oAuthUri))
// throw new CException("OAuthUri not found, please check the Web.config's configuration/appSettings.");
//if (string.IsNullOrEmpty(_publicKey))
// throw new CException("PublicKey not found, please check the Web.config's configuration/appSettings.");
//if (string.IsNullOrEmpty(_privateKey))
// throw new CException("PrivateKey not found, please check the Web.config's configuration/appSettings.");
if (!string.IsNullOrEmpty(enabledPermission))
bool.TryParse(enabledPermission, out _enabledPermission);
if (string.IsNullOrEmpty(appClassName))
throw new CException("WebAppClassName not found, please check the Web.config's configuration/appSettings.");
Type appType = Type.GetType(appClassName, false);
if (appType == null)
throw new CException("Can not load the type of WebAppClassName '" + appClassName + "'");
MethodInfo initMethod = appType.GetMethod("Init", new Type[0]);
if (initMethod == null || !initMethod.IsStatic)
throw new CException("Can not found the static Init method of " + appType.FullName);
RegisterAssembly(appType.Assembly);
initMethod.Invoke(null, null);
if (_sessionType == null)
throw new CException("WebAppConfig.SessionType is null.");
if (_securityType == null)
throw new CException("WebAppConfig.SecurityType is null.");
LoadControllerClasses();
if (_timeProvider == null)
{
_timeProvider = new RealTimeProvider();
}
if (_deserializeProvider == null)
{
_deserializeProvider = new JSONDeserializer();
}
if (_serializeProvider == null)
{
_serializeProvider = new JSONSerializer();
}
if (_securityProvider == null)
{
_securityProvider = MiniSecurity.CreateInstance();
}
if (_stringFilterProvider == null)
{
_stringFilterProvider = new MFilter();
}
}
internal static bool EnabledHttpCompress
{
get { return _enabledHttpCompress; }
}
public static string DefaultLanguageCode
{
get { return _defaultLanguageCode; }
}
public static string Extension
{
get { return _extension; }
}
public static string AppKey
{
get { return _appKey; }
}
public static string AppSecret
{
get { return _appSecret; }
}
public static string OAuthUri
{
get { return _oAuthUri; }
}
public static string DefaultLayout
{
get { return _defaultLayout; }
}
public static string Version
{
get { return _version; }
}
public static bool EnabledPermission
{
get { return _enabledPermission; }
}
public static ITimeProvider TimeProvider
{
get { return _timeProvider; }
}
public static ILoggingProvider LoggingProvider
{
get { return _loggingProvider; }
set
{
lock (_locked)
{
if (_loggingProvider == null)
_loggingProvider = value;
}
}
}
public static ISecurityProvider SecurityProvider
{
get { return _securityProvider; }
set
{
lock (_locked)
{
if (_securityProvider == null)
_securityProvider = value;
}
}
}
public static ISessionDataProvider SessionDataProvider
{
get { return _sessionDataProvider; }
set { _sessionDataProvider = value; }
}
public static IDeserializerProvider DeserializeProvider
{
get { return _deserializeProvider; }
}
public static ISerializerProvider SerializeProvider
{
get { return _serializeProvider; }
}
public static IVisitorProvider VisitorProvider
{
get { return _visitorProvider; }
set { _visitorProvider = value; }
}
public static void Init()
{
}
public static Type SessionType
{
get { return _sessionType; }
set
{
if (!typeof(SessionBase).IsAssignableFrom(value))
throw new CException("Session type should be derived from SessionBase.");
_sessionType = value;
}
}
public static Type SecurityType
{
get { return _securityType; }
set
{
if (!typeof(Controller).IsAssignableFrom(value))
throw new CException("Security type should be derived from Controller.");
_securityType = value;
}
}
public static ISessionLoggingProvider SessionLoggingProvider
{
get { return _sessionLoggingProvider; }
set { _sessionLoggingProvider = value; }
}
public static ISessionSerializer SessionSerializer
{
get { return _sessionSerializer; }
set { _sessionSerializer = value; }
}
public static IStringFilter StringFilterProvider
{
get { return _stringFilterProvider; }
set
{
lock (_locked)
{
if (_stringFilterProvider == null)
_stringFilterProvider = value;
}
}
}
internal static int TemplateCacheDuration
{
get { return _templateCacheDuration; }
}
internal static Encoding TemplateFileEncoding
{
get { return _templateFileEncoding; }
}
public static string ThemePath
{
get
{
string theme = WebAppContext.Session.Theme ?? _defaultTheme;
if (WebAppContext.Request.ApplicationPath != "/")
{
return string.Concat(WebAppContext.Request.ApplicationPath, "/Themes/", theme);
}
else
{
return string.Concat("/Themes/", theme);
}
}
}
internal static bool FireSessionCreated(SessionBase session)
{
if (SessionCreated != null)
{
SessionCreated(session);
return true;
}
return false;
}
public static void RegisterAssembly(Assembly assembly)
{
if (_registeredAssemblies.Find(delegate(Assembly a) { return a.FullName == assembly.FullName; }) == null)
{
_registeredAssemblies.Add(assembly);
}
}
public static void RegisterAssembly(string assemblyPath)
{
Assembly assembly = Assembly.LoadFrom(assemblyPath);
RegisterAssembly(assembly);
}
public static string[] GetSecurityMethods()
{
List<string> list = new List<string>();
foreach (ControllerClass c in _controllerClasses.Values)
{
if (SecurityType.IsAssignableFrom(c.ClassType))
{
string[] methods = c.GetMethods();
foreach (string m in methods)
{
list.Add(string.Concat(c.Name, "$", m));
}
}
}
list.Sort();
return list.ToArray();
}
internal static ControllerClass GetControllerClass(string url)
{
ControllerClass controllerClass = null;
_controllerClasses.TryGetValue(url, out controllerClass);
return controllerClass;
}
private static void LoadControllerClasses()
{
_controllerClasses = new Dictionary<string, ControllerClass>(StringComparer.Ordinal);
List<Type> controllerTypes = new List<Type>();
foreach (Assembly assembly in _registeredAssemblies)
{
controllerTypes.AddRange(Util.FindCompatibleTypes(assembly, typeof(Controller)));
}
foreach (Type type in controllerTypes)
{
string baseAssemblyNamespace = type.Assembly.FullName.Split(',')[0] + ".PageControllers";
if (type.FullName.IndexOf(baseAssemblyNamespace) != -1)
{
string url = type.FullName.Substring(baseAssemblyNamespace.Length + 1).Replace('.', '/');
ControllerClass controllerClass = new ControllerClass(type, url.ToLower());
_controllerClasses.Add(controllerClass.Name, controllerClass);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace TemplateWebApplication.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Net;
using System.Net.Sockets;
using gov.va.medora.utils;
using gov.va.medora.mdo.exceptions;
using gov.va.medora.mdo.src.mdo;
using System.IO;
namespace gov.va.medora.mdo.dao.vista
{
public class VistaConnection : AbstractConnection
{
public Dictionary<string, bool> IssedBulletin = new Dictionary<string, bool>();
public IList<string> Rpcs = new List<string>();
const int CONNECTION_TIMEOUT = 30000;
const int READ_TIMEOUT = 60000;
const int DEFAULT_PORT = 9200;
public Socket socket;
public int port;
ISystemFileHandler sysFileHandler;
public VistaConnection(DataSource dataSource) : base(dataSource)
{
Account = new VistaAccount(this);
if (ConnectTimeout == 0)
{
ConnectTimeout = CONNECTION_TIMEOUT;
}
if (ReadTimeout == 0)
{
ReadTimeout = READ_TIMEOUT;
}
port = (dataSource.Port == 0) ? DEFAULT_PORT : dataSource.Port;
sysFileHandler = new VistaSystemFileHandler(this);
}
public override void connect()
{
IsConnecting = true;
ConnectStrategy.connect();
IsTestSource = isTestSystem();
IsConnecting = false;
}
//// Needs to return object so it can be either User or Exception on multi-site connections.
//public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission)
//{
// try
// {
// connect();
// return Account.authenticateAndAuthorize(credentials, permission);
// }
// catch (Exception ex)
// {
// return ex;
// }
//}
// Needs to return object so it can be either User or Exception on multi-site connections.
public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource)
{
try
{
connect();
return Account.authenticateAndAuthorize(credentials, permission, validationDataSource);
}
catch (Exception ex)
{
return ex;
}
}
public override ISystemFileHandler SystemFileHandler
{
get
{
if (sysFileHandler == null)
{
sysFileHandler = new VistaSystemFileHandler(this);
}
return sysFileHandler;
}
}
public override object query(MdoQuery vq, AbstractPermission context = null)
{
// see http://trac.medora.va.gov/web/ticket/2716
if (Rpcs == null)
{
Rpcs = new List<string>();
}
Rpcs.Add(vq.RpcName);
string request = vq.buildMessage();
return query(request, context);
}
public override object query(string request, AbstractPermission context = null)
{
// see http://trac.medora.va.gov/web/ticket/2716
if (Rpcs == null)
{
Rpcs = new List<string>();
}
try
{
// TBD - do we want to just not log calls if not passed through query(MdoQuery)??? it seems excessive to use reflection on every query
// to determine if the calling function was query(MdoQuery) and thus has already been logged.
// don't want to duplicate calls being logged by query(MdoQuery) so make sure that was NOT the calling function
if (!String.Equals(new System.Diagnostics.StackFrame(1).GetMethod().Name, "query", StringComparison.CurrentCultureIgnoreCase))
{
// we can't get RPC since we just received message but that information is human readable so save anyways
Rpcs.Add(request);
}
}
catch (Exception) { /* don't want to blow everything up - just hide this */ }
if (!IsConnecting && !IsConnected)
{
throw new NotConnectedException();
}
AbstractPermission currentContext = null;
if (context != null && context.Name != this.Account.PrimaryPermission.Name)
{
currentContext = this.Account.PrimaryPermission;
((VistaAccount)this.Account).setContext(context);
}
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
Byte[] bytesReceived = new Byte[256];
socket.Send(bytesSent, bytesSent.Length, 0);
int bytes = 0;
string reply = "";
StringBuilder sb = new StringBuilder();
string thisBatch = "";
bool isErrorMsg = false;
int endIdx = -1;
// first read from socket so we don't need to use isHdr any more
bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
if (bytes == 0)
{
throw new ConnectionException("Timeout waiting for response from VistA");
}
thisBatch = Encoding.ASCII.GetString(bytesReceived, 0, bytes);
endIdx = thisBatch.IndexOf('\x04');
if (endIdx != -1)
{
thisBatch = thisBatch.Substring(0, endIdx);
}
if (bytesReceived[0] != 0)
{
thisBatch = thisBatch.Substring(1, bytesReceived[0]);
isErrorMsg = true;
}
else if (bytesReceived[1] != 0)
{
thisBatch = thisBatch.Substring(2);
isErrorMsg = true;
}
else
{
thisBatch = thisBatch.Substring(2);
}
sb.Append(thisBatch);
// now we can start reading from socket in a loop
MemoryStream ms = new MemoryStream();
while (endIdx == -1)
{
bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
if (bytes == 0)
{
throw new ConnectionException("Timeout waiting for response from VistA");
}
for (int i = 0; i < bytes; i++)
{
if (bytesReceived[i] == '\x04')
{
endIdx = i;
break;
}
else
{
ms.WriteByte(bytesReceived[i]);
}
}
}
sb.Append(Encoding.ASCII.GetString(ms.ToArray()));
reply = sb.ToString();
if (currentContext != null)
{
((VistaAccount)this.Account).setContext(currentContext);
}
if (isErrorMsg || reply.Contains("M ERROR"))
{
throw new MdoException(MdoExceptionCode.VISTA_FAULT, reply);
}
return reply;
}
public override void disconnect()
{
if (!IsConnected)
{
return;
}
//string msg = StringUtils.strPack(StringUtils.strPack("#BYE#", 5), 5);
string msg = "[XWB]10304\x0005#BYE#\x0004";
msg = (string)query(msg);
//@todo msg should contain "BYE" - do anything if it doesn't?
socket.Close();
IsConnected = false;
}
public override string getWelcomeMessage()
{
MdoQuery request = buildGetWelcomeMessageRequest();
string response = (string)query(request);
return response;
}
internal MdoQuery buildGetWelcomeMessageRequest()
{
return new VistaQuery("XUS INTRO MSG");
}
public override bool hasPatch(string patchId)
{
MdoQuery request = buildHasPatchRequest(patchId);
string response = (string)query(request);
return (response == "1");
}
internal MdoQuery buildHasPatchRequest(string patchId)
{
VistaQuery vq = new VistaQuery("ORWU PATCH");
vq.addParameter(vq.LITERAL, patchId);
return vq;
}
internal bool isTestSystem()
{
VistaQuery vq = new VistaQuery("XUS SIGNON SETUP");
string response = (string)query(vq.buildMessage());
string[] flds = StringUtils.split(response, StringUtils.CRLF);
return flds[7] == "0";
}
public override string getServerTimeout()
{
string arg = "$P($G(^XTV(8989.3,1,\"XWB\")),U)";
MdoQuery request = VistaUtils.buildGetVariableValueRequest(arg);
string response = (string)query(request);
return response;
}
public override object query(SqlQuery request, Delegate functionToInvoke, AbstractPermission permission = null)
{
throw new NotImplementedException();
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Xml;
using System.Configuration;
using System.Windows.Forms;
using System.Collections;
using System.Text;
using WebsitePanel.Setup.Actions;
namespace WebsitePanel.Setup
{
public class Portal : BaseSetup
{
public static object Install(object obj)
{
return InstallBase(obj, "1.0.1");
}
internal static object InstallBase(object obj, string minimalInstallerVersion)
{
Hashtable args = Utils.GetSetupParameters(obj);
//check CS version
var shellMode = Utils.GetStringSetupParameter(args, Global.Parameters.ShellMode);
var version = new Version(Utils.GetStringSetupParameter(args, Global.Parameters.ShellVersion));
var setupVariables = new SetupVariables
{
SetupAction = SetupActions.Install,
ConfigurationFile = "web.config",
WebSiteIP = Global.WebPortal.DefaultIP, //empty - to detect IP
WebSitePort = Global.WebPortal.DefaultPort,
WebSiteDomain = String.Empty,
NewWebSite = true,
NewVirtualDirectory = false,
EnterpriseServerURL = Global.WebPortal.DefaultEntServURL
};
//
InitInstall(args, setupVariables);
//
var wam = new WebPortalActionManager(setupVariables);
//
wam.PrepareDistributiveDefaults();
//
if (shellMode.Equals(Global.SilentInstallerShell, StringComparison.OrdinalIgnoreCase))
{
if (version < new Version(minimalInstallerVersion))
{
Utils.ShowConsoleErrorMessage(Global.Messages.InstallerVersionIsObsolete, minimalInstallerVersion);
//
return false;
}
try
{
var success = true;
//
setupVariables.EnterpriseServerURL = Utils.GetStringSetupParameter(args, Global.Parameters.EnterpriseServerUrl);
//
wam.ActionError += new EventHandler<ActionErrorEventArgs>((object sender, ActionErrorEventArgs e) =>
{
Utils.ShowConsoleErrorMessage(e.ErrorMessage);
//
Log.WriteError(e.ErrorMessage);
//
success = false;
});
//
wam.Start();
//
return success;
}
catch (Exception ex)
{
Log.WriteError("Failed to install the component", ex);
//
return false;
}
}
else
{
if (version < new Version(minimalInstallerVersion))
{
//
MessageBox.Show(String.Format(Global.Messages.InstallerVersionIsObsolete, minimalInstallerVersion), "Setup Wizard", MessageBoxButtons.OK, MessageBoxIcon.Warning);
//
return DialogResult.Cancel;
}
//
InstallerForm form = new InstallerForm();
Wizard wizard = form.Wizard;
wizard.SetupVariables = setupVariables;
wizard.ActionManager = wam;
//Unattended setup
LoadSetupVariablesFromSetupXml(wizard.SetupVariables.SetupXml, wizard.SetupVariables);
//create wizard pages
var introPage = new IntroductionPage();
var licPage = new LicenseAgreementPage();
var page1 = new ConfigurationCheckPage();
ConfigurationCheck check1 = new ConfigurationCheck(CheckTypes.OperationSystem, "Operating System Requirement") { SetupVariables = setupVariables };
ConfigurationCheck check2 = new ConfigurationCheck(CheckTypes.IISVersion, "IIS Requirement") { SetupVariables = setupVariables };
ConfigurationCheck check3 = new ConfigurationCheck(CheckTypes.ASPNET, "ASP.NET Requirement") { SetupVariables = setupVariables };
page1.Checks.AddRange(new ConfigurationCheck[] { check1, check2, check3 });
var page2 = new InstallFolderPage();
var page3 = new WebPage();
var page4 = new UserAccountPage();
var page5 = new UrlPage();
var page6 = new ExpressInstallPage2();
var page7 = new FinishPage();
wizard.Controls.AddRange(new Control[] { introPage, licPage, page1, page2, page3, page4, page5, page6, page7 });
wizard.LinkPages();
wizard.SelectedPage = introPage;
//show wizard
IWin32Window owner = args[Global.Parameters.ParentForm] as IWin32Window;
return form.ShowModal(owner);
}
}
public static DialogResult Uninstall(object obj)
{
Hashtable args = Utils.GetSetupParameters(obj);
string shellVersion = Utils.GetStringSetupParameter(args, Global.Parameters.ShellVersion);
//
var setupVariables = new SetupVariables
{
ComponentId = Utils.GetStringSetupParameter(args, Global.Parameters.ComponentId),
IISVersion = Global.IISVersion,
SetupAction = SetupActions.Uninstall
};
//
AppConfig.LoadConfiguration();
InstallerForm form = new InstallerForm();
Wizard wizard = form.Wizard;
wizard.SetupVariables = setupVariables;
//
AppConfig.LoadComponentSettings(wizard.SetupVariables);
//
IntroductionPage page1 = new IntroductionPage();
ConfirmUninstallPage page2 = new ConfirmUninstallPage();
UninstallPage page3 = new UninstallPage();
//create uninstall currentScenario
InstallAction action = new InstallAction(ActionTypes.DeleteShortcuts);
action.Description = "Deleting shortcuts...";
action.Log = "- Delete shortcuts";
action.Name = "Login to WebsitePanel.url";
page3.Actions.Add(action);
page2.UninstallPage = page3;
FinishPage page4 = new FinishPage();
wizard.Controls.AddRange(new Control[] { page1, page2, page3, page4 });
wizard.LinkPages();
wizard.SelectedPage = page1;
//show wizard
IWin32Window owner = args[Global.Parameters.ParentForm] as IWin32Window;
return form.ShowModal(owner);
}
public static DialogResult Setup(object obj)
{
Hashtable args = Utils.GetSetupParameters(obj);
string shellVersion = Utils.GetStringSetupParameter(args, Global.Parameters.ShellVersion);
//
var setupVariables = new SetupVariables
{
ComponentId = Utils.GetStringSetupParameter(args, Global.Parameters.ComponentId),
SetupAction = SetupActions.Setup,
IISVersion = Global.IISVersion
};
//
AppConfig.LoadConfiguration();
InstallerForm form = new InstallerForm();
Wizard wizard = form.Wizard;
wizard.SetupVariables = setupVariables;
//
AppConfig.LoadComponentSettings(wizard.SetupVariables);
WebPage page1 = new WebPage();
UrlPage page2 = new UrlPage();
ExpressInstallPage page3 = new ExpressInstallPage();
//create install currentScenario
InstallAction action = new InstallAction(ActionTypes.UpdateWebSite);
action.Description = "Updating web site...";
page3.Actions.Add(action);
action = new InstallAction(ActionTypes.UpdateEnterpriseServerUrl);
action.Description = "Updating site settings...";
page3.Actions.Add(action);
action = new InstallAction(ActionTypes.UpdateConfig);
action.Description = "Updating system configuration...";
page3.Actions.Add(action);
FinishPage page4 = new FinishPage();
wizard.Controls.AddRange(new Control[] { page1, page2, page3, page4 });
wizard.LinkPages();
wizard.SelectedPage = page1;
//show wizard
IWin32Window owner = args[Global.Parameters.ParentForm] as IWin32Window;
return form.ShowModal(owner);
}
public static DialogResult Update(object obj)
{
Hashtable args = Utils.GetSetupParameters(obj);
var setupVariables = new SetupVariables
{
ComponentId = Utils.GetStringSetupParameter(args, Global.Parameters.ComponentId),
SetupAction = SetupActions.Update,
IISVersion = Global.IISVersion
};
AppConfig.LoadConfiguration();
InstallerForm form = new InstallerForm();
Wizard wizard = form.Wizard;
wizard.SetupVariables = setupVariables;
//
AppConfig.LoadComponentSettings(wizard.SetupVariables);
//
IntroductionPage introPage = new IntroductionPage();
LicenseAgreementPage licPage = new LicenseAgreementPage();
ExpressInstallPage page2 = new ExpressInstallPage();
//create install currentScenario
InstallAction action = new InstallAction(ActionTypes.Backup);
action.Description = "Backing up...";
page2.Actions.Add(action);
action = new InstallAction(ActionTypes.DeleteFiles);
action.Description = "Deleting files...";
action.Path = "setup\\delete.txt";
page2.Actions.Add(action);
action = new InstallAction(ActionTypes.CopyFiles);
action.Description = "Copying files...";
page2.Actions.Add(action);
action = new InstallAction(ActionTypes.UpdateConfig);
action.Description = "Updating system configuration...";
page2.Actions.Add(action);
FinishPage page3 = new FinishPage();
wizard.Controls.AddRange(new Control[] { introPage, licPage, page2, page3 });
wizard.LinkPages();
wizard.SelectedPage = introPage;
//show wizard
IWin32Window owner = args[Global.Parameters.ParentForm] as IWin32Window;
return form.ShowModal(owner);
}
}
}
| |
using Data.DbClient.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Data.DbClient.BulkCopy
{
public class SqlBulkCopyUtility
{
#region Import Methods
//TODO: Rework into new SqlServerBulkCopy method similiar to below methods.
public void ImportDataTableToSql(
ref DataTable dt,
string server,
string database,
string destinationTableName,
int connectTimeout = 360,
int packetSize = 8192,
IEnumerable<SqlBulkCopyColumnMapping> sqlBulkCopyColumnMappings = null,
int batchSize = 0,
int bulkCopyTimeout = 0,
bool enableIndentityInsert = false
)
{
var cb = new SqlConnectionStringBuilder
{
DataSource = server,
InitialCatalog = database,
IntegratedSecurity = true,
ConnectTimeout = connectTimeout,
PacketSize = packetSize
};
using (var bulkCopy = new SqlBulkCopy(cb.ConnectionString, enableIndentityInsert ? SqlBulkCopyOptions.KeepIdentity : SqlBulkCopyOptions.Default))
{
bulkCopy.DestinationTableName = destinationTableName;
if (batchSize > 0) bulkCopy.BatchSize = batchSize;
if (bulkCopyTimeout > 0) bulkCopy.BulkCopyTimeout = bulkCopyTimeout;
if (sqlBulkCopyColumnMappings != null)
{
foreach (var mapId in sqlBulkCopyColumnMappings)
{
bulkCopy.ColumnMappings.Add(mapId);
}
}
bulkCopy.WriteToServer(dt);
}
}
public void SqlServerBulkCopy(
string sourceConnStr,
string destConnStr,
string sourceCmdStr,
string destTableName,
int batchSize = 0,
int bulkCopyTimeout = 0,
bool enableIndentityInsert = false,
IDictionary<string, string> sqlBulkCopyColumnMappings = null
)
{
using (var sourceConn = new SqlConnection(sourceConnStr))
{
sourceConn.Open();
var command = new SqlCommand(sourceCmdStr, sourceConn);
using (var bulkCopy = new SqlBulkCopy(destConnStr, enableIndentityInsert ? SqlBulkCopyOptions.KeepIdentity : SqlBulkCopyOptions.Default))
{
bulkCopy.DestinationTableName = destTableName;
if (batchSize > 0) bulkCopy.BatchSize = batchSize;
if (bulkCopyTimeout > 0) bulkCopy.BulkCopyTimeout = bulkCopyTimeout;
if (sqlBulkCopyColumnMappings != null)
{
foreach (var mapId in sqlBulkCopyColumnMappings.GetSqlBulkCopyColumnMappings())
{
bulkCopy.ColumnMappings.Add(mapId);
}
}
using (IDataReader reader = command.ExecuteReader())
{
bulkCopy.WriteToServer(reader);
}
}
}
}
public void SqlServerBulkCopy(
ref DbDataReader dataReader,
string destConnStr,
string destTableName,
int batchSize = 0,
int bulkCopyTimeout = 0,
bool enableIndentityInsert = false,
IDictionary<string, string> sqlBulkCopyColumnMappings = null
)
{
using (var bulkCopy = new SqlBulkCopy(destConnStr, enableIndentityInsert ? SqlBulkCopyOptions.KeepIdentity : SqlBulkCopyOptions.Default))
{
bulkCopy.DestinationTableName = destTableName;
if (batchSize > 0) bulkCopy.BatchSize = batchSize;
if (bulkCopyTimeout > 0) bulkCopy.BulkCopyTimeout = bulkCopyTimeout;
if (sqlBulkCopyColumnMappings != null)
{
foreach (var mapId in sqlBulkCopyColumnMappings.GetSqlBulkCopyColumnMappings())
{
bulkCopy.ColumnMappings.Add(mapId);
}
}
bulkCopy.WriteToServer(dataReader);
}
}
public static void BulkInsert<T>(
IEnumerable<T> list,
string destConnStr,
string destTableName,
int batchSize = 0,
int bulkCopyTimeout = 0,
bool enableIndentityInsert = false,
IDictionary<string, string> sqlBulkCopyColumnMappings = null
)
{
using (var bulkCopy = new SqlBulkCopy(destConnStr))
{
bulkCopy.DestinationTableName = destTableName;
if (batchSize > 0) bulkCopy.BatchSize = batchSize;
if (bulkCopyTimeout > 0) bulkCopy.BulkCopyTimeout = bulkCopyTimeout;
var table = new DataTable();
var props = TypeDescriptor.GetProperties(typeof(T))
//Dirty hack to make sure we only have system data types
//i.e. filter out the relationships/collections
.Cast<PropertyDescriptor>()
.Where(propertyInfo => propertyInfo.PropertyType.Namespace != null && propertyInfo.PropertyType.Namespace.Equals("System"))
.ToArray();
if (sqlBulkCopyColumnMappings != null)
{
foreach (var mapId in sqlBulkCopyColumnMappings.GetSqlBulkCopyColumnMappings())
{
bulkCopy.ColumnMappings.Add(mapId);
}
}
else
{
foreach (var propertyInfo in props)
{
bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
}
}
foreach (var propertyInfo in props)
{
table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
}
var values = new object[props.Length];
foreach (var item in list)
{
for (var i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
bulkCopy.WriteToServer(table);
}
}
//public static void BulkInsert<T>(
// IEnumerable<T> list,
// string destConnStr,
// string destTableName,
// Int32 batchSize = 0,
// Int32 bulkCopyTimeout = 0,
// Boolean enableIndentityInsert = false,
// IDictionary<string, string> sqlBulkCopyColumnMappings = null
// )
//{
// using (var bulkCopy = new SqlBulkCopy(destConnStr))
// {
// bulkCopy.DestinationTableName = destTableName;
// if (batchSize > 0) bulkCopy.BatchSize = batchSize;
// if (bulkCopyTimeout > 0) bulkCopy.BulkCopyTimeout = bulkCopyTimeout;
// if (sqlBulkCopyColumnMappings != null)
// {
// foreach (var mapId in sqlBulkCopyColumnMappings.GetSqlBulkCopyColumnMappings())
// {
// bulkCopy.ColumnMappings.Add(mapId);
// }
// }
// var table = new DataTable();
// var props = TypeDescriptor.GetProperties(typeof(T))
// //Dirty hack to make sure we only have system data types
// //i.e. filter out the relationships/collections
// .Cast<PropertyDescriptor>()
// .Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System"))
// .ToArray();
// foreach (var propertyInfo in props)
// {
// bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
// table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
// }
// var values = new object[props.Length];
// foreach (var item in list)
// {
// for (var i = 0; i < values.Length; i++)
// {
// values[i] = props[i].GetValue(item);
// }
// table.Rows.Add(values);
// }
// bulkCopy.WriteToServer(table);
// }
//}
//public static void BulkInsert<T>(string connection, string tableName, IList<T> list)
//{
// using (var bulkCopy = new SqlBulkCopy(connection))
// {
// bulkCopy.BatchSize = list.Count;
// bulkCopy.DestinationTableName = tableName;
// var table = new DataTable();
// var props = TypeDescriptor.GetProperties(typeof(T))
// //Dirty hack to make sure we only have system data types
// //i.e. filter out the relationships/collections
// .Cast<PropertyDescriptor>()
// .Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System"))
// .ToArray();
// foreach (var propertyInfo in props)
// {
// bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
// table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
// }
// var values = new object[props.Length];
// foreach (var item in list)
// {
// for (var i = 0; i < values.Length; i++)
// {
// values[i] = props[i].GetValue(item);
// }
// table.Rows.Add(values);
// }
// bulkCopy.WriteToServer(table);
// }
//}
public bool ImportSeperatedTxtToSql(string connectionString, string tableName, int timeOutSeconds, string filePathStr, string schemaFilePath, int batchRowSize, bool colHeaders, string fieldSeperator, string textQualifier, string nullValue, bool enableIndentityInsert = false)
{
var dt = new DataTable(tableName);
var fi = new FileInfo(filePathStr);
if (fi.Exists)
{
var fi2 = new FileInfo(schemaFilePath);
if (!fi2.Exists)
{
SqlConnection conn = null;
try
{
conn = new SqlConnection(connectionString);
conn.Open();
var cmd = new SqlCommand("SELECT * FROM " + tableName, conn) { CommandType = CommandType.Text };
var da = new SqlDataAdapter(cmd);
da.FillSchema(dt, SchemaType.Source);
conn.Close();
dt.WriteXmlSchema(schemaFilePath);
}
finally
{
if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
conn?.Dispose();
}
}
else
{
dt.ReadXmlSchema(schemaFilePath);
}
}
else
{
return false;
}
using (var sr = fi.OpenText())
{
using (var bulkCopy = new SqlBulkCopy(connectionString, enableIndentityInsert ? SqlBulkCopyOptions.KeepIdentity : SqlBulkCopyOptions.Default))
{
if (colHeaders)
{
sr.ReadLine(); // skip first line if contains Column Headers
}
string tempStr;
var csvParser = SeperatedLineParser(fieldSeperator, textQualifier);
while ((tempStr = sr.ReadLine()) != null)
{
if (!tempStr.Contains(fieldSeperator)) continue;
var drow = dt.NewRow();
var stringArray = csvParser.Split(tempStr).Select(x => x.Replace(textQualifier, string.Empty)).ToArray();
for (var j = 0; j < dt.Columns.Count; j++)
{
if (stringArray[j] == nullValue || stringArray[j].Trim() == string.Empty)
{
drow[j] = DBNull.Value;
}
else
{
drow[j] = stringArray[j];
}
}
dt.Rows.Add(drow);
if (dt.Rows.Count != batchRowSize) continue;
bulkCopy.BatchSize = batchRowSize;
bulkCopy.BulkCopyTimeout = timeOutSeconds;
bulkCopy.DestinationTableName = tableName;
bulkCopy.WriteToServer(dt);
dt.Clear();
}
bulkCopy.BatchSize = batchRowSize;
bulkCopy.BulkCopyTimeout = timeOutSeconds;
bulkCopy.DestinationTableName = tableName;
bulkCopy.WriteToServer(dt);
}
}
return true;
}
public bool ImportSeperatedTxtToSql(string connectionString, string tableName, int timeOutSeconds, string filePathStr, string schemaFilePath, int batchRowSize, bool colHeaders, string fieldSeperator, string textQualifier, string nullValue, string filterExpression, bool enableIndentityInsert = false)
{
var dt = new DataTable(tableName);
var fi = new FileInfo(filePathStr);
if (fi.Exists)
{
var fi2 = new FileInfo(schemaFilePath);
if (!fi2.Exists)
{
SqlConnection conn = null;
try
{
conn = new SqlConnection(connectionString);
conn.Open();
var cmd = new SqlCommand("SELECT * FROM " + tableName, conn) { CommandType = CommandType.Text };
var da = new SqlDataAdapter(cmd);
da.FillSchema(dt, SchemaType.Source);
conn.Close();
dt.WriteXmlSchema(schemaFilePath);
}
finally
{
if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
conn?.Dispose();
}
}
else
{
dt.ReadXmlSchema(schemaFilePath);
}
dt.DefaultView.RowFilter = filterExpression;
}
else
{
return false;
}
using (var sr = fi.OpenText())
{
using (var bulkCopy = new SqlBulkCopy(connectionString, enableIndentityInsert ? SqlBulkCopyOptions.KeepIdentity : SqlBulkCopyOptions.Default))
{
if (colHeaders)
{
sr.ReadLine(); // skip first line if contains Column Headers
}
string tempStr;
var csvParser = SeperatedLineParser(fieldSeperator, textQualifier);
while ((tempStr = sr.ReadLine()) != null)
{
if (!tempStr.Contains(fieldSeperator)) continue;
var drow = dt.NewRow();
var stringArray = csvParser.Split(tempStr).Select(x => x.Replace(textQualifier, string.Empty)).ToArray();
for (var j = 0; j < dt.Columns.Count; j++)
{
if (stringArray[j] == nullValue || stringArray[j].Trim() == string.Empty)
{
drow[j] = DBNull.Value;
}
else
{
drow[j] = stringArray[j];
}
}
dt.Rows.Add(drow);
if (dt.Rows.Count != batchRowSize) continue;
bulkCopy.BatchSize = batchRowSize;
bulkCopy.BulkCopyTimeout = timeOutSeconds;
bulkCopy.DestinationTableName = tableName;
bulkCopy.WriteToServer(dt.DefaultView.ToTable());
dt.Clear();
}
bulkCopy.BatchSize = batchRowSize;
bulkCopy.BulkCopyTimeout = timeOutSeconds;
bulkCopy.DestinationTableName = tableName;
bulkCopy.WriteToServer(dt.DefaultView.ToTable());
}
}
return true;
}
#endregion Import Methods
#region Export Methods
public int ExportSeperatedTxt(
string connectionString,
string commandString,
string filePathStr,
int batchRowSize = 1000,
bool colHeaders = false,
string fieldSeperator = "\t",
string textQualifier = null,
string newLineChar = "\r\n",
string nullValue = "",
int? timeOutSeconds = 600)
{
return ExportSeperatedTxt(connectionString, new SqlCommand(commandString), filePathStr, batchRowSize, colHeaders, fieldSeperator, textQualifier, newLineChar, nullValue, timeOutSeconds);
}
public int ExportSeperatedTxt(
string connectionString,
SqlCommand commandObj,
string filePathStr,
int batchRowSize = 1000,
bool colHeaders = false,
string fieldSeperator = "\t",
string textQualifier = null,
string newLineChar = "\r\n",
string nullValue = "",
int? timeOutSeconds = 600)
{
var returnvalue = 0;
using (var conn = new SqlConnection(connectionString))
{
commandObj.Connection = conn;
if (timeOutSeconds.HasValue) commandObj.CommandTimeout = timeOutSeconds.Value;
conn.Open();
var sqlDr = commandObj.ExecuteReader(CommandBehavior.CloseConnection);
if (!sqlDr.HasRows) return returnvalue;
if (batchRowSize < 1)
{
batchRowSize = 1;
}
var flushcnt = batchRowSize;
using (var sw = new StreamWriter(filePathStr, true))
{
var schemaDt = sqlDr.GetSchemaTable();
if (schemaDt != null)
{
var colCnt = schemaDt.Rows.Count;
var useFormat = new bool[colCnt];
var fmtString = new string[colCnt];
for (var i = 0; i < colCnt; i++)
{
var fieldtype = sqlDr.GetProviderSpecificFieldType(i);
if (fieldtype == typeof(SqlString))
{
if (string.IsNullOrEmpty(textQualifier)) continue;
fmtString[i] = textQualifier + "{0}" + textQualifier;
useFormat[i] = true;
}
else if (fieldtype == typeof(SqlDateTime))
{
fmtString[i] = "{0:yyyy-MM-dd HH:mm:ss.fff}";
useFormat[i] = true;
}
else if (fieldtype == typeof(SqlBoolean))
{
useFormat[i] = true;
}
else if (fieldtype == typeof(SqlBinary))
{
useFormat[i] = true;
}
else
{
useFormat[i] = false;
}
}
if (colHeaders)
{
if (!string.IsNullOrEmpty(textQualifier))
{
var fmtHeadString = textQualifier + "{0}" + textQualifier;
for (var i = 0; i < colCnt - 1; i++)
{
sw.Write(fmtHeadString, sqlDr.GetName(i));
sw.Write(fieldSeperator);
}
sw.Write(fmtHeadString, sqlDr.GetName(sqlDr.FieldCount - 1));
}
else
{
for (var i = 0; i < colCnt - 1; i++)
{
sw.Write(sqlDr.GetName(i) + fieldSeperator);
}
sw.Write(sqlDr.GetName(sqlDr.FieldCount - 1));
}
sw.Write(newLineChar);
}
foreach (DbDataRecord rec in sqlDr)
{
for (var i = 0; i < colCnt - 1; i++)
{
if (!rec.IsDBNull(i))
{
if (useFormat[i])
{
if (!string.IsNullOrEmpty(fmtString[i]))
{
sw.Write(fmtString[i], rec.GetValue(i));
}
else
{
var fieldtype = sqlDr.GetProviderSpecificFieldType(i);
if (fieldtype == typeof(SqlBoolean))
{
if ((bool)rec.GetValue(i))
{
sw.Write(1);
}
else
{
sw.Write(0);
}
}
else if (fieldtype == typeof(SqlBinary))
{
if (schemaDt.Rows[i][SchemaTableOptionalColumn.IsRowVersion].ToString() == "true")
{
// used for timestamp rowversion columns to convert to Int64 / bigint
var arr = (Byte[])rec.GetValue(i);
if (arr.Length == 8)
{
sw.Write(Int64.Parse(BitConverter.ToString((Byte[])rec.GetValue(i), 0).Replace("-", ""), NumberStyles.HexNumber));
}
else
{
BitConverter.ToString((Byte[])rec.GetValue(i), 0); // if not write byte[] to string.
}
}
else
{
BitConverter.ToString((Byte[])rec.GetValue(i), 0); // if not write byte[] to string.
}
}
}
}
else
{
sw.Write(rec.GetValue(i));
}
}
else if (!string.IsNullOrWhiteSpace(nullValue))
{
sw.Write(nullValue);
}
sw.Write(fieldSeperator);
}
// write last column
if (!rec.IsDBNull(colCnt - 1))
{
if (useFormat[colCnt - 1])
{
if (!string.IsNullOrEmpty(fmtString[colCnt - 1]))
{
sw.Write(fmtString[colCnt - 1], rec.GetValue(colCnt - 1));
}
else
{
var fieldtype = sqlDr.GetProviderSpecificFieldType(colCnt - 1);
if (fieldtype == typeof(SqlBoolean))
{
if ((bool)rec.GetValue(colCnt - 1))
{
sw.Write(1);
}
else
{
sw.Write(0);
}
}
if (fieldtype == typeof(SqlBinary))
{
// used for timestamp rowversion columns to convert to Int64 / bigint
var arr = (Byte[])rec.GetValue(colCnt - 1);
if (arr.Length == 8)
{
sw.Write(Int64.Parse(BitConverter.ToString((Byte[])rec.GetValue(colCnt - 1), 0).Replace("-", ""), NumberStyles.HexNumber));
}
else
{
BitConverter.ToString((Byte[])rec.GetValue(colCnt - 1), 0); // if not write byte[] to string.
}
}
}
}
else
{
sw.Write(rec.GetValue(colCnt - 1));
}
}
else if (!string.IsNullOrWhiteSpace(nullValue))
{
sw.Write(nullValue);
}
sw.Write(newLineChar);
returnvalue++;
flushcnt--;
if (flushcnt >= 1) continue;
flushcnt = batchRowSize;
sw.Flush();
}
}
sw.Flush();
}
}
return returnvalue;
}
public int ExportSeperatedGZipTxt(
string connectionString,
string commandString,
string filePathStr,
int batchRowSize = 1000,
bool colHeaders = false,
string fieldSeperator = "\t",
string textQualifier = null,
string newLineChar = "\r\n",
string nullValue = "")
{
return ExportSeperatedGZipTxt(connectionString, new SqlCommand(commandString), filePathStr, batchRowSize, colHeaders, fieldSeperator, textQualifier, newLineChar, nullValue);
}
public int ExportSeperatedGZipTxt(
string connectionString,
SqlCommand commandObj,
string filePathStr,
int batchRowSize = 1000,
bool colHeaders = false,
string fieldSeperator = "\t",
string textQualifier = null,
string newLineChar = "\r\n",
string nullValue = "")
{
var returnvalue = 0;
using (var conn = new SqlConnection(connectionString))
{
commandObj.Connection = conn;
conn.Open();
var sqlDr = commandObj.ExecuteReader(CommandBehavior.CloseConnection);
if (sqlDr.HasRows)
{
if (batchRowSize < 1)
{
batchRowSize = 1;
}
var flushcnt = batchRowSize;
var encoding = Encoding.ASCII;
using (var fs = new FileStream(filePathStr, FileMode.Create, FileAccess.Write, FileShare.None))
{
// start gz
using (var gzip = new GZipStream(fs, CompressionMode.Compress, true))
{
using (var sw = new StreamWriter(gzip, encoding))
{
var schemaDt = sqlDr.GetSchemaTable();
if (schemaDt != null)
{
var colCnt = schemaDt.Rows.Count;
var useFormat = new bool[colCnt];
var fmtString = new string[colCnt];
for (var i = 0; i < colCnt; i++)
{
var fieldtype = sqlDr.GetProviderSpecificFieldType(i);
if (fieldtype == typeof(SqlString))
{
if (string.IsNullOrEmpty(textQualifier)) continue;
fmtString[i] = textQualifier + "{0}" + textQualifier;
useFormat[i] = true;
}
else if (fieldtype == typeof(SqlDateTime))
{
fmtString[i] = "{0:yyyy-MM-dd HH:mm:ss.fff}";
useFormat[i] = true;
}
else if (fieldtype == typeof(SqlBoolean))
{
useFormat[i] = true;
}
else if (fieldtype == typeof(SqlBinary))
{
useFormat[i] = true;
}
else
{
useFormat[i] = false;
}
}
if (colHeaders)
{
if (!string.IsNullOrEmpty(textQualifier))
{
string fmtHeadString = textQualifier + "{0}" + textQualifier;
for (var i = 0; i < colCnt - 1; i++)
{
sw.Write(fmtHeadString, sqlDr.GetName(i));
sw.Write(fieldSeperator);
}
sw.Write(fmtHeadString, sqlDr.GetName(sqlDr.FieldCount - 1));
}
else
{
for (var i = 0; i < colCnt - 1; i++)
{
sw.Write(sqlDr.GetName(i) + fieldSeperator);
}
sw.Write(sqlDr.GetName(sqlDr.FieldCount - 1));
}
sw.Write(newLineChar);
}
foreach (DbDataRecord rec in sqlDr)
{
for (var i = 0; i < colCnt - 1; i++)
{
if (!rec.IsDBNull(i))
{
if (useFormat[i])
{
if (!string.IsNullOrEmpty(fmtString[i]))
{
sw.Write(fmtString[i], rec.GetValue(i));
}
else
{
var fieldtype = sqlDr.GetProviderSpecificFieldType(i);
if (fieldtype == typeof(SqlBoolean))
{
if ((bool)rec.GetValue(i))
{
sw.Write(1);
}
else
{
sw.Write(0);
}
}
else if (fieldtype == typeof(SqlBinary))
{
if (schemaDt.Rows[i][SchemaTableOptionalColumn.IsRowVersion].ToString() == "true")
{
// used for timestamp rowversion columns to convert to Int64 / bigint
var arr = (Byte[])rec.GetValue(i);
if (arr.Length == 8)
{
sw.Write(Int64.Parse(BitConverter.ToString((Byte[])rec.GetValue(i), 0).Replace("-", ""), NumberStyles.HexNumber));
}
else
{
BitConverter.ToString((Byte[])rec.GetValue(i), 0); // if not write byte[] to string.
}
}
else
{
BitConverter.ToString((Byte[])rec.GetValue(i), 0); // if not write byte[] to string.
}
}
}
}
else
{
sw.Write(rec.GetValue(i));
}
}
else if (!string.IsNullOrWhiteSpace(nullValue))
{
sw.Write(nullValue);
}
sw.Write(fieldSeperator);
}
// write last column
if (!rec.IsDBNull(colCnt - 1))
{
if (useFormat[colCnt - 1])
{
if (!string.IsNullOrEmpty(fmtString[colCnt - 1]))
{
sw.Write(fmtString[colCnt - 1], rec.GetValue(colCnt - 1));
}
else
{
var fieldtype = sqlDr.GetProviderSpecificFieldType(colCnt - 1);
if (fieldtype == typeof(SqlBoolean))
{
if ((bool)rec.GetValue(colCnt - 1))
{
sw.Write(1);
}
else
{
sw.Write(0);
}
}
if (fieldtype == typeof(SqlBinary))
{
// used for timestamp rowversion columns to convert to Int64 / bigint
var arr = (Byte[])rec.GetValue(colCnt - 1);
if (arr.Length == 8)
{
sw.Write(Int64.Parse(BitConverter.ToString((Byte[])rec.GetValue(colCnt - 1), 0).Replace("-", ""), NumberStyles.HexNumber));
}
else
{
BitConverter.ToString((Byte[])rec.GetValue(colCnt - 1), 0); // if not write byte[] to string.
}
}
}
}
else
{
sw.Write(rec.GetValue(colCnt - 1));
}
}
else if (!string.IsNullOrWhiteSpace(nullValue))
{
sw.Write(nullValue);
}
sw.Write(newLineChar);
returnvalue++;
flushcnt--;
if (flushcnt >= 1) continue;
flushcnt = batchRowSize;
sw.Flush();
}
}
sw.Flush();
gzip.Flush();
}
// end gz
}
}
}
}
return returnvalue;
}
#endregion Export Methods
#region Helper Methods
public DataTable GetDataTableWithSchema(string server, string database, string table)
{
var dt = new DataTable();
var cb = new SqlConnectionStringBuilder
{
DataSource = server,
InitialCatalog = database,
IntegratedSecurity = true,
ConnectTimeout = 360
};
//cb.PacketSize = ???
using (var conn = new SqlConnection(cb.ConnectionString))
{
conn.Open();
var cmd = new SqlCommand("SELECT * FROM " + table, conn) { CommandType = CommandType.Text };
var da = new SqlDataAdapter(cmd);
da.FillSchema(dt, SchemaType.Source);
conn.Close();
}
return dt;
}
private string AddNull(string str)
{
if (string.IsNullOrEmpty(str))
{
str = "NULL";
}
return str;
}
private string AddStrNull(string str)
{
if (!string.IsNullOrWhiteSpace(str)) return "\"" + str + "\"";
str = "NULL";
return str;
}
private Regex SeperatedLineParser(string fieldSeperator, string textQualifier)
{
//if (String.IsNullOrWhiteSpace(textQualifier))
//{
//}
var regexPattern = string.Format("{0}(?=(?:[^{1}]*{1}[^{1}]*{1})*(?![^{1}]*{1}))", fieldSeperator, textQualifier);
return new Regex(regexPattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.CultureInvariant);
// alternative http://www.schiffhauer.com/c-split-csv-values-with-a-regular-expression/
// ((?<=\")[^\"]*(?=\"(,|$)+)|(?<=,|^)[^,\"]*(?=,|$))
// ((?<=\")[^\"]*(?=\"(\t|$)+)|(?<=\t|^)[^\t\"]*(?=\t|$))
}
#endregion Helper Methods
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created on 28-Oct-2004
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Tokenattributes;
using Lucene.Net.Documents;
using Lucene.Net.Index;
namespace Lucene.Net.Search.Highlight
{
/// <summary> Hides implementation issues associated with obtaining a TokenStream for use with
/// the higlighter - can obtain from TermFreqVectors with offsets and (optionally) positions or
/// from Analyzer class reparsing the stored content.
/// </summary>
public class TokenSources
{
public class StoredTokenStream : TokenStream
{
protected internal Token[] tokens;
protected internal int currentToken = 0;
protected internal ITermAttribute termAtt;
protected internal IOffsetAttribute offsetAtt;
protected internal StoredTokenStream(Token[] tokens)
{
this.tokens = tokens;
termAtt = AddAttribute<ITermAttribute>();
offsetAtt = AddAttribute<IOffsetAttribute>();
}
public override bool IncrementToken()
{
if (currentToken >= tokens.Length)
{
return false;
}
ClearAttributes();
Token token = tokens[currentToken++];
termAtt.SetTermBuffer(token.Term);
offsetAtt.SetOffset(token.StartOffset, token.EndOffset);
return true;
}
protected override void Dispose(bool disposing)
{
// do nothing
}
}
/// <summary>
/// A convenience method that tries to first get a TermPositionVector for the specified docId, then, falls back to
/// using the passed in {@link org.apache.lucene.document.Document} to retrieve the TokenStream. This is useful when
/// you already have the document, but would prefer to use the vector first.
/// </summary>
/// <param name="reader">The <see cref="IndexReader"/> to use to try and get the vector from</param>
/// <param name="docId">The docId to retrieve.</param>
/// <param name="field">The field to retrieve on the document</param>
/// <param name="doc">The document to fall back on</param>
/// <param name="analyzer">The analyzer to use for creating the TokenStream if the vector doesn't exist</param>
/// <returns>The <see cref="TokenStream"/> for the <see cref="IFieldable"/> on the <see cref="Document"/></returns>
/// <exception cref="IOException">if there was an error loading</exception>
public static TokenStream GetAnyTokenStream(IndexReader reader, int docId, String field, Document doc,
Analyzer analyzer)
{
TokenStream ts = null;
var tfv = reader.GetTermFreqVector(docId, field);
if (tfv != null)
{
var termPositionVector = tfv as TermPositionVector;
if (termPositionVector != null)
{
ts = GetTokenStream(termPositionVector);
}
}
//No token info stored so fall back to analyzing raw content
return ts ?? GetTokenStream(doc, field, analyzer);
}
/// <summary>
/// A convenience method that tries a number of approaches to getting a token stream.
/// The cost of finding there are no termVectors in the index is minimal (1000 invocations still
/// registers 0 ms). So this "lazy" (flexible?) approach to coding is probably acceptable
/// </summary>
/// <returns>null if field not stored correctly</returns>
public static TokenStream GetAnyTokenStream(IndexReader reader, int docId, String field, Analyzer analyzer)
{
TokenStream ts = null;
var tfv = reader.GetTermFreqVector(docId, field);
if (tfv != null)
{
var termPositionVector = tfv as TermPositionVector;
if (termPositionVector != null)
{
ts = GetTokenStream(termPositionVector);
}
}
//No token info stored so fall back to analyzing raw content
return ts ?? GetTokenStream(reader, docId, field, analyzer);
}
public static TokenStream GetTokenStream(TermPositionVector tpv)
{
//assumes the worst and makes no assumptions about token position sequences.
return GetTokenStream(tpv, false);
}
/// <summary>
/// Low level api.
/// Returns a token stream or null if no offset info available in index.
/// This can be used to feed the highlighter with a pre-parsed token stream
///
/// In my tests the speeds to recreate 1000 token streams using this method are:
/// - with TermVector offset only data stored - 420 milliseconds
/// - with TermVector offset AND position data stored - 271 milliseconds
/// (nb timings for TermVector with position data are based on a tokenizer with contiguous
/// positions - no overlaps or gaps)
/// The cost of not using TermPositionVector to store
/// pre-parsed content and using an analyzer to re-parse the original content:
/// - reanalyzing the original content - 980 milliseconds
///
/// The re-analyze timings will typically vary depending on -
/// 1) The complexity of the analyzer code (timings above were using a
/// stemmer/lowercaser/stopword combo)
/// 2) The number of other fields (Lucene reads ALL fields off the disk
/// when accessing just one document field - can cost dear!)
/// 3) Use of compression on field storage - could be faster due to compression (less disk IO)
/// or slower (more CPU burn) depending on the content.
/// </summary>
/// <param name="tpv"/>
/// <param name="tokenPositionsGuaranteedContiguous">true if the token position numbers have no overlaps or gaps. If looking
/// to eek out the last drops of performance, set to true. If in doubt, set to false.</param>
public static TokenStream GetTokenStream(TermPositionVector tpv, bool tokenPositionsGuaranteedContiguous)
{
//code to reconstruct the original sequence of Tokens
String[] terms = tpv.GetTerms();
int[] freq = tpv.GetTermFrequencies();
int totalTokens = freq.Sum();
var tokensInOriginalOrder = new Token[totalTokens];
List<Token> unsortedTokens = null;
for (int t = 0; t < freq.Length; t++)
{
TermVectorOffsetInfo[] offsets = tpv.GetOffsets(t);
if (offsets == null)
{
return null;
}
int[] pos = null;
if (tokenPositionsGuaranteedContiguous)
{
//try get the token position info to speed up assembly of tokens into sorted sequence
pos = tpv.GetTermPositions(t);
}
if (pos == null)
{
//tokens NOT stored with positions or not guaranteed contiguous - must add to list and sort later
if (unsortedTokens == null)
{
unsortedTokens = new List<Token>();
}
foreach (TermVectorOffsetInfo t1 in offsets)
{
var token = new Token(t1.StartOffset, t1.EndOffset);
token.SetTermBuffer(terms[t]);
unsortedTokens.Add(token);
}
}
else
{
//We have positions stored and a guarantee that the token position information is contiguous
// This may be fast BUT wont work if Tokenizers used which create >1 token in same position or
// creates jumps in position numbers - this code would fail under those circumstances
//tokens stored with positions - can use this to index straight into sorted array
for (int tp = 0; tp < pos.Length; tp++)
{
var token = new Token(terms[t], offsets[tp].StartOffset, offsets[tp].EndOffset);
tokensInOriginalOrder[pos[tp]] = token;
}
}
}
//If the field has been stored without position data we must perform a sort
if (unsortedTokens != null)
{
tokensInOriginalOrder = unsortedTokens.ToArray();
Array.Sort(tokensInOriginalOrder, (t1, t2) =>
{
if (t1.StartOffset > t2.EndOffset)
return 1;
if (t1.StartOffset < t2.StartOffset)
return -1;
return 0;
});
}
return new StoredTokenStream(tokensInOriginalOrder);
}
public static TokenStream GetTokenStream(IndexReader reader, int docId, System.String field)
{
var tfv = reader.GetTermFreqVector(docId, field);
if (tfv == null)
{
throw new ArgumentException(field + " in doc #" + docId
+ "does not have any term position data stored");
}
if (tfv is TermPositionVector)
{
var tpv = (TermPositionVector) reader.GetTermFreqVector(docId, field);
return GetTokenStream(tpv);
}
throw new ArgumentException(field + " in doc #" + docId
+ "does not have any term position data stored");
}
//convenience method
public static TokenStream GetTokenStream(IndexReader reader, int docId, String field, Analyzer analyzer)
{
Document doc = reader.Document(docId);
return GetTokenStream(doc, field, analyzer);
}
public static TokenStream GetTokenStream(Document doc, String field, Analyzer analyzer)
{
String contents = doc.Get(field);
if (contents == null)
{
throw new ArgumentException("Field " + field + " in document is not stored and cannot be analyzed");
}
return GetTokenStream(field, contents, analyzer);
}
//convenience method
public static TokenStream GetTokenStream(String field, String contents, Analyzer analyzer)
{
return analyzer.TokenStream(field, new StringReader(contents));
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region Using directives
#define USE_TRACING
using System;
using System.Xml;
using System.IO;
#endregion
//////////////////////////////////////////////////////////////////////
// <summary>basenametable, holds common names for atom&rss parsing</summary>
//////////////////////////////////////////////////////////////////////
namespace Google.GData.Client
{
//////////////////////////////////////////////////////////////////////
/// <summary>BaseNameTable. An initialized nametable for faster XML processing
/// parses:
/// * opensearch:totalResults - the total number of search results available (not necessarily all present in the feed).
/// * opensearch:startIndex - the 1-based index of the first result.
/// * opensearch:itemsPerPage - the maximum number of items that appear on one page. This allows clients to generate direct links to any set of subsequent pages.
/// * gData:processed
/// </summary>
//////////////////////////////////////////////////////////////////////
public class BaseNameTable
{
/// <summary>the nametable itself, based on XML core</summary>
private NameTable atomNameTable;
/// <summary>opensearch:totalResults</summary>
private object totalResults;
/// <summary>opensearch:startIndex</summary>
private object startIndex;
/// <summary>opensearch:itemsPerPage</summary>
private object itemsPerPage;
/// <summary>xml base</summary>
private object baseUri;
/// <summary>xml language</summary>
private object language;
// batch extensions
private object batchId;
private object batchStatus;
private object batchOperation;
private object batchInterrupt;
private object batchContentType;
private object batchStatusCode;
private object batchReason;
private object batchErrors;
private object batchError;
private object batchSuccessCount;
private object batchFailureCount;
private object batchParsedCount;
private object batchField;
private object batchUnprocessed;
private object type;
private object value;
private object name;
private object eTagAttribute;
/// <summary>
/// namespace of the opensearch v1.0 elements
/// </summary>
public const string NSOpenSearchRss = "http://a9.com/-/spec/opensearchrss/1.0/";
/// <summary>
/// namespace of the opensearch v1.1 elements
/// </summary>
public const string NSOpenSearch11 = "http://a9.com/-/spec/opensearch/1.1/";
/// <summary>static namespace string declaration</summary>
public const string NSAtom = "http://www.w3.org/2005/Atom";
/// <summary>namespace for app publishing control, draft version</summary>
public const string NSAppPublishing = "http://purl.org/atom/app#";
/// <summary>namespace for app publishing control, final version</summary>
public const string NSAppPublishingFinal = "http://www.w3.org/2007/app";
/// <summary>xml namespace</summary>
public const string NSXml = "http://www.w3.org/XML/1998/namespace";
/// <summary>GD namespace</summary>
public const string gNamespace = "http://schemas.google.com/g/2005";
/// <summary>GData batch extension namespace</summary>
public const string gBatchNamespace = "http://schemas.google.com/gdata/batch";
/// <summary>GD namespace prefix</summary>
public const string gNamespacePrefix = gNamespace+ "#";
/// <summary>the post definiton in the link collection</summary>
public const string ServicePost = gNamespacePrefix + "post";
/// <summary>the feed definition in the link collection</summary>
public const string ServiceFeed = gNamespacePrefix + "feed";
/// <summary>the batch URI definition in the link collection</summary>
public const string ServiceBatch = gNamespacePrefix + "batch";
/// <summary>GData Kind Scheme</summary>
public const string gKind = gNamespacePrefix + "kind";
/// <summary>label scheme</summary>
public const string gLabels = gNamespace + "/labels";
/// <summary>the edit definition in the link collection</summary>
public const string ServiceEdit = "edit";
/// <summary>the next chunk URI in the link collection</summary>
public const string ServiceNext = "next";
/// <summary>the previous chunk URI in the link collection</summary>
public const string ServicePrev = "previous";
/// <summary>the self URI in the link collection</summary>
public const string ServiceSelf = "self";
/// <summary>the alternate URI in the link collection</summary>
public const string ServiceAlternate = "alternate";
/// <summary>the alternate URI in the link collection</summary>
public const string ServiceMedia = "edit-media";
/// <summary>prefix for atom if writing</summary>
public const string AtomPrefix = "atom";
/// <summary>prefix for gNamespace if writing</summary>
public const string gDataPrefix = "gd";
/// <summary>prefix for gdata:batch if writing</summary>
public const string gBatchPrefix = "batch";
// app publishing control strings
/// <summary>prefix for appPublishing if writing</summary>
public const string gAppPublishingPrefix = "app";
/// <summary>xmlelement for app:control</summary>
public const string XmlElementPubControl = "control";
/// <summary>xmlelement for app:draft</summary>
public const string XmlElementPubDraft = "draft";
/// <summary>xmlelement for app:draft</summary>
public const string XmlElementPubEdited = "edited";
/// <summary>
/// static string for parsing the etag attribute
/// </summary>
/// <returns></returns>
public const string XmlEtagAttribute = "etag";
// batch strings:
/// <summary>xmlelement for batch:id</summary>
public const string XmlElementBatchId = "id";
/// <summary>xmlelement for batch:operation</summary>
public const string XmlElementBatchOperation = "operation";
/// <summary>xmlelement for batch:status</summary>
public const string XmlElementBatchStatus = "status";
/// <summary>xmlelement for batch:interrupted</summary>
public const string XmlElementBatchInterrupt = "interrupted";
/// <summary>xmlattribute for batch:status@contentType</summary>
public const string XmlAttributeBatchContentType = "content-type";
/// <summary>xmlattribute for batch:status@code</summary>
public const string XmlAttributeBatchStatusCode = "code";
/// <summary>xmlattribute for batch:status@reason</summary>
public const string XmlAttributeBatchReason = "reason";
/// <summary>xmlelement for batch:status:errors</summary>
public const string XmlElementBatchErrors = "errors";
/// <summary>xmlelement for batch:status:errors:error</summary>
public const string XmlElementBatchError = "error";
/// <summary>xmlattribute for batch:interrupted@success</summary>
public const string XmlAttributeBatchSuccess = "success";
/// <summary>XmlAttribute for batch:interrupted@parsed</summary>
public const string XmlAttributeBatchParsed = "parsed";
/// <summary>XmlAttribute for batch:interrupted@field</summary>
public const string XmlAttributeBatchField = "field";
/// <summary>XmlAttribute for batch:interrupted@unprocessed</summary>
public const string XmlAttributeBatchUnprocessed = "unprocessed";
/// <summary>XmlConstant for value in enums</summary>
public const string XmlValue = "value";
/// <summary>XmlConstant for name in enums</summary>
public const string XmlName = "name";
/// <summary>XmlAttribute for type in enums</summary>
public const string XmlAttributeType = "type";
//////////////////////////////////////////////////////////////////////
/// <summary>initializes the name table for use with atom parsing. This is the
/// only place where strings are defined for parsing</summary>
//////////////////////////////////////////////////////////////////////
public virtual void InitAtomParserNameTable()
{
// create the nametable object
Tracing.TraceCall("Initializing basenametable support");
this.atomNameTable = new NameTable();
// <summary>add the keywords for the Feed
this.totalResults = this.atomNameTable.Add("totalResults");
this.startIndex = this.atomNameTable.Add("startIndex");
this.itemsPerPage = this.atomNameTable.Add("itemsPerPage");
this.baseUri = this.atomNameTable.Add("base");
this.language = this.atomNameTable.Add("lang");
// batch keywords
this.batchId = this.atomNameTable.Add(BaseNameTable.XmlElementBatchId);
this.batchOperation = this.atomNameTable.Add(BaseNameTable.XmlElementBatchOperation);
this.batchStatus = this.atomNameTable.Add(BaseNameTable.XmlElementBatchStatus);
this.batchInterrupt = this.atomNameTable.Add(BaseNameTable.XmlElementBatchInterrupt);
this.batchContentType = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchContentType);
this.batchStatusCode = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchStatusCode);
this.batchReason = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchReason);
this.batchErrors = this.atomNameTable.Add(BaseNameTable.XmlElementBatchErrors);
this.batchError = this.atomNameTable.Add(BaseNameTable.XmlElementBatchError);
this.batchSuccessCount = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchSuccess);
this.batchFailureCount = this.batchError;
this.batchParsedCount = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchParsed);
this.batchField = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchField);
this.batchUnprocessed = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchUnprocessed);
this.type = this.atomNameTable.Add(BaseNameTable.XmlAttributeType);
this.value = this.atomNameTable.Add(BaseNameTable.XmlValue);
this.name = this.atomNameTable.Add(BaseNameTable.XmlName);
this.eTagAttribute = this.atomNameTable.Add(BaseNameTable.XmlEtagAttribute);
}
/////////////////////////////////////////////////////////////////////////////
#region Read only accessors 8/10/2005
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for atomNameTable</summary>
//////////////////////////////////////////////////////////////////////
internal NameTable Nametable
{
get {return this.atomNameTable;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchId</summary>
//////////////////////////////////////////////////////////////////////
public object BatchId
{
get {return this.batchId;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchOperation</summary>
//////////////////////////////////////////////////////////////////////
public object BatchOperation
{
get {return this.batchOperation;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchStatus</summary>
//////////////////////////////////////////////////////////////////////
public object BatchStatus
{
get {return this.batchStatus;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchInterrupt</summary>
//////////////////////////////////////////////////////////////////////
public object BatchInterrupt
{
get {return this.batchInterrupt;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchContentType</summary>
//////////////////////////////////////////////////////////////////////
public object BatchContentType
{
get {return this.batchContentType;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchStatusCode</summary>
//////////////////////////////////////////////////////////////////////
public object BatchStatusCode
{
get {return this.batchStatusCode;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchErrors</summary>
//////////////////////////////////////////////////////////////////////
public object BatchErrors
{
get {return this.batchErrors;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchError</summary>
//////////////////////////////////////////////////////////////////////
public object BatchError
{
get {return this.batchError;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchReason</summary>
//////////////////////////////////////////////////////////////////////
public object BatchReason
{
get {return this.batchReason;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchReason</summary>
//////////////////////////////////////////////////////////////////////
public object BatchField
{
get {return this.batchField;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchUnprocessed</summary>
//////////////////////////////////////////////////////////////////////
public object BatchUnprocessed
{
get {return this.batchUnprocessed;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchSuccessCount</summary>
//////////////////////////////////////////////////////////////////////
public object BatchSuccessCount
{
get {return this.batchSuccessCount;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchFailureCount</summary>
//////////////////////////////////////////////////////////////////////
public object BatchFailureCount
{
get {return this.batchFailureCount;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for BatchParsedCount</summary>
//////////////////////////////////////////////////////////////////////
public object BatchParsedCount
{
get {return this.batchParsedCount;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for totalResults</summary>
//////////////////////////////////////////////////////////////////////
public object TotalResults
{
get {return this.totalResults;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for startIndex</summary>
//////////////////////////////////////////////////////////////////////
public object StartIndex
{
get {return this.startIndex;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for itemsPerPage</summary>
//////////////////////////////////////////////////////////////////////
public object ItemsPerPage
{
get {return this.itemsPerPage;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for parameter</summary>
//////////////////////////////////////////////////////////////////////
static public string Parameter
{
get {return "parameter";}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for baseUri</summary>
//////////////////////////////////////////////////////////////////////
public object Base
{
get {return this.baseUri;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for language</summary>
//////////////////////////////////////////////////////////////////////
public object Language
{
get {return this.language;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for value</summary>
//////////////////////////////////////////////////////////////////////
public object Value
{
get {return this.value;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for value</summary>
//////////////////////////////////////////////////////////////////////
public object Type
{
get {return this.type;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for name</summary>
//////////////////////////////////////////////////////////////////////
public object Name
{
get {return this.name;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Read only accessor for etag</summary>
//////////////////////////////////////////////////////////////////////
public object ETag
{
get {return this.eTagAttribute;}
}
/////////////////////////////////////////////////////////////////////////////
#endregion end of Read only accessors
/// <summary>
/// returns the correct opensearchnamespace to use based
/// on the version information passed in. All protocols with
/// version > 1 use opensearch1.1 where version 1 uses
/// opensearch 1.0
/// </summary>
/// <param name="v">The versioninformation</param>
/// <returns></returns>
public static string OpenSearchNamespace(IVersionAware v)
{
int major = VersionDefaults.Major;
if (v != null)
major = v.ProtocolMajor;
if (major == 1)
return BaseNameTable.NSOpenSearchRss;
return BaseNameTable.NSOpenSearch11;
}
/// <summary>
/// returns the correct app:publishing namespace to use based
/// on the version information passed in. All protocols with
/// version > 1 use the final version of the namespace, where
/// version 1 uses the draft version.
/// </summary>
/// <param name="v">The versioninformation</param>
/// <returns></returns>
public static string AppPublishingNamespace(IVersionAware v)
{
int major = VersionDefaults.Major;
if (v != null)
major = v.ProtocolMajor;
if (major == 1)
return BaseNameTable.NSAppPublishing;
return BaseNameTable.NSAppPublishingFinal;
}
}
/////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Reflection;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Tests.Integration.Migrations;
using Moq;
using NUnit.Framework;
using NUnit.Should;
using System.Linq;
namespace FluentMigrator.Tests.Unit
{
[TestFixture]
public class MigrationRunnerTests
{
private MigrationRunner _runner;
private Mock<IAnnouncer> _announcer;
private Mock<IStopWatch> _stopWatch;
private Mock<IMigrationProcessor> _processorMock;
private Mock<IMigrationInformationLoader> _migrationLoaderMock;
private Mock<IProfileLoader> _profileLoaderMock;
private Mock<IRunnerContext> _runnerContextMock;
private SortedList<long, IMigrationInfo> _migrationList;
private TestVersionLoader _fakeVersionLoader;
private int _applicationContext;
[SetUp]
public void SetUp()
{
_applicationContext = new Random().Next();
_migrationList = new SortedList<long, IMigrationInfo>();
_runnerContextMock = new Mock<IRunnerContext>(MockBehavior.Loose);
_processorMock = new Mock<IMigrationProcessor>(MockBehavior.Loose);
_migrationLoaderMock = new Mock<IMigrationInformationLoader>(MockBehavior.Loose);
_profileLoaderMock = new Mock<IProfileLoader>(MockBehavior.Loose);
_announcer = new Mock<IAnnouncer>();
_stopWatch = new Mock<IStopWatch>();
_stopWatch.Setup(x => x.Time(It.IsAny<Action>())).Returns(new TimeSpan(1)).Callback((Action a) => a.Invoke());
var options = new ProcessorOptions
{
PreviewOnly = false
};
_processorMock.SetupGet(x => x.Options).Returns(options);
_processorMock.SetupGet(x => x.ConnectionString).Returns(IntegrationTestOptions.SqlServer2008.ConnectionString);
_runnerContextMock.SetupGet(x => x.Namespace).Returns("FluentMigrator.Tests.Integration.Migrations");
_runnerContextMock.SetupGet(x => x.Announcer).Returns(_announcer.Object);
_runnerContextMock.SetupGet(x => x.StopWatch).Returns(_stopWatch.Object);
_runnerContextMock.SetupGet(x => x.Targets).Returns(new string[] { Assembly.GetExecutingAssembly().ToString()});
_runnerContextMock.SetupGet(x => x.Connection).Returns(IntegrationTestOptions.SqlServer2008.ConnectionString);
_runnerContextMock.SetupGet(x => x.Database).Returns("sqlserver");
_runnerContextMock.SetupGet(x => x.ApplicationContext).Returns(_applicationContext);
_migrationLoaderMock.Setup(x => x.LoadMigrations()).Returns(()=> _migrationList);
_runner = new MigrationRunner(Assembly.GetAssembly(typeof(MigrationRunnerTests)), _runnerContextMock.Object, _processorMock.Object)
{
MigrationLoader = _migrationLoaderMock.Object,
ProfileLoader = _profileLoaderMock.Object,
};
_fakeVersionLoader = new TestVersionLoader(_runner, _runner.VersionLoader.VersionTableMetaData);
_runner.VersionLoader = _fakeVersionLoader;
_processorMock.Setup(x => x.SchemaExists(It.Is<string>(s => s == _runner.VersionLoader.VersionTableMetaData.SchemaName)))
.Returns(true);
_processorMock.Setup(x => x.TableExists(It.Is<string>(s => s == _runner.VersionLoader.VersionTableMetaData.SchemaName),
It.Is<string>(t => t == _runner.VersionLoader.VersionTableMetaData.TableName)))
.Returns(true);
}
private void LoadVersionData(params long[] fakeVersions)
{
_fakeVersionLoader.Versions.Clear();
_migrationList.Clear();
foreach (var version in fakeVersions)
{
_fakeVersionLoader.Versions.Add(version);
_migrationList.Add(version,new MigrationInfo(version, TransactionBehavior.Default, new TestMigration()));
}
_fakeVersionLoader.LoadVersionInfo();
}
[Test]
public void ProfilesAreAppliedWhenMigrateUpIsCalledWithNoVersion()
{
_runner.MigrateUp();
_profileLoaderMock.Verify(x => x.ApplyProfiles(), Times.Once());
}
[Test]
public void ProfilesAreAppliedWhenMigrateUpIsCalledWithVersionParameter()
{
_runner.MigrateUp(2009010101);
_profileLoaderMock.Verify(x => x.ApplyProfiles(), Times.Once());
}
[Test]
public void ProfilesAreAppliedWhenMigrateDownIsCalled()
{
_runner.MigrateDown(2009010101);
_profileLoaderMock.Verify(x => x.ApplyProfiles(), Times.Once());
}
/// <summary>Unit test which ensures that the application context is correctly propagated down to each migration class.</summary>
[Test(Description = "Ensure that the application context is correctly propagated down to each migration class.")]
public void CanPassApplicationContext()
{
IMigration migration = new TestEmptyMigration();
_runner.Up(migration);
Assert.AreEqual(_applicationContext, _runnerContextMock.Object.ApplicationContext, "The runner context does not have the expected application context.");
Assert.AreEqual(_applicationContext, _runner.RunnerContext.ApplicationContext, "The MigrationRunner does not have the expected application context.");
Assert.AreEqual(_applicationContext, migration.ApplicationContext, "The migration does not have the expected application context.");
_announcer.VerifyAll();
}
[Test]
public void CanPassConnectionString()
{
IMigration migration = new TestEmptyMigration();
_runner.Up(migration);
Assert.AreEqual(IntegrationTestOptions.SqlServer2008.ConnectionString, migration.ConnectionString, "The migration does not have the expected connection string.");
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceUp()
{
_announcer.Setup(x => x.Heading(It.IsRegex(containsAll("Test", "migrating"))));
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceUpFinish()
{
_announcer.Setup(x => x.Say(It.IsRegex(containsAll("Test", "migrated"))));
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceDown()
{
_announcer.Setup(x => x.Heading(It.IsRegex(containsAll("Test", "reverting"))));
_runner.Down(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceDownFinish()
{
_announcer.Setup(x => x.Say(It.IsRegex(containsAll("Test", "reverted"))));
_runner.Down(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceUpElapsedTime()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts)));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceDownElapsedTime()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts)));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
_runner.Down(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanReportExceptions()
{
_processorMock.Setup(x => x.Process(It.IsAny<CreateTableExpression>())).Throws(new Exception("Oops"));
var exception = Assert.Throws<Exception>(() => _runner.Up(new TestMigration()));
Assert.That(exception.Message, Is.StringContaining("Oops"));
}
[Test]
public void CanSayExpression()
{
_announcer.Setup(x => x.Say(It.IsRegex(containsAll("CreateTable"))));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(new TimeSpan(0, 0, 0, 1, 3));
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanTimeExpression()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts)));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
private string containsAll(params string[] words)
{
return ".*?" + string.Join(".*?", words) + ".*?";
}
[Test]
public void LoadsCorrectCallingAssembly()
{
var asm = _runner.MigrationAssemblies.Assemblies.Single();
asm.ShouldBe(Assembly.GetAssembly(typeof(MigrationRunnerTests)));
}
[Test]
public void RollbackOnlyOneStepsOfTwoShouldNotDeleteVersionInfoTable()
{
long fakeMigrationVersion = 2009010101;
long fakeMigrationVersion2 = 2009010102;
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
LoadVersionData(fakeMigrationVersion, fakeMigrationVersion2);
_runner.VersionLoader.LoadVersionInfo();
_runner.Rollback(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void RollbackLastVersionShouldDeleteVersionInfoTable()
{
long fakeMigrationVersion = 2009010101;
LoadVersionData(fakeMigrationVersion);
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.Rollback(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue();
}
[Test]
public void RollbackToVersionZeroShouldDeleteVersionInfoTable()
{
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.RollbackToVersion(0);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue();
}
[Test]
public void RollbackToVersionZeroShouldNotCreateVersionInfoTableAfterRemoval()
{
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.RollbackToVersion(0);
//Should only be called once in setup
_processorMock.Verify(
pm => pm.Process(It.Is<CreateTableExpression>(
dte => dte.TableName == versionInfoTableName)
),
Times.Once()
);
}
[Test]
public void RollbackToVersionShouldShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1,fakeMigration3);
_fakeVersionLoader.Versions.Add(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
_runner.RollbackToVersion(2011010101);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
}
[Test]
public void RollbackToVersionZeroShouldShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1, fakeMigration2, fakeMigration3);
_migrationList.Remove(fakeMigration1);
_migrationList.Remove(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
_runner.RollbackToVersion(0);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
}
[Test]
public void RollbackShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1, fakeMigration3);
_fakeVersionLoader.Versions.Add(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
_runner.Rollback(2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void RollbackToVersionShouldLoadVersionInfoIfVersionGreaterThanZero()
{
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.RollbackToVersion(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
//Once in setup
_processorMock.Verify(
pm => pm.Process(It.Is<CreateTableExpression>(
dte => dte.TableName == versionInfoTableName)
),
Times.Exactly(1)
);
//After setup is done, fake version loader owns the proccess
_fakeVersionLoader.DidLoadVersionInfoGetCalled.ShouldBe(true);
}
[Test]
public void ValidateVersionOrderingShouldReturnNothingIfNoUnappliedMigrations()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
LoadVersionData(version1, version2);
_migrationList.Clear();
_migrationList.Add(version1,new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
Assert.DoesNotThrow(() => _runner.ValidateVersionOrder());
_announcer.Verify(a => a.Say("Version ordering valid."));
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void ValidateVersionOrderingShouldReturnNothingIfUnappliedMigrationVersionIsGreaterThanLatestAppliedMigration()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
LoadVersionData(version1);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
Assert.DoesNotThrow(() => _runner.ValidateVersionOrder());
_announcer.Verify(a => a.Say("Version ordering valid."));
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void ValidateVersionOrderingShouldThrowExceptionIfUnappliedMigrationVersionIsLessThanGreatestAppliedMigrationVersion()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
const long version3 = 2011010103;
const long version4 = 2011010104;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
var mockMigration3 = new Mock<IMigration>();
var mockMigration4 = new Mock<IMigration>();
LoadVersionData(version1, version4);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
_migrationList.Add(version3, new MigrationInfo(version3, TransactionBehavior.Default, mockMigration3.Object));
_migrationList.Add(version4, new MigrationInfo(version4, TransactionBehavior.Default, mockMigration4.Object));
var exception = Assert.Throws<VersionOrderInvalidException>(() => _runner.ValidateVersionOrder());
exception.InvalidMigrations.Count().ShouldBe(2);
exception.InvalidMigrations.Any(p => p.Key == version2);
exception.InvalidMigrations.Any(p => p.Key == version3);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void CanListVersions()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
LoadVersionData(version1, version2);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
_runner.ListMigrations();
_announcer.Verify(a => a.Say("2011010101: IMigrationProxy"));
_announcer.Verify(a => a.Emphasize("2011010102: IMigrationProxy (current)"));
}
[Test]
public void IfMigrationHasAnInvalidExpressionDuringUpActionShouldThrowAnExceptionAndAnnounceTheError()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression {TableName = "Test"};
invalidMigration.Setup(m => m.GetUpExpressions(It.IsAny<IMigrationContext>())).Callback((IMigrationContext mc) => mc.Expressions.Add(invalidExpression));
Assert.Throws<InvalidMigrationException>(() => _runner.Up(invalidMigration.Object));
_announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains("UpdateDataExpression: Update statement is missing a condition. Specify one by calling .Where() or target all rows by calling .AllRows()."))));
}
[Test]
public void IfMigrationHasAnInvalidExpressionDuringDownActionShouldThrowAnExceptionAndAnnounceTheError()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression { TableName = "Test" };
invalidMigration.Setup(m => m.GetDownExpressions(It.IsAny<IMigrationContext>())).Callback((IMigrationContext mc) => mc.Expressions.Add(invalidExpression));
Assert.Throws<InvalidMigrationException>(() => _runner.Down(invalidMigration.Object));
_announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains("UpdateDataExpression: Update statement is missing a condition. Specify one by calling .Where() or target all rows by calling .AllRows()."))));
}
[Test]
public void IfMigrationHasTwoInvalidExpressionsShouldAnnounceBothErrors()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression { TableName = "Test" };
var secondInvalidExpression = new CreateColumnExpression();
invalidMigration.Setup(m => m.GetUpExpressions(It.IsAny<IMigrationContext>()))
.Callback((IMigrationContext mc) => { mc.Expressions.Add(invalidExpression); mc.Expressions.Add(secondInvalidExpression); });
Assert.Throws<InvalidMigrationException>(() => _runner.Up(invalidMigration.Object));
_announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains("UpdateDataExpression: Update statement is missing a condition. Specify one by calling .Where() or target all rows by calling .AllRows()."))));
_announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains("CreateColumnExpression: The table's name cannot be null or an empty string. The column's name cannot be null or an empty string. The column does not have a type defined."))));
}
}
}
| |
/*
' Copyright (c) 2011 DotNetNuke Corporation
' All rights reserved.
'
' 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 DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Users;
using DotNetNuke.Entities.Users.Social;
using DotNetNuke.Framework;
using DotNetNuke.Framework.JavaScriptLibraries;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Web.Client.ClientResourceManagement;
using DotNetNuke.Modules.Journal.Components;
using DotNetNuke.Security.Roles;
namespace DotNetNuke.Modules.Journal {
/// -----------------------------------------------------------------------------
/// <summary>
/// The ViewJournal class displays the content
/// </summary>
/// -----------------------------------------------------------------------------
public partial class View : JournalModuleBase {
public int PageSize = 20;
public bool AllowPhotos = true;
public bool AllowFiles = true;
public int MaxMessageLength = 250;
public bool CanRender = true;
public bool ShowEditor = true;
public bool CanComment = true;
public bool IsGroup = false;
public string BaseUrl;
public string ProfilePage;
public int Gid = -1;
public int Pid = -1;
public long MaxUploadSize = Config.GetMaxUploadSize();
public bool IsPublicGroup = false;
#region Event Handlers
override protected void OnInit(EventArgs e)
{
JavaScript.RequestRegistration(CommonJs.DnnPlugins);
JavaScript.RequestRegistration(CommonJs.jQueryFileUpload);
ServicesFramework.Instance.RequestAjaxAntiForgerySupport();
JavaScript.RequestRegistration(CommonJs.Knockout);
ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Journal/Scripts/journal.js");
ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Journal/Scripts/journalcomments.js");
ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Journal/Scripts/mentionsInput.js");
ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/Scripts/json2.js");
var isAdmin = UserInfo.IsInRole(RoleController.Instance.GetRoleById(PortalId, PortalSettings.AdministratorRoleId).RoleName);
if (!Request.IsAuthenticated || (!UserInfo.IsSuperUser && !isAdmin && UserInfo.IsInRole("Unverified Users")))
{
ShowEditor = false;
}
else
{
ShowEditor = EditorEnabled;
}
if (Settings.ContainsKey(Constants.DefaultPageSize))
{
PageSize = Convert.ToInt16(Settings[Constants.DefaultPageSize]);
}
if (Settings.ContainsKey(Constants.MaxCharacters))
{
MaxMessageLength = Convert.ToInt16(Settings[Constants.MaxCharacters]);
}
if (Settings.ContainsKey(Constants.AllowPhotos))
{
AllowPhotos = Convert.ToBoolean(Settings[Constants.AllowPhotos]);
}
if (Settings.ContainsKey(Constants.AllowFiles))
{
AllowFiles = Convert.ToBoolean(Settings[Constants.AllowFiles]);
}
ctlJournalList.Enabled = true;
ctlJournalList.ProfileId = -1;
ctlJournalList.PageSize = PageSize;
ctlJournalList.ModuleId = ModuleId;
ModuleInfo moduleInfo = ModuleContext.Configuration;
foreach (var module in ModuleController.Instance.GetTabModules(TabId).Values)
{
if (module.ModuleDefinition.FriendlyName == "Social Groups")
{
if (GroupId == -1 && FilterMode == JournalMode.Auto)
{
ShowEditor = false;
ctlJournalList.Enabled = false;
}
if (GroupId > 0)
{
RoleInfo roleInfo = RoleController.Instance.GetRoleById(moduleInfo.OwnerPortalID, GroupId);
if (roleInfo != null)
{
if (UserInfo.IsInRole(roleInfo.RoleName))
{
ShowEditor = true;
CanComment = true;
IsGroup = true;
} else
{
ShowEditor = false;
CanComment = false;
}
if (!roleInfo.IsPublic && !ShowEditor)
{
ctlJournalList.Enabled = false;
}
if (roleInfo.IsPublic && !ShowEditor)
{
ctlJournalList.Enabled = true;
}
if (roleInfo.IsPublic && ShowEditor)
{
ctlJournalList.Enabled = true;
}
if (roleInfo.IsPublic)
{
IsPublicGroup = true;
}
}
else
{
ShowEditor = false;
ctlJournalList.Enabled = false;
}
}
}
}
if (!String.IsNullOrEmpty(Request.QueryString["userId"]))
{
ctlJournalList.ProfileId = Convert.ToInt32(Request.QueryString["userId"]);
if (!UserInfo.IsSuperUser && !isAdmin && ctlJournalList.ProfileId != UserId)
{
ShowEditor = ShowEditor && Utilities.AreFriends(UserController.GetUserById(PortalId, ctlJournalList.ProfileId), UserInfo);
}
}
else if (GroupId > 0)
{
ctlJournalList.SocialGroupId = Convert.ToInt32(Request.QueryString["groupId"]);
}
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent() {
Load += Page_Load;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Page_Load runs when the control is loaded
/// </summary>
/// -----------------------------------------------------------------------------
private void Page_Load(object sender, EventArgs e) {
try
{
BaseUrl = Globals.ApplicationPath;
BaseUrl = BaseUrl.EndsWith("/") ? BaseUrl : BaseUrl + "/";
BaseUrl += "DesktopModules/Journal/";
ProfilePage = Common.Globals.NavigateURL(PortalSettings.UserTabId, string.Empty, new[] {"userId=xxx"});
if (!String.IsNullOrEmpty(Request.QueryString["userId"]))
{
Pid = Convert.ToInt32(Request.QueryString["userId"]);
ctlJournalList.ProfileId = Pid;
}
else if (GroupId > 0)
{
Gid = GroupId;
ctlJournalList.SocialGroupId = GroupId;
}
ctlJournalList.PageSize = PageSize;
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
#endregion
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.ui
{
public class FocusManager : global::haxe.lang.HxObject
{
static FocusManager()
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.ui.FocusManager.list = new global::haxe.ds.StringMap<object>();
}
public FocusManager(global::haxe.lang.EmptyObject empty)
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
{
}
}
#line default
}
public FocusManager()
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.ui.FocusManager.__hx_ctor_pony_ui_FocusManager(this);
}
#line default
}
public static void __hx_ctor_pony_ui_FocusManager(global::pony.ui.FocusManager __temp_me124)
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
{
}
}
#line default
}
public static global::haxe.ds.StringMap<object> list;
public static global::pony.ui.IFocus current;
public static void reg(global::pony.ui.IFocus o)
{
unchecked
{
#line 54 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
if ( ! (global::pony.ui.FocusManager.list.exists(global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.getField(o, "focusGroup", 1549161543, true)))) )
{
#line 54 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.Priority<object> @value = new global::pony.Priority<object>(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (default(global::Array<object>)) ))) ));
#line 54 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.ui.FocusManager.list.@set(global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.getField(o, "focusGroup", 1549161543, true)), @value);
}
global::pony.Priority<object> g = ((global::pony.Priority<object>) (global::pony.Priority<object>.__hx_cast<object>(((global::pony.Priority) (global::pony.ui.FocusManager.list.@get(global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.getField(o, "focusGroup", 1549161543, true))).@value) ))) );
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
g.addElement(o, global::haxe.lang.Null<object>.ofDynamic<int>(global::haxe.lang.Runtime.getField(o, "focusPriority", 1545678684, false)));
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
{
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object listener = default(object);
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object __temp_stmt601 = default(object);
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
{
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object l = default(object);
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
{
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (typeof(global::pony.ui.FocusManager)) ), global::haxe.lang.Runtime.toString("newFocus"), ((int) (668181336) ))) ), 2);
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
l = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
__temp_stmt601 = l;
}
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
listener = ((object) (__temp_stmt601) );
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.events.Signal this1 = ((global::pony.events.Signal) (global::haxe.lang.Runtime.getField(o, "focus", 76111832, true)) );
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
this1.@add(((object) (listener) ), new global::haxe.lang.Null<int>(-5, true));
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object __temp_expr602 = this1.target;
}
}
#line default
}
public static void unreg(global::pony.ui.IFocus o)
{
unchecked
{
#line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
((global::pony.Priority<object>) (global::pony.Priority<object>.__hx_cast<object>(((global::pony.Priority) (global::pony.ui.FocusManager.list.@get(global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.getField(o, "focusGroup", 1549161543, true))).@value) ))) ).removeElement(o);
{
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object listener = default(object);
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object __temp_stmt603 = default(object);
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
{
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object l = default(object);
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
{
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (typeof(global::pony.ui.FocusManager)) ), global::haxe.lang.Runtime.toString("newFocus"), ((int) (668181336) ))) ), 2);
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
l = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
__temp_stmt603 = l;
}
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
listener = ((object) (__temp_stmt603) );
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.events.Signal this1 = ((global::pony.events.Signal) (global::haxe.lang.Runtime.getField(o, "focus", 76111832, true)) );
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
this1.@remove(((object) (listener) ));
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object __temp_expr604 = this1.target;
}
}
#line default
}
public static void newFocus(bool b, global::pony.ui.IFocus o)
{
unchecked
{
#line 74 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
if (b)
{
if (( global::pony.ui.FocusManager.current != default(global::pony.ui.IFocus) ))
{
#line 75 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.events.Signal this1 = ((global::pony.events.Signal) (global::haxe.lang.Runtime.getField(global::pony.ui.FocusManager.current, "focus", 76111832, true)) );
#line 75 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
{
#line 75 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
this1.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<bool>(new bool[]{false})) ), ((object) (this1.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 75 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.events.Signal __temp_expr605 = this1;
}
#line 75 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object __temp_expr606 = this1.target;
}
global::pony.ui.FocusManager.current = o;
{
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.Priority<object> _this = ((global::pony.Priority<object>) (global::pony.Priority<object>.__hx_cast<object>(((global::pony.Priority) (global::pony.ui.FocusManager.list.@get(global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.getField(global::pony.ui.FocusManager.current, "focusGroup", 1549161543, true))).@value) ))) );
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
while (( ((global::pony.ui.IFocus) (_this.loop()) ) != o ))
{
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object __temp_expr607 = default(object);
}
}
}
else
{
#line 79 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
if (( global::pony.ui.FocusManager.current == o ))
{
#line 79 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.ui.FocusManager.current = default(global::pony.ui.IFocus);
}
}
}
#line default
}
public static void selectGroup(string name)
{
unchecked
{
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
if (string.Equals(name, default(string)))
{
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
name = "";
}
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.ui.IFocus __temp_stmt609 = default(global::pony.ui.IFocus);
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
{
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.Priority<object> _this = ((global::pony.Priority<object>) (global::pony.Priority<object>.__hx_cast<object>(((global::pony.Priority) (global::pony.ui.FocusManager.list.@get(name).@value) ))) );
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
__temp_stmt609 = ((global::pony.ui.IFocus) (_this.data[0]) );
}
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object __temp_stmt608 = global::haxe.lang.Runtime.getField(__temp_stmt609, "focus", 76111832, true);
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.events.Signal this1 = ((global::pony.events.Signal) (__temp_stmt608) );
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
{
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
this1.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<bool>(new bool[]{true})) ), ((object) (this1.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.events.Signal __temp_expr610 = this1;
}
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object __temp_expr611 = this1.target;
}
#line default
}
public static global::pony.ui.IFocus next()
{
unchecked
{
#line 96 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
if (( global::pony.ui.FocusManager.current == default(global::pony.ui.IFocus) ))
{
#line 96 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
return default(global::pony.ui.IFocus);
}
global::pony.ui.IFocus e = ((global::pony.ui.IFocus) (((global::pony.Priority<object>) (global::pony.Priority<object>.__hx_cast<object>(((global::pony.Priority) (global::pony.ui.FocusManager.list.@get(global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.getField(global::pony.ui.FocusManager.current, "focusGroup", 1549161543, true))).@value) ))) ).loop()) );
{
#line 98 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.events.Signal this1 = ((global::pony.events.Signal) (global::haxe.lang.Runtime.getField(e, "focus", 76111832, true)) );
#line 98 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
{
#line 98 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
this1.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<bool>(new bool[]{true})) ), ((object) (this1.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 98 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.events.Signal __temp_expr612 = this1;
}
#line 98 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object __temp_expr613 = this1.target;
}
return e;
}
#line default
}
public static global::pony.ui.IFocus prev()
{
unchecked
{
#line 107 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
if (( global::pony.ui.FocusManager.current == default(global::pony.ui.IFocus) ))
{
#line 107 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
return default(global::pony.ui.IFocus);
}
global::pony.ui.IFocus e = ((global::pony.ui.IFocus) (((global::pony.Priority<object>) (global::pony.Priority<object>.__hx_cast<object>(((global::pony.Priority) (global::pony.ui.FocusManager.list.@get(global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.getField(global::pony.ui.FocusManager.current, "focusGroup", 1549161543, true))).@value) ))) ).backLoop()) );
{
#line 109 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.events.Signal this1 = ((global::pony.events.Signal) (global::haxe.lang.Runtime.getField(e, "focus", 76111832, true)) );
#line 109 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
{
#line 109 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
this1.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<bool>(new bool[]{true})) ), ((object) (this1.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 109 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
global::pony.events.Signal __temp_expr614 = this1;
}
#line 109 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
object __temp_expr615 = this1.target;
}
return e;
}
#line default
}
public static global::pony.Priority<object> _get_p()
{
unchecked
{
#line 113 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
return ((global::pony.Priority<object>) (global::pony.Priority<object>.__hx_cast<object>(((global::pony.Priority) (global::pony.ui.FocusManager.list.@get(global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.getField(global::pony.ui.FocusManager.current, "focusGroup", 1549161543, true))).@value) ))) );
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
return new global::pony.ui.FocusManager(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/FocusManager.hx"
return new global::pony.ui.FocusManager();
}
#line default
}
public static global::pony.Priority<object> p
{
get { return _get_p(); }
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: operations/rpc/pbx_svc.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Operations.RPC {
/// <summary>Holder for reflection information generated from operations/rpc/pbx_svc.proto</summary>
public static partial class PbxSvcReflection {
#region Descriptor
/// <summary>File descriptor for operations/rpc/pbx_svc.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PbxSvcReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChxvcGVyYXRpb25zL3JwYy9wYnhfc3ZjLnByb3RvEhpob2xtcy50eXBlcy5v",
"cGVyYXRpb25zLnJwYxobZ29vZ2xlL3Byb3RvYnVmL2VtcHR5LnByb3RvGiVv",
"cGVyYXRpb25zL3BieF9ldmVudHMvcGJ4X2V2ZW50LnByb3RvIlQKEVBCWFN2",
"Y0FsbFJlc3BvbnNlEj8KCnBieF9ldmVudHMYASADKAsyKy5ob2xtcy50eXBl",
"cy5vcGVyYXRpb25zLnBieF9ldmVudHMuUEJYRXZlbnQiPwolUEJYU3ZjR2V0",
"QWN0aXZlQ29ubmVjdG9yQ291bnRSZXNwb25zZRIWCg5waW5nX3Jlc3BvbnNl",
"cxgBIAEoBTLVAQoGUEJYU3ZjElUKDEdldEFsbEV2ZW50cxIWLmdvb2dsZS5w",
"cm90b2J1Zi5FbXB0eRotLmhvbG1zLnR5cGVzLm9wZXJhdGlvbnMucnBjLlBC",
"WFN2Y0FsbFJlc3BvbnNlEnQKF0dldEFjdGl2ZUNvbm5lY3RvckNvdW50EhYu",
"Z29vZ2xlLnByb3RvYnVmLkVtcHR5GkEuaG9sbXMudHlwZXMub3BlcmF0aW9u",
"cy5ycGMuUEJYU3ZjR2V0QWN0aXZlQ29ubmVjdG9yQ291bnRSZXNwb25zZUIt",
"Wg5vcGVyYXRpb25zL3JwY6oCGkhPTE1TLlR5cGVzLk9wZXJhdGlvbnMuUlBD",
"YgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::HOLMS.Types.Operations.PBXEvents.PbxEventReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.PBXSvcAllResponse), global::HOLMS.Types.Operations.RPC.PBXSvcAllResponse.Parser, new[]{ "PbxEvents" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.PBXSvcGetActiveConnectorCountResponse), global::HOLMS.Types.Operations.RPC.PBXSvcGetActiveConnectorCountResponse.Parser, new[]{ "PingResponses" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class PBXSvcAllResponse : pb::IMessage<PBXSvcAllResponse> {
private static readonly pb::MessageParser<PBXSvcAllResponse> _parser = new pb::MessageParser<PBXSvcAllResponse>(() => new PBXSvcAllResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PBXSvcAllResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.RPC.PbxSvcReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PBXSvcAllResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PBXSvcAllResponse(PBXSvcAllResponse other) : this() {
pbxEvents_ = other.pbxEvents_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PBXSvcAllResponse Clone() {
return new PBXSvcAllResponse(this);
}
/// <summary>Field number for the "pbx_events" field.</summary>
public const int PbxEventsFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Operations.PBXEvents.PBXEvent> _repeated_pbxEvents_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Operations.PBXEvents.PBXEvent.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Operations.PBXEvents.PBXEvent> pbxEvents_ = new pbc::RepeatedField<global::HOLMS.Types.Operations.PBXEvents.PBXEvent>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Operations.PBXEvents.PBXEvent> PbxEvents {
get { return pbxEvents_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PBXSvcAllResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PBXSvcAllResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!pbxEvents_.Equals(other.pbxEvents_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= pbxEvents_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
pbxEvents_.WriteTo(output, _repeated_pbxEvents_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += pbxEvents_.CalculateSize(_repeated_pbxEvents_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PBXSvcAllResponse other) {
if (other == null) {
return;
}
pbxEvents_.Add(other.pbxEvents_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
pbxEvents_.AddEntriesFrom(input, _repeated_pbxEvents_codec);
break;
}
}
}
}
}
public sealed partial class PBXSvcGetActiveConnectorCountResponse : pb::IMessage<PBXSvcGetActiveConnectorCountResponse> {
private static readonly pb::MessageParser<PBXSvcGetActiveConnectorCountResponse> _parser = new pb::MessageParser<PBXSvcGetActiveConnectorCountResponse>(() => new PBXSvcGetActiveConnectorCountResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PBXSvcGetActiveConnectorCountResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.RPC.PbxSvcReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PBXSvcGetActiveConnectorCountResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PBXSvcGetActiveConnectorCountResponse(PBXSvcGetActiveConnectorCountResponse other) : this() {
pingResponses_ = other.pingResponses_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PBXSvcGetActiveConnectorCountResponse Clone() {
return new PBXSvcGetActiveConnectorCountResponse(this);
}
/// <summary>Field number for the "ping_responses" field.</summary>
public const int PingResponsesFieldNumber = 1;
private int pingResponses_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int PingResponses {
get { return pingResponses_; }
set {
pingResponses_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PBXSvcGetActiveConnectorCountResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PBXSvcGetActiveConnectorCountResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (PingResponses != other.PingResponses) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (PingResponses != 0) hash ^= PingResponses.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (PingResponses != 0) {
output.WriteRawTag(8);
output.WriteInt32(PingResponses);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (PingResponses != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PingResponses);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PBXSvcGetActiveConnectorCountResponse other) {
if (other == null) {
return;
}
if (other.PingResponses != 0) {
PingResponses = other.PingResponses;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
PingResponses = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections;
using System.Linq;
using Dibware.StoredProcedureFramework.Generics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Dibware.StoredProcedureFramework.Tests.UnitTests.Generics
{
[TestClass]
public class MaybeOfTTests
{
#region Constructor
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void WhenConstructedWithNullElements_ThrowsException()
{
// ARRANGE
new Maybe<string>(null);
// ACT
// ASSERT
}
[TestMethod]
public void WhenConstructedWithNoElements_ReturnsZeroCount()
{
// ARRANGE
const int expctedCount = 0;
var maybe = new Maybe<string>();
// ACT
var actualCount = maybe.Count();
// ASSERT
Assert.AreEqual(expctedCount, actualCount);
}
[TestMethod]
public void WhenConstructedWithOneElement_ReturnsCountOf1()
{
// ARRANGE
const int expctedCount = 1;
var maybe = new Maybe<string>("Bill");
// ACT
var actualCount = maybe.Count();
// ASSERT
Assert.AreEqual(expctedCount, actualCount);
Assert.AreEqual("Bill", maybe.Single());
}
[TestMethod]
public void WhenConstructedWithOneElement_ReturnsSameItem()
{
// ARRANGE
const string expctedValue = "Bill";
var maybe = new Maybe<string>(expctedValue);
// ACT
var actual = maybe.Single();
// ASSERT
Assert.AreSame(expctedValue, actual);
}
#endregion
#region HasItem
[TestMethod]
public void HasItem_WhenConstructedWithZeroElements_ReturnsFalse()
{
// ARRANGE
var maybe = new Maybe<string>();
// ACT
var actual = maybe.HasItem;
// ASSERT
Assert.IsFalse(actual);
}
[TestMethod]
public void HasItem_WhenConstructedWithOneElement_ReturnsTrue()
{
// ARRANGE
const string expctedValue = "Bill";
var maybe = new Maybe<string>(expctedValue);
// ACT
var actual = maybe.HasItem;
// ASSERT
Assert.IsTrue(actual);
}
#endregion
#region Or
[TestMethod]
public void Or_WhenFirstAndSecondIsConstructedWithZeroElements_ReturnsSecond()
{
// ARRANGE
var maybe1 = new Maybe<string>();
var maybe2 = new Maybe<string>();
// ACT
var actual = maybe1.Or(maybe2);
// ASSERT
Assert.AreNotSame(maybe1, actual);
Assert.AreSame(maybe2, actual);
}
[TestMethod]
public void Or_WhenFirstIsConstructedWithOneElementAndSecondIsConstructedWithZeroElements_ReturnsFirst()
{
// ARRANGE
var maybe1 = new Maybe<string>("Bill");
var maybe2 = new Maybe<string>();
// ACT
var actual = maybe1.Or(maybe2);
// ASSERT
Assert.AreSame(maybe1, actual);
Assert.AreNotSame(maybe2, actual);
}
[TestMethod]
public void Or_WhenFirstIsConstructedWithZeroElementsAndSecondIsConstructedWithOneElement_ReturnsSecond()
{
// ARRANGE
var maybe1 = new Maybe<string>();
var maybe2 = new Maybe<string>("Ted");
// ACT
var actual = maybe1.Or(maybe2);
// ASSERT
Assert.AreNotSame(maybe1, actual);
Assert.AreSame(maybe2, actual);
}
[TestMethod]
public void Or_WhenFirstAndSecondIsConstructedWithOneElement_ReturnsFirst()
{
// ARRANGE
var maybe1 = new Maybe<string>("Bill");
var maybe2 = new Maybe<string>("Ted");
// ACT
var actual = maybe1.Or(maybe2);
// ASSERT
Assert.AreSame(maybe1, actual);
Assert.AreNotSame(maybe2, actual);
}
#endregion
#region ToMaybe
[TestMethod]
public void ToMaybe_WhenSuppliedWithNull_ReturnsEmptyMaybe()
{
// ARRANGE
const string value = null;
const int expctedCount = 0;
var maybe = Maybe<string>.ToMaybe(value);
// ACT
var actualCount = maybe.Count();
// ASSERT
Assert.AreEqual(expctedCount, actualCount);
}
[TestMethod]
public void ToMaybe_WhenSuppliedWithNonNull_ReturnsMaybeWithOne()
{
// ARRANGE
const string value = "Jane";
const int expctedCount = 1;
var maybe = Maybe<string>.ToMaybe(value);
// ACT
var actualCount = maybe.Count();
// ASSERT
Assert.AreEqual(expctedCount, actualCount);
}
#endregion
#region IEnumerable.GetEnumerator
[TestMethod]
public void GetEnumerator_AfterContructionWithValidValue_CorrectlyIteratesThroughAllElements()
{
// ARRANGE
const string expectedValue = "ValidValue";
var maybe = Maybe<string>.ToMaybe(expectedValue);
IEnumerator iterator = ((IEnumerable)maybe).GetEnumerator();
// ACT
iterator.MoveNext();
var actual = iterator.Current;
// ASSERT
Assert.AreEqual(expectedValue, actual);
}
#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.Buffers.Text;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Globalization
{
internal static class TimeSpanFormat
{
private static unsafe void AppendNonNegativeInt32(StringBuilder sb, int n, int digits)
{
Debug.Assert(n >= 0);
uint value = (uint)n;
const int MaxUInt32Digits = 10;
char* buffer = stackalloc char[MaxUInt32Digits];
int index = 0;
do
{
uint div = value / 10;
buffer[index++] = (char)(value - (div * 10) + '0');
value = div;
}
while (value != 0);
Debug.Assert(index <= MaxUInt32Digits);
for (int i = digits - index; i > 0; --i) sb.Append('0');
for (int i = index - 1; i >= 0; --i) sb.Append(buffer[i]);
}
internal static readonly FormatLiterals PositiveInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: false);
internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: true);
/// <summary>Main method called from TimeSpan.ToString.</summary>
internal static string Format(TimeSpan value, string format, IFormatProvider formatProvider)
{
if (string.IsNullOrEmpty(format))
{
return FormatC(value); // formatProvider ignored, as "c" is invariant
}
if (format.Length == 1)
{
char c = format[0];
if (c == 'c' || (c | 0x20) == 't') // special-case to optimize the default TimeSpan format
{
return FormatC(value); // formatProvider ignored, as "c" is invariant
}
if ((c | 0x20) == 'g') // special-case to optimize the remaining 'g'/'G' standard formats
{
return FormatG(value, DateTimeFormatInfo.GetInstance(formatProvider), c == 'G' ? StandardFormat.G : StandardFormat.g);
}
throw new FormatException(SR.Format_InvalidString);
}
return StringBuilderCache.GetStringAndRelease(FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider), result: null));
}
/// <summary>Main method called from TimeSpan.TryFormat.</summary>
internal static bool TryFormat(TimeSpan value, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider formatProvider)
{
if (format.Length == 0)
{
return TryFormatStandard(value, StandardFormat.C, null, destination, out charsWritten);
}
if (format.Length == 1)
{
char c = format[0];
if (c == 'c' || ((c | 0x20) == 't'))
{
return TryFormatStandard(value, StandardFormat.C, null, destination, out charsWritten);
}
else
{
StandardFormat sf =
c == 'g' ? StandardFormat.g :
c == 'G' ? StandardFormat.G :
throw new FormatException(SR.Format_InvalidString);
return TryFormatStandard(value, sf, DateTimeFormatInfo.GetInstance(formatProvider).DecimalSeparator, destination, out charsWritten);
}
}
StringBuilder sb = FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider), result: null);
if (sb.Length <= destination.Length)
{
sb.CopyTo(0, destination, sb.Length);
charsWritten = sb.Length;
StringBuilderCache.Release(sb);
return true;
}
charsWritten = 0;
StringBuilderCache.Release(sb);
return false;
}
internal static string FormatC(TimeSpan value)
{
Span<char> destination = stackalloc char[26]; // large enough for any "c" TimeSpan
TryFormatStandard(value, StandardFormat.C, null, destination, out int charsWritten);
return new string(destination.Slice(0, charsWritten));
}
private static string FormatG(TimeSpan value, DateTimeFormatInfo dtfi, StandardFormat format)
{
string decimalSeparator = dtfi.DecimalSeparator;
int maxLength = 25 + decimalSeparator.Length; // large enough for any "g"/"G" TimeSpan
Span<char> destination = maxLength < 128 ?
stackalloc char[maxLength] :
new char[maxLength]; // the chances of needing this case are almost 0, as DecimalSeparator.Length will basically always == 1
TryFormatStandard(value, format, decimalSeparator, destination, out int charsWritten);
return new string(destination.Slice(0, charsWritten));
}
private enum StandardFormat { C, G, g }
private static bool TryFormatStandard(TimeSpan value, StandardFormat format, string decimalSeparator, Span<char> destination, out int charsWritten)
{
Debug.Assert(format == StandardFormat.C || format == StandardFormat.G || format == StandardFormat.g);
// First, calculate how large an output buffer is needed to hold the entire output.
int requiredOutputLength = 8; // start with "hh:mm:ss" and adjust as necessary
uint fraction;
ulong totalSecondsRemaining;
{
// Turn this into a non-negative TimeSpan if possible.
long ticks = value.Ticks;
if (ticks < 0)
{
requiredOutputLength = 9; // requiredOutputLength + 1 for the leading '-' sign
ticks = -ticks;
if (ticks < 0)
{
Debug.Assert(ticks == long.MinValue /* -9223372036854775808 */);
// We computed these ahead of time; they're straight from the decimal representation of Int64.MinValue.
fraction = 4775808;
totalSecondsRemaining = 922337203685;
goto AfterComputeFraction;
}
}
totalSecondsRemaining = Math.DivRem((ulong)ticks, TimeSpan.TicksPerSecond, out ulong fraction64);
fraction = (uint)fraction64;
}
AfterComputeFraction:
// Only write out the fraction if it's non-zero, and in that
// case write out the entire fraction (all digits).
Debug.Assert(fraction < 10_000_000);
int fractionDigits = 0;
switch (format)
{
case StandardFormat.C:
// "c": Write out a fraction only if it's non-zero, and write out all 7 digits of it.
if (fraction != 0)
{
fractionDigits = DateTimeFormat.MaxSecondsFractionDigits;
requiredOutputLength += fractionDigits + 1; // digits plus leading decimal separator
}
break;
case StandardFormat.G:
// "G": Write out a fraction regardless of whether it's 0, and write out all 7 digits of it.
fractionDigits = DateTimeFormat.MaxSecondsFractionDigits;
requiredOutputLength += fractionDigits + 1; // digits plus leading decimal separator
break;
default:
// "g": Write out a fraction only if it's non-zero, and write out only the most significant digits.
Debug.Assert(format == StandardFormat.g);
if (fraction != 0)
{
fractionDigits = DateTimeFormat.MaxSecondsFractionDigits - FormattingHelpers.CountDecimalTrailingZeros(fraction, out fraction);
requiredOutputLength += fractionDigits + 1; // digits plus leading decimal separator
}
break;
}
ulong totalMinutesRemaining = 0, seconds = 0;
if (totalSecondsRemaining > 0)
{
// Only compute minutes if the TimeSpan has an absolute value of >= 1 minute.
totalMinutesRemaining = Math.DivRem(totalSecondsRemaining, 60 /* seconds per minute */, out seconds);
Debug.Assert(seconds < 60);
}
ulong totalHoursRemaining = 0, minutes = 0;
if (totalMinutesRemaining > 0)
{
// Only compute hours if the TimeSpan has an absolute value of >= 1 hour.
totalHoursRemaining = Math.DivRem(totalMinutesRemaining, 60 /* minutes per hour */, out minutes);
Debug.Assert(minutes < 60);
}
// At this point, we can switch over to 32-bit DivRem since the data has shrunk far enough.
Debug.Assert(totalHoursRemaining <= uint.MaxValue);
uint days = 0, hours = 0;
if (totalHoursRemaining > 0)
{
// Only compute days if the TimeSpan has an absolute value of >= 1 day.
days = Math.DivRem((uint)totalHoursRemaining, 24 /* hours per day */, out hours);
Debug.Assert(hours < 24);
}
int hourDigits = 2;
if (format == StandardFormat.g && hours < 10)
{
// "g": Only writing a one-digit hour, rather than expected two-digit hour
hourDigits = 1;
requiredOutputLength--;
}
int dayDigits = 0;
if (days > 0)
{
dayDigits = FormattingHelpers.CountDigits(days);
Debug.Assert(dayDigits <= 8);
requiredOutputLength += dayDigits + 1; // for the leading "d."
}
else if (format == StandardFormat.G)
{
// "G": has a leading "0:" if days is 0
requiredOutputLength += 2;
dayDigits = 1;
}
if (destination.Length < requiredOutputLength)
{
charsWritten = 0;
return false;
}
// Write leading '-' if necessary
int idx = 0;
if (value.Ticks < 0)
{
destination[idx++] = '-';
}
// Write day and separator, if necessary
if (dayDigits != 0)
{
WriteDigits(days, destination.Slice(idx, dayDigits));
idx += dayDigits;
destination[idx++] = format == StandardFormat.C ? '.' : ':';
}
// Write "[h]h:mm:ss
Debug.Assert(hourDigits == 1 || hourDigits == 2);
if (hourDigits == 2)
{
WriteTwoDigits(hours, destination.Slice(idx));
idx += 2;
}
else
{
destination[idx++] = (char)('0' + hours);
}
destination[idx++] = ':';
WriteTwoDigits((uint)minutes, destination.Slice(idx));
idx += 2;
destination[idx++] = ':';
WriteTwoDigits((uint)seconds, destination.Slice(idx));
idx += 2;
// Write fraction and separator, if necessary
if (fractionDigits != 0)
{
if (format == StandardFormat.C)
{
destination[idx++] = '.';
}
else if (decimalSeparator.Length == 1)
{
destination[idx++] = decimalSeparator[0];
}
else
{
decimalSeparator.AsSpan().CopyTo(destination);
idx += decimalSeparator.Length;
}
WriteDigits(fraction, destination.Slice(idx, fractionDigits));
idx += fractionDigits;
}
Debug.Assert(idx == requiredOutputLength);
charsWritten = requiredOutputLength;
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void WriteTwoDigits(uint value, Span<char> buffer)
{
Debug.Assert(buffer.Length >= 2);
uint temp = '0' + value;
value /= 10;
buffer[1] = (char)(temp - (value * 10));
buffer[0] = (char)('0' + value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void WriteDigits(uint value, Span<char> buffer)
{
Debug.Assert(buffer.Length > 0);
for (int i = buffer.Length - 1; i >= 1; i--)
{
uint temp = '0' + value;
value /= 10;
buffer[i] = (char)(temp - (value * 10));
}
Debug.Assert(value < 10);
buffer[0] = (char)('0' + value);
}
/// <summary>Format the TimeSpan instance using the specified format.</summary>
private static StringBuilder FormatCustomized(TimeSpan value, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, StringBuilder result = null)
{
Debug.Assert(dtfi != null);
bool resultBuilderIsPooled = false;
if (result == null)
{
result = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
resultBuilderIsPooled = true;
}
int day = (int)(value.Ticks / TimeSpan.TicksPerDay);
long time = value.Ticks % TimeSpan.TicksPerDay;
if (value.Ticks < 0)
{
day = -day;
time = -time;
}
int hours = (int)(time / TimeSpan.TicksPerHour % 24);
int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
int fraction = (int)(time % TimeSpan.TicksPerSecond);
long tmp = 0;
int i = 0;
int tokenLen;
while (i < format.Length)
{
char ch = format[i];
int nextChar;
switch (ch)
{
case 'h':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
{
goto default; // to release the builder and throw
}
DateTimeFormat.FormatDigits(result, hours, tokenLen);
break;
case 'm':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
{
goto default; // to release the builder and throw
}
DateTimeFormat.FormatDigits(result, minutes, tokenLen);
break;
case 's':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
{
goto default; // to release the builder and throw
}
DateTimeFormat.FormatDigits(result, seconds, tokenLen);
break;
case 'f':
//
// The fraction of a second in single-digit precision. The remaining digits are truncated.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
{
goto default; // to release the builder and throw
}
tmp = fraction;
tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
result.AppendSpanFormattable(tmp, DateTimeFormat.fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture);
break;
case 'F':
//
// Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
{
goto default; // to release the builder and throw
}
tmp = fraction;
tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
int effectiveDigits = tokenLen;
while (effectiveDigits > 0)
{
if (tmp % 10 == 0)
{
tmp = tmp / 10;
effectiveDigits--;
}
else
{
break;
}
}
if (effectiveDigits > 0)
{
result.AppendSpanFormattable(tmp, DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture);
}
break;
case 'd':
//
// tokenLen == 1 : Day as digits with no leading zero.
// tokenLen == 2+: Day as digits with leading zero for single-digit days.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 8)
{
goto default; // to release the builder and throw
}
DateTimeFormat.FormatDigits(result, day, tokenLen, true);
break;
case '\'':
case '\"':
tokenLen = DateTimeFormat.ParseQuoteString(format, i, result);
break;
case '%':
// Optional format character.
// For example, format string "%d" will print day
// Most of the cases, "%" can be ignored.
nextChar = DateTimeFormat.ParseNextChar(format, i);
// nextChar will be -1 if we already reach the end of the format string.
// Besides, we will not allow "%%" appear in the pattern.
if (nextChar >= 0 && nextChar != (int)'%')
{
char nextCharChar = (char)nextChar;
StringBuilder origStringBuilder = FormatCustomized(value, MemoryMarshal.CreateReadOnlySpan<char>(ref nextCharChar, 1), dtfi, result);
Debug.Assert(ReferenceEquals(origStringBuilder, result));
tokenLen = 2;
}
else
{
//
// This means that '%' is at the end of the format string or
// "%%" appears in the format string.
//
goto default; // to release the builder and throw
}
break;
case '\\':
// Escaped character. Can be used to insert character into the format string.
// For example, "\d" will insert the character 'd' into the string.
//
nextChar = DateTimeFormat.ParseNextChar(format, i);
if (nextChar >= 0)
{
result.Append(((char)nextChar));
tokenLen = 2;
}
else
{
//
// This means that '\' is at the end of the formatting string.
//
goto default; // to release the builder and throw
}
break;
default:
// Invalid format string
if (resultBuilderIsPooled)
{
StringBuilderCache.Release(result);
}
throw new FormatException(SR.Format_InvalidString);
}
i += tokenLen;
}
return result;
}
internal struct FormatLiterals
{
internal string AppCompatLiteral;
internal int dd;
internal int hh;
internal int mm;
internal int ss;
internal int ff;
private string[] _literals;
internal string Start => _literals[0];
internal string DayHourSep => _literals[1];
internal string HourMinuteSep => _literals[2];
internal string MinuteSecondSep => _literals[3];
internal string SecondFractionSep => _literals[4];
internal string End => _literals[5];
/* factory method for static invariant FormatLiterals */
internal static FormatLiterals InitInvariant(bool isNegative)
{
FormatLiterals x = new FormatLiterals();
x._literals = new string[6];
x._literals[0] = isNegative ? "-" : string.Empty;
x._literals[1] = ".";
x._literals[2] = ":";
x._literals[3] = ":";
x._literals[4] = ".";
x._literals[5] = string.Empty;
x.AppCompatLiteral = ":."; // MinuteSecondSep+SecondFractionSep;
x.dd = 2;
x.hh = 2;
x.mm = 2;
x.ss = 2;
x.ff = DateTimeFormat.MaxSecondsFractionDigits;
return x;
}
// For the "v1" TimeSpan localized patterns, the data is simply literal field separators with
// the constants guaranteed to include DHMSF ordered greatest to least significant.
// Once the data becomes more complex than this we will need to write a proper tokenizer for
// parsing and formatting
internal void Init(ReadOnlySpan<char> format, bool useInvariantFieldLengths)
{
dd = hh = mm = ss = ff = 0;
_literals = new string[6];
for (int i = 0; i < _literals.Length; i++)
{
_literals[i] = string.Empty;
}
StringBuilder sb = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
bool inQuote = false;
char quote = '\'';
int field = 0;
for (int i = 0; i < format.Length; i++)
{
switch (format[i])
{
case '\'':
case '\"':
if (inQuote && (quote == format[i]))
{
/* we were in a quote and found a matching exit quote, so we are outside a quote now */
if (field >= 0 && field <= 5)
{
_literals[field] = sb.ToString();
sb.Length = 0;
inQuote = false;
}
else
{
Debug.Fail($"Unexpected field value: {field}");
return; // how did we get here?
}
}
else if (!inQuote)
{
/* we are at the start of a new quote block */
quote = format[i];
inQuote = true;
}
else
{
/* we were in a quote and saw the other type of quote character, so we are still in a quote */
}
break;
case '%':
Debug.Fail("Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
goto default;
case '\\':
if (!inQuote)
{
i++; /* skip next character that is escaped by this backslash or percent sign */
break;
}
goto default;
case 'd':
if (!inQuote)
{
Debug.Assert((field == 0 && sb.Length == 0) || field == 1, "field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 1; // DayHourSep
dd++;
}
break;
case 'h':
if (!inQuote)
{
Debug.Assert((field == 1 && sb.Length == 0) || field == 2, "field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 2; // HourMinuteSep
hh++;
}
break;
case 'm':
if (!inQuote)
{
Debug.Assert((field == 2 && sb.Length == 0) || field == 3, "field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 3; // MinuteSecondSep
mm++;
}
break;
case 's':
if (!inQuote)
{
Debug.Assert((field == 3 && sb.Length == 0) || field == 4, "field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 4; // SecondFractionSep
ss++;
}
break;
case 'f':
case 'F':
if (!inQuote)
{
Debug.Assert((field == 4 && sb.Length == 0) || field == 5, "field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 5; // End
ff++;
}
break;
default:
sb.Append(format[i]);
break;
}
}
Debug.Assert(field == 5);
AppCompatLiteral = MinuteSecondSep + SecondFractionSep;
Debug.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
if (useInvariantFieldLengths)
{
dd = 2;
hh = 2;
mm = 2;
ss = 2;
ff = DateTimeFormat.MaxSecondsFractionDigits;
}
else
{
if (dd < 1 || dd > 2) dd = 2; // The DTFI property has a problem. let's try to make the best of the situation.
if (hh < 1 || hh > 2) hh = 2;
if (mm < 1 || mm > 2) mm = 2;
if (ss < 1 || ss > 2) ss = 2;
if (ff < 1 || ff > 7) ff = 7;
}
StringBuilderCache.Release(sb);
}
}
}
}
| |
/*
* 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 System;
namespace Lucene.Net.Search
{
/// <summary> Encapsulates sort criteria for returned hits.
///
/// <p>The fields used to determine sort order must be carefully chosen.
/// Documents must contain a single term in such a field,
/// and the value of the term should indicate the document's relative position in
/// a given sort order. The field must be indexed, but should not be tokenized,
/// and does not need to be stored (unless you happen to want it back with the
/// rest of your document data). In other words:
///
/// <p><code>document.add (new Field ("byNumber", Integer.toString(x), Field.Store.NO, Field.Index.NO_ANALYZED));</code></p>
///
///
/// <p><h3>Valid Types of Values</h3>
///
/// <p>There are four possible kinds of term values which may be put into
/// sorting fields: Integers, Longs, Floats, or Strings. Unless
/// {@link SortField SortField} objects are specified, the type of value
/// in the field is determined by parsing the first term in the field.
///
/// <p>Integer term values should contain only digits and an optional
/// preceding negative sign. Values must be base 10 and in the range
/// <code>Integer.MIN_VALUE</code> and <code>Integer.MAX_VALUE</code> inclusive.
/// Documents which should appear first in the sort
/// should have low value integers, later documents high values
/// (i.e. the documents should be numbered <code>1..n</code> where
/// <code>1</code> is the first and <code>n</code> the last).
///
/// <p>Long term values should contain only digits and an optional
/// preceding negative sign. Values must be base 10 and in the range
/// <code>Long.MIN_VALUE</code> and <code>Long.MAX_VALUE</code> inclusive.
/// Documents which should appear first in the sort
/// should have low value integers, later documents high values.
///
/// <p>Float term values should conform to values accepted by
/// {@link Float Float.valueOf(String)} (except that <code>NaN</code>
/// and <code>Infinity</code> are not supported).
/// Documents which should appear first in the sort
/// should have low values, later documents high values.
///
/// <p>String term values can contain any valid String, but should
/// not be tokenized. The values are sorted according to their
/// {@link Comparable natural order}. Note that using this type
/// of term value has higher memory requirements than the other
/// two types.
///
/// <p><h3>object Reuse</h3>
///
/// <p>One of these objects can be
/// used multiple times and the sort order changed between usages.
///
/// <p>This class is thread safe.
///
/// <p><h3>Memory Usage</h3>
///
/// <p>Sorting uses of caches of term values maintained by the
/// internal HitQueue(s). The cache is static and contains an integer
/// or float array of length <code>IndexReader.maxDoc()</code> for each field
/// name for which a sort is performed. In other words, the size of the
/// cache in bytes is:
///
/// <p><code>4 * IndexReader.maxDoc() * (# of different fields actually used to sort)</code>
///
/// <p>For String fields, the cache is larger: in addition to the
/// above array, the value of every term in the field is kept in memory.
/// If there are many unique terms in the field, this could
/// be quite large.
///
/// <p>Note that the size of the cache is not affected by how many
/// fields are in the index and <i>might</i> be used to sort - only by
/// the ones actually used to sort a result set.
///
/// <p>Created: Feb 12, 2004 10:53:57 AM
///
/// </summary>
/// <since> lucene 1.4
/// </since>
/// <version> $Id: Sort.java 598376 2007-11-26 18:45:39Z dnaber $
/// </version>
[Serializable]
public class Sort
{
/// <summary> Represents sorting by computed relevance. Using this sort criteria returns
/// the same results as calling
/// {@link Searcher#Search(Query) Searcher#search()}without a sort criteria,
/// only with slightly more overhead.
/// </summary>
public static readonly Sort RELEVANCE = new Sort();
/// <summary>Represents sorting by index order. </summary>
public static readonly Sort INDEXORDER;
// internal representation of the sort criteria
internal SortField[] fields;
/// <summary> Sorts by computed relevance. This is the same sort criteria as calling
/// {@link Searcher#Search(Query) Searcher#search()}without a sort criteria,
/// only with slightly more overhead.
/// </summary>
public Sort() : this(new SortField[] {SortField.FIELD_SCORE, SortField.FIELD_DOC})
{
}
/// <summary> Sorts by the terms in <code>field</code> then by index order (document
/// number). The type of value in <code>field</code> is determined
/// automatically.
///
/// </summary>
/// <seealso cref="SortField#AUTO">
/// </seealso>
public Sort(System.String field)
{
SetSort(field, false);
}
/// <summary> Sorts possibly in reverse by the terms in <code>field</code> then by
/// index order (document number). The type of value in <code>field</code> is
/// determined automatically.
///
/// </summary>
/// <seealso cref="SortField#AUTO">
/// </seealso>
public Sort(System.String field, bool reverse)
{
SetSort(field, reverse);
}
/// <summary> Sorts in succession by the terms in each field. The type of value in
/// <code>field</code> is determined automatically.
///
/// </summary>
/// <seealso cref="SortField#AUTO">
/// </seealso>
public Sort(System.String[] fields)
{
SetSort(fields);
}
/// <summary>Sorts by the criteria in the given SortField. </summary>
public Sort(SortField field)
{
SetSort(field);
}
/// <summary>Sorts in succession by the criteria in each SortField. </summary>
public Sort(SortField[] fields)
{
SetSort(fields);
}
/// <summary> Sets the sort to the terms in <code>field</code> then by index order
/// (document number).
/// </summary>
public void SetSort(System.String field)
{
SetSort(field, false);
}
/// <summary> Sets the sort to the terms in <code>field</code> possibly in reverse,
/// then by index order (document number).
/// </summary>
public virtual void SetSort(System.String field, bool reverse)
{
SortField[] nfields = new SortField[]{new SortField(field, SortField.AUTO, reverse), SortField.FIELD_DOC};
fields = nfields;
}
/// <summary>Sets the sort to the terms in each field in succession. </summary>
public virtual void SetSort(System.String[] fieldnames)
{
int n = fieldnames.Length;
SortField[] nfields = new SortField[n];
for (int i = 0; i < n; ++i)
{
nfields[i] = new SortField(fieldnames[i], SortField.AUTO);
}
fields = nfields;
}
/// <summary>Sets the sort to the given criteria. </summary>
public virtual void SetSort(SortField field)
{
this.fields = new SortField[]{field};
}
/// <summary>Sets the sort to the given criteria in succession. </summary>
public virtual void SetSort(SortField[] fields)
{
this.fields = fields;
}
/// <summary> Representation of the sort criteria.</summary>
/// <returns> Array of SortField objects used in this sort criteria
/// </returns>
public virtual SortField[] GetSort()
{
return fields;
}
public override System.String ToString()
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
for (int i = 0; i < fields.Length; i++)
{
buffer.Append(fields[i].ToString());
if ((i + 1) < fields.Length)
buffer.Append(',');
}
return buffer.ToString();
}
static Sort()
{
INDEXORDER = new Sort(SortField.FIELD_DOC);
}
}
}
| |
using System;
using System.Linq;
using System.Numerics;
using hw.DebugFormatter;
using JetBrains.Annotations;
using Reni.Context;
namespace Reni.Runtime
{
static class DataHandler
{
internal sealed class RuntimeException : Exception
{
public RuntimeException(Exception exception)
: base("Runtime exception during Dereference.", exception) { }
}
internal static int RefBytes
=> Root.DefaultRefAlignParam.RefSize.SaveByteCount;
/// <summary>
/// Moves the bytes.
/// </summary>
/// <param name="count"> The count. </param>
/// <param name="destination"> The destination. </param>
/// <param name="destByte"> The destination byte. </param>
/// <param name="source"> The source. </param>
/// created 08.10.2006 17:43
internal static unsafe void MoveBytes
(int count, byte[] destination, int destByte, long source)
{
fixed(byte* destPtr = &destination[destByte])
MoveBytes(count, destPtr, (byte*)&source);
}
/// <summary>
/// Moves the bytes.
/// </summary>
/// <param name="count"> The count. </param>
/// <param name="destination"> The destination. </param>
/// <param name="source"> The source. </param>
/// created 08.10.2006 17:43
static unsafe void MoveBytes(int count, byte* destination, byte* source)
{
if(destination < source)
for(var i = 0; i < count; i++)
destination[i] = source[i];
else if(destination > source)
for(var i = count - 1; i >= 0; i--)
destination[i] = source[i];
}
/// <summary>
/// Moves the bytes with offset.
/// </summary>
/// <param name="count"> The count. </param>
/// <param name="destination"> The destination. </param>
/// <param name="destOffset"> The destination offset. </param>
/// <param name="source"> The source. </param>
/// <param name="sourceOffset"> The source offset. </param>
/// created 08.10.2006 20:07
internal static void MoveBytes
(int count, byte[] destination, int destOffset, byte[] source, int sourceOffset)
{
for(var i = 0; i < count; i++)
destination[i + destOffset] = source[i + sourceOffset];
}
static unsafe void BitCast(int count, byte* x, int bitsToCast)
{
var isNegative = IsNegative(x[count - 1]);
while(bitsToCast >= 8)
{
count--;
x[count] = (byte)(isNegative? -1 : 0);
bitsToCast -= 8;
}
if(bitsToCast > 0)
{
count--;
var @sbyte = (int)(sbyte)x[count];
var sbyte1 = @sbyte << bitsToCast;
var i = sbyte1 >> bitsToCast;
x[count] = (byte)i;
}
if(bitsToCast < 0)
throw new NotImplementedException();
}
static bool IsNegative(byte x) => x >= 0x80;
public static void Set(byte[] dest, int destStart, params byte[] source) => source.CopyTo(dest, destStart);
internal static unsafe byte[] Pointer(this byte[] data, int dataStart)
{
var bytes = RefBytes;
var result = new byte[bytes];
fixed(byte* dataPointer = data)
{
(sizeof(long) == sizeof(byte*)).Assert(()
=> $"sizeof(long) = {sizeof(long)}, sizeof(byte*) = {sizeof(byte*)}");
var intPointer = (long)(dataPointer + dataStart);
var bytePointer = (byte*)&intPointer;
for(var i = 0; i < bytes; i++)
result[i] = bytePointer[i];
}
return result;
}
public static unsafe byte[] Dereference(this byte[] data, int dataStart, int bytes)
{
try
{
(data.Length >= dataStart + RefBytes).Assert();
var result = new byte[bytes];
fixed(byte* dataPointer = &data[dataStart])
{
var bytePointer = *(byte**)dataPointer;
for(var i = 0; i < bytes; i++)
result[i] = bytePointer[i];
}
return result;
}
catch(AccessViolationException exception)
{
throw new RuntimeException(exception);
}
}
internal static unsafe void DoRefPlus(this byte[] data, int dataStart, int offset)
{
(data != null).Assert("data != null");
fixed(byte* dataPointer = &data[dataStart])
{
var intPointer = (int*)dataPointer;
*intPointer += offset;
}
}
internal static byte[] Get(this byte[] source, int sourceStart, int bytes)
{
var result = new byte[bytes];
for(var i = 0; i < bytes; i++)
result[i] = source[sourceStart + i];
return result;
}
[UsedImplicitly]
public static unsafe void BitCast(byte[] data, int dataStart, int bytes, int bits)
{
fixed(byte* dataPointer = &data[dataStart])
BitCast(bytes, dataPointer, bits);
}
internal static void PrintNumber(this byte[] data) => PrintText(new BigInteger(data).ToString());
internal static void PrintText(this string text) => Data.OutStream.AddData(text);
internal static void PrintText(this byte[] text) => new string(text.Select(x => (char)x).ToArray()).PrintText();
internal static unsafe void AssignFromPointers
(this byte[] leftData, byte[] rightData, int bytes)
{
fixed(byte* leftPointer = leftData)
fixed(byte* rightPointer = rightData)
MoveBytes(bytes, *(byte**)leftPointer, *(byte**)rightPointer);
}
internal static bool IsLessEqual(byte[] left, byte[] right) => !IsGreater(left, right);
internal static bool IsGreaterEqual(byte[] left, byte[] right) => !IsLess(left, right);
internal static bool IsNotEqual(byte[] left, byte[] right) => !IsEqual(left, right);
internal static bool IsLess(byte[] left, byte[] right) => IsGreater(right, left);
internal static bool IsGreater(byte[] left, byte[] right)
{
var leftBytes = left.Length;
var rightBytes = right.Length;
var isLeftNegative = left[leftBytes - 1] > 127;
var isRightNegative = right[rightBytes - 1] > 127;
if(isLeftNegative != isRightNegative)
return isRightNegative;
for(var i = Math.Max(leftBytes, rightBytes) - 1; i >= 0; i--)
{
var leftByte = (sbyte)(isLeftNegative? -1 : 0);
var rightByte = (sbyte)(isRightNegative? -1 : 0);
if(i < leftBytes)
leftByte = (sbyte)left[i];
if(i < rightBytes)
rightByte = (sbyte)right[i];
if(leftByte < rightByte)
return false;
if(leftByte > rightByte)
return true;
}
return false;
}
internal static bool IsEqual(byte[] left, byte[] right)
{
var leftBytes = left.Length;
var rightBytes = right.Length;
var d = 0;
var i = 0;
for(; i < leftBytes && i < rightBytes; i++)
{
d = (sbyte)left[i];
if(d != (sbyte)right[i])
return false;
}
for(; i < leftBytes; i++)
{
if(d < 0 && (sbyte)left[i] != -1)
return false;
if(d >= 0 && (sbyte)left[i] != 0)
return false;
}
for(; i < rightBytes; i++)
{
if(d < 0 && (sbyte)right[i] != -1)
return false;
if(d >= 0 && (sbyte)right[i] != 0)
return false;
}
return true;
}
internal static byte[] Plus(this byte[] left, byte[] right, int bytes)
{
var leftBytes = left.Length;
var rightBytes = right.Length;
var result = new byte[bytes];
var d = 0;
var carry = 0;
for(var i = 0; i < bytes; i++)
{
if(i < leftBytes)
carry += (sbyte)left[i] & 0xff;
if(i < rightBytes)
{
d = (sbyte)right[i];
carry += d & 0xff;
}
else if(d < 0)
carry += 0xff;
result[i] = (byte)(carry & 0xff);
carry >>= 8;
}
return result;
}
[UsedImplicitly]
internal static byte[] PlusSimple(this byte[] left, byte[] right)
{
(left.Length == right.Length).Assert();
var bytes = left.Length;
var result = new byte[bytes];
var carry = 0;
for(var i = 0; i < bytes; i++)
{
carry += (sbyte)left[i] & 0xff;
carry += (sbyte)right[i] & 0xff;
result[i] = (byte)(carry & 0xff);
carry >>= 8;
}
return result;
}
internal static void MinusPrefix(this byte[] data)
{
var carry = 1;
for(var i = 0; i < data.Length; i++)
{
data[i] = (byte)((sbyte)~(sbyte)data[i] + carry);
carry = data[i] == 0? 1 : 0;
}
}
internal static byte[] Times(this byte[] left, byte[] right, int bytes)
=> (new BigInteger(left) * new BigInteger(right))
.ToByteArray()
.ByteAlign(bytes);
static byte[] ByteAlign(this byte[] data, int bytes)
{
if(data.Length == bytes)
return data;
var result = new byte[bytes];
var i = 0;
for(; i < bytes && i < data.Length; i++)
result[i] = data[i];
if(i < bytes)
{
var sign = (byte)(data[i - 1] >= 128? 127 : 0);
for(; i < bytes; i++)
result[i] = sign;
}
return result;
}
internal static byte[] Times(this byte[] left, int right, int bytes)
=> (new BigInteger(left) * new BigInteger(right))
.ToByteArray()
.ByteAlign(bytes);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.AddUsing
{
public partial class AddUsingTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestWhereExtension()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var q = args.[|Where|] }
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q = args.Where }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestSelectExtension()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var q = args.[|Select|] }
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q = args.Select }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestGroupByExtension()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var q = args.[|GroupBy|] }
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q = args.GroupBy }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestJoinExtension()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var q = args.[|Join|] }
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q = args.Join }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task RegressionFor8455()
{
await TestMissingAsync(
@"class C
{
void M()
{
int dim = (int)Math.[|Min|]();
}
}");
}
[WorkItem(772321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772321")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestExtensionWithThePresenceOfTheSameNameNonExtensionMethod()
{
await TestAsync(
@"namespace NS1
{
class Program
{
void Main()
{
[|new C().Foo(4);|]
}
}
class C
{
public void Foo(string y)
{
}
}
}
namespace NS2
{
static class CExt
{
public static void Foo(this NS1.C c, int x)
{
}
}
}",
@"using NS2;
namespace NS1
{
class Program
{
void Main()
{
new C().Foo(4);
}
}
class C
{
public void Foo(string y)
{
}
}
}
namespace NS2
{
static class CExt
{
public static void Foo(this NS1.C c, int x)
{
}
}
}");
}
[WorkItem(772321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772321")]
[WorkItem(920398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/920398")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestExtensionWithThePresenceOfTheSameNameNonExtensionPrivateMethod()
{
await TestAsync(
@"namespace NS1
{
class Program
{
void Main()
{
[|new C().Foo(4);|]
}
}
class C
{
private void Foo(int x)
{
}
}
}
namespace NS2
{
static class CExt
{
public static void Foo(this NS1.C c, int x)
{
}
}
}",
@"using NS2;
namespace NS1
{
class Program
{
void Main()
{
new C().Foo(4);
}
}
class C
{
private void Foo(int x)
{
}
}
}
namespace NS2
{
static class CExt
{
public static void Foo(this NS1.C c, int x)
{
}
}
}");
}
[WorkItem(772321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772321")]
[WorkItem(920398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/920398")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestExtensionWithThePresenceOfTheSameNameExtensionPrivateMethod()
{
await TestAsync(
@"using NS2;
namespace NS1
{
class Program
{
void Main()
{
[|new C().Foo(4);|]
}
}
class C
{
}
}
namespace NS2
{
static class CExt
{
private static void Foo(this NS1.C c, int x)
{
}
}
}
namespace NS3
{
static class CExt
{
public static void Foo(this NS1.C c, int x)
{
}
}
}",
@"using NS2;
using NS3;
namespace NS1
{
class Program
{
void Main()
{
new C().Foo(4);
}
}
class C
{
}
}
namespace NS2
{
static class CExt
{
private static void Foo(this NS1.C c, int x)
{
}
}
}
namespace NS3
{
static class CExt
{
public static void Foo(this NS1.C c, int x)
{
}
}
}");
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestAddUsingForAddExtentionMethod()
{
await TestAsync(
@"using System;
using System.Collections;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { [|1|] };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
@"using System;
using System.Collections;
using Ext;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { 1 };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestAddUsingForAddExtentionMethod2()
{
await TestAsync(
@"using System;
using System.Collections;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { 1, 2, [|3|] };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
@"using System;
using System.Collections;
using Ext;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { 1, 2, 3 };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestAddUsingForAddExtentionMethod3()
{
await TestAsync(
@"using System;
using System.Collections;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { 1, [|2|], 3 };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
@"using System;
using System.Collections;
using Ext;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { 1, 2, 3 };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestAddUsingForAddExtentionMethod4()
{
await TestAsync(
@"using System;
using System.Collections;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { { 1, 2, 3 }, [|{ 4, 5, 6 }|], { 7, 8, 9 } };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
@"using System;
using System.Collections;
using Ext;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestAddUsingForAddExtentionMethod5()
{
await TestAsync(
@"using System;
using System.Collections;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { { 1, 2, 3 }, { 4, 5, 6 }, [|{ 7, 8, 9 }|] };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
@"using System;
using System.Collections;
using Ext;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestAddUsingForAddExtentionMethod6()
{
await TestAsync(
@"using System;
using System.Collections;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { { 1, 2, 3 }, { ""Four"", ""Five"", ""Six"" }, [|{ '7', '8', '9' }|] };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
@"using System;
using System.Collections;
using Ext;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { { 1, 2, 3 }, { ""Four"", ""Five"", ""Six"" }, { '7', '8', '9' } };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestAddUsingForAddExtentionMethod7()
{
await TestAsync(
@"using System;
using System.Collections;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { { 1, 2, 3 }, [|{ ""Four"", ""Five"", ""Six"" }|], { '7', '8', '9' } };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
@"using System;
using System.Collections;
using Ext;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { { 1, 2, 3 }, { ""Four"", ""Five"", ""Six"" }, { '7', '8', '9' } };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestAddUsingForAddExtentionMethod8()
{
await TestAsync(
@"using System;
using System.Collections;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { [|{ 1, 2, 3 }|] };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
@"using System;
using System.Collections;
using Ext;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { { 1, 2, 3 } };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestAddUsingForAddExtentionMethod9()
{
await TestAsync(
@"using System;
using System.Collections;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { [|""This""|] };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
@"using System;
using System.Collections;
using Ext;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { ""This"" };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestAddUsingForAddExtentionMethod10()
{
await TestAsync(
@"using System;
using System.Collections;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { [|{ 1, 2, 3 }|], { ""Four"", ""Five"", ""Six"" }, { '7', '8', '9' } };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}
namespace Ext2
{
static class Extensions
{
public static void Add(this X x, object[] i)
{
}
}
}",
@"using System;
using System.Collections;
using Ext;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { { 1, 2, 3 }, { ""Four"", ""Five"", ""Six"" }, { '7', '8', '9' } };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}
namespace Ext2
{
static class Extensions
{
public static void Add(this X x, object[] i)
{
}
}
}",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestAddUsingForAddExtentionMethod11()
{
await TestAsync(
@"using System;
using System.Collections;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { [|{ 1, 2, 3 }|], { ""Four"", ""Five"", ""Six"" }, { '7', '8', '9' } };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}
namespace Ext2
{
static class Extensions
{
public static void Add(this X x, object[] i)
{
}
}
}",
@"using System;
using System.Collections;
using Ext2;
class X : IEnumerable
{
public IEnumerator GetEnumerator()
{
new X { { 1, 2, 3 }, { ""Four"", ""Five"", ""Six"" }, { '7', '8', '9' } };
return null;
}
}
namespace Ext
{
static class Extensions
{
public static void Add(this X x, int i)
{
}
}
}
namespace Ext2
{
static class Extensions
{
public static void Add(this X x, object[] i)
{
}
}
}",
index: 1,
parseOptions: null);
}
[WorkItem(3818, "https://github.com/dotnet/roslyn/issues/3818")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task InExtensionMethodUnderConditionalAccessExpression()
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
namespace Sample
{
class Program
{
static void Main(string[] args)
{
string myString = ""Sample"";
var other = myString?[|.StringExtension()|].Substring(0);
}
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Sample.Extensions
{
public static class StringExtensions
{
public static string StringExtension(this string s)
{
return ""Ok"";
}
}
}
</Document>
</Project>
</Workspace>";
var expectedText =
@"using Sample.Extensions;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
string myString = ""Sample"";
var other = myString?.StringExtension().Substring(0);
}
}
}";
await TestAsync(initialText, expectedText);
}
[WorkItem(3818, "https://github.com/dotnet/roslyn/issues/3818")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task InExtensionMethodUnderMultipleConditionalAccessExpressions()
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
public T F<T>(T x)
{
return F(new C())?.F(new C())?[|.Extn()|];
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Sample.Extensions
{
public static class Extensions
{
public static C Extn(this C obj)
{
return obj.F(new C());
}
}
}
</Document>
</Project>
</Workspace>";
var expectedText =
@"using Sample.Extensions;
public class C
{
public T F<T>(T x)
{
return F(new C())?.F(new C())?.Extn();
}
}";
await TestAsync(initialText, expectedText);
}
[WorkItem(3818, "https://github.com/dotnet/roslyn/issues/3818")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task InExtensionMethodUnderMultipleConditionalAccessExpressions2()
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
public T F<T>(T x)
{
return F(new C())?.F(new C())[|.Extn()|]?.F(newC());
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Sample.Extensions
{
public static class Extensions
{
public static C Extn(this C obj)
{
return obj.F(new C());
}
}
}
</Document>
</Project>
</Workspace>";
var expectedText =
@"using Sample.Extensions;
public class C
{
public T F<T>(T x)
{
return F(new C())?.F(new C()).Extn()?.F(newC());
}
}";
await TestAsync(initialText, expectedText);
}
}
}
| |
using UnityEngine;
using System.Collections;
[ExecuteInEditMode] // Make water live-update even when not in play mode
public class SeaShader : MonoBehaviour
{
//private WhirldObject whirldObject;
public enum WaterMode {
Simple = 0,
Reflective = 1,
Refractive = 2,
};
public WaterMode m_WaterMode = WaterMode.Reflective;
public bool m_DisablePixelLights = true;
public int m_TextureSize = 256;
public float m_ClipPlaneOffset = 0.07f;
public LayerMask cullingMask;
public Transform WaterTransform;
public LayerMask m_ReflectLayers = -1;
public LayerMask m_RefractLayers = -1;
public Shader m_ShaderFull;
public Shader m_ShaderSimple;
public bool isSurface = true;
private Hashtable m_ReflectionCameras = new Hashtable(); // Camera -> Camera table
private Hashtable m_RefractionCameras = new Hashtable(); // Camera -> Camera table
private RenderTexture m_ReflectionTexture = null;
private RenderTexture m_RefractionTexture = null;
private WaterMode m_HardwareWaterSupport = WaterMode.Reflective;
private int m_OldReflectionTextureSize = 0;
private int m_OldRefractionTextureSize = 0;
//private double tickTime = 0.0f;
private Terrain m_Terrain;
private static bool s_InsideWater = false;
// This is called when it's known that the object will be rendered by some
// camera. We render reflections / refractions and do other updates here.
// Because the script executes in edit mode, reflections for the scene view
// camera will just work!
/*void Start() {
whirldObject = transform.parent.gameObject.GetComponent(WhirldObject);
if(whirldObject == null || whirldObject.params == null) {
return;
}
if(whirldObject.params["Mode"]) {
m_SeaMode = Enum.Parse(typeof(SeaMode), whirldObject.params["Mode"], true);
}
}*/
/*public void SetSeaMode(string mode)
{
m_SeaMode = (SeaMode) System.Enum.Parse(typeof(SeaMode), mode, true);
}*/
public void OnWillRenderObject()
{
if( !enabled || !GetComponent<Renderer>() || !GetComponent<Renderer>().sharedMaterial || !GetComponent<Renderer>().enabled ) // || Time.time < tickTime)
return;
//tickTime = Time.time + .05;
if( !m_Terrain ) {
m_Terrain = Terrain.activeTerrain;
/*GameObject go = GameObject.Find("Terrain");
if( !go )
return;
m_Terrain = go.GetComponent(typeof(Terrain)) as Terrain;
if( !m_Terrain )
return;*/
}
Camera cam = Camera.current;
if( !cam )
return;
// Safeguard from recursive water reflections.
if( s_InsideWater )
return;
s_InsideWater = true;
// Actual water rendering mode depends on both the current setting AND
// the hardware support. There's no point in rendering refraction textures
// if they won't be visible in the end.
m_HardwareWaterSupport = FindHardwareWaterSupport();
WaterMode mode = GetWaterMode();
Shader newShader = ( mode == WaterMode.Refractive ) ? m_ShaderFull : m_ShaderSimple;
if( GetComponent<Renderer>().sharedMaterial.shader != newShader )
GetComponent<Renderer>().sharedMaterial.shader = newShader;
Camera reflectionCamera, refractionCamera;
CreateWaterObjects( cam, out reflectionCamera, out refractionCamera );
//Apply SeaMode
//renderer.sharedMaterial.SetColor( "_RefrColor", SeaModeColors[ (int)m_SeaMode ] );
// find out the reflection plane: position and normal in world space
Vector3 pos = transform.position;
Vector3 normal = transform.up;
// Optionally disable pixel lights for reflection/refraction
int oldPixelLightCount = QualitySettings.pixelLightCount;
if( m_DisablePixelLights )
QualitySettings.pixelLightCount = 0;
UpdateCameraModes( cam, reflectionCamera );
UpdateCameraModes( cam, refractionCamera );
bool oldSoftVegetation = QualitySettings.softVegetation;
QualitySettings.softVegetation = false;
// Render reflection if needed
if( mode >= WaterMode.Reflective/* && isSurface*/)
{
// Reflect camera around reflection plane
float d = -Vector3.Dot (normal, pos) - m_ClipPlaneOffset;
Vector4 reflectionPlane = new Vector4 (normal.x, normal.y, normal.z, d);
Matrix4x4 reflection = Matrix4x4.zero;
CalculateReflectionMatrix (ref reflection, reflectionPlane);
Vector3 oldpos = cam.transform.position;
Vector3 newpos = reflection.MultiplyPoint( oldpos );
reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
// Setup oblique projection matrix so that near plane is our reflection
// plane. This way we clip everything below/above it for free.
Vector4 clipPlane = CameraSpacePlane( reflectionCamera, pos, normal, 1.0f );
Matrix4x4 projection = cam.projectionMatrix;
CalculateObliqueMatrix (ref projection, clipPlane);
reflectionCamera.projectionMatrix = projection;
reflectionCamera.cullingMask = cullingMask & m_ReflectLayers.value; // never render water layer
reflectionCamera.targetTexture = m_ReflectionTexture;
GL.SetRevertBackfacing (true);
reflectionCamera.transform.position = newpos;
Vector3 euler = cam.transform.eulerAngles;
reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z);
// don't render tree meshes or grass in reflection :)
float oldDetailDist = m_Terrain.detailObjectDistance;
float oldTreeDist = m_Terrain.treeDistance;
float oldTreeBillDist = m_Terrain.treeBillboardDistance;
float oldSplatDist = m_Terrain.basemapDistance;
m_Terrain.detailObjectDistance = 0.0f;
m_Terrain.treeBillboardDistance = 0.0f;
m_Terrain.basemapDistance = 0.0f;
reflectionCamera.Render();
m_Terrain.detailObjectDistance = oldDetailDist;
m_Terrain.treeDistance = oldTreeDist;
m_Terrain.treeBillboardDistance = oldTreeBillDist;
m_Terrain.basemapDistance = oldSplatDist;
reflectionCamera.transform.position = oldpos;
GL.SetRevertBackfacing (false);
GetComponent<Renderer>().sharedMaterial.SetTexture( "_ReflectionTex", m_ReflectionTexture );
}
else GetComponent<Renderer>().sharedMaterial.SetTexture( "_ReflectionTex", null );
// Render refraction
if( mode >= WaterMode.Refractive )
{
refractionCamera.worldToCameraMatrix = cam.worldToCameraMatrix;
// Setup oblique projection matrix so that near plane is our reflection
// plane. This way we clip everything below/above it for free.
Vector4 clipPlane = CameraSpacePlane( refractionCamera, pos, normal, -1.0f );
Matrix4x4 projection = cam.projectionMatrix;
CalculateObliqueMatrix (ref projection, clipPlane);
refractionCamera.projectionMatrix = projection;
refractionCamera.cullingMask = cullingMask & m_RefractLayers.value; // never render water layer
refractionCamera.targetTexture = m_RefractionTexture;
refractionCamera.transform.position = cam.transform.position;
refractionCamera.transform.rotation = cam.transform.rotation;
// don't render trees or grass in refraction :)
float oldDetailDist = m_Terrain.detailObjectDistance;
float oldTreeDist = m_Terrain.treeDistance;
float oldTreeBillDist = m_Terrain.treeBillboardDistance;
m_Terrain.detailObjectDistance = 0.0f;
m_Terrain.treeDistance = 0.0f;
m_Terrain.treeBillboardDistance = 0.0f;
refractionCamera.Render();
m_Terrain.detailObjectDistance = oldDetailDist;
m_Terrain.treeDistance = oldTreeDist;
m_Terrain.treeBillboardDistance = oldTreeBillDist;
GetComponent<Renderer>().sharedMaterial.SetTexture( "_RefractionTex", m_RefractionTexture );
}
QualitySettings.softVegetation = oldSoftVegetation;
// Restore pixel light count
if( m_DisablePixelLights )
QualitySettings.pixelLightCount = oldPixelLightCount;
// Setup shader keywords based on water mode
switch( mode )
{
case WaterMode.Simple:
Shader.EnableKeyword( "WATER_SIMPLE" );
Shader.DisableKeyword( "WATER_REFLECTIVE" );
Shader.DisableKeyword( "WATER_REFRACTIVE" );
break;
case WaterMode.Reflective:
Shader.DisableKeyword( "WATER_SIMPLE" );
Shader.EnableKeyword( "WATER_REFLECTIVE" );
Shader.DisableKeyword( "WATER_REFRACTIVE" );
break;
case WaterMode.Refractive:
Shader.DisableKeyword( "WATER_SIMPLE" );
Shader.DisableKeyword( "WATER_REFLECTIVE" );
Shader.EnableKeyword( "WATER_REFRACTIVE" );
break;
}
s_InsideWater = false;
}
// Cleanup all the objects we possibly have created
void OnDisable()
{
if( GetComponent<Renderer>() )
{
Material mat = GetComponent<Renderer>().sharedMaterial;
if( mat )
{
mat.SetTexture( "_ReflectionTex", null );
mat.SetTexture( "_RefractionTex", null );
mat.shader = m_ShaderSimple;
}
}
if( m_ReflectionTexture ) {
DestroyImmediate( m_ReflectionTexture );
m_ReflectionTexture = null;
}
if( m_RefractionTexture ) {
DestroyImmediate( m_RefractionTexture );
m_RefractionTexture = null;
}
foreach( DictionaryEntry kvp in m_ReflectionCameras )
DestroyImmediate( ((Camera)kvp.Value).gameObject );
m_ReflectionCameras.Clear();
foreach( DictionaryEntry kvp in m_RefractionCameras )
DestroyImmediate( ((Camera)kvp.Value).gameObject );
m_RefractionCameras.Clear();
}
// This just sets up some matrices in the material; for really
// old cards to make water texture scroll.
void Update()
{
Camera cam = Camera.main;
if( !cam )
return;
//Flip upsidedown if cam is below us
isSurface = (cam.transform.position.y > WaterTransform.position.y);
WaterTransform.rotation = (isSurface ? Quaternion.identity : Quaternion.Euler(180, 0, 0));
if( !GetComponent<Renderer>() )
return;
Material mat = GetComponent<Renderer>().sharedMaterial;
if( !mat )
return;
Vector4 waveSpeed = mat.GetVector( "WaveSpeed" );
float waveScale = mat.GetFloat( "_WaveScale" );
float t = Time.time / 40.0f;
Vector3 scale = new Vector3( 1.0f/waveScale, 1.0f/waveScale, 1 );
Vector3 offset = new Vector3( t * waveSpeed.x / scale.x, t * waveSpeed.y / scale.y, 0 );
Matrix4x4 scrollMatrix = Matrix4x4.TRS( offset, Quaternion.identity, scale );
mat.SetMatrix( "_WaveMatrix", scrollMatrix );
offset = new Vector3( t * waveSpeed.z / scale.x, t * waveSpeed.w / scale.y, 0 );
scrollMatrix = Matrix4x4.TRS( offset, Quaternion.identity, scale * 0.45f );
mat.SetMatrix( "_WaveMatrix2", scrollMatrix );
}
private void UpdateCameraModes( Camera src, Camera dest )
{
if( dest == null )
return;
// set water camera to clear the same way as current camera
dest.clearFlags = src.clearFlags;
dest.backgroundColor = src.backgroundColor;
if( src.clearFlags == CameraClearFlags.Skybox )
{
Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox;
Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox;
if( !sky || !sky.material )
{
mysky.enabled = false;
}
else
{
mysky.enabled = true;
mysky.material = sky.material;
}
}
// update other values to match current camera.
// even if we are supplying custom camera&projection matrices,
// some of values are used elsewhere (e.g. skybox uses far plane)
dest.farClipPlane = src.farClipPlane;
dest.nearClipPlane = src.nearClipPlane;
dest.orthographic = src.orthographic;
dest.fieldOfView = src.fieldOfView;
dest.aspect = src.aspect;
dest.orthographicSize = src.orthographicSize;
}
// On-demand create any objects we need for water
private void CreateWaterObjects( Camera currentCamera, out Camera reflectionCamera, out Camera refractionCamera )
{
WaterMode mode = GetWaterMode();
reflectionCamera = null;
refractionCamera = null;
if( mode >= WaterMode.Reflective )
{
// Reflection render texture
if( !m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize )
{
if( m_ReflectionTexture )
DestroyImmediate( m_ReflectionTexture );
m_ReflectionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 );
m_ReflectionTexture.name = "__WaterReflection" + GetInstanceID();
m_ReflectionTexture.isPowerOfTwo = true;
m_ReflectionTexture.hideFlags = HideFlags.DontSave;
m_OldReflectionTextureSize = m_TextureSize;
}
// Camera for reflection
reflectionCamera = m_ReflectionCameras[currentCamera] as Camera;
if( !reflectionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
{
GameObject go = new GameObject( "Water Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) );
reflectionCamera = go.GetComponent<Camera>();
reflectionCamera.enabled = false;
reflectionCamera.transform.position = transform.position;
reflectionCamera.transform.rotation = transform.rotation;
reflectionCamera.gameObject.AddComponent<FlareLayer>();
go.hideFlags = HideFlags.HideAndDontSave;
m_ReflectionCameras[currentCamera] = reflectionCamera;
}
}
if( mode >= WaterMode.Refractive )
{
// Refraction render texture
if( !m_RefractionTexture || m_OldRefractionTextureSize != m_TextureSize )
{
if( m_RefractionTexture )
DestroyImmediate( m_RefractionTexture );
m_RefractionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 );
m_RefractionTexture.name = "__WaterRefraction" + GetInstanceID();
m_RefractionTexture.isPowerOfTwo = true;
m_RefractionTexture.hideFlags = HideFlags.DontSave;
m_OldRefractionTextureSize = m_TextureSize;
}
// Camera for refraction
refractionCamera = m_RefractionCameras[currentCamera] as Camera;
if( !refractionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
{
GameObject go = new GameObject( "Water Refr Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) );
refractionCamera = go.GetComponent<Camera>();
refractionCamera.enabled = false;
refractionCamera.transform.position = transform.position;
refractionCamera.transform.rotation = transform.rotation;
refractionCamera.gameObject.AddComponent<FlareLayer>();
go.hideFlags = HideFlags.HideAndDontSave;
m_RefractionCameras[currentCamera] = refractionCamera;
}
}
}
public WaterMode GetWaterMode()
{
if( m_HardwareWaterSupport < m_WaterMode )
return m_HardwareWaterSupport;
else
return m_WaterMode;
}
public WaterMode FindHardwareWaterSupport()
{
if( !SystemInfo.supportsRenderTextures || !GetComponent<Renderer>() || !m_ShaderFull )
return WaterMode.Simple;
Material mat = GetComponent<Renderer>().sharedMaterial;
if( !mat )
return WaterMode.Simple;
if( m_ShaderFull.isSupported )
return WaterMode.Refractive;
string mode = mat.GetTag("WATERMODE", false);
if( mode == "Refractive" )
return WaterMode.Refractive;
if( mode == "Reflective" )
return WaterMode.Reflective;
return WaterMode.Simple;
}
// Extended sign: returns -1, 0 or 1 based on sign of a
private static float sgn(float a)
{
if (a > 0.0f) return 1.0f;
if (a < 0.0f) return -1.0f;
return 0.0f;
}
// Given position/normal of the plane, calculates plane in camera space.
private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
{
Vector3 offsetPos = pos + normal * m_ClipPlaneOffset;
Matrix4x4 m = cam.worldToCameraMatrix;
Vector3 cpos = m.MultiplyPoint( offsetPos );
Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign;
return new Vector4( cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal) );
}
// Adjusts the given projection matrix so that near plane is the given clipPlane
// clipPlane is given in camera space. See article in Game Programming Gems 5.
private static void CalculateObliqueMatrix (ref Matrix4x4 projection, Vector4 clipPlane)
{
Vector4 q;
q.x = (sgn(clipPlane.x) + projection[8]) / projection[0];
q.y = (sgn(clipPlane.y) + projection[9]) / projection[5];
q.z = -1.0F;
q.w = (1.0F + projection[10]) / projection[14];
Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
projection[2] = c.x;
projection[6] = c.y;
projection[10] = c.z + 1.0F;
projection[14] = c.w;
}
// Calculates reflection matrix around the given plane
private static void CalculateReflectionMatrix (ref Matrix4x4 reflectionMat, Vector4 plane)
{
reflectionMat.m00 = (1F - 2F*plane[0]*plane[0]);
reflectionMat.m01 = ( - 2F*plane[0]*plane[1]);
reflectionMat.m02 = ( - 2F*plane[0]*plane[2]);
reflectionMat.m03 = ( - 2F*plane[3]*plane[0]);
reflectionMat.m10 = ( - 2F*plane[1]*plane[0]);
reflectionMat.m11 = (1F - 2F*plane[1]*plane[1]);
reflectionMat.m12 = ( - 2F*plane[1]*plane[2]);
reflectionMat.m13 = ( - 2F*plane[3]*plane[1]);
reflectionMat.m20 = ( - 2F*plane[2]*plane[0]);
reflectionMat.m21 = ( - 2F*plane[2]*plane[1]);
reflectionMat.m22 = (1F - 2F*plane[2]*plane[2]);
reflectionMat.m23 = ( - 2F*plane[3]*plane[2]);
reflectionMat.m30 = 0F;
reflectionMat.m31 = 0F;
reflectionMat.m32 = 0F;
reflectionMat.m33 = 1F;
}
}
| |
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
/// ******************************************************************************************************************
/// * Copyright (c) 2011 Dialect Software LLC *
/// * This software is distributed under the terms of the Apache License http://www.apache.org/licenses/LICENSE-2.0 *
/// * *
/// ******************************************************************************************************************
namespace DialectSoftware.Networking
{
/// <summary>
/// Summary description for DynamicDiscovery.
/// </summary>
public class AsyncSocketAdapter:AsyncNetworkAdapter
{
private Socket socket = null;
private EndPoint remoteEP = null;
private System.Threading.Timer monitor = null;
private Int32 _timeout = System.Threading.Timeout.Infinite;
public AsyncSocketAdapter(Socket socket,AsyncNetworkErrorCallBack Error):base(Error)
{
//
// TODO: Add constructor logic here
//
this.socket = socket;
this.monitor = new System.Threading.Timer(new System.Threading.TimerCallback(Expire),this,_timeout,_timeout);
}
public int TimeOut
{
get { return _timeout; }
}
public EndPoint RemoteAddress
{
get{return this.remoteEP;}
}
public int DataAvailable
{
get{return this.socket.Available;}
}
protected override System.AsyncCallback AsyncReadCallback
{
get{return new System.AsyncCallback(this.ReadCallBack);}
}
protected override System.AsyncCallback AsyncWriteCallback
{
get{return new System.AsyncCallback(this.WriteCallBack);}
}
//Monitor
private static void Expire(object state)
{
((AsyncSocketAdapter)state).monitor.Change(System.Threading.Timeout.Infinite,System.Threading.Timeout.Infinite);
if(((AsyncSocketAdapter)state).socket == null)
return;
else if(((AsyncSocketAdapter)state).socket.Available == 0)
((AsyncSocketAdapter)state).socket.Close();
else
{
Int32 TimeOut =(Int32)((AsyncSocketAdapter)state).GetType().GetField("_timeout",System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.NonPublic).GetValue(state);
((AsyncSocketAdapter)state).monitor.Change(TimeOut,System.Threading.Timeout.Infinite);
}
}
//Listener
public /*override*/ void BeginRead(AsyncNetworkCallBack ReadComplete,Int32 TimeOut)
{
base.BeginRead(ReadComplete);
this.socket.BeginReceive(this._buffer,0,_bufferSize,System.Net.Sockets.SocketFlags.None,this.AsyncReadCallback,null);
this._timeout = TimeOut;
this.monitor.Change(TimeOut,System.Threading.Timeout.Infinite);
}
public void BeginRead(long Length,AsyncNetworkCallBack ReadComplete, Int32 TimeOut)
{
base.BeginRead(ReadComplete);
this.socket.BeginReceive(this._buffer,0,((Int64)this._bufferSize >= Length)? (Int32)Length:this._bufferSize,System.Net.Sockets.SocketFlags.None,this.AsyncReadCallback,Length);
this._timeout = TimeOut;
this.monitor.Change(TimeOut,System.Threading.Timeout.Infinite);
}
public void BeginRead(ref EndPoint remoteEP,AsyncNetworkCallBack ReadComplete, Int32 TimeOut)
{
base.BeginRead(ReadComplete);
this.remoteEP = remoteEP;
this.socket.BeginReceiveFrom(this._buffer,0,_bufferSize,System.Net.Sockets.SocketFlags.None,ref remoteEP,this.AsyncReadCallback,null);
this._timeout = TimeOut;
this.monitor.Change(TimeOut,System.Threading.Timeout.Infinite);
}
public void BeginRead(long Length,ref EndPoint remoteEP,AsyncNetworkCallBack ReadComplete, Int32 TimeOut)
{
base.BeginRead(ReadComplete);
this.remoteEP = remoteEP;
this.socket.BeginReceiveFrom(this._buffer,0,((Int64)this._bufferSize >= Length)? (Int32)Length:this._bufferSize,System.Net.Sockets.SocketFlags.None,ref remoteEP,this.AsyncReadCallback,Length);
this._timeout = TimeOut;
this.monitor.Change(TimeOut,System.Threading.Timeout.Infinite);
}
public /*override*/ void Read(Int32 TimeOut)
{
base.Read();
this.socket.BeginReceive(this._buffer,0,_bufferSize,System.Net.Sockets.SocketFlags.None,this.AsyncReadCallback,null);
this._timeout = TimeOut;
this.monitor.Change(TimeOut,System.Threading.Timeout.Infinite);
}
public void Read(long Length,Int32 TimeOut)
{
base.Read();
this.socket.BeginReceive(this._buffer,0,((Int64)this._bufferSize >= Length)? (Int32)Length:this._bufferSize,System.Net.Sockets.SocketFlags.None,this.AsyncReadCallback,Length);
this._timeout = TimeOut;
this.monitor.Change(TimeOut,System.Threading.Timeout.Infinite);
}
public void Read(ref EndPoint remoteEP,Int32 TimeOut)
{
base.Read();
this.remoteEP = remoteEP;
this.socket.BeginReceiveFrom(this._buffer,0,_bufferSize,System.Net.Sockets.SocketFlags.None,ref remoteEP,this.AsyncReadCallback,null);
this._timeout = TimeOut;
this.monitor.Change(TimeOut,System.Threading.Timeout.Infinite);
}
public void Read(long Length,ref EndPoint remoteEP, Int32 TimeOut)
{
base.Read();
this.remoteEP = remoteEP;
this.socket.BeginReceiveFrom(this._buffer,0,((Int64)this._bufferSize >= Length)? (Int32)Length:this._bufferSize,System.Net.Sockets.SocketFlags.None,ref remoteEP,this.AsyncReadCallback,Length);
this._timeout = TimeOut;
this.monitor.Change(TimeOut,System.Threading.Timeout.Infinite);
}
//Read Callback
protected override void ReadCallBack(IAsyncResult result)
{
this.monitor.Change(System.Threading.Timeout.Infinite,System.Threading.Timeout.Infinite);
try
{
//if((int)this.socket.Handle ==-1)
//{
// throw new System.InvalidOperationException("Operation not allowed on non-connected sockets.");
//}
Int32 length = 0;
if(this.remoteEP == null)
length = this.socket.EndReceive(result);
else
length = this.socket.EndReceiveFrom(result,ref this.remoteEP);
this.buffer.Write(this._buffer,0,length);
this.buffer.Flush();
this.Clear(this._buffer);
if(result.AsyncState != null)
{
Int64 Length = (Int64)result.AsyncState;
Length -= length;
if(Length > 0 )
{
if(this.remoteEP == null)
this.socket.BeginReceive(this._buffer,0,((Int64)this._bufferSize >= Length)? (Int32)Length:this._bufferSize,System.Net.Sockets.SocketFlags.None,this.AsyncReadCallback,Length);
else
this.socket.BeginReceiveFrom(this._buffer,0,((Int64)this._bufferSize >= Length)? (Int32)Length:this._bufferSize,System.Net.Sockets.SocketFlags.None,ref this.remoteEP,this.AsyncReadCallback,Length);
this.monitor.Change(this._timeout,System.Threading.Timeout.Infinite);
return;
}
}
else
{
if(this.socket.Available > 0)
{
if(this.remoteEP == null)
this.socket.BeginReceive(this._buffer,0,_bufferSize,System.Net.Sockets.SocketFlags.None,this.AsyncReadCallback,null);
else
this.socket.BeginReceiveFrom(this._buffer,0,_bufferSize,System.Net.Sockets.SocketFlags.None,ref this.remoteEP,this.AsyncReadCallback,null);
this.monitor.Change(this._timeout,System.Threading.Timeout.Infinite);
return;
}
}
base.ReadCallBack (result);
}
catch(System.Exception e)
{
base.ErrorCallBack(result,e);
}
}
//Sender
public /*override*/ void BeginWrite(byte[] data, AsyncNetworkCallBack WriteComplete, Int32 TimeOut)
{
base.BeginWrite(data,WriteComplete);
Int32 length = this.buffer.Read(this._buffer,0,_bufferSize);
this.socket.BeginSend(this._buffer,0,length,System.Net.Sockets.SocketFlags.None,this.AsyncWriteCallback,null);
this._timeout = TimeOut;
this.monitor.Change(TimeOut,System.Threading.Timeout.Infinite);
}
public void BeginWrite(EndPoint remoteEP,byte[] data, AsyncNetworkCallBack WriteComplete, Int32 TimeOut)
{
base.BeginWrite(data,WriteComplete);
this.remoteEP = remoteEP;
Int32 length = this.buffer.Read(this._buffer,0,_bufferSize);
this.socket.BeginSendTo(this._buffer,0,length,System.Net.Sockets.SocketFlags.None,remoteEP,this.AsyncWriteCallback,null);
this._timeout = TimeOut;
this.monitor.Change(TimeOut,System.Threading.Timeout.Infinite);
}
//Write Callback
protected override void WriteCallBack(IAsyncResult result)
{
this.monitor.Change(System.Threading.Timeout.Infinite,System.Threading.Timeout.Infinite);
try
{
//if((int)this.socket.Handle ==-1)
//{
// throw new System.InvalidOperationException("Operation not allowed on non-connected sockets.");
//}
if(this.remoteEP == null)
this.socket.EndSend(result);
else
this.socket.EndSendTo(result);
if(this.buffer.Position != this.buffer.Length)
{
this.Clear(this._buffer);
Int32 length = this.buffer.Read(this._buffer,0,_bufferSize);
if(this.remoteEP == null)
this.socket.BeginSend(this._buffer,0,length,System.Net.Sockets.SocketFlags.None,this.AsyncWriteCallback,null);
else
this.socket.BeginSendTo(this._buffer,0,length,System.Net.Sockets.SocketFlags.None,this.remoteEP,this.AsyncWriteCallback,null);
this.monitor.Change(this._timeout,System.Threading.Timeout.Infinite);
}
else
{
base.WriteCallBack (result);
}
}
catch(System.Exception e)
{
base.ErrorCallBack(result,e);
}
}
//Finalize/Dispose
public override void Dispose()
{
if(this.State != AsyncNetworkState.Disposed)
{
if((int)this.socket.Handle!= -1)
this.socket.Close();
this.socket = null;
this.remoteEP = null;
base.Dispose ();
}
}
~AsyncSocketAdapter()
{
this.Dispose();
}
}
}
| |
/*
* 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.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using OpenMetaverse;
using Nini.Config;
using OpenSim.Framework.Servers.HttpServer;
using log4net;
namespace OpenSim.Framework.Console
{
public class ConsoleConnection
{
public int last;
public long lastLineSeen;
public bool newConnection = true;
}
// A console that uses REST interfaces
//
public class RemoteConsole : CommandConsole
{
private IHttpServer m_Server = null;
private IConfigSource m_Config = null;
private List<string> m_Scrollback = new List<string>();
private ManualResetEvent m_DataEvent = new ManualResetEvent(false);
private List<string> m_InputData = new List<string>();
private long m_LineNumber = 0;
private Dictionary<UUID, ConsoleConnection> m_Connections =
new Dictionary<UUID, ConsoleConnection>();
private string m_UserName = String.Empty;
private string m_Password = String.Empty;
private string m_AllowedOrigin = String.Empty;
public RemoteConsole(string defaultPrompt) : base(defaultPrompt)
{
}
public void ReadConfig(IConfigSource config)
{
m_Config = config;
IConfig netConfig = m_Config.Configs["Network"];
if (netConfig == null)
return;
m_UserName = netConfig.GetString("ConsoleUser", String.Empty);
m_Password = netConfig.GetString("ConsolePass", String.Empty);
m_AllowedOrigin = netConfig.GetString("ConsoleAllowedOrigin", String.Empty);
}
public void SetServer(IHttpServer server)
{
m_Server = server;
m_Server.AddHTTPHandler("/StartSession/", HandleHttpStartSession);
m_Server.AddHTTPHandler("/CloseSession/", HandleHttpCloseSession);
m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand);
}
public override void Output(string text, string level)
{
lock (m_Scrollback)
{
while (m_Scrollback.Count >= 1000)
m_Scrollback.RemoveAt(0);
m_LineNumber++;
m_Scrollback.Add(String.Format("{0}", m_LineNumber)+":"+level+":"+text);
}
FireOnOutput(text.Trim());
System.Console.WriteLine(text.Trim());
}
public override void Output(string text)
{
Output(text, "normal");
}
public override string ReadLine(string p, bool isCommand, bool e)
{
if (isCommand)
Output("+++"+p);
else
Output("-++"+p);
m_DataEvent.WaitOne();
string cmdinput;
lock (m_InputData)
{
if (m_InputData.Count == 0)
{
m_DataEvent.Reset();
return "";
}
cmdinput = m_InputData[0];
m_InputData.RemoveAt(0);
if (m_InputData.Count == 0)
m_DataEvent.Reset();
}
if (isCommand)
{
string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
if (cmd.Length != 0)
{
int i;
for (i=0 ; i < cmd.Length ; i++)
{
if (cmd[i].Contains(" "))
cmd[i] = "\"" + cmd[i] + "\"";
}
return String.Empty;
}
}
return cmdinput;
}
private Hashtable CheckOrigin(Hashtable result)
{
if (!string.IsNullOrEmpty(m_AllowedOrigin))
result["access_control_allow_origin"] = m_AllowedOrigin;
return result;
}
/* TODO: Figure out how PollServiceHTTPHandler can access the request headers
* in order to use m_AllowedOrigin as a regular expression
private Hashtable CheckOrigin(Hashtable headers, Hashtable result)
{
if (!string.IsNullOrEmpty(m_AllowedOrigin))
{
if (headers.ContainsKey("origin"))
{
string origin = headers["origin"].ToString();
if (Regex.IsMatch(origin, m_AllowedOrigin))
result["access_control_allow_origin"] = origin;
}
}
return result;
}
*/
private void DoExpire()
{
List<UUID> expired = new List<UUID>();
lock (m_Connections)
{
foreach (KeyValuePair<UUID, ConsoleConnection> kvp in m_Connections)
{
if (System.Environment.TickCount - kvp.Value.last > 500000)
expired.Add(kvp.Key);
}
foreach (UUID id in expired)
{
m_Connections.Remove(id);
CloseConnection(id);
}
}
}
private Hashtable HandleHttpStartSession(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 401;
reply["content_type"] = "text/plain";
if (m_UserName == String.Empty)
return reply;
if (post["USER"] == null || post["PASS"] == null)
return reply;
if (m_UserName != post["USER"].ToString() ||
m_Password != post["PASS"].ToString())
{
return reply;
}
ConsoleConnection c = new ConsoleConnection();
c.last = System.Environment.TickCount;
c.lastLineSeen = 0;
UUID sessionID = UUID.Random();
lock (m_Connections)
{
m_Connections[sessionID] = c;
}
string uri = "/ReadResponses/" + sessionID.ToString() + "/";
m_Server.AddPollServiceHTTPHandler(
uri, new PollServiceEventArgs(null, HasEvents, GetEvents, NoEvents, sessionID));
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement id = xmldoc.CreateElement("", "SessionID", "");
id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));
rootElement.AppendChild(id);
XmlElement prompt = xmldoc.CreateElement("", "Prompt", "");
prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));
rootElement.AppendChild(prompt);
rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
private Hashtable HandleHttpCloseSession(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
lock (m_Connections)
{
if (m_Connections.ContainsKey(id))
{
m_Connections.Remove(id);
CloseConnection(id);
}
}
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement("", "Result", "");
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
private Hashtable HandleHttpSessionCommand(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(id))
return reply;
}
if (post["COMMAND"] == null)
return reply;
lock (m_InputData)
{
m_DataEvent.Set();
m_InputData.Add(post["COMMAND"].ToString());
}
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement("", "Result", "");
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
private Hashtable DecodePostString(string data)
{
Hashtable result = new Hashtable();
string[] terms = data.Split(new char[] {'&'});
foreach (string term in terms)
{
string[] elems = term.Split(new char[] {'='});
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
result[name] = value;
}
return result;
}
public void CloseConnection(UUID id)
{
try
{
string uri = "/ReadResponses/" + id.ToString() + "/";
m_Server.RemovePollServiceHTTPHandler("", uri);
}
catch (Exception)
{
}
}
private bool HasEvents(UUID RequestID, UUID sessionID)
{
ConsoleConnection c = null;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(sessionID))
return false;
c = m_Connections[sessionID];
}
c.last = System.Environment.TickCount;
if (c.lastLineSeen < m_LineNumber)
return true;
return false;
}
private Hashtable GetEvents(UUID RequestID, UUID sessionID, string request)
{
ConsoleConnection c = null;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(sessionID))
return NoEvents(RequestID, UUID.Zero);
c = m_Connections[sessionID];
}
c.last = System.Environment.TickCount;
if (c.lastLineSeen >= m_LineNumber)
return NoEvents(RequestID, UUID.Zero);
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
if (c.newConnection)
{
c.newConnection = false;
Output("+++" + DefaultPrompt);
}
lock (m_Scrollback)
{
long startLine = m_LineNumber - m_Scrollback.Count;
long sendStart = startLine;
if (sendStart < c.lastLineSeen)
sendStart = c.lastLineSeen;
for (long i = sendStart ; i < m_LineNumber ; i++)
{
XmlElement res = xmldoc.CreateElement("", "Line", "");
long line = i + 1;
res.SetAttribute("Number", line.ToString());
res.AppendChild(xmldoc.CreateTextNode(m_Scrollback[(int)(i - startLine)]));
rootElement.AppendChild(res);
}
}
c.lastLineSeen = m_LineNumber;
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "application/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
result = CheckOrigin(result);
return result;
}
private Hashtable NoEvents(UUID RequestID, UUID id)
{
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "text/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
result = CheckOrigin(result);
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
//
// This is the "Type Library" we are going to reflect on
//
namespace System.Reflection.CustomAttributesTests.Data
{
public enum MyColorEnum
{
RED = 1,
BLUE = 2,
GREEN = 3
}
public class Util
{
public static string ObjectToString(Object o)
{
string s = string.Empty;
if (o != null)
{
if (o is Array)
{
Array a = (Array)o;
for (int i = 0; i < a.Length; i += 1)
{
if (i > 0)
{
s = s + ", ";
}
if (a.GetValue(i) is Array)
s = s + Util.ObjectToString((Array)a.GetValue(i));
else
s = s + a.GetValue(i).ToString();
}
}
else
s = s + o.ToString();
}
return s;
}
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
public class Attr : Attribute
{
public Attr()
{
}
public Attr(int i)
{
value = i;
sValue = null;
}
public Attr(int i, string s)
{
value = i;
sValue = s;
}
public override string ToString()
{
return "Attr ToString : " + value.ToString() + " " + sValue;
}
public string name;
public int value;
public string sValue;
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
public class Int32Attr : Attribute
{
public Int32Attr(int i)
{
value = i;
arrayValue = null;
}
public Int32Attr(int i, int[] a)
{
value = i;
arrayValue = a;
}
public string name;
public readonly int value;
public int field;
public readonly int[] arrayValue;
public int[] arrayField;
private int _property = 0;
public int property { get { return _property; } set { _property = value; } }
private int[] _arrayProperty;
public int[] arrayProperty { get { return _arrayProperty; } set { _arrayProperty = value; } }
public override string ToString()
{
return GetType().ToString() + " - name : " + name
+ "; value : " + Util.ObjectToString(value)
+ "; field : " + Util.ObjectToString(field)
+ "; property : " + Util.ObjectToString(property)
+ "; array value : " + Util.ObjectToString(arrayValue)
+ "; array field : " + Util.ObjectToString(arrayField)
+ "; array property : " + Util.ObjectToString(arrayProperty);
}
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
public class Int64Attr : Attribute
{
public Int64Attr(long l)
{
value = l;
arrayValue = null;
}
public Int64Attr(long l, long[] a)
{
value = l;
arrayValue = a;
}
public string name;
public readonly long value;
public long field;
public readonly long[] arrayValue;
public long[] arrayField;
private long _property = 0;
public long property { get { return _property; } set { _property = value; } }
private long[] _arrayProperty;
public long[] arrayProperty { get { return _arrayProperty; } set { _arrayProperty = value; } }
public override string ToString()
{
return GetType().ToString() + " - name : " + name
+ "; value : " + Util.ObjectToString(value)
+ "; field : " + Util.ObjectToString(field)
+ "; property : " + Util.ObjectToString(property)
+ "; array value : " + Util.ObjectToString(arrayValue)
+ "; array field : " + Util.ObjectToString(arrayField)
+ "; array property : " + Util.ObjectToString(arrayProperty);
}
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
public class EnumAttr : Attribute
{
public EnumAttr(MyColorEnum e)
{
value = e;
arrayValue = null;
}
public EnumAttr(MyColorEnum e, MyColorEnum[] a)
{
value = e;
arrayValue = a;
}
public string name;
public readonly MyColorEnum value;
public MyColorEnum field;
public readonly MyColorEnum[] arrayValue;
public MyColorEnum[] arrayField;
private MyColorEnum _property = 0;
public MyColorEnum property { get { return _property; } set { _property = value; } }
private MyColorEnum[] _arrayProperty;
public MyColorEnum[] arrayProperty { get { return _arrayProperty; } set { _arrayProperty = value; } }
public override string ToString()
{
return GetType().ToString() + " - name : " + name
+ "; value : " + Util.ObjectToString(value)
+ "; field : " + Util.ObjectToString(field)
+ "; property : " + Util.ObjectToString(property)
+ "; array value : " + Util.ObjectToString(arrayValue)
+ "; array field : " + Util.ObjectToString(arrayField)
+ "; array property : " + Util.ObjectToString(arrayProperty);
}
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
public class StringAttr : Attribute
{
public StringAttr(string s)
{
value = s;
arrayValue = null;
}
public StringAttr(string s, string[] a)
{
value = s;
arrayValue = a;
}
public string name;
public readonly string value;
public string field;
public readonly string[] arrayValue;
public string[] arrayField;
private string _property;
public string property { get { return _property; } set { _property = value; } }
private string[] _arrayProperty;
public string[] arrayProperty { get { return _arrayProperty; } set { _arrayProperty = value; } }
public override string ToString()
{
return GetType().ToString() + " - name : " + name
+ "; value : " + Util.ObjectToString(value)
+ "; field : " + Util.ObjectToString(field)
+ "; property : " + Util.ObjectToString(property)
+ "; array value : " + Util.ObjectToString(arrayValue)
+ "; array field : " + Util.ObjectToString(arrayField)
+ "; array property : " + Util.ObjectToString(arrayProperty);
}
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
public class TypeAttr : Attribute
{
public TypeAttr(Type t)
{
value = t;
arrayValue = null;
}
public TypeAttr(Type t, Type[] a)
{
value = t;
arrayValue = a;
}
public string name;
public readonly Type value;
public Type field;
public readonly Type[] arrayValue;
public Type[] arrayField;
private Type _property;
public Type property { get { return _property; } set { _property = value; } }
private Type[] _arrayProperty;
public Type[] arrayProperty { get { return _arrayProperty; } set { _arrayProperty = value; } }
public override string ToString()
{
return GetType().ToString() + " - name : " + name
+ "; value : " + Util.ObjectToString(value)
+ "; field : " + Util.ObjectToString(field)
+ "; property : " + Util.ObjectToString(property)
+ "; array value : " + Util.ObjectToString(arrayValue)
+ "; array field : " + Util.ObjectToString(arrayField)
+ "; array property : " + Util.ObjectToString(arrayProperty);
}
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
public class ObjectAttr : Attribute
{
public ObjectAttr(Object v)
{
value = v;
arrayValue = null;
}
public ObjectAttr(Object v, Object[] a)
{
value = v;
arrayValue = a;
}
public string name;
public readonly Object value;
public Object field;
public readonly Object[] arrayValue;
public Object[] arrayField;
private Object _property = 0;
public Object property { get { return _property; } set { _property = value; } }
private Object[] _arrayProperty;
public Object[] arrayProperty { get { return _arrayProperty; } set { _arrayProperty = value; } }
public override string ToString()
{
return GetType().ToString() + " - name : " + name
+ "; value : " + Util.ObjectToString(value)
+ "; field : " + Util.ObjectToString(field)
+ "; property : " + Util.ObjectToString(property)
+ "; array value : " + Util.ObjectToString(arrayValue)
+ "; array field : " + Util.ObjectToString(arrayField)
+ "; array property : " + Util.ObjectToString(arrayProperty);
}
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
public class NullAttr : Attribute
{
public NullAttr(string s, Type t, int[] a)
{
}
public NullAttr(String s)
{
}
public string name;
public string stringField;
public Type typeField;
public int[] arrayField;
public string stringProperty { get { return null; } set { } }
public Type typeProperty { get { return null; } set { } }
public int[] arrayProperty { get { return null; } set { } }
}
}
| |
#region Copyright (c) 2003, newtelligence AG. All rights reserved.
/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com)
// 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.
// (3) Neither the name of the newtelligence AG 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.
// -------------------------------------------------------------------------
//
// Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com)
//
// newtelligence is a registered trademark of newtelligence Aktiengesellschaft.
//
// For portions of this software, the some additional copyright notices may apply
// which can either be found in the license.txt file included in the source distribution
// or following this notice.
//
*/
#endregion
using System;
using CookComputing.XmlRpc;
namespace newtelligence.DasBlog.Web.Services.MovableType
{
/// <summary>
///
/// </summary>
public struct Category
{
/// <summary>
///
/// </summary>
public string categoryId;
/// <summary>
///
/// </summary>
[XmlRpcMissingMapping(MappingAction.Ignore)]
public string categoryName;
[XmlRpcMissingMapping(MappingAction.Ignore)]
public bool isPrimary;
}
/// <summary>
///
/// </summary>
public struct PostTitle
{
/// <summary>
///
/// </summary>
[XmlRpcMember(Description="This is in the timezone of the weblog blogid.")]
public DateTime dateCreated;
/// <summary>
///
/// </summary>
public string postid;
/// <summary>
///
/// </summary>
public string userid;
/// <summary>
///
/// </summary>
public string title;
}
/// <summary>
///
/// </summary>
public struct TrackbackPing
{
/// <summary>
///
/// </summary>
[XmlRpcMember(Description="The title of the entry sent in the ping.")]
public string pingTitle;
/// <summary>
///
/// </summary>
[XmlRpcMember(Description="The URL of the entry.")]
public string pingURL;
/// <summary>
///
/// </summary>
[XmlRpcMember(Description="The IP address of the host that sent the ping.")]
public string pingIP;
}
/// <summary>
///
/// </summary>
public struct TextFilter
{
/// <summary>
///
/// </summary>
[XmlRpcMember(Description="unique string identifying a text formatting plugin")]
public string key;
/// <summary>
///
/// </summary>
[XmlRpcMember(Description="readable description to be displayed to a user")]
public string value;
}
/// <summary>
///
/// </summary>
public interface IMovableType
{
/// <summary>
///
/// </summary>
/// <param name="blogid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
[XmlRpcMethod("mt.getCategoryList",
Description="Returns a list of all categories defined in the weblog.")]
[return: XmlRpcReturnValue(
Description="The isPrimary member of each Category structs is not used.")]
Category[] mt_getCategoryList(
string blogid,
string username,
string password);
/// <summary>
///
/// </summary>
/// <param name="postid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
[XmlRpcMethod("mt.getPostCategories",
Description="Returns a list of all categories to which the post is "
+ "assigned.")]
Category[] mt_getPostCategories(
string postid,
string username,
string password);
/// <summary>
///
/// </summary>
/// <param name="blogid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="numberOfPosts"></param>
/// <returns></returns>
[XmlRpcMethod("mt.getRecentPostTitles",
Description="Returns a bandwidth-friendly list of the most recent "
+ "posts in the system.")]
PostTitle[] mt_getRecentPostTitles(
string blogid,
string username,
string password,
int numberOfPosts);
/// <summary>
///
/// </summary>
/// <param name="postid"></param>
/// <returns></returns>
[XmlRpcMethod("mt.getTrackbackPings",
Description="Retrieve the list of TrackBack pings posted to a "
+ "particular entry. This could be used to programmatically "
+ "retrieve the list of pings for a particular entry, then "
+ "iterate through each of those pings doing the same, until "
+ "one has built up a graph of the web of entries referencing "
+ "one another on a particular topic.")]
TrackbackPing[] mt_getTrackbackPings(
string postid);
/// <summary>
///
/// </summary>
/// <param name="postid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
[XmlRpcMethod("mt.publishPost",
Description="Publish (rebuild) all of the static files related "
+ "to an entry from your weblog. Equivalent to saving an entry "
+ "in the system (but without the ping).")]
[return: XmlRpcReturnValue(Description="Always returns true.")]
bool mt_publishPost(
string postid,
string username,
string password);
/// <summary>
///
/// </summary>
/// <param name="postid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="categories"></param>
/// <returns></returns>
[XmlRpcMethod("mt.setPostCategories",
Description="Sets the categories for a post.")]
[return: XmlRpcReturnValue(Description="Always returns true.")]
bool mt_setPostCategories(
string postid,
string username,
string password,
[XmlRpcParameter(
Description="categoryName not required in Category struct.")]
Category[] categories);
/// <summary>
///
/// </summary>
/// <returns></returns>
[XmlRpcMethod("mt.supportedMethods",
Description="The method names supported by the server.")]
[return: XmlRpcReturnValue(
Description="The method names supported by the server.")]
string[] mt_supportedMethods();
/// <summary>
///
/// </summary>
/// <returns></returns>
[XmlRpcMethod("mt.supportedTextFilters",
Description="The text filters names supported by the server.")]
[return: XmlRpcReturnValue(
Description="The text filters names supported by the server.")]
TextFilter[] mt_supportedTextFilters();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.