context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime
{
internal class ClientObserverRegistrar : SystemTarget, IClientObserverRegistrar, ILifecycleParticipant<ISiloLifecycle>
{
private static readonly TimeSpan EXP_BACKOFF_ERROR_MIN = TimeSpan.FromSeconds(1);
private static readonly TimeSpan EXP_BACKOFF_ERROR_MAX = TimeSpan.FromSeconds(30);
private static readonly TimeSpan EXP_BACKOFF_STEP = TimeSpan.FromSeconds(1);
private readonly ILocalGrainDirectory grainDirectory;
private readonly SiloAddress myAddress;
private readonly OrleansTaskScheduler scheduler;
private readonly IClusterMembershipService clusterMembershipService;
private readonly SiloMessagingOptions messagingOptions;
private readonly ILogger logger;
private readonly IAsyncTimer refreshTimer;
private readonly CancellationTokenSource shutdownCancellation = new CancellationTokenSource();
private HostedClient hostedClient;
private Gateway gateway;
private Task clientRefreshLoopTask;
public ClientObserverRegistrar(
ILocalSiloDetails siloDetails,
ILocalGrainDirectory grainDirectory,
OrleansTaskScheduler scheduler,
IOptions<SiloMessagingOptions> messagingOptions,
ILoggerFactory loggerFactory,
IClusterMembershipService clusterMembershipService,
IAsyncTimerFactory timerFactory)
: base(Constants.ClientObserverRegistrarType, siloDetails.SiloAddress, loggerFactory)
{
this.grainDirectory = grainDirectory;
this.myAddress = siloDetails.SiloAddress;
this.scheduler = scheduler;
this.clusterMembershipService = clusterMembershipService;
this.messagingOptions = messagingOptions.Value;
this.logger = loggerFactory.CreateLogger<ClientObserverRegistrar>();
this.refreshTimer = timerFactory.Create(this.messagingOptions.ClientRegistrationRefresh, "ClientObserverRegistrar.ClientRefreshTimer");
}
internal void SetHostedClient(HostedClient client)
{
this.hostedClient = client;
if (client != null)
{
this.scheduler.QueueAction(Start, this);
}
}
internal void SetGateway(Gateway gateway)
{
this.gateway = gateway;
// Only start ClientRefreshTimer if this silo has a gateway.
// Need to start the timer in the system target context.
scheduler.QueueAction(Start, this);
}
private void Start()
{
if (clientRefreshLoopTask is object)
{
return;
}
clientRefreshLoopTask = RunClientRefreshLoop();
if (logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Client registrar service started successfully."); }
}
private async Task RunClientRefreshLoop()
{
var membershipUpdates = this.clusterMembershipService.MembershipUpdates.GetAsyncEnumerator(this.shutdownCancellation.Token);
Task<bool> membershipTask = null;
Task<bool> timerTask = this.refreshTimer.NextTick(new SafeRandom().NextTimeSpan(this.messagingOptions.ClientRegistrationRefresh));
while (true)
{
membershipTask ??= membershipUpdates.MoveNextAsync().AsTask();
timerTask ??= this.refreshTimer.NextTick();
// Wait for either of the tasks to complete.
await Task.WhenAny(membershipTask, timerTask);
if (timerTask.IsCompleted)
{
if (!await timerTask)
{
break;
}
timerTask = null;
}
if (membershipTask.IsCompleted)
{
if (!await membershipTask)
{
break;
}
membershipTask = null;
}
await OnRefreshClients();
}
}
internal void ClientAdded(ClientGrainId clientId)
{
// Use a ActivationId that is hashed from clientId, and not random ActivationId.
// That way, when we refresh it in the directory, it's the same one.
var addr = GetClientActivationAddress(clientId);
scheduler.QueueTask(
() => ExecuteWithRetries(() => grainDirectory.RegisterAsync(addr, singleActivation:false), ErrorCode.ClientRegistrarFailedToRegister, String.Format("Directory.RegisterAsync {0} failed.", addr)),
this).Ignore();
}
internal void ClientDropped(ClientGrainId clientId)
{
var addr = GetClientActivationAddress(clientId);
scheduler.QueueTask(
() => ExecuteWithRetries(() => grainDirectory.UnregisterAsync(addr, Orleans.GrainDirectory.UnregistrationCause.Force), ErrorCode.ClientRegistrarFailedToUnregister, String.Format("Directory.UnRegisterAsync {0} failed.", addr)),
this).Ignore();
}
private async Task ExecuteWithRetries(Func<Task> functionToExecute, ErrorCode errorCode, string errorStr)
{
try
{
// Try to register/unregister the client in the directory.
// If failed, keep retrying with exponentially increasing time intervals in between, until:
// either succeeds or max time of orleansConfig.Globals.ClientRegistrationRefresh has reached.
// If failed to register after that time, it will be retried further on by clientRefreshTimer.
// In the unregsiter case just drop it. At the worst, where will be garbage in the directory.
await AsyncExecutorWithRetries.ExecuteWithRetries(
_ =>
{
return functionToExecute();
},
AsyncExecutorWithRetries.INFINITE_RETRIES, // Do not limit the number of on-error retries, control it via "maxExecutionTime"
(exc, i) => true, // Retry on all errors.
this.messagingOptions.ClientRegistrationRefresh, // "maxExecutionTime"
new ExponentialBackoff(EXP_BACKOFF_ERROR_MIN, EXP_BACKOFF_ERROR_MAX, EXP_BACKOFF_STEP)); // how long to wait between error retries
}
catch (Exception exc)
{
logger.Error(errorCode, errorStr, exc);
}
}
private async Task OnRefreshClients()
{
try
{
List<ClientGrainId> clients = null;
if (this.gateway is Gateway gw)
{
var gatewayClients = gw.GetConnectedClients();
clients = new List<ClientGrainId>(gatewayClients.Count + 1);
clients.AddRange(gatewayClients);
}
if (this.hostedClient?.ClientId is ClientGrainId hostedClientId)
{
clients ??= new List<ClientGrainId>(1);
clients.Add(hostedClientId);
}
if (clients is null)
{
return;
}
var tasks = new List<Task>();
foreach (ClientGrainId clientId in clients)
{
var addr = GetClientActivationAddress(clientId);
Task task = grainDirectory.RegisterAsync(addr, singleActivation: false).
LogException(logger, ErrorCode.ClientRegistrarFailedToRegister_2, String.Format("Directory.RegisterAsync {0} failed.", addr));
tasks.Add(task);
}
await Task.WhenAll(tasks);
}
catch (Exception exc)
{
logger.Error(ErrorCode.ClientRegistrarTimerFailed,
String.Format("OnClientRefreshTimer has thrown an exceptions."), exc);
}
}
private ActivationAddress GetClientActivationAddress(ClientGrainId clientId)
{
// Need to pick a unique deterministic ActivationId for this client.
// We store it in the grain directory and there for every GrainId we use ActivationId as a key
// so every GW needs to behave as a different "activation" with a different ActivationId (its not enough that they have different SiloAddress)
string stringToHash = clientId.ToString() + myAddress.Endpoint + myAddress.Generation.ToString(System.Globalization.CultureInfo.InvariantCulture);
Guid hash = Utils.CalculateGuidHash(stringToHash);
var activationId = ActivationId.GetActivationId(UniqueKey.NewKey(hash));
return ActivationAddress.GetAddress(myAddress, clientId.GrainId, activationId);
}
public void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe(
nameof(ClientObserverRegistrar),
ServiceLifecycleStage.RuntimeServices,
_ => Task.CompletedTask,
async ct =>
{
shutdownCancellation.Cancel();
refreshTimer?.Dispose();
if (clientRefreshLoopTask is Task task)
{
await Task.WhenAny(ct.WhenCancelled(), task);
}
});
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="DictionaryContent.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Provides a syndication content that holds name/value pairs.
// </summary>
//
// @owner [....]
//---------------------------------------------------------------------
namespace System.Data.Services.Serializers
{
#region Namespaces.
using System.Collections.Generic;
using System.Diagnostics;
using System.ServiceModel.Syndication;
using System.Xml;
#endregion Namespaces.
/// <summary>
/// Use this class to hold the name/value pairs of content that will be written
/// to the content element of a syndication item.
/// </summary>
internal class DictionaryContent : SyndicationContent
{
#region Private fields.
/// <summary>Content for a property value: one of a string, dictionary or null.</summary>
private List<object> valueContents;
/// <summary>Names for property values.</summary>
private List<string> valueNames;
/// <summary>Declared type names for property values.</summary>
private List<string> valueTypes;
#endregion Private fields.
#region Constructors.
/// <summary>Initializes a new DictionaryContent instance.</summary>
public DictionaryContent()
{
this.valueContents = new List<object>();
this.valueTypes = new List<string>();
this.valueNames = new List<string>();
}
/// <summary>Initializes a new DictionaryContent instance.</summary>
/// <param name='capacity'>Initial capacity for entries.</param>
public DictionaryContent(int capacity)
{
this.valueContents = new List<object>(capacity);
this.valueTypes = new List<string>(capacity);
this.valueNames = new List<string>(capacity);
}
/// <summary>
/// Initializes a new DictionaryContent instance by copying values from
/// the specified one.
/// </summary>
/// <param name="other">Dictionary to copy content from.</param>
/// <remarks>This produces a shallow copy only.</remarks>
private DictionaryContent(DictionaryContent other)
{
Debug.Assert(other != null, "other != null");
this.valueContents = other.valueContents;
this.valueTypes = other.valueTypes;
this.valueNames = other.valueNames;
}
#endregion Constructors.
#region Properties.
/// <summary>The MIME type of this content.</summary>
public override string Type
{
get { return XmlConstants.MimeApplicationXml; }
}
/// <summary>True if there is no properties to serialize out.</summary>
public bool IsEmpty
{
get { return this.valueNames.Count == 0; }
}
#endregion Properties.
#region Methods.
/// <summary>Creates a shallow copy of this content.</summary>
/// <returns>A shallow copy of this content.</returns>
public override SyndicationContent Clone()
{
return new DictionaryContent(this);
}
/// <summary>Adds the specified property.</summary>
/// <param name="name">Property name.</param>
/// <param name="expectedTypeName">Expected type name for value.</param>
/// <param name="value">Property value in text form.</param>
internal void Add(string name, string expectedTypeName, object value)
{
Debug.Assert(value != null, "value != null -- otherwise AddNull should have been called.");
Debug.Assert(
value is DictionaryContent || value is string,
"value is DictionaryContent || value is string -- only sub-dictionaries and formatted strings are allowed.");
Debug.Assert(!this.valueNames.Contains(name), "!this.valueNames.Contains(name) -- otherwise repeated property set.");
this.valueNames.Add(name);
this.valueTypes.Add(expectedTypeName);
this.valueContents.Add(value);
Debug.Assert(this.valueNames.Count == this.valueTypes.Count, "this.valueNames.Count == this.valueTypes.Count");
Debug.Assert(this.valueNames.Count == this.valueContents.Count, "this.valueNames.Count == this.valueContents.Count");
}
/// <summary>Adds a property with a null value.</summary>
/// <param name="expectedTypeName">Type for the property.</param>
/// <param name="name">Property name.</param>
internal void AddNull(string expectedTypeName, string name)
{
Debug.Assert(!this.valueNames.Contains(name), "!this.valueNames.Contains(name) -- otherwise repeated property set.");
this.valueNames.Add(name);
this.valueTypes.Add(expectedTypeName);
this.valueContents.Add(null);
Debug.Assert(this.valueNames.Count == this.valueTypes.Count, "this.valueNames.Count == this.valueTypes.Count");
Debug.Assert(this.valueNames.Count == this.valueContents.Count, "this.valueNames.Count == this.valueContents.Count");
}
/// <summary>
/// Gets a XmlReader to the property contents.
/// </summary>
/// <returns>XmlReader for the property contents.</returns>
internal XmlReader GetPropertyContentsReader()
{
Debug.Assert(!this.IsEmpty, "!this.IsEmpty -- calling with 0 properties is disallowed.");
System.IO.MemoryStream stream = new System.IO.MemoryStream();
using (XmlWriter writer = XmlWriter.Create(stream))
{
writer.WriteStartElement(XmlConstants.DataWebMetadataNamespacePrefix, XmlConstants.AtomPropertiesElementName, XmlConstants.DataWebMetadataNamespace);
writer.WriteAttributeString(XmlConstants.XmlnsNamespacePrefix, XmlConstants.DataWebNamespacePrefix, null, XmlConstants.DataWebNamespace);
this.WritePropertyContentsTo(writer);
writer.WriteEndElement();
writer.Flush();
stream.Position = 0;
return XmlReader.Create(stream);
}
}
/// <summary>
/// Looks up the dictionary content value for the property bag for complex property
/// </summary>
/// <param name="propertyName">Name of property to lookup</param>
/// <param name="found">Was content found</param>
/// <returns>The property bag or null if the property never existed</returns>
internal DictionaryContent Lookup(string propertyName, out bool found)
{
int index = this.valueNames.IndexOf(propertyName);
if (index >= 0)
{
found = true;
object value = this.valueContents[index];
if (value != null)
{
Debug.Assert(value is DictionaryContent, "Must only look for complex properties, primitives must not be found");
return value as DictionaryContent;
}
else
{
// It might have been the case that the complex property was itself null
return null;
}
}
else
{
found = false;
return null;
}
}
/// <summary>Writes the contents of this SyndicationContent object to the specified XmlWriter.</summary>
/// <param name='writer'>The XmlWriter to write to.</param>
protected override void WriteContentsTo(XmlWriter writer)
{
if (0 < this.valueNames.Count)
{
writer.WriteStartElement(XmlConstants.AtomPropertiesElementName, XmlConstants.DataWebMetadataNamespace);
this.WritePropertyContentsTo(writer);
writer.WriteEndElement();
}
}
/// <summary>Writes the contents of this SyndicationContent object to the specified XmlWriter.</summary>
/// <param name='writer'>The XmlWriter to write to.</param>
private void WritePropertyContentsTo(XmlWriter writer)
{
for (int i = 0; i < this.valueNames.Count; i++)
{
string propertyName = this.valueNames[i];
string propertyTypeName = this.valueTypes[i];
object propertyValue = this.valueContents[i];
if (propertyValue == null)
{
PlainXmlSerializer.WriteNullValue(writer, propertyName, propertyTypeName);
}
else if (propertyValue is DictionaryContent)
{
PlainXmlSerializer.WriteStartElementWithType(writer, propertyName, propertyTypeName);
((DictionaryContent)propertyValue).WritePropertyContentsTo(writer);
writer.WriteEndElement();
}
else
{
string propertyText = (string)propertyValue;
PlainXmlSerializer.WriteTextValue(writer, propertyName, propertyTypeName, propertyText);
}
}
}
#endregion Methods.
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERCLevel;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D09_Region_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="D09_Region_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="D08_Region"/> collection.
/// </remarks>
[Serializable]
public partial class D09_Region_ReChild : BusinessBase<D09_Region_ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name");
/// <summary>
/// Gets or sets the Cities Child Name.
/// </summary>
/// <value>The Cities Child Name.</value>
public string Region_Child_Name
{
get { return GetProperty(Region_Child_NameProperty); }
set { SetProperty(Region_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D09_Region_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D09_Region_ReChild"/> object.</returns>
internal static D09_Region_ReChild NewD09_Region_ReChild()
{
return DataPortal.CreateChild<D09_Region_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="D09_Region_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="region_ID2">The Region_ID2 parameter of the D09_Region_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="D09_Region_ReChild"/> object.</returns>
internal static D09_Region_ReChild GetD09_Region_ReChild(int region_ID2)
{
return DataPortal.FetchChild<D09_Region_ReChild>(region_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D09_Region_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public D09_Region_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D09_Region_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D09_Region_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="region_ID2">The Region ID2.</param>
protected void Child_Fetch(int region_ID2)
{
var args = new DataPortalHookArgs(region_ID2);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var dal = dalManager.GetProvider<ID09_Region_ReChildDal>();
var data = dal.Fetch(region_ID2);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="D09_Region_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Region_Child_NameProperty, dr.GetString("Region_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="D09_Region_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D08_Region parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<ID09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.Region_ID,
Region_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D09_Region_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(D08_Region parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<ID09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.Region_ID,
Region_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="D09_Region_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(D08_Region parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<ID09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Region_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// Data sources for logging in RRDs
/// First published in XenServer 5.0.
/// </summary>
public partial class Data_source : XenObject<Data_source>
{
#region Constructors
public Data_source()
{
}
public Data_source(string name_label,
string name_description,
bool enabled,
bool standard,
string units,
double min,
double max,
double value)
{
this.name_label = name_label;
this.name_description = name_description;
this.enabled = enabled;
this.standard = standard;
this.units = units;
this.min = min;
this.max = max;
this.value = value;
}
/// <summary>
/// Creates a new Data_source from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Data_source(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Data_source from a Proxy_Data_source.
/// </summary>
/// <param name="proxy"></param>
public Data_source(Proxy_Data_source proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Data_source.
/// </summary>
public override void UpdateFrom(Data_source record)
{
name_label = record.name_label;
name_description = record.name_description;
enabled = record.enabled;
standard = record.standard;
units = record.units;
min = record.min;
max = record.max;
value = record.value;
}
internal void UpdateFrom(Proxy_Data_source proxy)
{
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
enabled = (bool)proxy.enabled;
standard = (bool)proxy.standard;
units = proxy.units == null ? null : proxy.units;
min = Convert.ToDouble(proxy.min);
max = Convert.ToDouble(proxy.max);
value = Convert.ToDouble(proxy.value);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Data_source
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("enabled"))
enabled = Marshalling.ParseBool(table, "enabled");
if (table.ContainsKey("standard"))
standard = Marshalling.ParseBool(table, "standard");
if (table.ContainsKey("units"))
units = Marshalling.ParseString(table, "units");
if (table.ContainsKey("min"))
min = Marshalling.ParseDouble(table, "min");
if (table.ContainsKey("max"))
max = Marshalling.ParseDouble(table, "max");
if (table.ContainsKey("value"))
value = Marshalling.ParseDouble(table, "value");
}
public Proxy_Data_source ToProxy()
{
Proxy_Data_source result_ = new Proxy_Data_source();
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.enabled = enabled;
result_.standard = standard;
result_.units = units ?? "";
result_.min = min;
result_.max = max;
result_.value = value;
return result_;
}
public bool DeepEquals(Data_source other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._enabled, other._enabled) &&
Helper.AreEqual2(this._standard, other._standard) &&
Helper.AreEqual2(this._units, other._units) &&
Helper.AreEqual2(this._min, other._min) &&
Helper.AreEqual2(this._max, other._max) &&
Helper.AreEqual2(this._value, other._value);
}
public override string SaveChanges(Session session, string opaqueRef, Data_source server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// true if the data source is being logged
/// </summary>
public virtual bool enabled
{
get { return _enabled; }
set
{
if (!Helper.AreEqual(value, _enabled))
{
_enabled = value;
NotifyPropertyChanged("enabled");
}
}
}
private bool _enabled;
/// <summary>
/// true if the data source is enabled by default. Non-default data sources cannot be disabled
/// </summary>
public virtual bool standard
{
get { return _standard; }
set
{
if (!Helper.AreEqual(value, _standard))
{
_standard = value;
NotifyPropertyChanged("standard");
}
}
}
private bool _standard;
/// <summary>
/// the units of the value
/// </summary>
public virtual string units
{
get { return _units; }
set
{
if (!Helper.AreEqual(value, _units))
{
_units = value;
NotifyPropertyChanged("units");
}
}
}
private string _units = "";
/// <summary>
/// the minimum value of the data source
/// </summary>
public virtual double min
{
get { return _min; }
set
{
if (!Helper.AreEqual(value, _min))
{
_min = value;
NotifyPropertyChanged("min");
}
}
}
private double _min;
/// <summary>
/// the maximum value of the data source
/// </summary>
public virtual double max
{
get { return _max; }
set
{
if (!Helper.AreEqual(value, _max))
{
_max = value;
NotifyPropertyChanged("max");
}
}
}
private double _max;
/// <summary>
/// current value of the data source
/// </summary>
public virtual double value
{
get { return _value; }
set
{
if (!Helper.AreEqual(value, _value))
{
_value = value;
NotifyPropertyChanged("value");
}
}
}
private double _value;
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
namespace Lucene.Net.Index
{
using System.IO;
/*
* 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 CodecUtil = Lucene.Net.Codecs.CodecUtil;
using Directory = Lucene.Net.Store.Directory;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using OpenMode = Lucene.Net.Index.IndexWriterConfig.OpenMode_e;
/// <summary>
/// A <seealso cref="SnapshotDeletionPolicy"/> which adds a persistence layer so that
/// snapshots can be maintained across the life of an application. The snapshots
/// are persisted in a <seealso cref="Directory"/> and are committed as soon as
/// <seealso cref="#snapshot()"/> or <seealso cref="#release(IndexCommit)"/> is called.
/// <p>
/// <b>NOTE:</b> Sharing <seealso cref="PersistentSnapshotDeletionPolicy"/>s that write to
/// the same directory across <seealso cref="IndexWriter"/>s will corrupt snapshots. You
/// should make sure every <seealso cref="IndexWriter"/> has its own
/// <seealso cref="PersistentSnapshotDeletionPolicy"/> and that they all write to a
/// different <seealso cref="Directory"/>. It is OK to use the same
/// Directory that holds the index.
///
/// <p> this class adds a <seealso cref="#release(long)"/> method to
/// release commits from a previous snapshot's <seealso cref="IndexCommit#getGeneration"/>.
///
/// @lucene.experimental
/// </summary>
public class PersistentSnapshotDeletionPolicy : SnapshotDeletionPolicy
{
/// <summary>
/// Prefix used for the save file. </summary>
public const string SNAPSHOTS_PREFIX = "snapshots_";
private const int VERSION_START = 0;
private const int VERSION_CURRENT = VERSION_START;
private const string CODEC_NAME = "snapshots";
// The index writer which maintains the snapshots metadata
private long NextWriteGen;
private readonly Directory Dir;
/// <summary>
/// <seealso cref="PersistentSnapshotDeletionPolicy"/> wraps another
/// <seealso cref="IndexDeletionPolicy"/> to enable flexible
/// snapshotting, passing <seealso cref="OpenMode#CREATE_OR_APPEND"/>
/// by default.
/// </summary>
/// <param name="primary">
/// the <seealso cref="IndexDeletionPolicy"/> that is used on non-snapshotted
/// commits. Snapshotted commits, by definition, are not deleted until
/// explicitly released via <seealso cref="#release"/>. </param>
/// <param name="dir">
/// the <seealso cref="Directory"/> which will be used to persist the snapshots
/// information. </param>
public PersistentSnapshotDeletionPolicy(IndexDeletionPolicy primary, Directory dir)
: this(primary, dir, OpenMode.CREATE_OR_APPEND)
{
}
/// <summary>
/// <seealso cref="PersistentSnapshotDeletionPolicy"/> wraps another
/// <seealso cref="IndexDeletionPolicy"/> to enable flexible snapshotting.
/// </summary>
/// <param name="primary">
/// the <seealso cref="IndexDeletionPolicy"/> that is used on non-snapshotted
/// commits. Snapshotted commits, by definition, are not deleted until
/// explicitly released via <seealso cref="#release"/>. </param>
/// <param name="dir">
/// the <seealso cref="Directory"/> which will be used to persist the snapshots
/// information. </param>
/// <param name="mode">
/// specifies whether a new index should be created, deleting all
/// existing snapshots information (immediately), or open an existing
/// index, initializing the class with the snapshots information. </param>
public PersistentSnapshotDeletionPolicy(IndexDeletionPolicy primary, Directory dir, OpenMode mode)
: base(primary)
{
this.Dir = dir;
if (mode == OpenMode.CREATE)
{
ClearPriorSnapshots();
}
LoadPriorSnapshots();
if (mode == OpenMode.APPEND && NextWriteGen == 0)
{
throw new InvalidOperationException("no snapshots stored in this directory");
}
}
/// <summary>
/// Snapshots the last commit. Once this method returns, the
/// snapshot information is persisted in the directory.
/// </summary>
/// <seealso cref= SnapshotDeletionPolicy#snapshot </seealso>
public override IndexCommit Snapshot()
{
lock (this)
{
IndexCommit ic = base.Snapshot();
bool success = false;
try
{
Persist();
success = true;
}
finally
{
if (!success)
{
try
{
base.Release(ic);
}
catch (Exception e)
{
// Suppress so we keep throwing original exception
}
}
}
return ic;
}
}
/// <summary>
/// Deletes a snapshotted commit. Once this method returns, the snapshot
/// information is persisted in the directory.
/// </summary>
/// <seealso cref= SnapshotDeletionPolicy#release </seealso>
public override void Release(IndexCommit commit)
{
lock (this)
{
base.Release(commit);
bool success = false;
try
{
Persist();
success = true;
}
finally
{
if (!success)
{
try
{
IncRef(commit);
}
catch (Exception e)
{
// Suppress so we keep throwing original exception
}
}
}
}
}
/// <summary>
/// Deletes a snapshotted commit by generation. Once this method returns, the snapshot
/// information is persisted in the directory.
/// </summary>
/// <seealso cref= IndexCommit#getGeneration </seealso>
/// <seealso cref= SnapshotDeletionPolicy#release </seealso>
public virtual void Release(long gen)
{
lock (this)
{
base.ReleaseGen(gen);
Persist();
}
}
private void Persist()
{
lock (this)
{
string fileName = SNAPSHOTS_PREFIX + NextWriteGen;
IndexOutput @out = Dir.CreateOutput(fileName, IOContext.DEFAULT);
bool success = false;
try
{
CodecUtil.WriteHeader(@out, CODEC_NAME, VERSION_CURRENT);
@out.WriteVInt(RefCounts.Count);
foreach (KeyValuePair<long, int> ent in RefCounts)
{
@out.WriteVLong(ent.Key);
@out.WriteVInt(ent.Value);
}
success = true;
}
finally
{
if (!success)
{
IOUtils.CloseWhileHandlingException(@out);
try
{
Dir.DeleteFile(fileName);
}
catch (Exception e)
{
// Suppress so we keep throwing original exception
}
}
else
{
IOUtils.Close(@out);
}
}
Dir.Sync(/*Collections.singletonList(*/new[] { fileName }/*)*/);
if (NextWriteGen > 0)
{
string lastSaveFile = SNAPSHOTS_PREFIX + (NextWriteGen - 1);
try
{
Dir.DeleteFile(lastSaveFile);
}
catch (IOException ioe)
{
// OK: likely it didn't exist
}
}
NextWriteGen++;
}
}
private void ClearPriorSnapshots()
{
lock (this)
{
foreach (string file in Dir.ListAll())
{
if (file.StartsWith(SNAPSHOTS_PREFIX))
{
Dir.DeleteFile(file);
}
}
}
}
/// <summary>
/// Returns the file name the snapshots are currently
/// saved to, or null if no snapshots have been saved.
/// </summary>
public virtual string LastSaveFile
{
get
{
if (NextWriteGen == 0)
{
return null;
}
else
{
return SNAPSHOTS_PREFIX + (NextWriteGen - 1);
}
}
}
/// <summary>
/// Reads the snapshots information from the given <seealso cref="Directory"/>. this
/// method can be used if the snapshots information is needed, however you
/// cannot instantiate the deletion policy (because e.g., some other process
/// keeps a lock on the snapshots directory).
/// </summary>
private void LoadPriorSnapshots()
{
lock (this)
{
long genLoaded = -1;
IOException ioe = null;
IList<string> snapshotFiles = new List<string>();
foreach (string file in Dir.ListAll())
{
if (file.StartsWith(SNAPSHOTS_PREFIX))
{
long gen = Convert.ToInt64(file.Substring(SNAPSHOTS_PREFIX.Length));
if (genLoaded == -1 || gen > genLoaded)
{
snapshotFiles.Add(file);
IDictionary<long, int> m = new Dictionary<long, int>();
IndexInput @in = Dir.OpenInput(file, IOContext.DEFAULT);
try
{
CodecUtil.CheckHeader(@in, CODEC_NAME, VERSION_START, VERSION_START);
int count = @in.ReadVInt();
for (int i = 0; i < count; i++)
{
long commitGen = @in.ReadVLong();
int refCount = @in.ReadVInt();
m[commitGen] = refCount;
}
}
catch (IOException ioe2)
{
// Save first exception & throw in the end
if (ioe == null)
{
ioe = ioe2;
}
}
finally
{
@in.Dispose();
}
genLoaded = gen;
RefCounts.Clear();
RefCounts.PutAll(m);
}
}
}
if (genLoaded == -1)
{
// Nothing was loaded...
if (ioe != null)
{
// ... not for lack of trying:
throw ioe;
}
}
else
{
if (snapshotFiles.Count > 1)
{
// Remove any broken / old snapshot files:
string curFileName = SNAPSHOTS_PREFIX + genLoaded;
foreach (string file in snapshotFiles)
{
if (!curFileName.Equals(file))
{
Dir.DeleteFile(file);
}
}
}
NextWriteGen = 1 + genLoaded;
}
}
}
}
}
| |
#region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2010 the Open Toolkit library.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#endregion
// Created by Erik Ylvisaker on 3/17/08.
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
#if !MINIMAL
using System.Drawing;
#endif
using EventTime = System.Double;
namespace OpenTK.Platform.MacOS.Carbon
{
#region --- Types defined in MacTypes.h ---
[StructLayout(LayoutKind.Sequential)]
internal struct CarbonPoint
{
internal short V;
internal short H;
public CarbonPoint(int x, int y)
{
V = (short)x;
H = (short)y;
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct Rect
{
short top;
short left;
short bottom;
short right;
internal Rect(short _left, short _top, short _width, short _height)
{
top = _top;
left = _left;
bottom = (short)(_top + _height);
right = (short)(_left + _width);
}
internal short X
{
get { return left; }
set
{
short width = Width;
left = value;
right = (short)(left + width);
}
}
internal short Y
{
get { return top; }
set
{
short height = Height;
top = value;
bottom = (short)(top + height);
}
}
internal short Width
{
get { return (short)(right - left); }
set { right = (short)(left + value); }
}
internal short Height
{
get { return (short)(bottom - top); }
set { bottom = (short)(top + value); }
}
public override string ToString()
{
return string.Format(
"Rect: [{0}, {1}, {2}, {3}]", X, Y, Width, Height);
}
public Rectangle ToRectangle()
{
return new Rectangle(X, Y, Width, Height);
}
}
#endregion
#region --- Types defined in HIGeometry.h ---
[StructLayout(LayoutKind.Sequential)]
internal struct HIPoint
{
public float X;
public float Y;
public HIPoint(float x, float y)
{
X = x;
Y = y;
}
public HIPoint(double x, double y)
: this((float)x, (float)y)
{ }
}
[StructLayout(LayoutKind.Sequential)]
internal struct HISize
{
public float Width;
public float Height;
}
[StructLayout(LayoutKind.Sequential)]
internal struct HIRect
{
public HIPoint Origin;
public HISize Size;
public override string ToString()
{
return string.Format(
"Rect: [{0}, {1}, {2}, {3}]", Origin.X, Origin.Y, Size.Width, Size.Height);
}
}
#endregion
#region --- Types defined in CarbonEvents.h ---
enum EventAttributes : uint
{
kEventAttributeNone = 0,
kEventAttributeUserEvent = (1 << 0),
kEventAttributeMonitored = 1 << 3,
}
[StructLayout(LayoutKind.Sequential)]
internal struct EventTypeSpec
{
internal EventTypeSpec(EventClass evtClass, AppEventKind evtKind)
{
this.EventClass = evtClass;
this.EventKind = (uint)evtKind;
}
internal EventTypeSpec(EventClass evtClass, AppleEventKind appleKind)
{
this.EventClass = evtClass;
this.EventKind = (uint)appleKind;
}
internal EventTypeSpec(EventClass evtClass, MouseEventKind evtKind)
{
this.EventClass = evtClass;
this.EventKind = (uint)evtKind;
}
internal EventTypeSpec(EventClass evtClass, KeyboardEventKind evtKind)
{
this.EventClass = evtClass;
this.EventKind = (uint)evtKind;
}
internal EventTypeSpec(EventClass evtClass, WindowEventKind evtKind)
{
this.EventClass = evtClass;
this.EventKind = (uint)evtKind;
}
internal EventClass EventClass;
internal uint EventKind;
}
internal enum EventClass : int
{
/*
kEventClassMouse = FOUR_CHAR_CODE('mous'),
kEventClassKeyboard = FOUR_CHAR_CODE('keyb'),
kEventClassTextInput = FOUR_CHAR_CODE('text'),
kEventClassApplication = FOUR_CHAR_CODE('appl'),
kEventClassAppleEvent = FOUR_CHAR_CODE('eppc'),
kEventClassMenu = FOUR_CHAR_CODE('menu'),
kEventClassWindow = FOUR_CHAR_CODE('wind'),
kEventClassControl = FOUR_CHAR_CODE('cntl'),
kEventClassCommand = FOUR_CHAR_CODE('cmds')
*/
Mouse = 0x6d6f7573,
Keyboard = 0x6b657962,
Application = 0x6170706c,
AppleEvent = 0x65707063,
Menu = 0x6d656e75,
Window = 0x77696e64,
}
internal enum WindowEventKind : int
{
// window events
WindowUpdate = 1,
WindowDrawContent = 2,
WindowDrawStructure = 3,
WindowEraseContent = 4,
WindowActivate = 5,
WindowDeactivate = 6,
WindowSizeChanged = 23,
WindowBoundsChanging = 26,
WindowBoundsChanged = 27,
WindowClickDragRgn = 32,
WindowClickResizeRgn = 33,
WindowClickCollapseRgn = 34,
WindowClickCloseRgn = 35,
WindowClickZoomRgn = 36,
WindowClickContentRgn = 37,
WindowClickProxyIconRgn = 38,
WindowClose = 72,
WindowClosed = 73,
}
internal enum MouseEventKind : int
{
MouseDown = 1,
MouseUp = 2,
MouseMoved = 5,
MouseDragged = 6,
MouseEntered = 8,
MouseExited = 9,
WheelMoved = 10,
}
internal enum MouseButton : short
{
Primary = 1,
Secondary = 2,
Tertiary = 3,
}
internal enum KeyboardEventKind : int
{
// raw keyboard events
RawKeyDown = 1,
RawKeyRepeat = 2,
RawKeyUp = 3,
RawKeyModifiersChanged = 4,
}
internal enum AppEventKind : int
{
// application events
AppActivated = 1,
AppDeactivated = 2,
AppQuit = 3,
AppLaunchNotification = 4,
}
enum AppleEventKind : int
{
AppleEvent = 1,
}
internal enum EventParamName : int
{
WindowRef = 0x77696e64, // typeWindowRef,
// Mouse Events
MouseLocation = 0x6d6c6f63, // typeHIPoint
WindowMouseLocation = 0x776d6f75, // typeHIPoint
MouseButton = 0x6d62746e, // typeMouseButton
ClickCount = 0x63636e74, // typeUInt32
MouseWheelAxis = 0x6d776178, // typeMouseWheelAxis
MouseWheelDelta = 0x6d77646c, // typeSInt32
MouseDelta = 0x6d647461, // typeHIPoint
// Keyboard events
KeyCode = 0x6b636f64, // typeUInt32
KeyMacCharCode = 0x6b636872, // typechar
KeyModifiers = 0x6b6d6f64, // typeUInt32
}
internal enum EventParamType : int
{
typeWindowRef = 0x77696e64,
typeMouseButton = 0x6d62746e,
typeMouseWheelAxis = 0x6d776178,
typeHIPoint = 0x68697074,
typeHISize = 0x6869737a,
typeHIRect = 0x68697263,
typeChar = 0x54455854,
typeUInt32 = 0x6d61676e,
typeSInt32 = 0x6c6f6e67,
typeSInt16 = 0x73686f72,
typeSInt64 = 0x636f6d70,
typeIEEE32BitFloatingPoint = 0x73696e67,
typeIEEE64BitFloatingPoint = 0x646f7562,
}
internal enum EventMouseButton : int
{
Primary = 0,
Secondary = 1,
Tertiary = 2,
}
internal enum WindowRegionCode : int
{
TitleBarRegion = 0,
TitleTextRegion = 1,
CloseBoxRegion = 2,
ZoomBoxRegion = 3,
DragRegion = 5,
GrowRegion = 6,
CollapseBoxRegion = 7,
TitleProxyIconRegion = 8,
StructureRegion = 32,
ContentRegion = 33,
UpdateRegion = 34,
OpaqueRegion = 35,
GlobalPortRegion = 40,
ToolbarButtonRegion = 41
};
#endregion
#region --- MacWindows.h ---
internal enum WindowClass : uint
{
Alert = 1, /* "I need your attention now."*/
MovableAlert = 2, /* "I need your attention now, but I'm kind enough to let you switch out of this app to do other things."*/
Modal = 3, /* system modal, not draggable*/
MovableModal = 4, /* application modal, draggable*/
Floating = 5, /* floats above all other application windows*/
Document = 6, /* document windows*/
Desktop = 7, /* desktop window (usually only one of these exists) - OS X only in CarbonLib 1.0*/
Utility = 8, /* Available in CarbonLib 1.1 and later, and in Mac OS X*/
Help = 10, /* Available in CarbonLib 1.1 and later, and in Mac OS X*/
Sheet = 11, /* Available in CarbonLib 1.3 and later, and in Mac OS X*/
Toolbar = 12, /* Available in CarbonLib 1.1 and later, and in Mac OS X*/
Plain = 13, /* Available in CarbonLib 1.2.5 and later, and Mac OS X*/
Overlay = 14, /* Available in Mac OS X*/
SheetAlert = 15, /* Available in CarbonLib 1.3 and later, and in Mac OS X 10.1 and later*/
AltPlain = 16, /* Available in CarbonLib 1.3 and later, and in Mac OS X 10.1 and later*/
Drawer = 20, /* Available in Mac OS X 10.2 or later*/
All = 0xFFFFFFFFu /* for use with GetFrontWindowOfClass, FindWindowOfClass, GetNextWindowOfClass*/
}
[Flags]
internal enum WindowAttributes : uint
{
NoAttributes = 0u, /* no attributes*/
CloseBox = (1u << 0), /* window has a close box*/
HorizontalZoom = (1u << 1), /* window has horizontal zoom box*/
VerticalZoom = (1u << 2), /* window has vertical zoom box*/
FullZoom = (VerticalZoom | HorizontalZoom),
CollapseBox = (1u << 3), /* window has a collapse box*/
Resizable = (1u << 4), /* window is resizable*/
SideTitlebar = (1u << 5), /* window wants a titlebar on the side (floating window class only)*/
NoUpdates = (1u << 16), /* this window receives no update events*/
NoActivates = (1u << 17), /* this window receives no activate events*/
NoBuffering = (1u << 20), /* this window is not buffered (Mac OS X only)*/
StandardHandler = (1u << 25),
InWindowMenu = (1u << 27),
LiveResize = (1u << 28),
StandardDocument = (CloseBox | FullZoom | CollapseBox | Resizable),
StandardFloating = (CloseBox | CollapseBox)
}
internal enum WindowPositionMethod : uint
{
CenterOnMainScreen = 1,
CenterOnParentWindow = 2,
CenterOnParentWindowScreen = 3,
CascadeOnMainScreen = 4,
CascadeOnParentWindow = 5,
CascadeOnParentWindowScreen = 6,
CascadeStartAtParentWindowScreen = 10,
AlertPositionOnMainScreen = 7,
AlertPositionOnParentWindow = 8,
AlertPositionOnParentWindowScreen = 9
}
internal delegate OSStatus MacOSEventHandler(IntPtr inCaller, IntPtr inEvent, IntPtr userData);
internal enum WindowPartCode : short
{
inDesk = 0,
inNoWindow = 0,
inMenuBar = 1,
inSysWindow = 2,
inContent = 3,
inDrag = 4,
inGrow = 5,
inGoAway = 6,
inZoomIn = 7,
inZoomOut = 8,
inCollapseBox = 11,
inProxyIcon = 12,
inToolbarButton = 13,
inStructure = 15,
}
#endregion
#region --- Enums from gestalt.h ---
internal enum GestaltSelector
{
SystemVersion = 0x73797376, // FOUR_CHAR_CODE("sysv"), /* system version*/
SystemVersionMajor = 0x73797331, // FOUR_CHAR_CODE("sys1"), /* The major system version number; in 10.4.17 this would be the decimal value 10 */
SystemVersionMinor = 0x73797332, // FOUR_CHAR_CODE("sys2"), /* The minor system version number; in 10.4.17 this would be the decimal value 4 */
SystemVersionBugFix = 0x73797333, // FOUR_CHAR_CODE("sys3") /* The bug fix system version number; in 10.4.17 this would be the decimal value 17 */
};
#endregion
#region --- Process Manager ---
enum ProcessApplicationTransformState : int
{
kProcessTransformToForegroundApplication = 1,
}
struct ProcessSerialNumber
{
public ulong high;
public ulong low;
}
#endregion
enum HICoordinateSpace
{
_72DPIGlobal = 1,
ScreenPixel = 2,
Window = 3,
View = 4
};
#region --- Carbon API Methods ---
internal partial class API
{
const string carbon = "/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon";
[DllImport(carbon)]
internal static extern EventClass GetEventClass(IntPtr inEvent);
[DllImport(carbon)]
internal static extern uint GetEventKind(IntPtr inEvent);
#region --- Window Construction ---
[DllImport(carbon,EntryPoint="CreateNewWindow")]
private static extern OSStatus _CreateNewWindow(WindowClass @class, WindowAttributes attributes, ref Rect r, out IntPtr window);
internal static IntPtr CreateNewWindow(WindowClass @class, WindowAttributes attributes, Rect r)
{
IntPtr retval;
OSStatus stat = _CreateNewWindow(@class, attributes, ref r, out retval);
Debug.Print("Created Window: {0}", retval);
if (stat != OSStatus.NoError)
{
throw new MacOSException(stat);
}
return retval;
}
[DllImport(carbon)]
internal static extern void DisposeWindow(IntPtr window);
#endregion
#region --- Showing / Hiding Windows ---
[DllImport(carbon)]
internal static extern void ShowWindow(IntPtr window);
[DllImport(carbon)]
internal static extern void HideWindow(IntPtr window);
[DllImport(carbon)]
internal static extern bool IsWindowVisible(IntPtr window);
[DllImport(carbon)]
internal static extern void SelectWindow(IntPtr window);
#endregion
#region --- Window Boundaries ---
[DllImport(carbon)]
internal static extern OSStatus RepositionWindow(IntPtr window, IntPtr parentWindow, WindowPositionMethod method);
[DllImport(carbon)]
internal static extern void SizeWindow(IntPtr window, short w, short h, bool fUpdate);
[DllImport(carbon)]
internal static extern void MoveWindow(IntPtr window, short x, short y, bool fUpdate);
[DllImport(carbon)]
static extern OSStatus GetWindowBounds(IntPtr window, WindowRegionCode regionCode, out Rect globalBounds);
internal static Rect GetWindowBounds(IntPtr window, WindowRegionCode regionCode)
{
Rect retval;
OSStatus result = GetWindowBounds(window, regionCode, out retval);
if (result != OSStatus.NoError)
throw new MacOSException(result);
return retval;
}
//[DllImport(carbon)]
//internal static extern void MoveWindow(IntPtr window, short hGlobal, short vGlobal, bool front);
#endregion
#region --- Processing Events ---
[DllImport(carbon)]
static extern IntPtr GetEventDispatcherTarget();
[DllImport(carbon,EntryPoint="ReceiveNextEvent")]
static extern OSStatus ReceiveNextEvent(uint inNumTypes,
IntPtr inList,
double inTimeout,
bool inPullEvent,
out IntPtr outEvent);
[DllImport(carbon)]
static extern void SendEventToEventTarget(IntPtr theEvent, IntPtr theTarget);
[DllImport(carbon)]
static extern void ReleaseEvent(IntPtr theEvent);
internal static void SendEvent(IntPtr theEvent)
{
IntPtr theTarget = GetEventDispatcherTarget();
SendEventToEventTarget(theEvent, theTarget);
}
// Processes events in the queue and then returns.
internal static void ProcessEvents()
{
IntPtr theEvent;
IntPtr theTarget = GetEventDispatcherTarget();
for (;;)
{
OSStatus status = ReceiveNextEvent(0, IntPtr.Zero, 0.0, true, out theEvent);
if (status == OSStatus.EventLoopTimedOut)
break;
if (status != OSStatus.NoError)
{
Debug.Print("Message Loop status: {0}", status);
break;
}
if (theEvent == IntPtr.Zero)
break;
try
{
SendEventToEventTarget(theEvent, theTarget);
}
catch (System.ExecutionEngineException e)
{
Console.Error.WriteLine("ExecutionEngineException caught.");
Console.Error.WriteLine("theEvent: " + new EventInfo(theEvent).ToString());
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine(e.StackTrace);
}
ReleaseEvent(theEvent);
}
}
#region --- Processing apple event ---
[StructLayout(LayoutKind.Sequential)]
struct EventRecord
{
public ushort what;
public uint message;
public uint when;
public CarbonPoint where;
public uint modifiers;
}
[DllImport(carbon)]
static extern bool ConvertEventRefToEventRecord(IntPtr inEvent, out EventRecord outEvent);
[DllImport(carbon)]
static extern OSStatus AEProcessAppleEvent(ref EventRecord theEventRecord);
static internal void ProcessAppleEvent(IntPtr inEvent)
{
EventRecord record;
ConvertEventRefToEventRecord(inEvent, out record);
AEProcessAppleEvent(ref record);
}
#endregion
#endregion
#region --- Getting Event Parameters ---
[DllImport(carbon,EntryPoint="CreateEvent")]
static extern OSStatus _CreateEvent( IntPtr inAllocator,
EventClass inClassID, UInt32 kind, EventTime when,
EventAttributes flags,out IntPtr outEvent);
internal static IntPtr CreateWindowEvent(WindowEventKind kind)
{
IntPtr retval;
OSStatus stat = _CreateEvent(IntPtr.Zero, EventClass.Window, (uint)kind,
0, EventAttributes.kEventAttributeNone, out retval);
if (stat != OSStatus.NoError)
{
throw new MacOSException(stat);
}
return retval;
}
[DllImport(carbon)]
static extern OSStatus GetEventParameter(
IntPtr inEvent, EventParamName inName, EventParamType inDesiredType,
IntPtr outActualType, uint inBufferSize, IntPtr outActualSize, IntPtr outData);
static internal MacOSKeyCode GetEventKeyboardKeyCode(IntPtr inEvent)
{
int code;
unsafe
{
int* codeAddr = &code;
OSStatus result = API.GetEventParameter(inEvent,
EventParamName.KeyCode, EventParamType.typeUInt32, IntPtr.Zero,
(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(UInt32)), IntPtr.Zero,
(IntPtr) codeAddr);
if (result != OSStatus.NoError)
{
throw new MacOSException(result);
}
}
return (MacOSKeyCode)code;
}
internal static char GetEventKeyboardChar(IntPtr inEvent)
{
char code;
unsafe
{
char* codeAddr = &code;
OSStatus result = API.GetEventParameter(inEvent,
EventParamName.KeyMacCharCode, EventParamType.typeChar, IntPtr.Zero,
(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(char)), IntPtr.Zero,
(IntPtr)codeAddr);
if (result != OSStatus.NoError)
{
throw new MacOSException(result);
}
}
return code;
}
static internal MouseButton GetEventMouseButton(IntPtr inEvent)
{
int button;
unsafe
{
int* btn = &button;
OSStatus result = API.GetEventParameter(inEvent,
EventParamName.MouseButton, EventParamType.typeMouseButton, IntPtr.Zero,
(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(short)), IntPtr.Zero,
(IntPtr)btn);
if (result != OSStatus.NoError)
throw new MacOSException(result);
}
return (MouseButton)button;
}
static internal int GetEventMouseWheelDelta(IntPtr inEvent)
{
int delta;
unsafe
{
int* d = δ
OSStatus result = API.GetEventParameter(inEvent,
EventParamName.MouseWheelDelta, EventParamType.typeSInt32,
IntPtr.Zero, (uint)sizeof(int), IntPtr.Zero, (IntPtr)d);
if (result != OSStatus.NoError)
throw new MacOSException(result);
}
return delta;
}
static internal OSStatus GetEventWindowMouseLocation(IntPtr inEvent, out HIPoint pt)
{
HIPoint point;
unsafe
{
HIPoint* parm = &point;
OSStatus result = API.GetEventParameter(inEvent,
EventParamName.WindowMouseLocation, EventParamType.typeHIPoint, IntPtr.Zero,
(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(HIPoint)), IntPtr.Zero,
(IntPtr)parm);
pt = point;
return result;
}
}
static internal OSStatus GetEventMouseDelta(IntPtr inEvent, out HIPoint pt)
{
HIPoint point;
unsafe
{
HIPoint* parm = &point;
OSStatus result = API.GetEventParameter(inEvent,
EventParamName.MouseDelta, EventParamType.typeHIPoint, IntPtr.Zero,
(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(HIPoint)), IntPtr.Zero,
(IntPtr)parm);
pt = point;
return result;
}
}
static internal OSStatus GetEventWindowRef(IntPtr inEvent, out IntPtr windowRef)
{
IntPtr retval;
unsafe
{
IntPtr* parm = &retval;
OSStatus result = API.GetEventParameter(inEvent,
EventParamName.WindowRef, EventParamType.typeWindowRef, IntPtr.Zero,
(uint)sizeof(IntPtr), IntPtr.Zero, (IntPtr)parm);
windowRef = retval;
return result;
}
}
static internal OSStatus GetEventMouseLocation(IntPtr inEvent, out HIPoint pt)
{
HIPoint point;
unsafe
{
HIPoint* parm = &point;
OSStatus result = API.GetEventParameter(inEvent,
EventParamName.MouseLocation, EventParamType.typeHIPoint, IntPtr.Zero,
(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(HIPoint)), IntPtr.Zero,
(IntPtr)parm);
pt = point;
return result;
}
}
static internal MacOSKeyModifiers GetEventKeyModifiers(IntPtr inEvent)
{
uint code;
unsafe
{
uint* codeAddr = &code;
OSStatus result = API.GetEventParameter(inEvent,
EventParamName.KeyModifiers, EventParamType.typeUInt32, IntPtr.Zero,
(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(uint)), IntPtr.Zero,
(IntPtr)codeAddr);
if (result != OSStatus.NoError)
{
throw new MacOSException(result);
}
}
return (MacOSKeyModifiers)code;
}
#endregion
#region --- Event Handlers ---
[DllImport(carbon,EntryPoint="InstallEventHandler")]
static extern OSStatus _InstallEventHandler(
IntPtr eventTargetRef, IntPtr handlerProc,
int numtypes, EventTypeSpec[] typeList,
IntPtr userData, IntPtr handlerRef);
internal static void InstallWindowEventHandler(IntPtr windowRef, IntPtr uppHandlerProc,
EventTypeSpec[] eventTypes, IntPtr userData, IntPtr handlerRef)
{
IntPtr windowTarget = GetWindowEventTarget(windowRef);
//Debug.Print("Window: {0}", windowRef);
//Debug.Print("Window Target: {0}", windowTarget);
//Debug.Print("Handler: {0}", uppHandlerProc);
//Debug.Print("Num Events: {0}", eventTypes.Length);
//Debug.Print("User Data: {0}", userData);
//Debug.Print("Handler Ref: {0}", handlerRef);
OSStatus error = _InstallEventHandler(windowTarget, uppHandlerProc,
eventTypes.Length, eventTypes,
userData, handlerRef);
//Debug.Print("Status: {0}", error);
if (error != OSStatus.NoError)
{
throw new MacOSException(error);
}
}
internal static void InstallApplicationEventHandler(IntPtr uppHandlerProc,
EventTypeSpec[] eventTypes, IntPtr userData, IntPtr handlerRef)
{
OSStatus error = _InstallEventHandler(GetApplicationEventTarget(), uppHandlerProc,
eventTypes.Length, eventTypes,
userData, handlerRef);
if (error != OSStatus.NoError)
{
throw new MacOSException(error);
}
}
[DllImport(carbon)]
internal static extern OSStatus RemoveEventHandler(IntPtr inHandlerRef);
#endregion
#region --- GetWindowEventTarget ---
[DllImport(carbon)]
internal static extern IntPtr GetWindowEventTarget(IntPtr window);
[DllImport(carbon)]
internal static extern IntPtr GetApplicationEventTarget();
#endregion
#region --- UPP Event Handlers ---
[DllImport(carbon)]
internal static extern IntPtr NewEventHandlerUPP(MacOSEventHandler handler);
[DllImport(carbon)]
internal static extern void DisposeEventHandlerUPP(IntPtr userUPP);
#endregion
#region --- Process Manager ---
[DllImport(carbon)]
internal static extern int TransformProcessType(ref Carbon.ProcessSerialNumber psn, ProcessApplicationTransformState type);
[DllImport(carbon)]
internal static extern int GetCurrentProcess(ref Carbon.ProcessSerialNumber psn);
[DllImport(carbon)]
internal static extern int SetFrontProcess(ref Carbon.ProcessSerialNumber psn);
#endregion
#region --- Setting Dock Tile ---
[DllImport(carbon)]
internal extern static IntPtr CGColorSpaceCreateDeviceRGB();
[DllImport(carbon)]
internal extern static IntPtr CGDataProviderCreateWithData(IntPtr info, IntPtr[] data, int size, IntPtr releasefunc);
[DllImport(carbon)]
internal extern static IntPtr CGImageCreate(int width, int height, int bitsPerComponent, int bitsPerPixel, int bytesPerRow, IntPtr colorspace, uint bitmapInfo, IntPtr provider, IntPtr decode, int shouldInterpolate, int intent);
[DllImport(carbon)]
internal extern static void SetApplicationDockTileImage(IntPtr imageRef);
[DllImport(carbon)]
internal extern static void RestoreApplicationDockTileImage();
#endregion
[DllImport(carbon)]
static extern IntPtr GetControlBounds(IntPtr control, out Rect bounds);
internal static Rect GetControlBounds(IntPtr control)
{
Rect retval;
GetControlBounds(control, out retval);
return retval;
}
[DllImport(carbon)]
internal static extern OSStatus ActivateWindow (IntPtr inWindow, bool inActivate);
[DllImport(carbon)]
internal static extern void RunApplicationEventLoop();
[DllImport(carbon)]
internal static extern void QuitApplicationEventLoop();
[DllImport(carbon)]
internal static extern IntPtr GetControlOwner(IntPtr control);
[DllImport(carbon)]
internal static extern IntPtr HIViewGetWindow(IntPtr inView);
[DllImport(carbon)]
static extern OSStatus HIViewGetFrame(IntPtr inView, out HIRect outRect);
internal static HIRect HIViewGetFrame(IntPtr inView)
{
HIRect retval;
OSStatus result = HIViewGetFrame(inView, out retval);
if (result != OSStatus.NoError)
throw new MacOSException(result);
return retval;
}
#region --- SetWindowTitle ---
[DllImport(carbon)]
static extern void SetWindowTitleWithCFString(IntPtr windowRef, IntPtr title);
internal static void SetWindowTitle(IntPtr windowRef, string title)
{
IntPtr str = __CFStringMakeConstantString(title);
Debug.Print("Setting window title: {0}, CFstring : {1}, Text : {2}", windowRef, str, title);
SetWindowTitleWithCFString(windowRef, str);
// Apparently releasing this reference to the CFConstantString here
// causes the program to crash on the fourth window created. But I am
// afraid that not releasing the string would result in a memory leak, but that would
// only be a serious issue if the window title is changed a lot.
//CFRelease(str);
}
#endregion
[DllImport(carbon,EntryPoint="ChangeWindowAttributes")]
static extern OSStatus _ChangeWindowAttributes(IntPtr windowRef, WindowAttributes setTheseAttributes, WindowAttributes clearTheseAttributes);
internal static void ChangeWindowAttributes(IntPtr windowRef, WindowAttributes setTheseAttributes, WindowAttributes clearTheseAttributes)
{
OSStatus error = _ChangeWindowAttributes(windowRef, setTheseAttributes, clearTheseAttributes);
if (error != OSStatus.NoError)
{
throw new MacOSException(error);
}
}
[DllImport(carbon)]
static extern IntPtr __CFStringMakeConstantString(string cStr);
[DllImport(carbon)]
static extern void CFRelease(IntPtr cfStr);
[DllImport(carbon)]
internal static extern OSStatus CallNextEventHandler(IntPtr nextHandler, IntPtr theEvent);
[DllImport(carbon)]
internal static extern IntPtr GetWindowPort(IntPtr windowRef);
#region --- Menus ---
[DllImport(carbon)]
internal static extern IntPtr AcquireRootMenu();
#endregion
[DllImport(carbon)]
internal static extern bool IsWindowCollapsed(IntPtr windowRef);
[DllImport(carbon, EntryPoint = "CollapseWindow")]
static extern OSStatus _CollapseWindow(IntPtr windowRef, bool collapse);
internal static void CollapseWindow(IntPtr windowRef, bool collapse)
{
OSStatus error = _CollapseWindow(windowRef, collapse);
if (error != OSStatus.NoError)
{
throw new MacOSException(error);
}
}
[DllImport(carbon, EntryPoint="IsWindowInStandardState")]
static extern bool _IsWindowInStandardState(IntPtr windowRef, IntPtr inIdealSize, IntPtr outIdealStandardState);
internal static bool IsWindowInStandardState(IntPtr windowRef)
{
return _IsWindowInStandardState(windowRef, IntPtr.Zero, IntPtr.Zero);
}
[DllImport(carbon, EntryPoint = "ZoomWindowIdeal")]
unsafe static extern OSStatus _ZoomWindowIdeal(IntPtr windowRef, short inPartCode, IntPtr toIdealSize);
internal static void ZoomWindowIdeal(IntPtr windowRef, WindowPartCode inPartCode, ref CarbonPoint toIdealSize)
{
CarbonPoint pt = toIdealSize;
OSStatus error ;
IntPtr handle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CarbonPoint)));
Marshal.StructureToPtr(toIdealSize, handle, false);
error = _ZoomWindowIdeal(windowRef, (short)inPartCode, handle);
toIdealSize = (CarbonPoint)Marshal.PtrToStructure(handle,typeof(CarbonPoint));
Marshal.FreeHGlobal(handle);
if (error != OSStatus.NoError)
{
throw new MacOSException(error);
}
}
[DllImport(carbon)]
internal unsafe static extern OSStatus DMGetGDeviceByDisplayID(
IntPtr displayID, out IntPtr displayDevice, Boolean failToMain);
#region Nonworking HIPointConvert routines
// These seem to crash when called, and I haven't figured out why.
// Currently a workaround is used to convert from screen to client coordinates.
//[DllImport(carbon, EntryPoint="HIPointConvert")]
//extern static OSStatus _HIPointConvert(ref HIPoint ioPoint,
// HICoordinateSpace inSourceSpace, IntPtr inSourceObject,
// HICoordinateSpace inDestinationSpace, IntPtr inDestinationObject);
//internal static HIPoint HIPointConvert(HIPoint inPoint,
// HICoordinateSpace inSourceSpace, IntPtr inSourceObject,
// HICoordinateSpace inDestinationSpace, IntPtr inDestinationObject)
//{
// OSStatus error = _HIPointConvert(ref inPoint, inSourceSpace, inSourceObject, inDestinationSpace, inDestinationObject);
// if (error != OSStatus.NoError)
// {
// throw new MacOSException(error);
// }
// return inPoint;
//}
//[DllImport(carbon, EntryPoint = "HIViewConvertPoint")]
//extern static OSStatus _HIViewConvertPoint(ref HIPoint inPoint, IntPtr inSourceView, IntPtr inDestView);
//internal static HIPoint HIViewConvertPoint( HIPoint point, IntPtr sourceHandle, IntPtr destHandle)
//{
// //Carbon.Rect window_bounds = new Carbon.Rect();
// //Carbon.API.GetWindowBounds(handle, WindowRegionCode.StructureRegion /*32*/, out window_bounds);
// //point.X -= window_bounds.X;
// //point.Y -= window_bounds.Y;
// OSStatus error = _HIViewConvertPoint(ref point, sourceHandle, destHandle);
// if (error != OSStatus.NoError)
// {
// throw new MacOSException(error);
// }
// return point;
//}
#endregion
const string gestaltlib = "/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon";
[DllImport(gestaltlib)]
internal static extern OSStatus Gestalt(GestaltSelector selector, out int response);
}
#endregion
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using Avalonia.Logging;
using Avalonia.Threading;
namespace Avalonia.Layout
{
/// <summary>
/// Manages measuring and arranging of controls.
/// </summary>
public class LayoutManager : ILayoutManager
{
private readonly Queue<ILayoutable> _toMeasure = new Queue<ILayoutable>();
private readonly Queue<ILayoutable> _toArrange = new Queue<ILayoutable>();
private bool _queued;
private bool _running;
/// <inheritdoc/>
public void InvalidateMeasure(ILayoutable control)
{
Contract.Requires<ArgumentNullException>(control != null);
Dispatcher.UIThread.VerifyAccess();
if (!control.IsAttachedToVisualTree)
{
#if DEBUG
throw new AvaloniaInternalException(
"LayoutManager.InvalidateMeasure called on a control that is detached from the visual tree.");
#else
return;
#endif
}
_toMeasure.Enqueue(control);
_toArrange.Enqueue(control);
QueueLayoutPass();
}
/// <inheritdoc/>
public void InvalidateArrange(ILayoutable control)
{
Contract.Requires<ArgumentNullException>(control != null);
Dispatcher.UIThread.VerifyAccess();
if (!control.IsAttachedToVisualTree)
{
#if DEBUG
throw new AvaloniaInternalException(
"LayoutManager.InvalidateArrange called on a control that is detached from the visual tree.");
#else
return;
#endif
}
_toArrange.Enqueue(control);
QueueLayoutPass();
}
/// <inheritdoc/>
public void ExecuteLayoutPass()
{
const int MaxPasses = 3;
Dispatcher.UIThread.VerifyAccess();
if (!_running)
{
_running = true;
Logger.Information(
LogArea.Layout,
this,
"Started layout pass. To measure: {Measure} To arrange: {Arrange}",
_toMeasure.Count,
_toArrange.Count);
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
try
{
for (var pass = 0; pass < MaxPasses; ++pass)
{
ExecuteMeasurePass();
ExecuteArrangePass();
if (_toMeasure.Count == 0)
{
break;
}
}
}
finally
{
_running = false;
}
stopwatch.Stop();
Logger.Information(LogArea.Layout, this, "Layout pass finished in {Time}", stopwatch.Elapsed);
}
_queued = false;
}
/// <inheritdoc/>
public void ExecuteInitialLayoutPass(ILayoutRoot root)
{
Measure(root);
Arrange(root);
// Running the initial layout pass may have caused some control to be invalidated
// so run a full layout pass now (this usually due to scrollbars; its not known
// whether they will need to be shown until the layout pass has run and if the
// first guess was incorrect the layout will need to be updated).
ExecuteLayoutPass();
}
private void ExecuteMeasurePass()
{
while (_toMeasure.Count > 0)
{
var control = _toMeasure.Dequeue();
if (!control.IsMeasureValid && control.IsAttachedToVisualTree)
{
Measure(control);
}
}
}
private void ExecuteArrangePass()
{
while (_toArrange.Count > 0 && _toMeasure.Count == 0)
{
var control = _toArrange.Dequeue();
if (!control.IsArrangeValid && control.IsAttachedToVisualTree)
{
Arrange(control);
}
}
}
private void Measure(ILayoutable control)
{
// Controls closest to the visual root need to be arranged first. We don't try to store
// ordered invalidation lists, instead we traverse the tree upwards, measuring the
// controls closest to the root first. This has been shown by benchmarks to be the
// fastest and most memory-efficient algorithm.
if (control.VisualParent is ILayoutable parent)
{
Measure(parent);
}
// If the control being measured has IsMeasureValid == true here then its measure was
// handed by an ancestor and can be ignored. The measure may have also caused the
// control to be removed.
if (!control.IsMeasureValid && control.IsAttachedToVisualTree)
{
if (control is ILayoutRoot root)
{
root.Measure(Size.Infinity);
}
else if (control.PreviousMeasure.HasValue)
{
control.Measure(control.PreviousMeasure.Value);
}
}
}
private void Arrange(ILayoutable control)
{
if (control.VisualParent is ILayoutable parent)
{
Arrange(parent);
}
if (!control.IsArrangeValid && control.IsAttachedToVisualTree)
{
if (control is IEmbeddedLayoutRoot embeddedRoot)
control.Arrange(new Rect(embeddedRoot.AllocatedSize));
else if (control is ILayoutRoot root)
control.Arrange(new Rect(root.DesiredSize));
else if (control.PreviousArrange != null)
{
// Has been observed that PreviousArrange sometimes is null, probably a bug somewhere else.
// Condition observed: control.VisualParent is Scrollbar, control is Border.
control.Arrange(control.PreviousArrange.Value);
}
}
}
private void QueueLayoutPass()
{
if (!_queued && !_running)
{
Dispatcher.UIThread.Post(ExecuteLayoutPass, DispatcherPriority.Layout);
_queued = true;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Compat;
using LibGit2Sharp.Core.Handles;
using Environment = System.Environment;
namespace LibGit2Sharp
{
/// <summary>
/// Show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, or changes between two files on disk.
/// <para>
/// Copied and renamed files currently cannot be detected, as the feature is not supported by libgit2 yet.
/// These files will be shown as a pair of Deleted/Added files.</para>
/// </summary>
public class Diff
{
private readonly Repository repo;
private static GitDiffOptions BuildOptions(DiffModifiers diffOptions, FilePath[] filePaths = null, MatchedPathsAggregator matchedPathsAggregator = null, CompareOptions compareOptions = null)
{
var options = new GitDiffOptions();
options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_TYPECHANGE;
compareOptions = compareOptions ?? new CompareOptions();
options.ContextLines = (ushort)compareOptions.ContextLines;
options.InterhunkLines = (ushort)compareOptions.InterhunkLines;
if (diffOptions.HasFlag(DiffModifiers.IncludeUntracked))
{
options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED |
GitDiffOptionFlags.GIT_DIFF_RECURSE_UNTRACKED_DIRS |
GitDiffOptionFlags.GIT_DIFF_SHOW_UNTRACKED_CONTENT;
}
if (diffOptions.HasFlag(DiffModifiers.IncludeIgnored))
{
options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_IGNORED |
GitDiffOptionFlags.GIT_DIFF_RECURSE_IGNORED_DIRS;
}
if (diffOptions.HasFlag(DiffModifiers.IncludeUnmodified) || compareOptions.IncludeUnmodified ||
(compareOptions.Similarity != null &&
(compareOptions.Similarity.RenameDetectionMode == RenameDetectionMode.CopiesHarder ||
compareOptions.Similarity.RenameDetectionMode == RenameDetectionMode.Exact)))
{
options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNMODIFIED;
}
if (diffOptions.HasFlag(DiffModifiers.DisablePathspecMatch))
{
options.Flags |= GitDiffOptionFlags.GIT_DIFF_DISABLE_PATHSPEC_MATCH;
}
if (matchedPathsAggregator != null)
{
options.NotifyCallback = matchedPathsAggregator.OnGitDiffNotify;
}
if (filePaths == null)
{
return options;
}
options.PathSpec = GitStrArrayIn.BuildFrom(filePaths);
return options;
}
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected Diff()
{ }
internal Diff(Repository repo)
{
this.repo = repo;
}
private static readonly IDictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> HandleRetrieverDispatcher = BuildHandleRetrieverDispatcher();
private static IDictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> BuildHandleRetrieverDispatcher()
{
return new Dictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>>
{
{ DiffTargets.Index, IndexToTree },
{ DiffTargets.WorkingDirectory, WorkdirToTree },
{ DiffTargets.Index | DiffTargets.WorkingDirectory, WorkdirAndIndexToTree },
};
}
private static readonly IDictionary<Type, Func<DiffSafeHandle, object>> ChangesBuilders = new Dictionary<Type, Func<DiffSafeHandle, object>>
{
{ typeof(Patch), diff => new Patch(diff) },
{ typeof(TreeChanges), diff => new TreeChanges(diff) },
{ typeof(PatchStats), diff => new PatchStats(diff) },
};
/// <summary>
/// Show changes between two <see cref="Blob"/>s.
/// </summary>
/// <param name="oldBlob">The <see cref="Blob"/> you want to compare from.</param>
/// <param name="newBlob">The <see cref="Blob"/> you want to compare to.</param>
/// <param name="compareOptions">Additional options to define comparison behavior.</param>
/// <returns>A <see cref="ContentChanges"/> containing the changes between the <paramref name="oldBlob"/> and the <paramref name="newBlob"/>.</returns>
public virtual ContentChanges Compare(Blob oldBlob, Blob newBlob, CompareOptions compareOptions = null)
{
using (GitDiffOptions options = BuildOptions(DiffModifiers.None, compareOptions: compareOptions))
{
return new ContentChanges(repo, oldBlob, newBlob, options);
}
}
/// <summary>
/// Show changes between two <see cref="Tree"/>s.
/// </summary>
/// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param>
/// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <param name="explicitPathsOptions">
/// If set, the passed <paramref name="paths"/> will be treated as explicit paths.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
/// <param name="compareOptions">Additional options to define patch generation behavior.</param>
/// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns>
public virtual T Compare<T>(Tree oldTree, Tree newTree, IEnumerable<string> paths = null, ExplicitPathsOptions explicitPathsOptions = null,
CompareOptions compareOptions = null) where T : class
{
Func<DiffSafeHandle, object> builder;
if (!ChangesBuilders.TryGetValue(typeof (T), out builder))
{
throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture,
"Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T),
typeof (TreeChanges), typeof (Patch)));
}
var comparer = TreeToTree(repo);
ObjectId oldTreeId = oldTree != null ? oldTree.Id : null;
ObjectId newTreeId = newTree != null ? newTree.Id : null;
var diffOptions = DiffModifiers.None;
if (explicitPathsOptions != null)
{
diffOptions |= DiffModifiers.DisablePathspecMatch;
if (explicitPathsOptions.ShouldFailOnUnmatchedPath ||
explicitPathsOptions.OnUnmatchedPath != null)
{
diffOptions |= DiffModifiers.IncludeUnmodified;
}
}
using (DiffSafeHandle diff = BuildDiffList(oldTreeId, newTreeId, comparer,
diffOptions, paths, explicitPathsOptions, compareOptions))
{
return (T)builder(diff);
}
}
/// <summary>
/// Show changes between a <see cref="Tree"/> and the Index, the Working Directory, or both.
/// <para>
/// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
/// or <see cref="Patch"/> type as the generic parameter.
/// </para>
/// </summary>
/// <param name="oldTree">The <see cref="Tree"/> to compare from.</param>
/// <param name="diffTargets">The targets to compare to.</param>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <param name="explicitPathsOptions">
/// If set, the passed <paramref name="paths"/> will be treated as explicit paths.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
/// <param name="compareOptions">Additional options to define patch generation behavior.</param>
/// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
/// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
/// <returns>A <typeparamref name="T"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns>
public virtual T Compare<T>(Tree oldTree, DiffTargets diffTargets, IEnumerable<string> paths = null,
ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class
{
Func<DiffSafeHandle, object> builder;
if (!ChangesBuilders.TryGetValue(typeof (T), out builder))
{
throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture,
"Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T),
typeof (TreeChanges), typeof (Patch)));
}
var comparer = HandleRetrieverDispatcher[diffTargets](repo);
ObjectId oldTreeId = oldTree != null ? oldTree.Id : null;
DiffModifiers diffOptions = diffTargets.HasFlag(DiffTargets.WorkingDirectory)
? DiffModifiers.IncludeUntracked
: DiffModifiers.None;
if (explicitPathsOptions != null)
{
diffOptions |= DiffModifiers.DisablePathspecMatch;
if (explicitPathsOptions.ShouldFailOnUnmatchedPath ||
explicitPathsOptions.OnUnmatchedPath != null)
{
diffOptions |= DiffModifiers.IncludeUnmodified;
}
}
using (DiffSafeHandle diff = BuildDiffList(oldTreeId, null, comparer,
diffOptions, paths, explicitPathsOptions, compareOptions))
{
return (T)builder(diff);
}
}
/// <summary>
/// Show changes between the working directory and the index.
/// <para>
/// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
/// or <see cref="Patch"/> type as the generic parameter.
/// </para>
/// </summary>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <param name="includeUntracked">If true, include untracked files from the working dir as additions. Otherwise ignore them.</param>
/// <param name="explicitPathsOptions">
/// If set, the passed <paramref name="paths"/> will be treated as explicit paths.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
/// <param name="compareOptions">Additional options to define patch generation behavior.</param>
/// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
/// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
/// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns>
public virtual T Compare<T>(IEnumerable<string> paths = null, bool includeUntracked = false, ExplicitPathsOptions explicitPathsOptions = null,
CompareOptions compareOptions = null) where T : class
{
return Compare<T>(includeUntracked ? DiffModifiers.IncludeUntracked : DiffModifiers.None, paths, explicitPathsOptions);
}
internal virtual T Compare<T>(DiffModifiers diffOptions, IEnumerable<string> paths = null,
ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class
{
Func<DiffSafeHandle, object> builder;
if (!ChangesBuilders.TryGetValue(typeof (T), out builder))
{
throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture,
"Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T),
typeof (TreeChanges), typeof (Patch)));
}
var comparer = WorkdirToIndex(repo);
if (explicitPathsOptions != null)
{
diffOptions |= DiffModifiers.DisablePathspecMatch;
if (explicitPathsOptions.ShouldFailOnUnmatchedPath ||
explicitPathsOptions.OnUnmatchedPath != null)
{
diffOptions |= DiffModifiers.IncludeUnmodified;
}
}
using (DiffSafeHandle diff = BuildDiffList(null, null, comparer,
diffOptions, paths, explicitPathsOptions, compareOptions))
{
return (T)builder(diff);
}
}
internal delegate DiffSafeHandle TreeComparisonHandleRetriever(ObjectId oldTreeId, ObjectId newTreeId, GitDiffOptions options);
private static TreeComparisonHandleRetriever TreeToTree(Repository repo)
{
return (oh, nh, o) => Proxy.git_diff_tree_to_tree(repo.Handle, oh, nh, o);
}
private static TreeComparisonHandleRetriever WorkdirToIndex(Repository repo)
{
return (oh, nh, o) => Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o);
}
private static TreeComparisonHandleRetriever WorkdirToTree(Repository repo)
{
return (oh, nh, o) => Proxy.git_diff_tree_to_workdir(repo.Handle, oh, o);
}
private static TreeComparisonHandleRetriever WorkdirAndIndexToTree(Repository repo)
{
TreeComparisonHandleRetriever comparisonHandleRetriever = (oh, nh, o) =>
{
DiffSafeHandle diff = null, diff2 = null;
try
{
diff = Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o);
diff2 = Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o);
Proxy.git_diff_merge(diff, diff2);
}
catch
{
diff.SafeDispose();
throw;
}
finally
{
diff2.SafeDispose();
}
return diff;
};
return comparisonHandleRetriever;
}
private static TreeComparisonHandleRetriever IndexToTree(Repository repo)
{
return (oh, nh, o) => Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o);
}
private DiffSafeHandle BuildDiffList(ObjectId oldTreeId, ObjectId newTreeId, TreeComparisonHandleRetriever comparisonHandleRetriever,
DiffModifiers diffOptions, IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions,
CompareOptions compareOptions)
{
var matchedPaths = new MatchedPathsAggregator();
var filePaths = repo.ToFilePaths(paths);
using (GitDiffOptions options = BuildOptions(diffOptions, filePaths, matchedPaths, compareOptions))
{
var diffList = comparisonHandleRetriever(oldTreeId, newTreeId, options);
try
{
if (explicitPathsOptions != null)
{
DispatchUnmatchedPaths(explicitPathsOptions, filePaths, matchedPaths);
}
}
catch
{
diffList.Dispose();
throw;
}
DetectRenames(diffList, compareOptions);
return diffList;
}
}
private void DetectRenames(DiffSafeHandle diffList, CompareOptions compareOptions)
{
var similarityOptions = (compareOptions == null) ? null : compareOptions.Similarity;
if (similarityOptions == null ||
similarityOptions.RenameDetectionMode == RenameDetectionMode.Default)
{
Proxy.git_diff_find_similar(diffList, null);
return;
}
if (similarityOptions.RenameDetectionMode == RenameDetectionMode.None)
{
return;
}
var opts = new GitDiffFindOptions
{
RenameThreshold = (ushort)similarityOptions.RenameThreshold,
RenameFromRewriteThreshold = (ushort)similarityOptions.RenameFromRewriteThreshold,
CopyThreshold = (ushort)similarityOptions.CopyThreshold,
BreakRewriteThreshold = (ushort)similarityOptions.BreakRewriteThreshold,
RenameLimit = (UIntPtr)similarityOptions.RenameLimit,
};
switch (similarityOptions.RenameDetectionMode)
{
case RenameDetectionMode.Exact:
opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_EXACT_MATCH_ONLY |
GitDiffFindFlags.GIT_DIFF_FIND_RENAMES |
GitDiffFindFlags.GIT_DIFF_FIND_COPIES |
GitDiffFindFlags.GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED;
break;
case RenameDetectionMode.Renames:
opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES;
break;
case RenameDetectionMode.Copies:
opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES |
GitDiffFindFlags.GIT_DIFF_FIND_COPIES;
break;
case RenameDetectionMode.CopiesHarder:
opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES |
GitDiffFindFlags.GIT_DIFF_FIND_COPIES |
GitDiffFindFlags.GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED;
break;
}
if (!compareOptions.IncludeUnmodified)
{
opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_REMOVE_UNMODIFIED;
}
switch (similarityOptions.WhitespaceMode)
{
case WhitespaceMode.DontIgnoreWhitespace:
opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_DONT_IGNORE_WHITESPACE;
break;
case WhitespaceMode.IgnoreLeadingWhitespace:
opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_IGNORE_LEADING_WHITESPACE;
break;
case WhitespaceMode.IgnoreAllWhitespace:
opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_IGNORE_WHITESPACE;
break;
}
Proxy.git_diff_find_similar(diffList, opts);
}
private static void DispatchUnmatchedPaths(ExplicitPathsOptions explicitPathsOptions,
IEnumerable<FilePath> filePaths,
IEnumerable<FilePath> matchedPaths)
{
List<FilePath> unmatchedPaths = (filePaths != null ?
filePaths.Except(matchedPaths) : Enumerable.Empty<FilePath>()).ToList();
if (!unmatchedPaths.Any())
{
return;
}
if (explicitPathsOptions.OnUnmatchedPath != null)
{
unmatchedPaths.ForEach(filePath => explicitPathsOptions.OnUnmatchedPath(filePath.Native));
}
if (explicitPathsOptions.ShouldFailOnUnmatchedPath)
{
throw new UnmatchedPathException(BuildUnmatchedPathsMessage(unmatchedPaths));
}
}
private static string BuildUnmatchedPathsMessage(List<FilePath> unmatchedPaths)
{
var message = new StringBuilder("There were some unmatched paths:" + Environment.NewLine);
unmatchedPaths.ForEach(filePath => message.AppendFormat("- {0}{1}", filePath.Native, Environment.NewLine));
return message.ToString();
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// #define LOGENABLE // uncomment this line to enable the log,
// create c:\temp\cim.log before invoking cimcmdlets
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Global Non-localization strings
/// </para>
/// </summary>
internal static class ConstValue
{
/// <summary>
/// <para>
/// Default computername
/// </para>
/// </summary>
internal static readonly string[] DefaultSessionName = { @"*" };
/// <summary>
/// <para>
/// Empty computername, which will create DCOM session
/// </para>
/// </summary>
internal static readonly string NullComputerName = null;
/// <summary>
/// <para>
/// Empty computername array, which will create DCOM session
/// </para>
/// </summary>
internal static readonly string[] NullComputerNames = { NullComputerName };
/// <summary>
/// <para>
/// localhost computername, which will create WSMAN session
/// </para>
/// </summary>
internal static readonly string LocalhostComputerName = @"localhost";
/// <summary>
/// <para>
/// Default namespace
/// </para>
/// </summary>
internal static readonly string DefaultNameSpace = @"root\cimv2";
/// <summary>
/// <para>
/// Default namespace
/// </para>
/// </summary>
internal static readonly string DefaultQueryDialect = @"WQL";
/// <summary>
/// Name of the note property that controls if "PSComputerName" column is shown.
/// </summary>
internal static readonly string ShowComputerNameNoteProperty = "PSShowComputerName";
/// <summary>
/// <para>
/// Whether given computername is either null or empty
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <returns></returns>
internal static bool IsDefaultComputerName(string computerName)
{
return string.IsNullOrEmpty(computerName);
}
/// <summary>
/// <para>
/// Get computer names, if it is null then return DCOM one
/// </para>
/// </summary>
/// <param name="computerNames"></param>
/// <returns></returns>
internal static IEnumerable<string> GetComputerNames(IEnumerable<string> computerNames)
{
return computerNames ?? NullComputerNames;
}
/// <summary>
/// Get computer name, if it is null then return default one.
/// </summary>
/// <param name="computerName"></param>
/// <returns></returns>
internal static string GetComputerName(string computerName)
{
return string.IsNullOrEmpty(computerName) ? NullComputerName : computerName;
}
/// <summary>
/// <para>
/// Get namespace, if it is null then return default one
/// </para>
/// </summary>
/// <param name="nameSpace"></param>
/// <returns></returns>
internal static string GetNamespace(string nameSpace)
{
return nameSpace ?? DefaultNameSpace;
}
/// <summary>
/// <para>
/// Get queryDialect, if it is null then return default query Dialect
/// </para>
/// </summary>
/// <param name="queryDialect"></param>
/// <returns></returns>
internal static string GetQueryDialectWithDefault(string queryDialect)
{
return queryDialect ?? DefaultQueryDialect;
}
}
/// <summary>
/// <para>
/// Debug helper class used to dump debug message to log file
/// </para>
/// </summary>
internal static class DebugHelper
{
#region private members
/// <summary>
/// Flag used to control generating log message into file.
/// </summary>
internal static bool GenerateLog { get; set; } = true;
/// <summary>
/// Whether the log been initialized.
/// </summary>
private static bool logInitialized = false;
internal static bool GenerateVerboseMessage { get; set; } = true;
/// <summary>
/// Flag used to control generating message into powershell.
/// </summary>
internal static readonly string logFile = @"c:\temp\Cim.log";
/// <summary>
/// Indent space string.
/// </summary>
internal static readonly string space = @" ";
/// <summary>
/// Indent space strings array.
/// </summary>
internal static readonly string[] spaces = {
string.Empty,
space,
space + space,
space + space + space,
space + space + space + space,
space + space + space + space + space,
};
/// <summary>
/// Lock the log file.
/// </summary>
internal static readonly object logLock = new();
#endregion
#region internal strings
internal static readonly string runspaceStateChanged = "Runspace {0} state changed to {1}";
internal static readonly string classDumpInfo = @"Class type is {0}";
internal static readonly string propertyDumpInfo = @"Property name {0} of type {1}, its value is {2}";
internal static readonly string defaultPropertyType = @"It is a default property, default value is {0}";
internal static readonly string propertyValueSet = @"This property value is set by user {0}";
internal static readonly string addParameterSetName = @"Add parameter set {0} name to cache";
internal static readonly string removeParameterSetName = @"Remove parameter set {0} name from cache";
internal static readonly string currentParameterSetNameCount = @"Cache have {0} parameter set names";
internal static readonly string currentParameterSetNameInCache = @"Cache have parameter set {0} valid {1}";
internal static readonly string currentnonMandatoryParameterSetInCache = @"Cache have optional parameter set {0} valid {1}";
internal static readonly string optionalParameterSetNameCount = @"Cache have {0} optional parameter set names";
internal static readonly string finalParameterSetName = @"------Final parameter set name of the cmdlet is {0}";
internal static readonly string addToOptionalParameterSet = @"Add to optional ParameterSetNames {0}";
internal static readonly string startToResolveParameterSet = @"------Resolve ParameterSet Name";
internal static readonly string reservedString = @"------";
#endregion
#region runtime methods
internal static string GetSourceCodeInformation(bool withFileName, int depth)
{
StackTrace trace = new();
StackFrame frame = trace.GetFrame(depth);
// if (withFileName)
// {
// return string.Format(CultureInfo.CurrentUICulture, "{0}#{1}:{2}:", frame.GetFileName()., frame.GetFileLineNumber(), frame.GetMethod().Name);
// }
// else
// {
// return string.Format(CultureInfo.CurrentUICulture, "{0}:", frame.GetMethod());
// }
return string.Format(CultureInfo.CurrentUICulture, "{0}::{1} ",
frame.GetMethod().DeclaringType.Name,
frame.GetMethod().Name);
}
#endregion
/// <summary>
/// Write message to log file named @logFile.
/// </summary>
/// <param name="message"></param>
internal static void WriteLog(string message)
{
WriteLog(message, 0);
}
/// <summary>
/// Write blank line to log file named @logFile.
/// </summary>
/// <param name="message"></param>
internal static void WriteEmptyLine()
{
WriteLog(string.Empty, 0);
}
/// <summary>
/// Write message to log file named @logFile with args.
/// </summary>
/// <param name="message"></param>
internal static void WriteLog(string message, int indent, params object[] args)
{
string outMessage = string.Empty;
FormatLogMessage(ref outMessage, message, args);
WriteLog(outMessage, indent);
}
/// <summary>
/// Write message to log file w/o arguments.
/// </summary>
/// <param name="message"></param>
/// <param name="indent"></param>
internal static void WriteLog(string message, int indent)
{
WriteLogInternal(message, indent, -1);
}
/// <summary>
/// Write message to log file named @logFile with args.
/// </summary>
/// <param name="message"></param>
internal static void WriteLogEx(string message, int indent, params object[] args)
{
string outMessage = string.Empty;
WriteLogInternal(string.Empty, 0, -1);
FormatLogMessage(ref outMessage, message, args);
WriteLogInternal(outMessage, indent, 3);
}
/// <summary>
/// Write message to log file w/o arguments.
/// </summary>
/// <param name="message"></param>
/// <param name="indent"></param>
internal static void WriteLogEx(string message, int indent)
{
WriteLogInternal(string.Empty, 0, -1);
WriteLogInternal(message, indent, 3);
}
/// <summary>
/// Write message to log file w/o arguments.
/// </summary>
/// <param name="message"></param>
/// <param name="indent"></param>
internal static void WriteLogEx()
{
WriteLogInternal(string.Empty, 0, -1);
WriteLogInternal(string.Empty, 0, 3);
}
/// <summary>
/// Format the message.
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
/// <returns></returns>
[Conditional("LOGENABLE")]
private static void FormatLogMessage(ref string outMessage, string message, params object[] args)
{
outMessage = string.Format(CultureInfo.CurrentCulture, message, args);
}
/// <summary>
/// Write message to log file named @logFile
/// with indent space ahead of the message.
/// </summary>
/// <param name="message"></param>
/// <param name="nIndent"></param>
[Conditional("LOGENABLE")]
private static void WriteLogInternal(string message, int indent, int depth)
{
if (!logInitialized)
{
lock (logLock)
{
if (!logInitialized)
{
DebugHelper.GenerateLog = File.Exists(logFile);
logInitialized = true;
}
}
}
if (GenerateLog)
{
if (indent < 0)
{
indent = 0;
}
if (indent > 5)
{
indent = 5;
}
string sourceInformation = string.Empty;
if (depth != -1)
{
sourceInformation = string.Format(
CultureInfo.InvariantCulture,
"Thread {0}#{1}:{2}:{3} {4}",
Environment.CurrentManagedThreadId,
DateTime.Now.Hour,
DateTime.Now.Minute,
DateTime.Now.Second,
GetSourceCodeInformation(true, depth));
}
lock (logLock)
{
using (FileStream fs = new(logFile, FileMode.OpenOrCreate))
using (StreamWriter writer = new(fs))
{
writer.WriteLineAsync(spaces[indent] + sourceInformation + @" " + message);
}
}
}
}
}
/// <summary>
/// <para>
/// Helper class used to validate given parameter
/// </para>
/// </summary>
internal static class ValidationHelper
{
/// <summary>
/// Validate the argument is not null.
/// </summary>
/// <param name="obj"></param>
/// <param name="argumentName"></param>
public static void ValidateNoNullArgument(object obj, string argumentName)
{
if (obj == null)
{
throw new ArgumentNullException(argumentName);
}
}
/// <summary>
/// Validate the argument is not null and not whitespace.
/// </summary>
/// <param name="obj"></param>
/// <param name="argumentName"></param>
public static void ValidateNoNullorWhiteSpaceArgument(string obj, string argumentName)
{
if (string.IsNullOrWhiteSpace(obj))
{
throw new ArgumentException(argumentName);
}
}
/// <summary>
/// Validate that given classname/propertyname is a valid name compliance with DMTF standard.
/// Only for verifying ClassName and PropertyName argument.
/// </summary>
/// <param name="parameterName"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="ArgumentException">Throw if the given value is not a valid name (class name or property name).</exception>
public static string ValidateArgumentIsValidName(string parameterName, string value)
{
DebugHelper.WriteLogEx();
if (value != null)
{
string trimed = value.Trim();
// The first character should be contained in set: [A-Za-z_]
// Inner characters should be contained in set: [A-Za-z0-9_]
Regex regex = new(@"^[a-zA-Z_][a-zA-Z0-9_]*\z");
if (regex.IsMatch(trimed))
{
DebugHelper.WriteLogEx("A valid name: {0}={1}", 0, parameterName, value);
return trimed;
}
}
DebugHelper.WriteLogEx("An invalid name: {0}={1}", 0, parameterName, value);
throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.InvalidParameterValue, value, parameterName));
}
/// <summary>
/// Validate given arry argument contains all valid name (for -SelectProperties).
/// * is valid for this case.
/// </summary>
/// <param name="parameterName"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="ArgumentException">Throw if the given value contains any invalid name (class name or property name).</exception>
public static string[] ValidateArgumentIsValidName(string parameterName, string[] value)
{
if (value != null)
{
foreach (string propertyName in value)
{
// * is wild char supported in select properties
if ((propertyName != null) && string.Equals(propertyName.Trim(), "*", StringComparison.OrdinalIgnoreCase))
{
continue;
}
ValidationHelper.ValidateArgumentIsValidName(parameterName, propertyName);
}
}
return value;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Security;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics.SymbolStore;
namespace System.Reflection.Emit
{
//-----------------------------------------------------------------------------------
// On Telesto, we don't ship the ISymWrapper.dll assembly. However, ReflectionEmit
// relies on that assembly to write out managed PDBs.
//
// This file implements the minimum subset of ISymWrapper.dll required to restore
// that functionality. Namely, the SymWriter and SymDocumentWriter objects.
//
// Ideally we wouldn't need ISymWrapper.dll on desktop either - it's an ugly piece
// of legacy. We could just use this (or COM-interop code) everywhere, but we might
// have to worry about compatibility.
//
// We've now got a real implementation even when no debugger is attached. It's
// up to the runtime to ensure it doesn't provide us with an insecure writer
// (eg. diasymreader) in the no-trust scenarios (no debugger, partial-trust code).
//-----------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// SymWrapperCore is never instantiated and is used as an encapsulation class.
// It is our "ISymWrapper.dll" assembly within an assembly.
//------------------------------------------------------------------------------
internal class SymWrapperCore
{
//------------------------------------------------------------------------------
// Block instantiation
//------------------------------------------------------------------------------
private SymWrapperCore()
{
}
//------------------------------------------------------------------------------
// Implements Telesto's version of SymDocumentWriter (in the desktop world,
// this type is exposed from ISymWrapper.dll.)
//
// The only thing user code can do with this wrapper is to receive it from
// SymWriter.DefineDocument and pass it back to SymWriter.DefineSequencePoints.
//------------------------------------------------------------------------------
private unsafe class SymDocumentWriter : ISymbolDocumentWriter
{
//------------------------------------------------------------------------------
// Ctor
//------------------------------------------------------------------------------
internal SymDocumentWriter(PunkSafeHandle pDocumentWriterSafeHandle)
{
m_pDocumentWriterSafeHandle = pDocumentWriterSafeHandle;
// The handle is actually a pointer to a native ISymUnmanagedDocumentWriter.
m_pDocWriter = (ISymUnmanagedDocumentWriter*)m_pDocumentWriterSafeHandle.DangerousGetHandle();
m_vtable = (ISymUnmanagedDocumentWriterVTable)(Marshal.PtrToStructure(m_pDocWriter->m_unmanagedVTable, typeof(ISymUnmanagedDocumentWriterVTable)));
}
//------------------------------------------------------------------------------
// Returns the underlying ISymUnmanagedDocumentWriter* (as a safehandle.)
//------------------------------------------------------------------------------
internal PunkSafeHandle GetUnmanaged()
{
return m_pDocumentWriterSafeHandle;
}
//=========================================================================================
// Public interface methods start here. (Well actually, they're all NotSupported
// stubs since that's what they are on the real ISymWrapper.dll.)
//=========================================================================================
//------------------------------------------------------------------------------
// SetSource() wrapper
//------------------------------------------------------------------------------
void ISymbolDocumentWriter.SetSource(byte[] source)
{
throw new NotSupportedException(); // Intentionally not supported to match desktop CLR
}
//------------------------------------------------------------------------------
// SetCheckSum() wrapper
//------------------------------------------------------------------------------
void ISymbolDocumentWriter.SetCheckSum(Guid algorithmId, byte[] checkSum)
{
int hr = m_vtable.SetCheckSum(m_pDocWriter, algorithmId, (uint)checkSum.Length, checkSum);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
private delegate int DSetCheckSum(ISymUnmanagedDocumentWriter* pThis, Guid algorithmId, uint checkSumSize, [In] byte[] checkSum);
//------------------------------------------------------------------------------
// This layout must match the unmanaged ISymUnmanagedDocumentWriter* COM vtable
// exactly. If a member is declared as an IntPtr rather than a delegate, it means
// we don't call that particular member.
//------------------------------------------------------------------------------
[StructLayout(LayoutKind.Sequential)]
private struct ISymUnmanagedDocumentWriterVTable
{
internal IntPtr QueryInterface;
internal IntPtr AddRef;
internal IntPtr Release;
internal IntPtr SetSource;
internal DSetCheckSum SetCheckSum;
}
//------------------------------------------------------------------------------
// This layout must match the (start) of the unmanaged ISymUnmanagedDocumentWriter
// COM object.
//------------------------------------------------------------------------------
[StructLayout(LayoutKind.Sequential)]
private struct ISymUnmanagedDocumentWriter
{
internal IntPtr m_unmanagedVTable;
}
//------------------------------------------------------------------------------
// Stores underlying ISymUnmanagedDocumentWriter* pointer (wrapped in a safehandle.)
//------------------------------------------------------------------------------
private PunkSafeHandle m_pDocumentWriterSafeHandle;
private ISymUnmanagedDocumentWriter* m_pDocWriter;
//------------------------------------------------------------------------------
// Stores the "managed vtable" (actually a structure full of delegates that
// P/Invoke to the corresponding unmanaged COM methods.)
//------------------------------------------------------------------------------
private ISymUnmanagedDocumentWriterVTable m_vtable;
} // class SymDocumentWriter
//------------------------------------------------------------------------------
// Implements Telesto's version of SymWriter (in the desktop world,
// this type is expored from ISymWrapper.dll.)
//------------------------------------------------------------------------------
internal unsafe class SymWriter : ISymbolWriter
{
//------------------------------------------------------------------------------
// Creates a SymWriter. The SymWriter is a managed wrapper around the unmanaged
// symbol writer provided by the runtime (ildbsymlib or diasymreader.dll).
//------------------------------------------------------------------------------
internal static ISymbolWriter CreateSymWriter()
{
return new SymWriter();
}
//------------------------------------------------------------------------------
// Basic ctor. You'd think this ctor would take the unmanaged symwriter object as an argument
// but to fit in with existing desktop code, the unmanaged writer is passed in
// through a subsequent call to InternalSetUnderlyingWriter
//------------------------------------------------------------------------------
private SymWriter()
{
}
//------------------------------------------------------------------------------
// DefineDocument() wrapper
//------------------------------------------------------------------------------
ISymbolDocumentWriter ISymbolWriter.DefineDocument(String url,
Guid language,
Guid languageVendor,
Guid documentType)
{
PunkSafeHandle psymUnmanagedDocumentWriter = new PunkSafeHandle();
int hr = m_vtable.DefineDocument(m_pWriter, url, ref language, ref languageVendor, ref documentType, out psymUnmanagedDocumentWriter);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
if (psymUnmanagedDocumentWriter.IsInvalid)
{
return null;
}
return new SymDocumentWriter(psymUnmanagedDocumentWriter);
}
//------------------------------------------------------------------------------
// OpenMethod() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.OpenMethod(SymbolToken method)
{
int hr = m_vtable.OpenMethod(m_pWriter, method.GetToken());
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// CloseMethod() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.CloseMethod()
{
int hr = m_vtable.CloseMethod(m_pWriter);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// DefineSequencePoints() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.DefineSequencePoints(ISymbolDocumentWriter document,
int[] offsets,
int[] lines,
int[] columns,
int[] endLines,
int[] endColumns)
{
int spCount = 0;
if (offsets != null)
{
spCount = offsets.Length;
}
else if (lines != null)
{
spCount = lines.Length;
}
else if (columns != null)
{
spCount = columns.Length;
}
else if (endLines != null)
{
spCount = endLines.Length;
}
else if (endColumns != null)
{
spCount = endColumns.Length;
}
if (spCount == 0)
{
return;
}
if ((offsets != null && offsets.Length != spCount) ||
(lines != null && lines.Length != spCount) ||
(columns != null && columns.Length != spCount) ||
(endLines != null && endLines.Length != spCount) ||
(endColumns != null && endColumns.Length != spCount))
{
throw new ArgumentException();
}
// Sure, claim to accept any type that implements ISymbolDocumentWriter but the only one that actually
// works is the one returned by DefineDocument. The desktop ISymWrapper commits the same signature fraud.
// Ideally we'd just return a sealed opaque cookie type, which had an internal accessor to
// get the writer out.
// Regardless, this cast is important for security - we cannot allow our caller to provide
// arbitrary instances of this interface.
SymDocumentWriter docwriter = (SymDocumentWriter)document;
int hr = m_vtable.DefineSequencePoints(m_pWriter, docwriter.GetUnmanaged(), spCount, offsets, lines, columns, endLines, endColumns);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// OpenScope() wrapper
//------------------------------------------------------------------------------
int ISymbolWriter.OpenScope(int startOffset)
{
int ret;
int hr = m_vtable.OpenScope(m_pWriter, startOffset, out ret);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
return ret;
}
//------------------------------------------------------------------------------
// CloseScope() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.CloseScope(int endOffset)
{
int hr = m_vtable.CloseScope(m_pWriter, endOffset);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// DefineLocalVariable() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.DefineLocalVariable(String name,
FieldAttributes attributes,
byte[] signature,
SymAddressKind addrKind,
int addr1,
int addr2,
int addr3,
int startOffset,
int endOffset)
{
int hr = m_vtable.DefineLocalVariable(m_pWriter,
name,
(int)attributes,
signature.Length,
signature,
(int)addrKind,
addr1,
addr2,
addr3,
startOffset,
endOffset);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// SetSymAttribute() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.SetSymAttribute(SymbolToken parent, String name, byte[] data)
{
int hr = m_vtable.SetSymAttribute(m_pWriter, parent.GetToken(), name, data.Length, data);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// UsingNamespace() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.UsingNamespace(String name)
{
int hr = m_vtable.UsingNamespace(m_pWriter, name);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// InternalSetUnderlyingWriter() wrapper.
//
// Furnishes the native ISymUnmanagedWriter* pointer.
//
// The parameter is actually a pointer to a pointer to an ISymUnmanagedWriter. As
// with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on pointers
// furnished through SetUnderlyingWriter. Lifetime management is entirely up to the caller.
//------------------------------------------------------------------------------
internal void InternalSetUnderlyingWriter(IntPtr ppUnderlyingWriter)
{
m_pWriter = *((ISymUnmanagedWriter**)ppUnderlyingWriter);
m_vtable = (ISymUnmanagedWriterVTable)(Marshal.PtrToStructure(m_pWriter->m_unmanagedVTable, typeof(ISymUnmanagedWriterVTable)));
}
//------------------------------------------------------------------------------
// Define delegates for the unmanaged COM methods we invoke.
//------------------------------------------------------------------------------
private delegate int DInitialize(ISymUnmanagedWriter* pthis,
IntPtr emitter, //IUnknown*
[MarshalAs(UnmanagedType.LPWStr)] String filename, //WCHAR*
IntPtr pIStream, //IStream*
[MarshalAs(UnmanagedType.Bool)] bool fFullBuild
);
private delegate int DDefineDocument(ISymUnmanagedWriter* pthis,
[MarshalAs(UnmanagedType.LPWStr)] String url,
[In] ref Guid language,
[In] ref Guid languageVender,
[In] ref Guid documentType,
[Out] out PunkSafeHandle ppsymUnmanagedDocumentWriter
);
private delegate int DSetUserEntryPoint(ISymUnmanagedWriter* pthis, int entryMethod);
private delegate int DOpenMethod(ISymUnmanagedWriter* pthis, int entryMethod);
private delegate int DCloseMethod(ISymUnmanagedWriter* pthis);
private delegate int DDefineSequencePoints(ISymUnmanagedWriter* pthis,
PunkSafeHandle document,
int spCount,
[In] int[] offsets,
[In] int[] lines,
[In] int[] columns,
[In] int[] endLines,
[In] int[] endColumns);
private delegate int DOpenScope(ISymUnmanagedWriter* pthis, int startOffset, [Out] out int pretval);
private delegate int DCloseScope(ISymUnmanagedWriter* pthis, int endOffset);
private delegate int DSetScopeRange(ISymUnmanagedWriter* pthis, int scopeID, int startOffset, int endOffset);
private delegate int DDefineLocalVariable(ISymUnmanagedWriter* pthis,
[MarshalAs(UnmanagedType.LPWStr)] String name,
int attributes,
int cSig,
[In] byte[] signature,
int addrKind,
int addr1,
int addr2,
int addr3,
int startOffset,
int endOffset
);
private delegate int DClose(ISymUnmanagedWriter* pthis);
private delegate int DSetSymAttribute(ISymUnmanagedWriter* pthis,
int parent,
[MarshalAs(UnmanagedType.LPWStr)] String name,
int cData,
[In] byte[] data
);
private delegate int DOpenNamespace(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name);
private delegate int DCloseNamespace(ISymUnmanagedWriter* pthis);
private delegate int DUsingNamespace(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name);
//------------------------------------------------------------------------------
// This layout must match the unmanaged ISymUnmanagedWriter* COM vtable
// exactly. If a member is declared as an IntPtr rather than a delegate, it means
// we don't call that particular member.
//------------------------------------------------------------------------------
[StructLayout(LayoutKind.Sequential)]
private struct ISymUnmanagedWriterVTable
{
internal IntPtr QueryInterface;
internal IntPtr AddRef;
internal IntPtr Release;
internal DDefineDocument DefineDocument;
internal DSetUserEntryPoint SetUserEntryPoint;
internal DOpenMethod OpenMethod;
internal DCloseMethod CloseMethod;
internal DOpenScope OpenScope;
internal DCloseScope CloseScope;
internal DSetScopeRange SetScopeRange;
internal DDefineLocalVariable DefineLocalVariable;
internal IntPtr DefineParameter;
internal IntPtr DefineField;
internal IntPtr DefineGlobalVariable;
internal DClose Close;
internal DSetSymAttribute SetSymAttribute;
internal DOpenNamespace OpenNamespace;
internal DCloseNamespace CloseNamespace;
internal DUsingNamespace UsingNamespace;
internal IntPtr SetMethodSourceRange;
internal DInitialize Initialize;
internal IntPtr GetDebugInfo;
internal DDefineSequencePoints DefineSequencePoints;
}
//------------------------------------------------------------------------------
// This layout must match the (start) of the unmanaged ISymUnmanagedWriter
// COM object.
//------------------------------------------------------------------------------
[StructLayout(LayoutKind.Sequential)]
private struct ISymUnmanagedWriter
{
internal IntPtr m_unmanagedVTable;
}
//------------------------------------------------------------------------------
// Stores native ISymUnmanagedWriter* pointer.
//
// As with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on this pointer.
// Managing lifetime is up to the caller (coreclr.dll).
//------------------------------------------------------------------------------
private ISymUnmanagedWriter* m_pWriter;
//------------------------------------------------------------------------------
// Stores the "managed vtable" (actually a structure full of delegates that
// P/Invoke to the corresponding unmanaged COM methods.)
//------------------------------------------------------------------------------
private ISymUnmanagedWriterVTable m_vtable;
} // class SymWriter
} //class SymWrapperCore
//--------------------------------------------------------------------------------------
// SafeHandle for RAW MTA IUnknown's.
//
// ! Because the Release occurs in the finalizer thread, this safehandle really takes
// ! an ostrich approach to apartment issues. We only tolerate this here because we're emulating
// ! the desktop CLR's use of ISymWrapper which also pays lip service to COM apartment rules.
// !
// ! However, think twice about pulling this safehandle out for other uses.
//
// Had to make this a non-nested class since FCall's don't like to bind to nested classes.
//--------------------------------------------------------------------------------------
internal sealed class PunkSafeHandle : SafeHandle
{
internal PunkSafeHandle()
: base((IntPtr)0, true)
{
}
override protected bool ReleaseHandle()
{
m_Release(handle);
return true;
}
public override bool IsInvalid
{
get { return handle == ((IntPtr)0); }
}
private delegate void DRelease(IntPtr punk); // Delegate type for P/Invoking to coreclr.dll and doing an IUnknown::Release()
private static DRelease m_Release;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr nGetDReleaseTarget(); // FCall gets us the native DRelease target (so we don't need named dllexport from coreclr.dll)
static PunkSafeHandle()
{
m_Release = (DRelease)(Marshal.GetDelegateForFunctionPointer(nGetDReleaseTarget(), typeof(DRelease)));
m_Release((IntPtr)0); // make one call to make sure the delegate is fully prepped before we're in the critical finalizer situation.
}
} // PunkSafeHandle
} //namespace System.Reflection.Emit
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.14.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Groups Migration API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/google-apps/groups-migration/'>Groups Migration API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20140416 (0)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/google-apps/groups-migration/'>
* https://developers.google.com/google-apps/groups-migration/</a>
* <tr><th>Discovery Name<td>groupsmigration
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Groups Migration API can be found at
* <a href='https://developers.google.com/google-apps/groups-migration/'>https://developers.google.com/google-apps/groups-migration/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.GroupsMigration.v1
{
/// <summary>The GroupsMigration Service.</summary>
public class GroupsMigrationService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public GroupsMigrationService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public GroupsMigrationService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
archive = new ArchiveResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "groupsmigration"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/groups/v1/groups/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "groups/v1/groups/"; }
}
/// <summary>Available OAuth 2.0 scopes for use with the Groups Migration API.</summary>
public class Scope
{
/// <summary>Manage messages in groups on your domain</summary>
public static string AppsGroupsMigration = "https://www.googleapis.com/auth/apps.groups.migration";
}
private readonly ArchiveResource archive;
/// <summary>Gets the Archive resource.</summary>
public virtual ArchiveResource Archive
{
get { return archive; }
}
}
///<summary>A base abstract class for GroupsMigration requests.</summary>
public abstract class GroupsMigrationBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new GroupsMigrationBaseServiceRequest instance.</summary>
protected GroupsMigrationBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes GroupsMigration parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "archive" collection of methods.</summary>
public class ArchiveResource
{
private const string Resource = "archive";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ArchiveResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Inserts a new mail into the archive of the Google group.</summary>
/// <param name="groupId">The group ID</param>
public virtual InsertRequest Insert(string groupId)
{
return new InsertRequest(service, groupId);
}
/// <summary>Inserts a new mail into the archive of the Google group.</summary>
public class InsertRequest : GroupsMigrationBaseServiceRequest<Google.Apis.GroupsMigration.v1.Data.Groups>
{
/// <summary>Constructs a new Insert request.</summary>
public InsertRequest(Google.Apis.Services.IClientService service, string groupId)
: base(service)
{
GroupId = groupId;
InitParameters();
}
/// <summary>The group ID</summary>
[Google.Apis.Util.RequestParameterAttribute("groupId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string GroupId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "insert"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{groupId}/archive"; }
}
/// <summary>Initializes Insert parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"groupId", new Google.Apis.Discovery.Parameter
{
Name = "groupId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Inserts a new mail into the archive of the Google group.</summary>
/// <param name="groupId">The group ID</param>
/// <param name="stream">The stream to upload.</param>
/// <param name="contentType">The content type of the stream to upload.</param>
public virtual InsertMediaUpload Insert(string groupId, System.IO.Stream stream, string contentType)
{
return new InsertMediaUpload(service, groupId, stream, contentType);
}
/// <summary>Insert media upload which supports resumable upload.</summary>
public class InsertMediaUpload : Google.Apis.Upload.ResumableUpload<string, Google.Apis.GroupsMigration.v1.Data.Groups>
{
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and
/// reports. Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are
/// provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>The group ID</summary>
[Google.Apis.Util.RequestParameterAttribute("groupId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string GroupId { get; private set; }
/// <summary>Constructs a new Insert media upload instance.</summary>
public InsertMediaUpload(Google.Apis.Services.IClientService service, string
groupId, System.IO.Stream stream, string contentType)
: base(service, string.Format("/{0}/{1}{2}", "upload", service.BasePath, "{groupId}/archive"), "POST", stream, contentType)
{
GroupId = groupId;
}
}
}
}
namespace Google.Apis.GroupsMigration.v1.Data
{
/// <summary>JSON response template for groups migration API.</summary>
public class Groups : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The kind of insert resource this is.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The status of the insert request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("responseCode")]
public virtual string ResponseCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Identity Verification History
///<para>SObject Name: VerificationHistory</para>
///<para>Custom Object: False</para>
///</summary>
public class SfVerificationHistory : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "VerificationHistory"; }
}
///<summary>
/// Identity Verification ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Verification Attempt
/// <para>Name: EventGroup</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "eventGroup")]
[Updateable(false), Createable(false)]
public int? EventGroup { get; set; }
///<summary>
/// Time
/// <para>Name: VerificationTime</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "verificationTime")]
[Updateable(false), Createable(false)]
public DateTimeOffset? VerificationTime { get; set; }
///<summary>
/// Method
/// <para>Name: VerificationMethod</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "verificationMethod")]
[Updateable(false), Createable(false)]
public string VerificationMethod { get; set; }
///<summary>
/// User ID
/// <para>Name: UserId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "userId")]
[Updateable(false), Createable(false)]
public string UserId { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: User</para>
///</summary>
[JsonProperty(PropertyName = "user")]
[Updateable(false), Createable(false)]
public SfUser User { get; set; }
///<summary>
/// User Activity
/// <para>Name: Activity</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "activity")]
[Updateable(false), Createable(false)]
public string Activity { get; set; }
///<summary>
/// Status
/// <para>Name: Status</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "status")]
[Updateable(false), Createable(false)]
public string Status { get; set; }
///<summary>
/// Login History ID
/// <para>Name: LoginHistoryId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "loginHistoryId")]
[Updateable(false), Createable(false)]
public string LoginHistoryId { get; set; }
///<summary>
/// ReferenceTo: LoginHistory
/// <para>RelationshipName: LoginHistory</para>
///</summary>
[JsonProperty(PropertyName = "loginHistory")]
[Updateable(false), Createable(false)]
public SfLoginHistory LoginHistory { get; set; }
///<summary>
/// Source IP
/// <para>Name: SourceIp</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "sourceIp")]
[Updateable(false), Createable(false)]
public string SourceIp { get; set; }
///<summary>
/// Login Geo Data ID
/// <para>Name: LoginGeoId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "loginGeoId")]
[Updateable(false), Createable(false)]
public string LoginGeoId { get; set; }
///<summary>
/// ReferenceTo: LoginGeo
/// <para>RelationshipName: LoginGeo</para>
///</summary>
[JsonProperty(PropertyName = "loginGeo")]
[Updateable(false), Createable(false)]
public SfLoginGeo LoginGeo { get; set; }
///<summary>
/// Activity Message
/// <para>Name: Remarks</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "remarks")]
[Updateable(false), Createable(false)]
public string Remarks { get; set; }
///<summary>
/// Connected App ID
/// <para>Name: ResourceId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "resourceId")]
[Updateable(false), Createable(false)]
public string ResourceId { get; set; }
///<summary>
/// ReferenceTo: ConnectedApplication
/// <para>RelationshipName: Resource</para>
///</summary>
[JsonProperty(PropertyName = "resource")]
[Updateable(false), Createable(false)]
public SfConnectedApplication Resource { get; set; }
///<summary>
/// Triggered By
/// <para>Name: Policy</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "policy")]
[Updateable(false), Createable(false)]
public string Policy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
}
}
| |
using System.IO;
using System.Text;
using System.Collections.Generic;
using Raccoon.Log;
namespace Raccoon {
public class StdOutputLoggerListener : ILoggerListener {
#region Private Members
private TextWriter _out;
private Dictionary<System.Type, TextFormatter> _contexts;
private Dictionary<string, TextFormatter> _categories;
private int _categorySectionLength;
private List<int> _sectionsTextLength = new List<int>();
#endregion Private Members
#region Constructors
public StdOutputLoggerListener() {
_out = System.Console.Out;
System.Console.OutputEncoding = new UTF8Encoding();
_contexts = new Dictionary<System.Type, TextFormatter> {
{
typeof(TimestampLoggerToken),
new TextFormatter() {
ForegroundColor = System.ConsoleColor.DarkGray
}
},
{
typeof(SubjectsLoggerToken),
new TextFormatter() {
ForegroundColor = System.ConsoleColor.DarkGray
}
}
};
_categories = new Dictionary<string, TextFormatter> {
{
"error",
new TextFormatter() {
ForegroundColor = System.ConsoleColor.Red
}
},
{
"info",
new TextFormatter() {
ForegroundColor = System.ConsoleColor.Blue
}
},
{
"warning",
new TextFormatter() {
ForegroundColor = System.ConsoleColor.Yellow
}
},
{
"critical",
new TextFormatter() {
ForegroundColor = System.ConsoleColor.DarkYellow
}
},
{
"success",
new TextFormatter() {
ForegroundColor = System.ConsoleColor.Green
}
}
};
// find category section length
foreach (string key in _categories.Keys) {
if (key.Length > _categorySectionLength) {
_categorySectionLength = key.Length;
}
}
}
#endregion Constructors
#region Public Properties
public bool IsDisposed { get; private set; }
#endregion Public Properties
#region Public Methods
public void WriteTokens(MessageLoggerTokenTree tokens) {
if (tokens == null) {
throw new System.ArgumentNullException(nameof(tokens));
}
if (tokens.HeaderToken != null) {
HeaderLoggerToken header = tokens.HeaderToken;
if (header.TimestampToken != null) {
CalculateLeftPadding(0, header.TimestampToken.Timestamp);
WriteToken<TimestampLoggerToken>(header.TimestampToken.Timestamp);
WriteMessage(" ");
} else {
WritePadding(sectionId: 0);
}
if (header.CategoryToken != null) {
string formatedCategoryName = string.Format($"{{0,{_categorySectionLength}}}", header.CategoryToken.CategoryName);
CalculateLeftPadding(1, formatedCategoryName);
if (_categories.TryGetValue(header.CategoryToken.CategoryName, out TextFormatter categoryFormatter)) {
WriteFormattedMessage(formatedCategoryName, categoryFormatter);
} else {
WriteToken<CategoryLoggerToken>(formatedCategoryName);
}
WriteMessage(" ");
} else {
WritePadding(sectionId: 1);
}
if (header.SubjectsToken != null
&& header.SubjectsToken.Subjects.Count > 0) {
string representation = header.SubjectsToken.Subjects[0];
for (int i = 1; i < header.SubjectsToken.Subjects.Count; i++) {
representation += "->" + header.SubjectsToken.Subjects[i];
}
WriteToken<SubjectsLoggerToken>(representation);
WriteMessage(" ");
}
}
if (tokens.TextToken != null) {
WriteToken<TextLoggerToken>(tokens.TextToken.Text);
}
Flush();
}
/*
public Context GetContext(string contextIdentifier) {
if (_contexts.TryGetValue(contextIdentifier, out Context context)) {
return context;
}
return null;
}
public void RegisterContext(string contextIdentifier, Context context, bool overrides = false) {
if (overrides) {
_contexts[contextIdentifier] = context;
return;
}
if (_contexts.ContainsKey(contextIdentifier)) {
throw new System.InvalidOperationException($"Context indentifier '{contextIdentifier}' is already registered.");
}
_contexts.Add(contextIdentifier, context);
}
public bool RemoveContext(string contextIdentifier) {
return _contexts.Remove(contextIdentifier);
}
public void ClearContexts() {
_contexts.Clear();
}
*/
public void Dispose() {
if (IsDisposed) {
return;
}
_out = null;
_contexts.Clear();
IsDisposed = true;
}
#endregion Public Methods
#region Protected Methods
protected void WriteToken<T>(string representation) where T : LoggerToken {
if (_contexts.TryGetValue(typeof(T), out TextFormatter textFormatter)) {
WriteFormattedMessage(representation, textFormatter);
return;
}
WriteMessage(representation);
}
protected virtual void WriteFormattedMessage(string message, TextFormatter formatter) {
if (formatter.ForegroundColor.HasValue) {
System.Console.ForegroundColor = formatter.ForegroundColor.Value;
}
if (formatter.BackgroundColor.HasValue) {
System.Console.BackgroundColor = formatter.BackgroundColor.Value;
}
WriteMessage(message);
System.Console.ResetColor();
}
protected virtual void WriteMessage(string message) {
_out.Write(message);
}
protected virtual void Flush() {
_out.Flush();
}
#endregion Protected Methods
#region Private Methods
private void CalculateLeftPadding(int sectionId, string text) {
if (sectionId < _sectionsTextLength.Count) {
_sectionsTextLength[sectionId] = text.Length + 2; // 2 => section spacing
} else {
_sectionsTextLength.Add(text.Length + 2);
}
}
private void WritePadding(int sectionId) {
if (_sectionsTextLength.Count > sectionId) {
WriteMessage(new string(' ', _sectionsTextLength[sectionId]));
}
}
#endregion Private Methods
#region TextFormatter Class
public class TextFormatter {
public TextFormatter() {
}
public System.ConsoleColor? ForegroundColor { get; set; }
public System.ConsoleColor? BackgroundColor { get; set; }
}
#endregion TextFormatter Class
}
}
| |
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.Serialization;
namespace DDay.iCal
{
/// <summary>
/// A class that contains time zone information, and is usually accessed
/// from an iCalendar object using the <see cref="DDay.iCal.iCalendar.GetTimeZone"/> method.
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
#pragma warning disable 0659
public class iCalTimeZoneInfo :
CalendarComponent,
ITimeZoneInfo
{
#region Private Fields
TimeZoneInfoEvaluator m_Evaluator;
#pragma warning disable 0169
DateTime m_End;
#pragma warning restore 0169
#endregion
#region Constructors
public iCalTimeZoneInfo() : base()
{
// FIXME: how do we ensure SEQUENCE doesn't get serialized?
//base.Sequence = null;
// iCalTimeZoneInfo does not allow sequence numbers
// Perhaps we should have a custom serializer that fixes this?
Initialize();
}
public iCalTimeZoneInfo(string name) : this()
{
this.Name = name;
}
void Initialize()
{
m_Evaluator = new TimeZoneInfoEvaluator(this);
SetService(m_Evaluator);
}
#endregion
#region Overrides
protected override void OnDeserializing(StreamingContext context)
{
base.OnDeserializing(context);
Initialize();
}
public override bool Equals(object obj)
{
iCalTimeZoneInfo tzi = obj as iCalTimeZoneInfo;
if (tzi != null)
{
return object.Equals(TimeZoneName, tzi.TimeZoneName) &&
object.Equals(OffsetFrom, tzi.OffsetFrom) &&
object.Equals(OffsetTo, tzi.OffsetTo);
}
return base.Equals(obj);
}
#endregion
#region ITimeZoneInfo Members
virtual public string TZID
{
get
{
ITimeZone tz = Parent as ITimeZone;
if (tz != null)
return tz.TZID;
return null;
}
}
/// <summary>
/// Returns the name of the current Time Zone.
/// <example>
/// The following are examples:
/// <list type="bullet">
/// <item>EST</item>
/// <item>EDT</item>
/// <item>MST</item>
/// <item>MDT</item>
/// </list>
/// </example>
/// </summary>
virtual public string TimeZoneName
{
get
{
if (TimeZoneNames.Count > 0)
return TimeZoneNames[0];
return null;
}
set
{
TimeZoneNames.Clear();
TimeZoneNames.Add(value);
}
}
virtual public IUTCOffset TZOffsetFrom
{
get { return OffsetFrom; }
set { OffsetFrom = value; }
}
virtual public IUTCOffset OffsetFrom
{
get { return Properties.Get<IUTCOffset>("TZOFFSETFROM"); }
set { Properties.Set("TZOFFSETFROM", value); }
}
virtual public IUTCOffset OffsetTo
{
get { return Properties.Get<IUTCOffset>("TZOFFSETTO"); }
set { Properties.Set("TZOFFSETTO", value); }
}
virtual public IUTCOffset TZOffsetTo
{
get { return OffsetTo; }
set { OffsetTo = value; }
}
virtual public IList<string> TimeZoneNames
{
get { return Properties.GetMany<string>("TZNAME"); }
set { Properties.Set("TZNAME", value); }
}
virtual public TimeZoneObservance? GetObservance(IDateTime dt)
{
if (Parent == null)
throw new Exception("Cannot call GetObservance() on a TimeZoneInfo whose Parent property is null.");
if (string.Equals(dt.TZID, TZID))
{
// Normalize date/time values within this time zone to a local value.
DateTime normalizedDt = dt.Value;
// Let's evaluate our time zone observances to find the
// observance that applies to this date/time value.
IEvaluator parentEval = Parent.GetService(typeof(IEvaluator)) as IEvaluator;
if (parentEval != null)
{
// Evaluate the date/time in question.
parentEval.Evaluate(Start, DateUtil.GetSimpleDateTimeData(Start), normalizedDt, true);
// NOTE: We avoid using period.Contains here, because we want to avoid
// doing an inadvertent time zone lookup with it.
var period = m_Evaluator
.Periods
.FirstOrDefault(p =>
p.StartTime.Value <= normalizedDt &&
p.EndTime.Value > normalizedDt
);
if (period != null)
{
return new TimeZoneObservance(period, this);
}
}
}
return null;
}
virtual public bool Contains(IDateTime dt)
{
TimeZoneObservance? retval = GetObservance(dt);
return (retval != null && retval.HasValue);
}
#endregion
#region IRecurrable Members
virtual public IDateTime DTStart
{
get { return Start; }
set { Start = value; }
}
virtual public IDateTime Start
{
get { return Properties.Get<IDateTime>("DTSTART"); }
set { Properties.Set("DTSTART", value); }
}
virtual public IList<IPeriodList> ExceptionDates
{
get { return Properties.GetMany<IPeriodList>("EXDATE"); }
set { Properties.Set("EXDATE", value); }
}
virtual public IList<IRecurrencePattern> ExceptionRules
{
get { return Properties.GetMany<IRecurrencePattern>("EXRULE"); }
set { Properties.Set("EXRULE", value); }
}
virtual public IList<IPeriodList> RecurrenceDates
{
get { return Properties.GetMany<IPeriodList>("RDATE"); }
set { Properties.Set("RDATE", value); }
}
virtual public IList<IRecurrencePattern> RecurrenceRules
{
get { return Properties.GetMany<IRecurrencePattern>("RRULE"); }
set { Properties.Set("RRULE", value); }
}
virtual public IDateTime RecurrenceID
{
get { return Properties.Get<IDateTime>("RECURRENCE-ID"); }
set { Properties.Set("RECURRENCE-ID", value); }
}
#endregion
#region IRecurrable Members
virtual public void ClearEvaluation()
{
RecurrenceUtil.ClearEvaluation(this);
}
virtual public IList<Occurrence> GetOccurrences(IDateTime dt)
{
return RecurrenceUtil.GetOccurrences(this, dt, true);
}
virtual public IList<Occurrence> GetOccurrences(DateTime dt)
{
return RecurrenceUtil.GetOccurrences(this, new iCalDateTime(dt), true);
}
virtual public IList<Occurrence> GetOccurrences(IDateTime startTime, IDateTime endTime)
{
return RecurrenceUtil.GetOccurrences(this, startTime, endTime, true);
}
virtual public IList<Occurrence> GetOccurrences(DateTime startTime, DateTime endTime)
{
return RecurrenceUtil.GetOccurrences(this, new iCalDateTime(startTime), new iCalDateTime(endTime), true);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using Mischel.Collections;
using OpenMetaverse;
using Aurora.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.ClientStack.LindenUDP
{
public class LLImageManager
{
private readonly IAssetService m_assetCache; //Asset Cache
private readonly LLClientView m_client; //Client we're assigned to
private readonly IJ2KDecoder m_j2kDecodeModule; //Our J2K module
private static AssetBase m_missingImage;
private readonly PriorityQueue<J2KImage, float> m_queue = new PriorityQueue<J2KImage, float>();
private readonly object m_syncRoot = new object();
private bool m_shuttingdown;
public LLImageManager(LLClientView client, IAssetService pAssetCache, IJ2KDecoder pJ2kDecodeModule)
{
m_client = client;
m_assetCache = pAssetCache;
if (pAssetCache != null && m_missingImage == null)
m_missingImage = pAssetCache.Get("5748decc-f629-461c-9a36-a35a221fe21f");
if (m_missingImage == null)
MainConsole.Instance.Error(
"[ClientView] - Couldn't set missing image asset, falling back to missing image packet. This is known to crash the client");
m_j2kDecodeModule = pJ2kDecodeModule;
}
public LLClientView Client
{
get { return m_client; }
}
public AssetBase MissingImage
{
get { return m_missingImage; }
}
/// <summary>
/// Handles an incoming texture request or update to an existing texture request
/// </summary>
/// <param name = "newRequest"></param>
public void EnqueueReq(TextureRequestArgs newRequest)
{
//Make sure we're not shutting down..
if (!m_shuttingdown)
{
// Do a linear search for this texture download
J2KImage imgrequest = FindImage(newRequest);
if (imgrequest != null)
{
if (newRequest.DiscardLevel == -1 && newRequest.Priority == 0f)
{
//MainConsole.Instance.Debug("[TEX]: (CAN) ID=" + newRequest.RequestedAssetID);
try
{
lock (m_syncRoot)
m_queue.Remove(imgrequest);
}
catch (Exception)
{
}
}
else
{
//MainConsole.Instance.DebugFormat("[TEX]: (UPD) ID={0}: D={1}, S={2}, P={3}",
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
//Check the packet sequence to make sure this isn't older than
//one we've already received
if (newRequest.requestSequence > imgrequest.LastSequence)
{
//Update the sequence number of the last RequestImage packet
imgrequest.LastSequence = newRequest.requestSequence;
//Update the requested discard level
imgrequest.DiscardLevel = newRequest.DiscardLevel;
//Update the requested packet number
imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
//Update the requested priority
imgrequest.Priority = newRequest.Priority;
lock(m_syncRoot)
m_queue.Remove(imgrequest);
AddImageToQueue(imgrequest);
//Run an update
imgrequest.RunUpdate();
}
}
}
else
{
if (newRequest.DiscardLevel == -1 && newRequest.Priority == 0f)
{
//MainConsole.Instance.Debug("[TEX]: (CAN) ID=" + newRequest.RequestedAssetID);
//MainConsole.Instance.DebugFormat("[TEX]: (IGN) ID={0}: D={1}, S={2}, P={3}",
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
}
else
{
//MainConsole.Instance.DebugFormat("[TEX]: (NEW) ID={0}: D={1}, S={2}, P={3}",
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
imgrequest = new J2KImage(this)
{
J2KDecoder = m_j2kDecodeModule,
AssetService = m_assetCache,
AgentID = m_client.AgentId,
InventoryAccessModule =
m_client.Scene.RequestModuleInterface<IInventoryAccessModule>(),
DiscardLevel = newRequest.DiscardLevel,
StartPacket = Math.Max(1, newRequest.PacketNumber),
Priority = newRequest.Priority,
TextureID = newRequest.RequestedAssetID
};
imgrequest.Priority = newRequest.Priority;
//Add this download to the priority queue
AddImageToQueue(imgrequest);
//Run an update
imgrequest.RunUpdate();
}
}
}
}
private J2KImage FindImage(TextureRequestArgs newRequest)
{
if (newRequest == null)
return null;
lock (m_syncRoot)
return m_queue.Find(new J2KImage(this) {TextureID = newRequest.RequestedAssetID},
new Comparer());
}
public bool ProcessImageQueue(int packetsToSend)
{
int StartTime = Util.EnvironmentTickCount();
int packetsSent = 0;
List<J2KImage> imagesToReAdd = new List<J2KImage>();
while (packetsSent < packetsToSend)
{
J2KImage image = GetHighestPriorityImage();
// If null was returned, the texture priority queue is currently empty
if (image == null)
break;
//Break so that we add any images back that we might remove because they arn't finished decoding
if (image.IsDecoded)
{
if (image.Layers == null)
{
//We don't have it, tell the client that it doesn't exist
m_client.SendAssetUploadCompleteMessage((sbyte) AssetType.Texture, false, image.TextureID);
packetsSent++;
}
else
{
int sent;
bool imageDone = image.SendPackets(m_client, packetsToSend - packetsSent, out sent);
packetsSent += sent;
// If the send is complete, destroy any knowledge of this transfer
if (!imageDone)
AddImageToQueue(image);
}
}
else
{
//Add it to the other queue and delete it from the top
imagesToReAdd.Add(image);
packetsSent++; //We tried to send one
// UNTODO: This was a limitation of how LLImageManager is currently
// written. Undecoded textures should not be going into the priority
// queue, because a high priority undecoded texture will clog up the
// pipeline for a client
//return true;
}
}
//Add all the ones we removed so that we wouldn't block the queue
if (imagesToReAdd.Count != 0)
{
foreach (J2KImage image in imagesToReAdd)
{
AddImageToQueue(image);
}
}
int EndTime = Util.EnvironmentTickCountSubtract(StartTime);
IMonitorModule module = m_client.Scene.RequestModuleInterface<IMonitorModule>();
if (module != null)
{
IImageFrameTimeMonitor monitor =
(IImageFrameTimeMonitor)
module.GetMonitor(m_client.Scene.RegionInfo.RegionID.ToString(), MonitorModuleHelper.ImagesFrameTime);
monitor.AddImageTime(EndTime);
}
lock (m_syncRoot)
return m_queue.Count > 0;
}
/// <summary>
/// Faux destructor
/// </summary>
public void Close()
{
m_shuttingdown = true;
}
#region Priority Queue Helpers
private J2KImage GetHighestPriorityImage()
{
J2KImage image = null;
lock (m_syncRoot)
{
if (m_queue.Count > 0)
{
try
{
PriorityQueueItem<J2KImage, float> item;
if (m_queue.TryDequeue(out item))
image = item.Value;
}
catch (Exception)
{
}
}
}
return image;
}
private void AddImageToQueue(J2KImage image)
{
lock (m_syncRoot)
try
{
m_queue.Enqueue(image, image.Priority);
}
catch (Exception)
{
}
}
#endregion Priority Queue Helpers
#region Nested type: Comparer
private class Comparer : IComparer<J2KImage>
{
#region IComparer<J2KImage> Members
public int Compare(J2KImage x, J2KImage y)
{
if (x == null || y == null)
return -1;
if (x.TextureID == y.TextureID)
return 2;
return 0;
}
#endregion
}
#endregion
#region Nested type: J2KImageComparer
/*
private sealed class J2KImageComparer : IComparer<J2KImage>
{
#region IComparer<J2KImage> Members
public int Compare(J2KImage x, J2KImage y)
{
return x.Priority.CompareTo(y.Priority);
}
#endregion
}
*/
#endregion
}
}
| |
// ReSharper disable InconsistentNaming
using NUnit.Framework;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Threading;
namespace EasyNetQ.Tests.Integration
{
[TestFixture]
public class RequestResponseTests
{
private IBus bus;
private const string defaultRpcExchange = "easy_net_q_rpc";
private readonly Dictionary<Type, string> customRpcRequestConventionDictionary = new Dictionary<Type, string>()
{
{typeof (TestModifiedRequestExhangeRequestMessage), "ChangedRpcRequestExchange"}
};
private readonly Dictionary<Type, string> customRpcResponseConventionDictionary = new Dictionary<Type, string>()
{
{typeof (TestModifiedResponseExhangeResponseMessage), "ChangedRpcResponseExchange"}
};
[SetUp]
public void SetUp()
{
bus = RabbitHutch.CreateBus("host=localhost");
bus.Advanced.Conventions.RpcRequestExchangeNamingConvention = type => customRpcRequestConventionDictionary.ContainsKey(type) ? customRpcRequestConventionDictionary[type] : defaultRpcExchange;
bus.Advanced.Conventions.RpcResponseExchangeNamingConvention = type => customRpcResponseConventionDictionary.ContainsKey(type) ? customRpcResponseConventionDictionary[type] : defaultRpcExchange;
bus.Respond<TestRequestMessage, TestResponseMessage>(req => new TestResponseMessage { Text = req.Text });
}
[TearDown]
public void TearDown()
{
bus.Dispose();
}
// First start the EasyNetQ.Tests.SimpleService console app.
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Large_number_of_request_calls_should_not_create_a_large_number_of_open_channels()
{
const int numberOfCalls = 100;
var countdownEvent = new CountdownEvent(numberOfCalls);
for (int i = 0; i < numberOfCalls; i++)
{
bus.RequestAsync<TestRequestMessage, TestResponseMessage>(
new TestRequestMessage {Text = string.Format("Hello from client number: {0}! ", i)})
.ContinueWith(
response =>
{
Console.WriteLine("Got response: " + response.Result.Text);
countdownEvent.Signal();
}
);
}
countdownEvent.Wait(1000);
Console.WriteLine("Test end");
}
// First start the EasyNetQ.Tests.SimpleService console app.
// Run this test. You should see the SimpleService report that it's
// responding and the response should appear here.
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_be_able_to_do_simple_request_response()
{
var request = new TestRequestMessage {Text = "Hello from the client! "};
Console.WriteLine("Making request");
var response = bus.Request<TestRequestMessage, TestResponseMessage>(request);
Console.WriteLine("Got response: '{0}'", response.Text);
}
// First start the EasyNetQ.Tests.SimpleService console app.
// Run this test. You should see the SimpleService report that it's
// responding to 1000 messages and you should see the messages return here.
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_be_able_to_do_simple_request_response_lots()
{
const int numberOfCalls = 5000;
var countdownEvent = new CountdownEvent(numberOfCalls);
var count = 0;
for (int i = 0; i < numberOfCalls; i++)
{
var request = new TestRequestMessage { Text = "Hello from the client! " + i.ToString() };
bus.RequestAsync<TestRequestMessage, TestResponseMessage>(request).ContinueWith(response =>
{
Console.WriteLine("Got response: '{0}'", response.Result.Text);
count++;
countdownEvent.Signal();
});
}
countdownEvent.Wait(15000);
count.ShouldEqual(numberOfCalls);
}
// First start the EasyNetQ.Tests.SimpleService console app.
// Run this test. You should see the SimpleService report that it's
// responding and the response should appear here.
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_be_able_to_make_a_request_that_runs_async_on_the_server()
{
var autoResetEvent = new AutoResetEvent(false);
var request = new TestAsyncRequestMessage {Text = "Hello async from the client!"};
Console.Out.WriteLine("Making request");
bus.RequestAsync<TestAsyncRequestMessage, TestAsyncResponseMessage>(request).ContinueWith(response =>
{
Console.Out.WriteLine("response = {0}", response.Result.Text);
autoResetEvent.Set();
});
autoResetEvent.WaitOne(2000);
}
// First start the EasyNetQ.Tests.SimpleService console app.
// Run this test. You should see the SimpleService report that it's
// responding and the response should appear here.
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_be_able_to_make_a_request_to_customly_defined_exchange()
{
var request = new TestModifiedRequestExhangeRequestMessage { Text = "Hello from the client to funky exchange!" };
Console.Out.WriteLine("Making request");
var response = bus.RequestAsync<TestModifiedRequestExhangeRequestMessage, TestModifiedRequestExhangeResponseMessage>(request);
Console.Out.WriteLine("response = {0}", response.Result.Text);
}
// First start the EasyNetQ.Tests.SimpleService console app.
// Run this test. You should see the SimpleService report that it's
// responding and the response should appear here.
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_be_able_to_make_a_request_and_receive_response_to_customly_defined_exchange()
{
var request = new TestModifiedResponseExhangeRequestMessage { Text = "Hello from the client! I Wanna receive response via funky exchange!" };
Console.Out.WriteLine("Making request");
var response = bus.RequestAsync<TestModifiedResponseExhangeRequestMessage, TestModifiedResponseExhangeResponseMessage>(request);
Console.Out.WriteLine("response = {0}", response.Result.Text);
}
// First start the EasyNetQ.Tests.SimpleService console app.
// Run this test. You should see 1000 response messages on the SimpleService
// and then 1000 messages appear back here.
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_be_able_to_make_many_async_requests()
{
const int numberOfCalls = 500;
var countdownEvent = new CountdownEvent(numberOfCalls);
var count = 0;
for (int i = 0; i < 1000; i++)
{
var request = new TestAsyncRequestMessage { Text = "Hello async from the client! " + i };
bus.RequestAsync<TestAsyncRequestMessage, TestAsyncResponseMessage>(request).ContinueWith(response =>
{
Console.Out.WriteLine("response = {0}", response.Result.Text);
Interlocked.Increment(ref count);
countdownEvent.Signal();
});
}
countdownEvent.Wait(10000);
count.ShouldEqual(numberOfCalls);
}
/// <summary>
/// First start the EasyNetQ.Tests.SimpleService console app.
/// Run this test. You should see an error message written to the error queue
/// and an error logged
/// </summary>
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Service_should_handle_sychronous_message_of_the_wrong_type()
{
const string routingKey = "EasyNetQ_Tests_TestRequestMessage:EasyNetQ_Tests_Messages";
const string type = "not_the_type_you_are_expecting";
MakeRpcRequest(type, routingKey);
}
/// <summary>
/// First start the EasyNetQ.Tests.SimpleService console app.
/// Run this test. You should see an error message written to the error queue
/// and an error logged
/// </summary>
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Service_should_handle_asychronous_message_of_the_wrong_type()
{
const string routingKey = "EasyNetQ_Tests_TestAsyncRequestMessage:EasyNetQ_Tests_Messages";
const string type = "not_the_type_you_are_expecting";
MakeRpcRequest(type, routingKey);
}
private static void MakeRpcRequest(string type, string routingKey)
{
var connectionFactory = new ConnectionFactory
{
HostName = "localhost"
};
using (var connection = connectionFactory.CreateConnection())
using (var model = connection.CreateModel())
{
var properties = model.CreateBasicProperties();
properties.Type = type;
model.BasicPublish(
"easy_net_q_rpc", // exchange
routingKey, // routing key
false, // mandatory
properties,
new byte[0]);
}
}
// First start the EasyNetQ.Tests.SimpleService console app.
// Run this test. You should see the SimpleService report that it's
// Thrown and a new error message in the error queue.
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_be_able_to_do_simple_request_response_that_throws_on_server()
{
var request = new TestRequestMessage
{
Text = "Hello from the client! ",
CausesExceptionInServer = true
};
Console.WriteLine("Making request");
bus.RequestAsync<TestRequestMessage, TestResponseMessage>(request).ContinueWith(response =>
Console.WriteLine("Got response: '{0}'", response.Result.Text));
Thread.Sleep(500);
}
// First start the EasyNetQ.Tests.SimpleService console app.
// Run this test. You should see the SimpleService report that it's
// Thrown, a new error message in the error queue and an EasyNetQResponderException
// exception should be thrown by the consumer as a response.
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
[ExpectedException(ExpectedException = typeof(EasyNetQResponderException), ExpectedMessage = "This should be the original exception message!")]
public void Should_throw_an_exception_at_consumer_on_simple_request_response_that_throws_on_server()
{
var request = new TestRequestMessage
{
Text = "Hello from the client! ",
CausesExceptionInServer = true,
ExceptionInServerMessage = "This should be the original exception message!"
};
Console.WriteLine("Making request");
try
{
bus.RequestAsync<TestRequestMessage, TestResponseMessage>(request).Wait(1000);
}
catch (AggregateException e)
{
throw e.InnerException;
}
}
// First start the EasyNetQ.Tests.SimpleService console app.
// Run this test. You should see the SimpleService report that it's
// responding and the response should appear here with an exception report.
// you should also see a new error message in the error queue.
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_be_able_to_do_simple_request_response_that_throws_on_response_consumer()
{
var autoResetEvent = new AutoResetEvent(false);
var request = new TestRequestMessage { Text = "Hello from the client! " };
Console.WriteLine("Making request");
bus.RequestAsync<TestRequestMessage, TestResponseMessage>(request).ContinueWith(response =>
{
Console.WriteLine("Got response: '{0}'", response.Result.Text);
autoResetEvent.Set();
throw new SomeRandomException("Something very bad just happened!");
});
autoResetEvent.WaitOne(1000);
}
// First start the EasyNetQ.Tests.SimpleService console app.
// Run this test. You should see the SimpleService report that it's
// responding and the response should appear here.
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_be_able_to_do_simple_request_response_that_takes_a_long_time()
{
var autoResetEvent = new AutoResetEvent(false);
var request = new TestRequestMessage
{
Text = "Hello from the client! ",
CausesServerToTakeALongTimeToRespond = true
};
Console.WriteLine("Making request");
bus.RequestAsync<TestRequestMessage, TestResponseMessage>(request).ContinueWith(response =>
{
Console.WriteLine("Got response: '{0}'", response.Result.Text);
autoResetEvent.Set();
});
autoResetEvent.WaitOne(10000);
}
}
public class SomeRandomException : Exception
{
//
// For guidelines regarding the creation of new exception types, see
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp
// and
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp
//
public SomeRandomException() {}
public SomeRandomException(string message) : base(message) {}
public SomeRandomException(string message, Exception inner) : base(message, inner) {}
}
}
// ReSharper restore InconsistentNaming
| |
/*
* (c) Copyright Marek Ledvina, Foriero Studo
*/
using UnityEngine;
using System.Collections;
using ForieroEngine.MIDIUnified;
[AddComponentMenu("MIDIUnified/Generators/MidiPlayMakerInput")]
public class MidiPlayMakerInput : MonoBehaviour, IMidiEvents {
public event ShortMessageEventHandler ShortMessageEvent;
ShortMessageEventHandler shortMessageEventHandler;
public static MidiPlayMakerInput singleton;
public bool midiOut = false;
public ChannelEnum midiChannel = ChannelEnum.None;
public bool useCustomVolume = false;
public float customVolume = 1f;
MidiOutHelper midiOutHelper = new MidiOutHelper();
void Awake(){
if(singleton != null){
Debug.LogError("GENERATOR : MidiPlayMakerInput already in scene.");
Destroy(this);
return;
}
shortMessageEventHandler = new ShortMessageEventHandler(ShortMessageHelper);
midiOutHelper.ShortMessageEvent += shortMessageEventHandler;
singleton = this;
}
void OnDestroy(){
singleton = null;
}
public ChannelEnum GetMidiChannel(){
return midiChannel == ChannelEnum.None ? ChannelEnum.C0 : midiChannel;
}
public void SetInstrument(ProgramEnum anInstrument, ChannelEnum aChannel){
if(midiOut) {
midiOutHelper.SetInstrument(anInstrument, GetMidiChannel());
}
}
public void SetInstrument(int anInstrument){
if(midiOut) {
midiOutHelper.SetInstrument(anInstrument, (int)GetMidiChannel());
}
}
public void NoteOn(int aNoteIndex, int aVolume){
if(midiOut) {
midiOutHelper.NoteOn(aNoteIndex, aVolume,(int)GetMidiChannel());
}
}
public void NoteOn(NoteEnum aNote, AccidentalEnum anAccidental, OctaveEnum anOctave, int aVolume){
if(midiOut) {
midiOutHelper.NoteOn(aNote, anAccidental, anOctave, aVolume, GetMidiChannel());
}
}
public void NoteOff(int aNoteIndex){
if(midiOut) {
midiOutHelper.NoteOff(aNoteIndex);
}
}
public void NoteOff(NoteEnum aNote, AccidentalEnum anAccidental,OctaveEnum anOctave){
if(midiOut) {
midiOutHelper.NoteOff(aNote, anAccidental, anOctave, GetMidiChannel());
}
}
public void Pedal(int aPedal, int aValue){
if(midiOut) {
midiOutHelper.Pedal(aPedal, aValue, (int)GetMidiChannel());
}
}
public void Pedal(PedalEnum aPedal, int aValue){
if(midiOut) {
midiOutHelper.Pedal(aPedal, aValue, GetMidiChannel());
}
}
public void SendControl(ControllerEnum aControl, int aValue){
if(midiOut) {
midiOutHelper.SendControl(aControl, aValue, GetMidiChannel());
}
}
public void SendControl(int aControl, int aValue){
if(midiOut) {
midiOutHelper.SendControl(aControl, aValue, (int)GetMidiChannel());
}
}
public void AllSoundOff(){
if(midiOut) {
midiOutHelper.AllSoundOff();
}
}
public void ResetAllControllers(){
if(midiOut) {
midiOutHelper.ResetAllControllers();
}
}
void ShortMessageHelper(int aCommand, int aData1, int aData2){
SendShortMessage(aCommand, aData1, aData2);
}
public void SendShortMessage(int aCommand, int aData1, int aData2){
if(ShortMessageEvent != null) {
ShortMessageEvent(
midiChannel == ChannelEnum.None ? aCommand : (aCommand | (int)midiChannel),
aData1,
useCustomVolume ? MidiConversion.GetByteVolume(customVolume, aData2) : aData2
);
}
if(midiOut){
MidiOut.SendShortMessage(
midiChannel == ChannelEnum.None ? aCommand : (aCommand | (int)midiChannel),
aData1,
useCustomVolume ? MidiConversion.GetByteVolume(customVolume, aData2) : aData2
);
}
}
class MidiOutHelper{
public event ShortMessageEventHandler ShortMessageEvent;
public void SetInstrument(ProgramEnum anInstrument, ChannelEnum aChannel = ChannelEnum.C0){
SendShortMessage((int)aChannel + (int)CommandEnum.ProgramChange,(int)anInstrument,0);
}
public void SetInstrument(int anInstrument, int aChannel = 0){
SendShortMessage(aChannel + (int)CommandEnum.ProgramChange,anInstrument,0);
}
public void NoteOn(int aNoteIndex, int aVolume = 80, int aChannel = 0){
SendShortMessage(aChannel + (int)CommandEnum.NoteOn, aNoteIndex, aVolume);
}
public void NoteOn(NoteEnum aNote, AccidentalEnum anAccidental, OctaveEnum anOctave, int aVolume = 80, ChannelEnum aChannel = ChannelEnum.C0){
int noteIndex = ((int)aNote + (int)anAccidental + ((int)(anOctave == OctaveEnum.None ? OctaveEnum.Octave4 : anOctave) * 12) + 24);
NoteOn(noteIndex, aVolume, (int)aChannel);
}
public void NoteOff(int aNoteIndex, int aChannel = 0){
SendShortMessage(aChannel + (int)CommandEnum.NoteOff, aNoteIndex, 0);
}
public void NoteOff(NoteEnum aNote, AccidentalEnum anAccidental,OctaveEnum anOctave, ChannelEnum aChannel = ChannelEnum.C0){
int noteIndex = ((int)aNote + (int)anAccidental+ ((int)(anOctave == OctaveEnum.None ? OctaveEnum.Octave4 : anOctave) * 12) + 24);
NoteOff(noteIndex, (int)aChannel);
}
public void Pedal(int aPedal, int aValue, int aChannel = 0){
SendShortMessage(aChannel + (int)CommandEnum.Controller, aPedal, aValue);
}
public void Pedal(PedalEnum aPedal, int aValue, ChannelEnum aChannel = ChannelEnum.C0){
SendShortMessage((int)aChannel + (int)CommandEnum.Controller, (int)aPedal, aValue);
}
public void SendControl(ControllerEnum aControl, int aValue, ChannelEnum aChannel = ChannelEnum.C0){
SendShortMessage((int)aChannel + (int)CommandEnum.Controller, (int)aControl, aValue);
}
public void SendControl(int aControl, int aValue, int aChannel = 0){
SendShortMessage(aChannel + (int)CommandEnum.Controller, aControl, aValue);
}
public void AllSoundOff(){
for(int i = 0; i < 16; i++){
SendShortMessage(i + (int)CommandEnum.Controller, (int)ControllerEnum.AllSoundOff,0);
}
}
public void ResetAllControllers(){
for(int i = 0; i < 16; i++){
SendShortMessage(i +(int)CommandEnum.Controller, (int)ControllerEnum.ResetControllers,0);
}
}
public void SendShortMessage(int aCommand, int aData1, int aData2){
if(ShortMessageEvent != null) ShortMessageEvent(aCommand, aData1, aData2);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using Xunit;
namespace System.Numerics.Tests
{
public static class Driver
{
public static BigInteger b1;
public static BigInteger b2;
public static BigInteger b3;
public static BigInteger[][] results;
private static Random s_random = new Random(100);
[Fact]
[OuterLoop]
public static void RunTests()
{
int cycles = 1;
//Get the BigIntegers to be testing;
b1 = new BigInteger(GetRandomByteArray(s_random));
b2 = new BigInteger(GetRandomByteArray(s_random));
b3 = new BigInteger(GetRandomByteArray(s_random));
results = new BigInteger[32][];
// ...Sign
results[0] = new BigInteger[3];
results[0][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uSign");
results[0][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uSign");
results[0][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uSign");
// ...Op ~
results[1] = new BigInteger[3];
results[1][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u~");
results[1][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u~");
results[1][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u~");
// ...Log10
results[2] = new BigInteger[3];
results[2][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uLog10");
results[2][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uLog10");
results[2][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uLog10");
// ...Log
results[3] = new BigInteger[3];
results[3][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uLog");
results[3][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uLog");
results[3][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uLog");
// ...Abs
results[4] = new BigInteger[3];
results[4][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uAbs");
results[4][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uAbs");
results[4][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uAbs");
// ...Op --
results[5] = new BigInteger[3];
results[5][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u--");
results[5][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u--");
results[5][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u--");
// ...Op ++
results[6] = new BigInteger[3];
results[6][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u++");
results[6][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u++");
results[6][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u++");
// ...Negate
results[7] = new BigInteger[3];
results[7][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uNegate");
results[7][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uNegate");
results[7][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uNegate");
// ...Op -
results[8] = new BigInteger[3];
results[8][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u-");
results[8][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u-");
results[8][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u-");
// ...Op +
results[9] = new BigInteger[3];
results[9][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u+");
results[9][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u+");
results[9][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u+");
// ...Min
results[10] = new BigInteger[9];
results[10][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bMin");
results[10][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bMin");
results[10][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bMin");
results[10][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bMin");
results[10][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bMin");
results[10][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bMin");
results[10][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bMin");
results[10][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bMin");
results[10][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bMin");
// ...Max
results[11] = new BigInteger[9];
results[11][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bMax");
results[11][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bMax");
results[11][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bMax");
results[11][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bMax");
results[11][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bMax");
results[11][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bMax");
results[11][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bMax");
results[11][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bMax");
results[11][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bMax");
// ...Op >>
results[12] = new BigInteger[9];
results[12][0] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b1), "b>>");
results[12][1] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b2), "b>>");
results[12][2] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b3), "b>>");
results[12][3] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b1), "b>>");
results[12][4] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b2), "b>>");
results[12][5] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b3), "b>>");
results[12][6] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b1), "b>>");
results[12][7] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b2), "b>>");
results[12][8] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b3), "b>>");
// ...Op <<
results[13] = new BigInteger[9];
results[13][0] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b1), "b<<");
results[13][1] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b2), "b<<");
results[13][2] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b3), "b<<");
results[13][3] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b1), "b<<");
results[13][4] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b2), "b<<");
results[13][5] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b3), "b<<");
results[13][6] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b1), "b<<");
results[13][7] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b2), "b<<");
results[13][8] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b3), "b<<");
// ...Op ^
results[14] = new BigInteger[9];
results[14][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b^");
results[14][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b^");
results[14][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b^");
results[14][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b^");
results[14][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b^");
results[14][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b^");
results[14][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b^");
results[14][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b^");
results[14][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b^");
// ...Op |
results[15] = new BigInteger[9];
results[15][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b|");
results[15][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b|");
results[15][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b|");
results[15][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b|");
results[15][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b|");
results[15][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b|");
results[15][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b|");
results[15][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b|");
results[15][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b|");
// ...Op &
results[16] = new BigInteger[9];
results[16][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b&");
results[16][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b&");
results[16][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b&");
results[16][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b&");
results[16][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b&");
results[16][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b&");
results[16][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b&");
results[16][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b&");
results[16][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b&");
// ...Log
results[17] = new BigInteger[9];
results[17][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bLog");
results[17][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bLog");
results[17][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bLog");
results[17][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bLog");
results[17][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bLog");
results[17][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bLog");
results[17][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bLog");
results[17][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bLog");
results[17][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bLog");
// ...GCD
results[18] = new BigInteger[9];
results[18][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bGCD");
results[18][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bGCD");
results[18][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bGCD");
results[18][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bGCD");
results[18][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bGCD");
results[18][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bGCD");
results[18][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bGCD");
results[18][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bGCD");
results[18][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bGCD");
// ...DivRem
results[20] = new BigInteger[9];
results[20][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bDivRem");
results[20][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bDivRem");
results[20][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bDivRem");
results[20][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bDivRem");
results[20][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bDivRem");
results[20][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bDivRem");
results[20][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bDivRem");
results[20][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bDivRem");
results[20][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bDivRem");
// ...Remainder
results[21] = new BigInteger[9];
results[21][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bRemainder");
results[21][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bRemainder");
results[21][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bRemainder");
results[21][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bRemainder");
results[21][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bRemainder");
results[21][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bRemainder");
results[21][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bRemainder");
results[21][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bRemainder");
results[21][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bRemainder");
// ...Op %
results[22] = new BigInteger[9];
results[22][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b%");
results[22][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b%");
results[22][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b%");
results[22][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b%");
results[22][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b%");
results[22][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b%");
results[22][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b%");
results[22][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b%");
results[22][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b%");
// ...Divide
results[23] = new BigInteger[9];
results[23][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bDivide");
results[23][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bDivide");
results[23][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bDivide");
results[23][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bDivide");
results[23][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bDivide");
results[23][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bDivide");
results[23][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bDivide");
results[23][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bDivide");
results[23][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bDivide");
// ...Op /
results[24] = new BigInteger[9];
results[24][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b/");
results[24][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b/");
results[24][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b/");
results[24][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b/");
results[24][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b/");
results[24][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b/");
results[24][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b/");
results[24][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b/");
results[24][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b/");
// ...Multiply
results[25] = new BigInteger[9];
results[25][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bMultiply");
results[25][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bMultiply");
results[25][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bMultiply");
results[25][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bMultiply");
results[25][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bMultiply");
results[25][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bMultiply");
results[25][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bMultiply");
results[25][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bMultiply");
results[25][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bMultiply");
// ...Op *
results[26] = new BigInteger[9];
results[26][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b*");
results[26][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b*");
results[26][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b*");
results[26][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b*");
results[26][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b*");
results[26][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b*");
results[26][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b*");
results[26][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b*");
results[26][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b*");
// ...Subtract
results[27] = new BigInteger[9];
results[27][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bSubtract");
results[27][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bSubtract");
results[27][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bSubtract");
results[27][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bSubtract");
results[27][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bSubtract");
results[27][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bSubtract");
results[27][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bSubtract");
results[27][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bSubtract");
results[27][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bSubtract");
// ...Op -
results[28] = new BigInteger[9];
results[28][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b-");
results[28][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b-");
results[28][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b-");
results[28][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b-");
results[28][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b-");
results[28][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b-");
results[28][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b-");
results[28][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b-");
results[28][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b-");
// ...Add
results[29] = new BigInteger[9];
results[29][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bAdd");
results[29][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bAdd");
results[29][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bAdd");
results[29][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bAdd");
results[29][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bAdd");
results[29][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bAdd");
results[29][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bAdd");
results[29][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bAdd");
results[29][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bAdd");
// ...Op +
results[30] = new BigInteger[9];
results[30][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b+");
results[30][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b+");
results[30][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b+");
results[30][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b+");
results[30][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b+");
results[30][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b+");
results[30][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b+");
results[30][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b+");
results[30][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b+");
// ...ModPow
results[31] = new BigInteger[27];
results[31][0] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b1 < 0 ? -b1 : b1), b1, "tModPow");
results[31][1] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b1 < 0 ? -b1 : b1), b2, "tModPow");
results[31][2] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b1 < 0 ? -b1 : b1), b3, "tModPow");
results[31][3] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b2 < 0 ? -b2 : b2), b1, "tModPow");
results[31][4] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b2 < 0 ? -b2 : b2), b2, "tModPow");
results[31][5] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b2 < 0 ? -b2 : b2), b3, "tModPow");
results[31][6] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b3 < 0 ? -b3 : b3), b1, "tModPow");
results[31][7] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b3 < 0 ? -b3 : b3), b2, "tModPow");
results[31][8] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b3 < 0 ? -b3 : b3), b3, "tModPow");
results[31][9] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b1 < 0 ? -b1 : b1), b1, "tModPow");
results[31][10] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b1 < 0 ? -b1 : b1), b2, "tModPow");
results[31][11] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b1 < 0 ? -b1 : b1), b3, "tModPow");
results[31][12] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b2 < 0 ? -b2 : b2), b1, "tModPow");
results[31][13] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b2 < 0 ? -b2 : b2), b2, "tModPow");
results[31][14] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b2 < 0 ? -b2 : b2), b3, "tModPow");
results[31][15] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b3 < 0 ? -b3 : b3), b1, "tModPow");
results[31][16] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b3 < 0 ? -b3 : b3), b2, "tModPow");
results[31][17] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b3 < 0 ? -b3 : b3), b3, "tModPow");
results[31][18] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b1 < 0 ? -b1 : b1), b1, "tModPow");
results[31][19] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b1 < 0 ? -b1 : b1), b2, "tModPow");
results[31][20] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b1 < 0 ? -b1 : b1), b3, "tModPow");
results[31][21] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b2 < 0 ? -b2 : b2), b1, "tModPow");
results[31][22] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b2 < 0 ? -b2 : b2), b2, "tModPow");
results[31][23] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b2 < 0 ? -b2 : b2), b3, "tModPow");
results[31][24] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b3 < 0 ? -b3 : b3), b1, "tModPow");
results[31][25] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b3 < 0 ? -b3 : b3), b2, "tModPow");
results[31][26] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b3 < 0 ? -b3 : b3), b3, "tModPow");
for (int i = 0; i < cycles; i++)
{
Worker worker = new Worker(new Random(s_random.Next()), i);
worker.DoWork();
Assert.True(worker.Valid, "Verification Failed");
}
}
private static byte[] GetRandomByteArray(Random random)
{
return MyBigIntImp.GetNonZeroRandomByteArray(random, random.Next(1, 18));
}
private static int Makeint(BigInteger input)
{
int output;
if (input < 0)
{
input = -input;
}
input = input + int.MaxValue;
byte[] temp = input.ToByteArray();
temp[1] = 0;
temp[2] = 0;
temp[3] = 0;
output = BitConverter.ToInt32(temp, 0);
if (output == 0)
{
output = 1;
}
return output;
}
}
public class Worker
{
private Random random;
private int id;
public bool Valid
{
get;
set;
}
public Worker(Random r, int i)
{
random = r;
id = i;
}
public void DoWork()
{
Valid = true;
BigInteger b1 = Driver.b1;
BigInteger b2 = Driver.b2;
BigInteger b3 = Driver.b3;
BigInteger[][] results = Driver.results;
var threeOrderOperations = new Action<BigInteger, BigInteger>[] {
new Action<BigInteger, BigInteger>((a, expected) => { Sign(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Op_Not(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Log10(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Log(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Abs(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Op_Decrement(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Op_Increment(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Negate(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Op_Negate(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Op_Plus(a, expected); })
};
var nineOrderOperations = new Action<BigInteger, BigInteger, BigInteger>[] {
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Min(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Max(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_RightShift(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_LeftShift(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Xor(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Or(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_And(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Log(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { GCD(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Pow(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { DivRem(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Remainder(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Modulus(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Divide(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Divide(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Multiply(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Multiply(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Subtract(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Subtract(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Add(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Add(a, b, expected); })
};
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
while (stopWatch.ElapsedMilliseconds < 10000)
{
// Remove the Pow operation for performance reasons
int op;
do
{
op = random.Next(0, 32);
}
while (op == 19);
int order = random.Next(0, 27);
switch (op)
{
case 0: // Sign
case 1: // Op_Not
case 2: // Log10
case 3: // Log
case 4: // Abs
case 5: // Op_Decrement
case 6: // Op_Increment
case 7: // Negate
case 8: // Op_Negate
case 9: // Op_Plus
switch (order % 3)
{
case 0:
threeOrderOperations[op](b1, results[op][0]);
break;
case 1:
threeOrderOperations[op](b2, results[op][1]);
break;
case 2:
threeOrderOperations[op](b3, results[op][2]);
break;
default:
Valid = false;
break;
}
break;
case 10: // Min
case 11: // Max
case 12: // Op_RightShift
case 13: // Op_LeftShift
case 14: // Op_Xor
case 15: // Op_Or
case 16: // Op_And
case 17: // Log
case 18: // GCD
case 19: // Pow
case 20: // DivRem
case 21: // Remainder
case 22: // Op_Modulus
case 23: // Divide
case 24: // Op_Divide
case 25: // Multiply
case 26: // Op_Multiply
case 27: // Subtract
case 28: // Op_Subtract
case 29: // Add
case 30: // Op_Add
switch (order % 9)
{
case 0:
nineOrderOperations[op-10](b1, b1, results[op][0]);
break;
case 1:
nineOrderOperations[op-10](b1, b2, results[op][1]);
break;
case 2:
nineOrderOperations[op-10](b1, b3, results[op][2]);
break;
case 3:
nineOrderOperations[op-10](b2, b1, results[op][3]);
break;
case 4:
nineOrderOperations[op-10](b2, b2, results[op][4]);
break;
case 5:
nineOrderOperations[op-10](b2, b3, results[op][5]);
break;
case 6:
nineOrderOperations[op-10](b3, b1, results[op][6]);
break;
case 7:
nineOrderOperations[op-10](b3, b2, results[op][7]);
break;
case 8:
nineOrderOperations[op-10](b3, b3, results[op][8]);
break;
default:
Valid = false;
break;
}
break;
case 31:
switch (order % 27)
{
case 0:
ModPow(b1, b1, b1, results[31][0]);
break;
case 1:
ModPow(b1, b1, b2, results[31][1]);
break;
case 2:
ModPow(b1, b1, b3, results[31][2]);
break;
case 3:
ModPow(b1, b2, b1, results[31][3]);
break;
case 4:
ModPow(b1, b2, b2, results[31][4]);
break;
case 5:
ModPow(b1, b2, b3, results[31][5]);
break;
case 6:
ModPow(b1, b3, b1, results[31][6]);
break;
case 7:
ModPow(b1, b3, b2, results[31][7]);
break;
case 8:
ModPow(b1, b3, b3, results[31][8]);
break;
case 9:
ModPow(b2, b1, b1, results[31][9]);
break;
case 10:
ModPow(b2, b1, b2, results[31][10]);
break;
case 11:
ModPow(b2, b1, b3, results[31][11]);
break;
case 12:
ModPow(b2, b2, b1, results[31][12]);
break;
case 13:
ModPow(b2, b2, b2, results[31][13]);
break;
case 14:
ModPow(b2, b2, b3, results[31][14]);
break;
case 15:
ModPow(b2, b3, b1, results[31][15]);
break;
case 16:
ModPow(b2, b3, b2, results[31][16]);
break;
case 17:
ModPow(b2, b3, b3, results[31][17]);
break;
case 18:
ModPow(b3, b1, b1, results[31][18]);
break;
case 19:
ModPow(b3, b1, b2, results[31][19]);
break;
case 20:
ModPow(b3, b1, b3, results[31][20]);
break;
case 21:
ModPow(b3, b2, b1, results[31][21]);
break;
case 22:
ModPow(b3, b2, b2, results[31][22]);
break;
case 23:
ModPow(b3, b2, b3, results[31][23]);
break;
case 24:
ModPow(b3, b3, b1, results[31][24]);
break;
case 25:
ModPow(b3, b3, b2, results[31][25]);
break;
case 26:
ModPow(b3, b3, b3, results[31][26]);
break;
default:
Valid = false;
break;
}
break;
default:
Valid = false;
break;
}
Assert.True(Valid, String.Format("Cycle {0} corrupted with operation {1} on order {2}", id, op, order));
}
}
private void Sign(BigInteger a, BigInteger expected)
{
Assert.Equal(a.Sign, expected);
}
private void Op_Not(BigInteger a, BigInteger expected)
{
Assert.Equal(~a, expected);
}
private void Log10(BigInteger a, BigInteger expected)
{
Assert.Equal(MyBigIntImp.ApproximateBigInteger(BigInteger.Log10(a)), expected);
}
private void Log(BigInteger a, BigInteger expected)
{
Assert.Equal(MyBigIntImp.ApproximateBigInteger(BigInteger.Log(a)), expected);
}
private void Abs(BigInteger a, BigInteger expected)
{
Assert.Equal(BigInteger.Abs(a), expected);
}
private void Op_Decrement(BigInteger a, BigInteger expected)
{
Assert.Equal(--a, expected);
}
private void Op_Increment(BigInteger a, BigInteger expected)
{
Assert.Equal(++a, expected);
}
private void Negate(BigInteger a, BigInteger expected)
{
Assert.Equal(BigInteger.Negate(a), expected);
}
private void Op_Negate(BigInteger a, BigInteger expected)
{
Assert.Equal(-a, expected);
}
private void Op_Plus(BigInteger a, BigInteger expected)
{
Assert.Equal(+a, expected);
}
private void Min(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Min(a, b), expected);
}
private void Max(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Max(a, b), expected);
}
private void Op_RightShift(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a >> MakeInt32(b)), expected);
}
private void Op_LeftShift(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a << MakeInt32(b)), expected);
}
private void Op_Xor(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a ^ b), expected);
}
private void Op_Or(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a | b), expected);
}
private void Op_And(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a & b), expected);
}
private void Log(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(MyBigIntImp.ApproximateBigInteger(BigInteger.Log(a, (double)b)), expected);
}
private void GCD(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.GreatestCommonDivisor(a, b), expected);
}
public bool Pow(BigInteger a, BigInteger b, BigInteger expected)
{
b = MakeInt32(b);
if (b < 0)
{
b = -b;
}
return (BigInteger.Pow(a, (int)b) == expected);
}
public bool DivRem(BigInteger a, BigInteger b, BigInteger expected)
{
BigInteger c = 0;
return (BigInteger.DivRem(a, b, out c) == expected);
}
private void Remainder(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Remainder(a, b), expected);
}
private void Op_Modulus(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a % b), expected);
}
private void Divide(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Divide(a, b), expected);
}
private void Op_Divide(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a / b), expected);
}
private void Multiply(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Multiply(a, b), expected);
}
private void Op_Multiply(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a * b), expected);
}
private void Subtract(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Subtract(a, b), expected);
}
private void Op_Subtract(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a - b), expected);
}
private void Add(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Add(a, b), expected);
}
private void Op_Add(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a + b), expected);
}
public bool ModPow(BigInteger a, BigInteger b, BigInteger c, BigInteger expected)
{
if (b < 0)
{
b = -b;
}
return (BigInteger.ModPow(a, b, c) == expected);
}
private int MakeInt32(BigInteger input)
{
int output;
if (input < 0)
{
input = -input;
}
input = input + int.MaxValue;
byte[] temp = input.ToByteArray();
temp[1] = 0;
temp[2] = 0;
temp[3] = 0;
output = BitConverter.ToInt32(temp, 0);
if (output == 0)
{
output = 1;
}
return output;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using DynamicMVC.Data.Interfaces;
using DynamicMVC.DynamicEntityMetadataLibrary.Interfaces;
using DynamicMVC.DynamicEntityMetadataLibrary.Models;
using DynamicMVC.Shared;
using DynamicMVC.UI.DynamicMVC.Interfaces;
using DynamicMVC.UI.DynamicMVC.ViewModels;
namespace DynamicMVC.UI.DynamicMVC.Managers
{
/// <summary>
/// Exposes methods called by the client application
/// </summary>
public class DynamicMvcManager : IDynamicMvcManager
{
private readonly IDynamicEntityMetadataManager _dynamicEntityMetadataManager;
private readonly INavigationPropertyManager _navigationPropertyManager;
public DynamicMvcManager(IDynamicEntityMetadataManager dynamicEntityMetadataManager, INavigationPropertyManager navigationPropertyManager)
{
_dynamicEntityMetadataManager = dynamicEntityMetadataManager;
_navigationPropertyManager = navigationPropertyManager;
}
/// <summary>
/// Provides DynamicMVC with everything it needs to read from the client application
/// </summary>
public void RegisterDynamicMvc()
{
DynamicMVCContext.DynamicEntityMetadatas = _dynamicEntityMetadataManager.GetDynamicEntityMetadatas();
}
public DynamicMVCContextOptions Options
{
get { return DynamicMVCContext.Options; }
}
/// <summary>
/// Sets routeCollection for models that do not have a controller defined
/// </summary>
/// <param CustomPropertyName="routeCollection"></param>
/// <param name="routeCollection">The route collection for the mvc application.</param>
public void SetDynamicRoutes(RouteCollection routeCollection)
{
var newRouteCollection = new RouteCollection();
var firstRoute = routeCollection.First();
newRouteCollection.Add(firstRoute);
foreach (var dynamicEntityMetadata in DynamicMVCContext.DynamicEntityMetadatas)
{
if (dynamicEntityMetadata.ControllerExists())
{
newRouteCollection.MapRoute(
name: "Dynamic" + dynamicEntityMetadata.TypeName(),
url: dynamicEntityMetadata.TypeName() + "/{action}/{id}",
defaults: new { controller = dynamicEntityMetadata.TypeName(), action = "Index", id = UrlParameter.Optional, typeName = dynamicEntityMetadata.TypeName() }
);
}
else
{
newRouteCollection.MapRoute(
name: "Dynamic" + dynamicEntityMetadata.TypeName(),
url: dynamicEntityMetadata.TypeName() + "/{action}/{id}",
defaults: new { controller = "Dynamic", action = "Index", id = UrlParameter.Optional, typeName = dynamicEntityMetadata.TypeName() }
);
}
}
foreach (var oldRoute in routeCollection.Where(x => x != firstRoute))
{
newRouteCollection.Add(oldRoute);
}
routeCollection.Clear();
foreach (var newRoute in newRouteCollection)
{
routeCollection.Add(newRoute);
}
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public int GetItemsCountFunction(Type type)
{
using (var dynamicRepository = Container.Resolve<IDynamicRepository>())
{
return dynamicRepository.GetItemsCount(type);
}
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="keyValue"></param>
/// <returns></returns>
public object GetItemByTypeAndKeyFunction(Type type, dynamic keyValue)
{
var keyName = DynamicMVCContext.GetDynamicEntityMetadata(type.Name).KeyProperty().PropertyName();
using (var dynamicRepository = Container.Resolve<IDynamicRepository>())
{
return dynamicRepository.GetItem(type, keyName, keyValue);
}
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="keyValue"></param>
/// <returns></returns>
public IEnumerable<dynamic> GetItemByTypeAndPropertyNameFunction(Type type, string propertyName, dynamic propertyValue)
{
using (var dynamicRepository = Container.Resolve<IDynamicRepository>())
{
return dynamicRepository.GetItems(type,propertyName, propertyValue);
}
}
public string GetSelectItemText(Type type, dynamic value, string textFieldName)
{
var textProperty = type.GetProperties().Single(x => x.Name == textFieldName);
var v = value.ToString();
IEnumerable<dynamic> items = GetItemByTypeAndPropertyNameFunction(type, textFieldName, v);
if (!items.Any() || items.Count()>1)
return "";
return textProperty.GetValue(items.First()).ToString();
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public IEnumerable GetItemsByTypeFunction(Type type)
{
using (var dynamicRepository = Container.Resolve<IDynamicRepository>())
{
return dynamicRepository.GetItems(type);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IEnumerable<DynamicMenuItemViewModel> GetDynamicMenuItems()
{
var results = new List<DynamicMenuItemViewModel>();
foreach (var dynamicEntityMetadata in DynamicMVCContext.DynamicEntityMetadatas.Where(x => x.DynamicMenuInfo().HasMenuItem))
{
var menuItem = new DynamicMenuItemViewModel(dynamicEntityMetadata, dynamicEntityMetadata.DynamicMenuInfo().MenuItemDisplayName);
var parentMenu = results.SingleOrDefault(x => x.DisplayName == dynamicEntityMetadata.DynamicMenuInfo().MenuItemCategory);
if (parentMenu == null)
{
parentMenu = new DynamicMenuItemViewModel(dynamicEntityMetadata.DynamicMenuInfo().MenuItemCategory);
results.Add(parentMenu);
}
parentMenu.DynamicMenuItemViewModels.Add(menuItem);
}
return results;
}
/// <summary>
///
/// </summary>
/// <param name="typeName"></param>
/// <returns></returns>
public DynamicEntityMetadata GetDynamicEntityMetadata(string typeName)
{
return DynamicMVCContext.GetDynamicEntityMetadata(typeName);
}
/// <summary>
/// This is called on the create to load related entities
/// </summary>
/// <param name="dynamicEntityMetadata"></param>
/// <param name="item"></param>
/// <param name="dynamicRepository"></param>
/// <param name="includes"></param>
public void LoadCreateIncludes(DynamicEntityMetadata dynamicEntityMetadata, dynamic item, IDynamicRepository dynamicRepository, params string[] includes)
{
foreach (var include in includes.ToList())
{
var currentInclude = include;
string subinclude = null;
if (currentInclude.Contains("."))
{
var index = currentInclude.IndexOf('.');
subinclude = currentInclude.Substring(index + 1);
currentInclude = include.Substring(0, index);
}
currentInclude = currentInclude.Trim();
var property = dynamicEntityMetadata.DynamicPropertyMetadatas.Single(x => x.PropertyName() == currentInclude);
if (property.IsDynamicCollection())
{
//its not possible to have a fk to this object b/c its not created yet
}
else if (property.IsDynamicEntity())
{
var typeName = property.TypeName();
var dynamicMetadata = GetDynamicEntityMetadata(typeName);
var id = ((DynamicComplexPropertyMetadata)property).DynamicForiegnKeyPropertyMetadata.GetValueFunction()(item);
var value = string.IsNullOrWhiteSpace(subinclude) ?
dynamicRepository.GetItem(dynamicMetadata.EntityTypeFunction()(), dynamicMetadata.KeyProperty().PropertyName(), id)
: dynamicRepository.GetItem(dynamicMetadata.EntityTypeFunction()(), dynamicMetadata.KeyProperty().PropertyName(), id, subinclude);
property.SetValueAction()(item, value);
//Add item to the collection for this entity
var collectionProperty = _navigationPropertyManager.GetCollectionProperty(dynamicEntityMetadata, property);
if (collectionProperty != null)
{
var collection = collectionProperty.GetValueFunction()(value);
//Todo: throw exception here if collection is null
collection .GetType().GetMethod("Add").Invoke(collection, new[] { item });
}
}
}
}
}
}
| |
/*
* @author Valentin Simonov / http://va.lent.in/
* @author Andrew David Griffiths
*/
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace TouchScript.InputSources
{
/// <summary>
/// Processes Windows 8 touch events.
/// Known issues:
/// <list type="bullet">
/// <item>DOES NOT WORK IN EDITOR.</item>
/// </list>
/// </summary>
[AddComponentMenu("TouchScript/Input Sources/Windows 8 Touch Input")]
public sealed class Win8TouchInput : InputSource
{
#region Constants
private const string PRESS_AND_HOLD_ATOM = "MicrosoftTabletPenServiceProperty";
private delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
#endregion
#region Public properties
/// <summary>
/// Tags added to touches coming from this input.
/// </summary>
public Tags TouchTags = new Tags(Tags.INPUT_TOUCH);
/// <summary>
/// Tags added to mouse touches coming from this input.
/// </summary>
public Tags MouseTags = new Tags(Tags.INPUT_MOUSE);
/// <summary>
/// Tags added to pen touches coming from this input.
/// </summary>
public Tags PenTags = new Tags(Tags.INPUT_PEN);
#endregion
#region Private variables
private IntPtr hMainWindow;
private IntPtr oldWndProcPtr;
private IntPtr newWndProcPtr;
private WndProcDelegate newWndProc;
private ushort pressAndHoldAtomID;
private Dictionary<int, int> winToInternalId = new Dictionary<int, int>();
private bool isInitialized = false;
#endregion
#region Unity
/// <inheritdoc />
protected override void OnEnable()
{
// "WindowsEditor" in the Editor
if (Application.platform != RuntimePlatform.WindowsPlayer)
{
enabled = false;
return;
}
// disable mouse
var inputs = FindObjectsOfType<MouseInput>();
var count = inputs.Length;
for (var i = 0; i < count; i++)
{
inputs[i].enabled = false;
}
base.OnEnable();
init();
}
/// <inheritdoc />
protected override void OnDisable()
{
if (isInitialized)
{
if (pressAndHoldAtomID != 0)
{
RemoveProp(hMainWindow, PRESS_AND_HOLD_ATOM);
GlobalDeleteAtom(pressAndHoldAtomID);
}
SetWindowLongPtr(hMainWindow, -4, oldWndProcPtr);
hMainWindow = IntPtr.Zero;
oldWndProcPtr = IntPtr.Zero;
newWndProcPtr = IntPtr.Zero;
newWndProc = null;
}
foreach (var i in winToInternalId)
{
cancelTouch(i.Value);
}
base.OnDisable();
}
#endregion
#region Private functions
private void init()
{
hMainWindow = GetForegroundWindow();
newWndProc = wndProc;
newWndProcPtr = Marshal.GetFunctionPointerForDelegate(newWndProc);
oldWndProcPtr = SetWindowLongPtr(hMainWindow, -4, newWndProcPtr);
EnableMouseInPointer(true);
pressAndHoldAtomID = GlobalAddAtom(PRESS_AND_HOLD_ATOM);
SetProp(hMainWindow, PRESS_AND_HOLD_ATOM, 1);
isInitialized = true;
}
private IntPtr wndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
switch (msg)
{
case WM_TOUCH:
CloseTouchInputHandle(lParam); // don't let Unity handle this
return IntPtr.Zero;
case WM_POINTERDOWN:
case WM_POINTERUP:
case WM_POINTERUPDATE:
decodeTouches(msg, wParam, lParam);
return IntPtr.Zero;
case WM_CLOSE:
// Not having this crashes app on quit
SetWindowLongPtr(hWnd, -4, oldWndProcPtr);
SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
return IntPtr.Zero;
default:
return CallWindowProc(oldWndProcPtr, hWnd, msg, wParam, lParam);
}
}
private void decodeTouches(uint msg, IntPtr wParam, IntPtr lParam)
{
int pointerId = LOWORD(wParam.ToInt32());
POINTER_INFO pointerInfo = new POINTER_INFO();
if (!GetPointerInfo(pointerId, ref pointerInfo))
{
return;
}
POINT p = new POINT();
p.X = pointerInfo.ptPixelLocation.X;
p.Y = pointerInfo.ptPixelLocation.Y;
ScreenToClient(hMainWindow, ref p);
int existingId;
switch (msg)
{
case WM_POINTERDOWN:
Tags tags = null;
switch (pointerInfo.pointerType)
{
case POINTER_INPUT_TYPE.PT_TOUCH:
tags = new Tags(TouchTags);
break;
case POINTER_INPUT_TYPE.PT_PEN:
tags = new Tags(PenTags);
break;
case POINTER_INPUT_TYPE.PT_MOUSE:
tags = new Tags(MouseTags);
break;
}
winToInternalId.Add(pointerId, beginTouch(new Vector2(p.X, Screen.height - p.Y), tags).Id);
break;
case WM_POINTERUP:
if (winToInternalId.TryGetValue(pointerId, out existingId))
{
winToInternalId.Remove(pointerId);
endTouch(existingId);
}
break;
case WM_POINTERUPDATE:
if (winToInternalId.TryGetValue(pointerId, out existingId))
{
moveTouch(existingId, new Vector2(p.X, Screen.height - p.Y));
}
break;
}
}
#endregion
#region p/invoke
// Touch event window message constants [winuser.h]
private const int WM_CLOSE = 0x0010;
private const int WM_TOUCH = 0x0240;
private const int WM_POINTERDOWN = 0x0246;
private const int WM_POINTERUP = 0x0247;
private const int WM_POINTERUPDATE = 0x0245;
private enum POINTER_INPUT_TYPE
{
PT_POINTER = 0x00000001,
PT_TOUCH = 0x00000002,
PT_PEN = 0x00000003,
PT_MOUSE = 0x00000004,
}
private enum POINTER_BUTTON_CHANGE_TYPE
{
POINTER_CHANGE_NONE,
POINTER_CHANGE_FIRSTBUTTON_DOWN,
POINTER_CHANGE_FIRSTBUTTON_UP,
POINTER_CHANGE_SECONDBUTTON_DOWN,
POINTER_CHANGE_SECONDBUTTON_UP,
POINTER_CHANGE_THIRDBUTTON_DOWN,
POINTER_CHANGE_THIRDBUTTON_UP,
POINTER_CHANGE_FOURTHBUTTON_DOWN,
POINTER_CHANGE_FOURTHBUTTON_UP,
POINTER_CHANGE_FIFTHBUTTON_DOWN,
POINTER_CHANGE_FIFTHBUTTON_UP,
}
// Touch API defined structures [winuser.h]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct POINTER_INFO
{
public POINTER_INPUT_TYPE pointerType;
public UInt32 pointerId;
public UInt32 frameId;
public UInt32 pointerFlags;
public IntPtr sourceDevice;
public IntPtr hwndTarget;
public POINT ptPixelLocation;
public POINT ptHimetricLocation;
public POINT ptPixelLocationRaw;
public POINT ptHimetricLocationRaw;
public UInt32 dwTime;
public UInt32 historyCount;
public Int32 inputData;
public UInt32 dwKeyStates;
public UInt64 PerformanceCount;
public POINTER_BUTTON_CHANGE_TYPE ButtonChangeType;
}
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
public int X;
public int Y;
}
private IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
{
if (IntPtr.Size == 8) return SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
return new IntPtr(SetWindowLong32(hWnd, nIndex, dwNewLong.ToInt32()));
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", EntryPoint = "SetWindowLong")]
private static extern int SetWindowLong32(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")]
private static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll")]
private static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool ScreenToClient(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetPointerInfo(int pointerID, ref POINTER_INFO pPointerInfo);
[DllImport("user32.dll")]
private static extern IntPtr EnableMouseInPointer(bool value);
[DllImport("Kernel32.dll")]
private static extern ushort GlobalAddAtom(string lpString);
[DllImport("Kernel32.dll")]
private static extern ushort GlobalDeleteAtom(ushort nAtom);
[DllImport("user32.dll")]
private static extern int SetProp(IntPtr hWnd, string lpString, int hData);
[DllImport("user32.dll")]
private static extern int RemoveProp(IntPtr hWnd, string lpString);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern void CloseTouchInputHandle(IntPtr lParam);
private int HIWORD(int value)
{
return (int)(value >> 0xf);
}
private int LOWORD(int value)
{
return (int)(value & 0xffff);
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="AdGroupAdAssetViewServiceClient"/> instances.</summary>
public sealed partial class AdGroupAdAssetViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AdGroupAdAssetViewServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AdGroupAdAssetViewServiceSettings"/>.</returns>
public static AdGroupAdAssetViewServiceSettings GetDefault() => new AdGroupAdAssetViewServiceSettings();
/// <summary>
/// Constructs a new <see cref="AdGroupAdAssetViewServiceSettings"/> object with default settings.
/// </summary>
public AdGroupAdAssetViewServiceSettings()
{
}
private AdGroupAdAssetViewServiceSettings(AdGroupAdAssetViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetAdGroupAdAssetViewSettings = existing.GetAdGroupAdAssetViewSettings;
OnCopy(existing);
}
partial void OnCopy(AdGroupAdAssetViewServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupAdAssetViewServiceClient.GetAdGroupAdAssetView</c> and
/// <c>AdGroupAdAssetViewServiceClient.GetAdGroupAdAssetViewAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetAdGroupAdAssetViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AdGroupAdAssetViewServiceSettings"/> object.</returns>
public AdGroupAdAssetViewServiceSettings Clone() => new AdGroupAdAssetViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AdGroupAdAssetViewServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class AdGroupAdAssetViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupAdAssetViewServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AdGroupAdAssetViewServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AdGroupAdAssetViewServiceClientBuilder()
{
UseJwtAccessWithScopes = AdGroupAdAssetViewServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AdGroupAdAssetViewServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupAdAssetViewServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AdGroupAdAssetViewServiceClient Build()
{
AdGroupAdAssetViewServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AdGroupAdAssetViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AdGroupAdAssetViewServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AdGroupAdAssetViewServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AdGroupAdAssetViewServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AdGroupAdAssetViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AdGroupAdAssetViewServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AdGroupAdAssetViewServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupAdAssetViewServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupAdAssetViewServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AdGroupAdAssetViewService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to fetch ad group ad asset views.
/// </remarks>
public abstract partial class AdGroupAdAssetViewServiceClient
{
/// <summary>
/// The default endpoint for the AdGroupAdAssetViewService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AdGroupAdAssetViewService scopes.</summary>
/// <remarks>
/// The default AdGroupAdAssetViewService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AdGroupAdAssetViewServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupAdAssetViewServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AdGroupAdAssetViewServiceClient"/>.</returns>
public static stt::Task<AdGroupAdAssetViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AdGroupAdAssetViewServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AdGroupAdAssetViewServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupAdAssetViewServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AdGroupAdAssetViewServiceClient"/>.</returns>
public static AdGroupAdAssetViewServiceClient Create() => new AdGroupAdAssetViewServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AdGroupAdAssetViewServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AdGroupAdAssetViewServiceSettings"/>.</param>
/// <returns>The created <see cref="AdGroupAdAssetViewServiceClient"/>.</returns>
internal static AdGroupAdAssetViewServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupAdAssetViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AdGroupAdAssetViewService.AdGroupAdAssetViewServiceClient grpcClient = new AdGroupAdAssetViewService.AdGroupAdAssetViewServiceClient(callInvoker);
return new AdGroupAdAssetViewServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AdGroupAdAssetViewService client</summary>
public virtual AdGroupAdAssetViewService.AdGroupAdAssetViewServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group ad asset view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupAdAssetView GetAdGroupAdAssetView(GetAdGroupAdAssetViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group ad asset view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAdAssetView> GetAdGroupAdAssetViewAsync(GetAdGroupAdAssetViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group ad asset view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAdAssetView> GetAdGroupAdAssetViewAsync(GetAdGroupAdAssetViewRequest request, st::CancellationToken cancellationToken) =>
GetAdGroupAdAssetViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group ad asset view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group ad asset view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupAdAssetView GetAdGroupAdAssetView(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAdAssetView(new GetAdGroupAdAssetViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group ad asset view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group ad asset view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAdAssetView> GetAdGroupAdAssetViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAdAssetViewAsync(new GetAdGroupAdAssetViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group ad asset view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group ad asset view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAdAssetView> GetAdGroupAdAssetViewAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupAdAssetViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group ad asset view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group ad asset view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupAdAssetView GetAdGroupAdAssetView(gagvr::AdGroupAdAssetViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAdAssetView(new GetAdGroupAdAssetViewRequest
{
ResourceNameAsAdGroupAdAssetViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group ad asset view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group ad asset view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAdAssetView> GetAdGroupAdAssetViewAsync(gagvr::AdGroupAdAssetViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAdAssetViewAsync(new GetAdGroupAdAssetViewRequest
{
ResourceNameAsAdGroupAdAssetViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group ad asset view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group ad asset view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAdAssetView> GetAdGroupAdAssetViewAsync(gagvr::AdGroupAdAssetViewName resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupAdAssetViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AdGroupAdAssetViewService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to fetch ad group ad asset views.
/// </remarks>
public sealed partial class AdGroupAdAssetViewServiceClientImpl : AdGroupAdAssetViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetAdGroupAdAssetViewRequest, gagvr::AdGroupAdAssetView> _callGetAdGroupAdAssetView;
/// <summary>
/// Constructs a client wrapper for the AdGroupAdAssetViewService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="AdGroupAdAssetViewServiceSettings"/> used within this client.
/// </param>
public AdGroupAdAssetViewServiceClientImpl(AdGroupAdAssetViewService.AdGroupAdAssetViewServiceClient grpcClient, AdGroupAdAssetViewServiceSettings settings)
{
GrpcClient = grpcClient;
AdGroupAdAssetViewServiceSettings effectiveSettings = settings ?? AdGroupAdAssetViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetAdGroupAdAssetView = clientHelper.BuildApiCall<GetAdGroupAdAssetViewRequest, gagvr::AdGroupAdAssetView>(grpcClient.GetAdGroupAdAssetViewAsync, grpcClient.GetAdGroupAdAssetView, effectiveSettings.GetAdGroupAdAssetViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetAdGroupAdAssetView);
Modify_GetAdGroupAdAssetViewApiCall(ref _callGetAdGroupAdAssetView);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetAdGroupAdAssetViewApiCall(ref gaxgrpc::ApiCall<GetAdGroupAdAssetViewRequest, gagvr::AdGroupAdAssetView> call);
partial void OnConstruction(AdGroupAdAssetViewService.AdGroupAdAssetViewServiceClient grpcClient, AdGroupAdAssetViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AdGroupAdAssetViewService client</summary>
public override AdGroupAdAssetViewService.AdGroupAdAssetViewServiceClient GrpcClient { get; }
partial void Modify_GetAdGroupAdAssetViewRequest(ref GetAdGroupAdAssetViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested ad group ad asset view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::AdGroupAdAssetView GetAdGroupAdAssetView(GetAdGroupAdAssetViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupAdAssetViewRequest(ref request, ref callSettings);
return _callGetAdGroupAdAssetView.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested ad group ad asset view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::AdGroupAdAssetView> GetAdGroupAdAssetViewAsync(GetAdGroupAdAssetViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupAdAssetViewRequest(ref request, ref callSettings);
return _callGetAdGroupAdAssetView.Async(request, callSettings);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Linq.Tests
{
public class ToArrayTests : EnumerableTests
{
[Fact]
public void ToArray_CreateACopyWhenNotEmpty()
{
int[] sourceArray = new int[] { 1, 2, 3, 4, 5 };
int[] resultArray = sourceArray.ToArray();
Assert.NotSame(sourceArray, resultArray);
Assert.Equal(sourceArray, resultArray);
}
[Fact]
public void ToArray_UseArrayEmptyWhenEmpty()
{
int[] emptySourceArray = Array.Empty<int>();
Assert.Same(emptySourceArray.ToArray(), emptySourceArray.ToArray());
Assert.Same(emptySourceArray.Select(i => i).ToArray(), emptySourceArray.Select(i => i).ToArray());
Assert.Same(emptySourceArray.ToList().Select(i => i).ToArray(), emptySourceArray.ToList().Select(i => i).ToArray());
Assert.Same(new Collection<int>(emptySourceArray).Select(i => i).ToArray(), new Collection<int>(emptySourceArray).Select(i => i).ToArray());
Assert.Same(emptySourceArray.OrderBy(i => i).ToArray(), emptySourceArray.OrderBy(i => i).ToArray());
Assert.Same(Enumerable.Range(5, 0).ToArray(), Enumerable.Range(3, 0).ToArray());
Assert.Same(Enumerable.Range(5, 3).Take(0).ToArray(), Enumerable.Range(3, 0).ToArray());
Assert.Same(Enumerable.Range(5, 3).Skip(3).ToArray(), Enumerable.Range(3, 0).ToArray());
Assert.Same(Enumerable.Repeat(42, 0).ToArray(), Enumerable.Range(84, 0).ToArray());
Assert.Same(Enumerable.Repeat(42, 3).Take(0).ToArray(), Enumerable.Range(84, 3).Take(0).ToArray());
Assert.Same(Enumerable.Repeat(42, 3).Skip(3).ToArray(), Enumerable.Range(84, 3).Skip(3).ToArray());
}
private void RunToArrayOnAllCollectionTypes<T>(T[] items, Action<T[]> validation)
{
validation(Enumerable.ToArray(items));
validation(Enumerable.ToArray(new List<T>(items)));
validation(new TestEnumerable<T>(items).ToArray());
validation(new TestReadOnlyCollection<T>(items).ToArray());
validation(new TestCollection<T>(items).ToArray());
}
[Fact]
public void ToArray_WorkWithEmptyCollection()
{
RunToArrayOnAllCollectionTypes(new int[0],
resultArray =>
{
Assert.NotNull(resultArray);
Assert.Equal(0, resultArray.Length);
});
}
[Fact]
public void ToArray_ProduceCorrectArray()
{
int[] sourceArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
RunToArrayOnAllCollectionTypes(sourceArray,
resultArray =>
{
Assert.Equal(sourceArray.Length, resultArray.Length);
Assert.Equal(sourceArray, resultArray);
});
string[] sourceStringArray = new string[] { "1", "2", "3", "4", "5", "6", "7", "8" };
RunToArrayOnAllCollectionTypes(sourceStringArray,
resultStringArray =>
{
Assert.Equal(sourceStringArray.Length, resultStringArray.Length);
for (int i = 0; i < sourceStringArray.Length; i++)
Assert.Same(sourceStringArray[i], resultStringArray[i]);
});
}
[Fact]
public void RunOnce()
{
Assert.Equal(new int[] {1, 2, 3, 4, 5, 6, 7}, Enumerable.Range(1, 7).RunOnce().ToArray());
Assert.Equal(
new string[] {"1", "2", "3", "4", "5", "6", "7", "8"},
Enumerable.Range(1, 8).Select(i => i.ToString()).RunOnce().ToArray());
}
[Fact]
public void ToArray_TouchCountWithICollection()
{
TestCollection<int> source = new TestCollection<int>(new int[] { 1, 2, 3, 4 });
var resultArray = source.ToArray();
Assert.Equal(source, resultArray);
Assert.Equal(1, source.CountTouched);
}
[Fact]
public void ToArray_ThrowArgumentNullExceptionWhenSourceIsNull()
{
int[] source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.ToArray());
}
// Generally the optimal approach. Anything that breaks this should be confirmed as not harming performance.
[Fact]
public void ToArray_UseCopyToWithICollection()
{
TestCollection<int> source = new TestCollection<int>(new int[] { 1, 2, 3, 4 });
var resultArray = source.ToArray();
Assert.Equal(source, resultArray);
Assert.Equal(1, source.CopyToTouched);
}
[Fact(Skip = "Valid test but too intensive to enable even in OuterLoop")]
public void ToArray_FailOnExtremelyLargeCollection()
{
var largeSeq = new FastInfiniteEnumerator<byte>();
var thrownException = Assert.ThrowsAny<Exception>(() => { largeSeq.ToArray(); });
Assert.True(thrownException.GetType() == typeof(OverflowException) || thrownException.GetType() == typeof(OutOfMemoryException));
}
[Theory]
[InlineData(new int[] { }, new string[] { })]
[InlineData(new int[] { 1 }, new string[] { "1" })]
[InlineData(new int[] { 1, 2, 3 }, new string[] { "1", "2", "3" })]
public void ToArray_ArrayWhereSelect(int[] sourceIntegers, string[] convertedStrings)
{
Assert.Equal(convertedStrings, sourceIntegers.Select(i => i.ToString()).ToArray());
Assert.Equal(sourceIntegers, sourceIntegers.Where(i => true).ToArray());
Assert.Equal(Array.Empty<int>(), sourceIntegers.Where(i => false).ToArray());
Assert.Equal(convertedStrings, sourceIntegers.Where(i => true).Select(i => i.ToString()).ToArray());
Assert.Equal(Array.Empty<string>(), sourceIntegers.Where(i => false).Select(i => i.ToString()).ToArray());
Assert.Equal(convertedStrings, sourceIntegers.Select(i => i.ToString()).Where(s => s != null).ToArray());
Assert.Equal(Array.Empty<string>(), sourceIntegers.Select(i => i.ToString()).Where(s => s == null).ToArray());
}
[Theory]
[InlineData(new int[] { }, new string[] { })]
[InlineData(new int[] { 1 }, new string[] { "1" })]
[InlineData(new int[] { 1, 2, 3 }, new string[] { "1", "2", "3" })]
public void ToArray_ListWhereSelect(int[] sourceIntegers, string[] convertedStrings)
{
var sourceList = new List<int>(sourceIntegers);
Assert.Equal(convertedStrings, sourceList.Select(i => i.ToString()).ToArray());
Assert.Equal(sourceList, sourceList.Where(i => true).ToArray());
Assert.Equal(Array.Empty<int>(), sourceList.Where(i => false).ToArray());
Assert.Equal(convertedStrings, sourceList.Where(i => true).Select(i => i.ToString()).ToArray());
Assert.Equal(Array.Empty<string>(), sourceList.Where(i => false).Select(i => i.ToString()).ToArray());
Assert.Equal(convertedStrings, sourceList.Select(i => i.ToString()).Where(s => s != null).ToArray());
Assert.Equal(Array.Empty<string>(), sourceList.Select(i => i.ToString()).Where(s => s == null).ToArray());
}
[Fact]
public void SameResultsRepeatCallsFromWhereOnIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > int.MinValue
select x;
Assert.Equal(q.ToArray(), q.ToArray());
}
[Fact]
public void SameResultsRepeatCallsFromWhereOnStringQuery()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", string.Empty }
where !string.IsNullOrEmpty(x)
select x;
Assert.Equal(q.ToArray(), q.ToArray());
}
[Fact]
public void SameResultsButNotSameObject()
{
var qInt = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > int.MinValue
select x;
var qString = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", string.Empty }
where !string.IsNullOrEmpty(x)
select x;
Assert.NotSame(qInt.ToArray(), qInt.ToArray());
Assert.NotSame(qString.ToArray(), qString.ToArray());
}
[Fact]
public void EmptyArraysSameObject()
{
// .NET Core returns the instance as an optimization.
// see https://github.com/dotnet/corefx/pull/2401.
Assert.True(ReferenceEquals(Enumerable.Empty<int>().ToArray(), Enumerable.Empty<int>().ToArray()));
var array = new int[0];
Assert.NotSame(array, array.ToArray());
}
[Fact]
public void SourceIsEmptyICollectionT()
{
int[] source = { };
ICollection<int> collection = source as ICollection<int>;
Assert.Empty(source.ToArray());
Assert.Empty(collection.ToArray());
}
[Fact]
public void SourceIsICollectionTWithFewElements()
{
int?[] source = { -5, null, 0, 10, 3, -1, null, 4, 9 };
int?[] expected = { -5, null, 0, 10, 3, -1, null, 4, 9 };
ICollection<int?> collection = source as ICollection<int?>;
Assert.Equal(expected, source.ToArray());
Assert.Equal(expected, collection.ToArray());
}
[Fact]
public void SourceNotICollectionAndIsEmpty()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-4, 0);
Assert.Null(source as ICollection<int>);
Assert.Empty(source.ToArray());
}
[Fact]
public void SourceNotICollectionAndHasElements()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-4, 10);
int[] expected = { -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 };
Assert.Null(source as ICollection<int>);
Assert.Equal(expected, source.ToArray());
}
[Fact]
public void SourceNotICollectionAndAllNull()
{
IEnumerable<int?> source = RepeatedNullableNumberGuaranteedNotCollectionType(null, 5);
int?[] expected = { null, null, null, null, null };
Assert.Null(source as ICollection<int>);
Assert.Equal(expected, source.ToArray());
}
[Fact]
public void ConstantTimeCountPartitionSelectSameTypeToArray()
{
var source = Enumerable.Range(0, 100).Select(i => i * 2).Skip(1).Take(5);
Assert.Equal(new[] { 2, 4, 6, 8, 10 }, source.ToArray());
}
[Fact]
public void ConstantTimeCountPartitionSelectDiffTypeToArray()
{
var source = Enumerable.Range(0, 100).Select(i => i.ToString()).Skip(1).Take(5);
Assert.Equal(new[] { "1", "2", "3", "4", "5" }, source.ToArray());
}
[Fact]
public void ConstantTimeCountEmptyPartitionSelectSameTypeToArray()
{
var source = Enumerable.Range(0, 100).Select(i => i * 2).Skip(1000);
Assert.Empty(source.ToArray());
}
[Fact]
public void ConstantTimeCountEmptyPartitionSelectDiffTypeToArray()
{
var source = Enumerable.Range(0, 100).Select(i => i.ToString()).Skip(1000);
Assert.Empty(source.ToArray());
}
[Fact]
public void NonConstantTimeCountPartitionSelectSameTypeToArray()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 100).OrderBy(i => i).Select(i => i * 2).Skip(1).Take(5);
Assert.Equal(new[] { 2, 4, 6, 8, 10 }, source.ToArray());
}
[Fact]
public void NonConstantTimeCountPartitionSelectDiffTypeToArray()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 100).OrderBy(i => i).Select(i => i.ToString()).Skip(1).Take(5);
Assert.Equal(new[] { "1", "2", "3", "4", "5" }, source.ToArray());
}
[Fact]
public void NonConstantTimeCountEmptyPartitionSelectSameTypeToArray()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 100).OrderBy(i => i).Select(i => i * 2).Skip(1000);
Assert.Empty(source.ToArray());
}
[Fact]
public void NonConstantTimeCountEmptyPartitionSelectDiffTypeToArray()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 100).OrderBy(i => i).Select(i => i.ToString()).Skip(1000);
Assert.Empty(source.ToArray());
}
[Theory]
[MemberData(nameof(JustBelowPowersOfTwoLengths))]
[MemberData(nameof(PowersOfTwoLengths))]
[MemberData(nameof(JustAbovePowersOfTwoLengths))]
public void ToArrayShouldWorkWithSpecialLengthLazyEnumerables(int length)
{
Debug.Assert(length >= 0);
var range = Enumerable.Range(0, length);
var lazyEnumerable = ForceNotCollection(range); // We won't go down the IIListProvider path
Assert.Equal(range, lazyEnumerable.ToArray());
}
// Consider that two very similar enums is not unheard of, if e.g. two assemblies map the
// same external source of numbers (codes, response codes, colour codes, etc.) to values.
private enum Enum0
{
First,
Second,
Third
}
private enum Enum1
{
First,
Second,
Third
}
[Fact]
public void ToArray_Cast()
{
Enum0[] source = { Enum0.First, Enum0.Second, Enum0.Third };
var cast = source.Cast<Enum1>();
Assert.IsType<Enum0[]>(cast);
var castArray = cast.ToArray();
Assert.IsType<Enum1[]>(castArray);
Assert.Equal(new[] { Enum1.First, Enum1.Second, Enum1.Third }, castArray);
}
public static IEnumerable<object[]> JustBelowPowersOfTwoLengths()
{
return SmallPowersOfTwo.Select(p => new object[] { p - 1 });
}
public static IEnumerable<object[]> PowersOfTwoLengths()
{
return SmallPowersOfTwo.Select(p => new object[] { p });
}
public static IEnumerable<object[]> JustAbovePowersOfTwoLengths()
{
return SmallPowersOfTwo.Select(p => new object[] { p + 1 });
}
private static IEnumerable<int> SmallPowersOfTwo
{
get
{
// By N being "small" we mean that allocating an array of
// size N doesn't come close to the risk of causing an OOME
const int MaxPower = 18;
for (int i = 0; i <= MaxPower; i++)
{
yield return 1 << i; // equivalent to pow(2, i)
}
}
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.ComponentModel;
using System.Reflection;
// Required for cloning the object information that we are after
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Pacman.GameLogic.Ghosts;
namespace Pacman.GameLogic
{
public class GameState : ICloneable
{
[CategoryAttribute("The level number"),DescriptionAttribute("The level number that the controller is on")]
private int level = 0;
public int Level { get { return level; } }
public static Random Random = new Random();
// ** NOTE ** //
// These were originally read only.
// Had to remove them because of cloning purposes.
[CategoryAttribute("Pacman Object"),DescriptionAttribute("The object responsible for Ms. Pacman within the gamestate")]
public Pacman Pacman;
[CategoryAttribute("Red Ghost"), DescriptionAttribute("The red ghost within the maze")]
public Red Red;
[CategoryAttribute("The pink ghost within the maze"), DescriptionAttribute("The object responsible for Ms. Pacman within the gamestate")]
public Pink Pink;
public Blue Blue;
public Brown Brown;
public Ghost[] Ghosts = new Ghost[4];
[NonSerialized()]
public BasePacman Controller;
[CategoryAttribute("MSPF"),DescriptionAttribute("MSPF description")]
public const int MSPF = 40;
[CategoryAttribute("Timer"),DescriptionAttribute("The in game timer ticker")]
public long Timer = 0;
[CategoryAttribute("Elapsed time"), DescriptionAttribute("Time elapsed since the simulation started")]
public long ElapsedTime = 0;
public long Frames = 0;
// Used for determining whether during simulation there was a failure.
[CategoryAttribute("GameoverCount"), DescriptionAttribute("The amount of times that the agent lost the game")]
public int m_GameOverCount = 0;
[NonSerialized()]
public static Image[] Mazes = new Image[1];
private static Map[] maps = new Map[1];
private Map map;
private bool started = false;
#region Properties
public Map Map { get { return map; } set { map = value; } }
public bool Started { get { return started; } }
#endregion
private const int reversalTime1 = 5000, reversalTime2 = 25000; // estimates
private int reversal1 = reversalTime1, reversal2 = reversalTime2;
// settings
[CategoryAttribute("PacmanMortal"),DescriptionAttribute("Was Pacman considered invincible during this game state?")]
public bool PacmanMortal = true;
[CategoryAttribute("NaturalReversals"),DescriptionAttribute("Will the ghosts return back to their normal state afterwards?")]
public bool NaturalReversals = true;
public bool Replay = false;
[CategoryAttribute("AutomaticLevelChange"),DescriptionAttribute("Has the level changed")]
public bool AutomaticLevelChange = true;
[field: NonSerializedAttribute()]
public event EventHandler GameOver;
public event EventHandler PillsEaten;
public event EventHandler GhostEaten;
public int CloneTimeBegin = 0;
public int CloneTimeEnd = 0;
// Store the amount of time in total that has been consumed
public int MCTSTimeTotal = 0;
public int MCTSGamesTotal = 0;
[field: NonSerializedAttribute()]
public event EventHandler PacmanDead = new EventHandler(delegate(object sender, EventArgs e) { });
// For registering how many pills have been eaten within the environment.
public int m_PillsEaten = 0;
public int m_PowerPillsEaten = 0;
public int m_GhostsEaten = 0;
public int m_TotalRoundScore = 0;
#region Constructors
public GameState(List<double> EvolvedValues, int RandomSeed) {
loadMazes();
map = maps[Level];
// default position ... find out where
Pacman = new Pacman(Pacman.StartX, Pacman.StartY, this, EvolvedValues[0]);
Ghosts[0] = Red = new Red(Red.StartX, Red.StartY, this, EvolvedValues[1], EvolvedValues[5]);
Ghosts[1] = Pink = new Pink(Pink.StartX, Pink.StartY, this, EvolvedValues[2], EvolvedValues[6]);
Ghosts[2] = Blue = new Blue(Blue.StartX, Blue.StartY, this, EvolvedValues[3], EvolvedValues[7]);
Ghosts[3] = Brown = new Brown(Brown.StartX, Brown.StartY, this, EvolvedValues[4], EvolvedValues[8]);
Random = new Random(RandomSeed);
}
public GameState(int RandomSeed = 0)
{
loadMazes();
map = maps[Level];
// default position ... find out where
Pacman = new Pacman(Pacman.StartX, Pacman.StartY, this, 3.0f);
Ghosts[0] = Red = new Red(Red.StartX, Red.StartY, this, 2.8f, 1.5f);
Ghosts[1] = Pink = new Pink(Pink.StartX, Pink.StartY, this, 2.8f, 1.5f);
Ghosts[2] = Blue = new Blue(Blue.StartX, Blue.StartY, this, 2.8f, 1.5f);
Ghosts[3] = Brown = new Brown(Brown.StartX, Brown.StartY, this, 2.8f, 1.5f);
if(RandomSeed != 0)
{
Random = new Random(RandomSeed);
}
}
#endregion
#region Methods
private void loadMazes(){
for( int i = 0; i < 1; i++ ) {
if (Mazes[i] == null || maps[i] == null)
{
Mazes[i] = Util.LoadImage("ms_pacman_maze" + (i + 1) + ".gif");
maps[i] = new Map((Bitmap)Mazes[i]);
}
}
}
// Simple function that increases the count in which the
// the controller has died.
private void IncreaseGameOverCount()
{
m_GameOverCount++;
}
public void StartPlay() {
started = true;
Timer = 0;
Frames = 0;
}
public void PausePlay() {
started = false;
}
public void ResumePlay() {
started = true;
}
public void ReverseGhosts() {
foreach( Ghost g in Ghosts ) {
g.Reversal();
}
}
public static Direction InverseDirection(Direction pDirection)
{
switch (pDirection)
{
case Direction.Up: return Direction.Down;
case Direction.Down: return Direction.Up;
case Direction.Left: return Direction.Right;
case Direction.Right: return Direction.Left;
}
return Direction.None;
}
/// <summary>
/// Move the Pacman agent in the given direction
/// </summary>
/// <param name="pDirection">The direction that we want the Pacman agent to move in</param>
public void AdvanceGame(Direction pDirection)
{
if (Pacman.Lives == -1)
{
InvokeGameOver(true);
return;
}
// Set the direction of PacMan within this gamestate.
// Expectedly meant to be cloned
Pacman.SetDirection(pDirection);
if (!started)
{
return;
}
Frames++;
Timer += MSPF;
ElapsedTime += MSPF;
// change level
// TODO: use levels instead of just mazes
if (Map.PillsLeft == 0 && AutomaticLevelChange)
{
level = Level + 1; // test for screenplayer
if (Level > maps.Length - 1) level = 0;
map = maps[Level];
map.Reset();
resetTimes();
Pacman.ResetPosition();
foreach (Ghost g in Ghosts)
{
g.ResetPosition();
}
if (Controller != null)
{
Controller.LevelCleared();
}
return;
}
// ghost reversals
if (NaturalReversals)
{
bool ghostFleeing = false;
foreach (Ghost g in Ghosts)
{
if (!g.Chasing)
{
ghostFleeing = true;
break;
}
}
if (ghostFleeing)
{
reversal1 += MSPF;
reversal2 += MSPF;
}
else
{
if (Timer > reversal1)
{
reversal1 += 1200000; // 20 min
ReverseGhosts();
}
if (Timer > reversal2)
{
reversal2 = Int32.MaxValue;
ReverseGhosts();
}
}
}
if (Replay)
{
// do nothing
}
else
{
// move
Pacman.MoveSimulated();
foreach (Ghost g in Ghosts)
{
g.Move();
// check collisions
if (g.Distance(Pacman) < 4.0f)
{
if (g.Chasing)
{
if (PacmanMortal)
{
resetTimes();
Pacman.Die();
PacmanDead(this, null);
foreach (Ghost g2 in Ghosts)
{
g2.PacmanDead();
}
//if (Pacman.Lives == -1)
//{
// InvokeGameOver(true);
//}
break;
}
}
else if (g.Entered)
{
Pacman.EatGhost();
g.Eaten();
}
}
}
}
}
// Generate a random move based on the simrandompac.
public Direction GenerateRandomMove()
{
List<Direction> possible = Pacman.PossibleDirections();
if (possible.Count > 0)
{
int select = Random.Next(0, possible.Count); //new Random().Next(0, possible.Count);
if (possible[select] != Pacman.InverseDirection(Pacman.Direction))
return possible[select];
}
return Direction.None;
}
/// <summary>
/// Used for the MCTS implementation so that we can see how the controller behaves
/// </summary>
public void UpdateSimulated()
{
if (Pacman.Lives == -1)
{
InvokeGameOver(true);
return;
}
// Get the next direction from the controller that we want to
// simulate from
Direction _nextDirection = GenerateRandomMove();
Pacman.SetDirection(_nextDirection);
if (!started)
{
return;
}
Frames++;
Timer += MSPF;
ElapsedTime += MSPF;
// change level
// TODO: use levels instead of just mazes
if (Map.PillsLeft == 0 && AutomaticLevelChange)
{
level = Level + 1; // test for screenplayer
if (Level > maps.Length - 1) level = 0;
map = maps[Level];
map.Reset();
resetTimes();
Pacman.ResetPosition();
foreach (Ghost g in Ghosts)
{
g.ResetPosition();
}
if (Controller != null)
{
Controller.LevelCleared();
}
return;
}
// ghost reversals
if (NaturalReversals)
{
bool ghostFleeing = false;
foreach (Ghost g in Ghosts)
{
if (!g.Chasing)
{
ghostFleeing = true;
break;
}
}
if (ghostFleeing)
{
reversal1 += MSPF;
reversal2 += MSPF;
}
else
{
if (Timer > reversal1)
{
reversal1 += 1200000; // 20 min
ReverseGhosts();
}
if (Timer > reversal2)
{
reversal2 = Int32.MaxValue;
ReverseGhosts();
}
}
}
if (Replay)
{
// do nothing
}
else
{
// move
Pacman.MoveSimulated();
foreach (Ghost g in Ghosts)
{
g.Move();
// check collisions
if (g.Distance(Pacman) < 4.0f)
{
if (g.Chasing)
{
if (PacmanMortal)
{
resetTimes();
Pacman.Die();
PacmanDead(this, null);
foreach (Ghost g2 in Ghosts)
{
g2.PacmanDead();
}
//if (Pacman.Lives <= -1)
//{
// InvokeGameOver(true);
//}
break;
}
}
else if (g.Entered)
{
Pacman.EatGhost();
g.Eaten();
}
}
}
}
}
public void Update() {
if( !started ) {
return;
}
Frames++;
Timer += MSPF;
ElapsedTime += MSPF;
// change level
// TODO: use levels instead of just mazes
if( Map.PillsLeft == 0 && AutomaticLevelChange ) {
level = Level + 1; // test for screenplayer
if( Level > maps.Length - 1 ) level = 0;
map = maps[Level];
map.Reset();
resetTimes();
Pacman.ResetPosition();
foreach( Ghost g in Ghosts ) {
g.ResetPosition();
}
if( Controller != null ) {
Controller.LevelCleared();
}
return;
}
// ghost reversals
if( NaturalReversals ) {
bool ghostFleeing = false;
foreach( Ghost g in Ghosts ) {
if( !g.Chasing ) {
ghostFleeing = true;
break;
}
}
if( ghostFleeing ) {
reversal1 += MSPF;
reversal2 += MSPF;
} else {
if( Timer > reversal1 ) {
reversal1 += 1200000; // 20 min
ReverseGhosts();
}
if( Timer > reversal2 ) {
reversal2 = Int32.MaxValue;
ReverseGhosts();
}
}
}
if( Replay ) {
// do nothing
}
else {
// move
Pacman.Move();
foreach( Ghost g in Ghosts ) {
g.Move();
// check collisions
if( g.Distance(Pacman) < 4.0f ) {
if( g.Chasing ) {
if( PacmanMortal ) {
resetTimes();
// Signal to the controller that we have restarted
// Store the states at the same time
Controller.Restart(this);
Pacman.Die();
PacmanDead(this, null);
foreach( Ghost g2 in Ghosts ) {
g2.PacmanDead();
}
if( Pacman.Lives == -1 ) {
InvokeGameOver();
}
break;
}
} else if( g.Entered ) {
Pacman.EatGhost();
g.Eaten();
}
}
}
}
}
public void InvokeGameOver(bool Simulated = false) {
m_GameOverCount++;
GameOver?.Invoke(this, null);
m_TotalRoundScore = 0;
m_PillsEaten = 0;
m_PowerPillsEaten = 0;
m_GhostsEaten = 0;
ElapsedTime = 0;
level = 0;
map = maps[Level];
if (!Simulated)
{
map.Reset();
Pacman.Reset();
foreach (Ghost g in Ghosts)
{
g.PacmanDead();
}
}
}
private void resetTimes() {
Timer = 0;
reversal1 = reversalTime1;
reversal2 = reversalTime2;
}
#endregion
// Save the output of the game state image so that we can
// examine the simulations that were made.
public void SaveGameStateImage(Graphics g)
{
}
/// <summary>
/// Return whether or not there is a ghost at the provided coordinates
/// </summary>
/// <param name="x">The x coordinate</param>
/// <param name="y">The y coordinate</param>
/// <returns>Returns whether or not there is a ghost at the provided position</returns>
public bool GhostIsAt(int x, int y)
{
foreach (var ghost in Ghosts)
{
if (ghost.Node.X == x &&
ghost.Node.Y == y)
return true;
}
return false;
}
#region ICloneable Members
/** CLONE ALL THE THINGS! **/
public object Clone()
{
CloneTimeBegin = Environment.TickCount;
// Create a new copy of the object that we want
GameState _temp = (GameState)this.MemberwiseClone();
_temp.Map = (Map)this.Map.Clone();
_temp.Pacman = (Pacman)this.Pacman.Clone(); // Grab a copy of pacman while we're at it
_temp.Pacman.GameState = _temp;
_temp.GameOver = delegate(object sender, EventArgs e) { };
// Genereate the maps
//_temp.maps = new Map[1];
//_temp.maps[0] = (Map)maps[0].Clone();
// Commenting this out for testing purposes
//for (int i = 0; i < maps.Length; i++)
//{
// _temp.maps[i] = (Map)maps[i].Clone();
//}
// Generate the new array of ghosts
_temp.Ghosts = new Ghost[4];
_temp.Ghosts[0] = _temp.Red = (Red)Red.Clone();
_temp.Ghosts[1] = _temp.Pink = (Pink)Pink.Clone();
_temp.Ghosts[2] = _temp.Blue = (Blue)Blue.Clone();
_temp.Ghosts[3] = _temp.Brown = (Brown)Brown.Clone();
// Assign the newly generated game state manually
// to the objects.
_temp.Brown.GameState = _temp;
_temp.Pink.GameState = _temp;
_temp.Blue.GameState = _temp;
_temp.Red.GameState = _temp;
// Generate a random controller for the future simulations
_temp.Controller = new SimRandomPac();
// Loop through the ghosts and assign the game state appropriately
for (int i = 0; i < _temp.Ghosts.Length; i++)
{
_temp.Ghosts[i].GameState = _temp;
}
CloneTimeEnd = Environment.TickCount;
return _temp;
}
//public object DeepCopy()
//{
// return CloneObject(this);
//}
//public object CloneObject(object o)
//{
// Type type = o.GetType();
// object new_obj = Activator.CreateInstance(type);
// foreach (FieldInfo info in type.GetFields())
// {
// if (info.IsValueType == true)
// {
// info.SetValue(new_obj, info.GetValue(o));
// }
// else
// {
// object cloned = CloneObject(info.GetValue(o));
// info.SetValue(new_obj, cloned);
// }
// }
// return new_obj;
//}
#endregion
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MoreLinq.Test
{
using System;
using System.Collections.Generic;
using NUnit.Framework;
[TestFixture]
public class GroupAdjacentTest
{
[Test]
public void GroupAdjacentIsLazy()
{
var bs = new BreakingSequence<object>();
bs.GroupAdjacent(delegate { return 0; });
bs.GroupAdjacent(delegate { return 0; }, o => o);
bs.GroupAdjacent(delegate { return 0; }, o => o, EqualityComparer<int>.Default);
bs.GroupAdjacent(delegate { return 0; }, EqualityComparer<int>.Default);
bs.GroupAdjacent(delegate { return 0; }, (k, g) => g);
bs.GroupAdjacent(delegate { return 0; }, (k, g) => g, EqualityComparer<int>.Default);
}
[Test]
public void GroupAdjacentSourceSequence()
{
const string one = "one";
const string two = "two";
const string three = "three";
const string four = "four";
const string five = "five";
const string six = "six";
const string seven = "seven";
const string eight = "eight";
const string nine = "nine";
const string ten = "ten";
var source = new[] { one, two, three, four, five, six, seven, eight, nine, ten };
var groupings = source.GroupAdjacent(s => s.Length);
using (var reader = groupings.Read())
{
AssertGrouping(reader, 3, one, two);
AssertGrouping(reader, 5, three);
AssertGrouping(reader, 4, four, five);
AssertGrouping(reader, 3, six);
AssertGrouping(reader, 5, seven, eight);
AssertGrouping(reader, 4, nine);
AssertGrouping(reader, 3, ten);
reader.ReadEnd();
}
}
[Test]
public void GroupAdjacentSourceSequenceComparer()
{
var source = new[] { "foo", "FOO", "Foo", "bar", "BAR", "Bar" };
var groupings = source.GroupAdjacent(s => s, StringComparer.OrdinalIgnoreCase);
using (var reader = groupings.Read())
{
AssertGrouping(reader, "foo", "foo", "FOO", "Foo");
AssertGrouping(reader, "bar", "bar", "BAR", "Bar");
reader.ReadEnd();
}
}
[Test]
public void GroupAdjacentSourceSequenceElementSelector()
{
var source = new[]
{
new { Month = 1, Value = 123 },
new { Month = 1, Value = 456 },
new { Month = 1, Value = 789 },
new { Month = 2, Value = 987 },
new { Month = 2, Value = 654 },
new { Month = 2, Value = 321 },
new { Month = 3, Value = 789 },
new { Month = 3, Value = 456 },
new { Month = 3, Value = 123 },
new { Month = 1, Value = 123 },
new { Month = 1, Value = 456 },
new { Month = 1, Value = 781 },
};
var groupings = source.GroupAdjacent(e => e.Month, e => e.Value * 2);
using (var reader = groupings.Read())
{
AssertGrouping(reader, 1, 123 * 2, 456 * 2, 789 * 2);
AssertGrouping(reader, 2, 987 * 2, 654 * 2, 321 * 2);
AssertGrouping(reader, 3, 789 * 2, 456 * 2, 123 * 2);
AssertGrouping(reader, 1, 123 * 2, 456 * 2, 781 * 2);
reader.ReadEnd();
}
}
[Test]
public void GroupAdjacentSourceSequenceElementSelectorComparer()
{
var source = new[]
{
new { Month = "jan", Value = 123 },
new { Month = "Jan", Value = 456 },
new { Month = "JAN", Value = 789 },
new { Month = "feb", Value = 987 },
new { Month = "Feb", Value = 654 },
new { Month = "FEB", Value = 321 },
new { Month = "mar", Value = 789 },
new { Month = "Mar", Value = 456 },
new { Month = "MAR", Value = 123 },
new { Month = "jan", Value = 123 },
new { Month = "Jan", Value = 456 },
new { Month = "JAN", Value = 781 },
};
var groupings = source.GroupAdjacent(e => e.Month, e => e.Value * 2, StringComparer.OrdinalIgnoreCase);
using (var reader = groupings.Read())
{
AssertGrouping(reader, "jan", 123 * 2, 456 * 2, 789 * 2);
AssertGrouping(reader, "feb", 987 * 2, 654 * 2, 321 * 2);
AssertGrouping(reader, "mar", 789 * 2, 456 * 2, 123 * 2);
AssertGrouping(reader, "jan", 123 * 2, 456 * 2, 781 * 2);
reader.ReadEnd();
}
}
[Test]
public void GroupAdjacentSourceSequenceResultSelector()
{
var source = new[]
{
new { Month = 1, Value = 123 },
new { Month = 1, Value = 456 },
new { Month = 1, Value = 789 },
new { Month = 2, Value = 987 },
new { Month = 2, Value = 654 },
new { Month = 2, Value = 321 },
new { Month = 3, Value = 789 },
new { Month = 3, Value = 456 },
new { Month = 3, Value = 123 },
new { Month = 1, Value = 123 },
new { Month = 1, Value = 456 },
new { Month = 1, Value = 781 },
};
var groupings = source.GroupAdjacent(e => e.Month, (key, group) => group.Sum(v => v.Value));
using (var reader = groupings.Read()) {
AssertResult(reader, 123 + 456 + 789);
AssertResult(reader, 987 + 654 + 321);
AssertResult(reader, 789 + 456 + 123);
AssertResult(reader, 123 + 456 + 781);
reader.ReadEnd();
}
}
[Test]
public void GroupAdjacentSourceSequenceResultSelectorComparer()
{
var source = new[]
{
new { Month = "jan", Value = 123 },
new { Month = "Jan", Value = 456 },
new { Month = "JAN", Value = 789 },
new { Month = "feb", Value = 987 },
new { Month = "Feb", Value = 654 },
new { Month = "FEB", Value = 321 },
new { Month = "mar", Value = 789 },
new { Month = "Mar", Value = 456 },
new { Month = "MAR", Value = 123 },
new { Month = "jan", Value = 123 },
new { Month = "Jan", Value = 456 },
new { Month = "JAN", Value = 781 },
};
var groupings = source.GroupAdjacent(e => e.Month, (key, group) => group.Sum(v => v.Value), StringComparer.OrdinalIgnoreCase);
using (var reader = groupings.Read()) {
AssertResult(reader, 123 + 456 + 789);
AssertResult(reader, 987 + 654 + 321);
AssertResult(reader, 789 + 456 + 123);
AssertResult(reader, 123 + 456 + 781);
reader.ReadEnd();
}
}
static void AssertGrouping<TKey, TElement>(SequenceReader<System.Linq.IGrouping<TKey, TElement>> reader,
TKey key, params TElement[] elements)
{
var grouping = reader.Read();
Assert.That(grouping, Is.Not.Null);
Assert.That(grouping.Key, Is.EqualTo(key));
grouping.AssertSequenceEqual(elements);
}
static void AssertResult<TElement>(SequenceReader<TElement> reader, TElement element)
{
var result = reader.Read();
Assert.That(result, Is.Not.Null);
Assert.AreEqual(element, result);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
namespace System.Net.Security
{
internal static class SslStreamPal
{
private static readonly StreamSizes s_streamSizes = new StreamSizes();
public static Exception GetException(SecurityStatusPal status)
{
return status.Exception ?? new Interop.OpenSsl.SslException((int)status.ErrorCode);
}
internal const bool StartMutualAuthAsAnonymous = false;
internal const bool CanEncryptEmptyMessage = false;
public static void VerifyPackageInfo()
{
}
public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context,
SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool remoteCertRequired)
{
return HandshakeInternal(credential, ref context, inputBuffer, outputBuffer, true, remoteCertRequired);
}
public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context,
string targetName, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer)
{
return HandshakeInternal(credential, ref context, inputBuffer, outputBuffer, false, false);
}
public static SecurityStatusPal InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer)
{
Debug.Assert(inputBuffers.Length == 2);
Debug.Assert(inputBuffers[1].token == null);
return HandshakeInternal(credential, ref context, inputBuffers[0], outputBuffer, false, false);
}
public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certificate,
SslProtocols protocols, EncryptionPolicy policy, bool isServer)
{
return new SafeFreeSslCredentials(certificate, protocols, policy);
}
public static SecurityStatusPal EncryptMessage(SafeDeleteContext securityContext, byte[] input, int offset, int size, int headerSize, int trailerSize, ref byte[] output, out int resultSize)
{
return EncryptDecryptHelper(securityContext, input, offset, size, true, ref output, out resultSize);
}
public static SecurityStatusPal DecryptMessage(SafeDeleteContext securityContext, byte[] buffer, ref int offset, ref int count)
{
int resultSize;
SecurityStatusPal retVal = EncryptDecryptHelper(securityContext, buffer, offset, count, false, ref buffer, out resultSize);
if (retVal.ErrorCode == SecurityStatusPalErrorCode.OK ||
retVal.ErrorCode == SecurityStatusPalErrorCode.Renegotiate)
{
count = resultSize;
}
return retVal;
}
public static ChannelBinding QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute)
{
ChannelBinding bindingHandle;
if (attribute == ChannelBindingKind.Endpoint)
{
bindingHandle = EndpointChannelBindingToken.Build(securityContext);
if (bindingHandle == null)
{
throw Interop.OpenSsl.CreateSslException(SR.net_ssl_invalid_certificate);
}
}
else
{
bindingHandle = Interop.OpenSsl.QueryChannelBinding(
((SafeDeleteSslContext)securityContext).SslContext,
attribute);
}
return bindingHandle;
}
public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes)
{
streamSizes = s_streamSizes;
}
public static void QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo)
{
connectionInfo = new SslConnectionInfo(((SafeDeleteSslContext)securityContext).SslContext);
}
private static SecurityStatusPal HandshakeInternal(SafeFreeCredentials credential, ref SafeDeleteContext context,
SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool isServer, bool remoteCertRequired)
{
Debug.Assert(!credential.IsInvalid);
try
{
if ((null == context) || context.IsInvalid)
{
context = new SafeDeleteSslContext(credential as SafeFreeSslCredentials, isServer, remoteCertRequired);
}
byte[] output = null;
int outputSize;
bool done;
if (null == inputBuffer)
{
done = Interop.OpenSsl.DoSslHandshake(((SafeDeleteSslContext)context).SslContext, null, 0, 0, out output, out outputSize);
}
else
{
done = Interop.OpenSsl.DoSslHandshake(((SafeDeleteSslContext)context).SslContext, inputBuffer.token, inputBuffer.offset, inputBuffer.size, out output, out outputSize);
}
outputBuffer.size = outputSize;
outputBuffer.offset = 0;
outputBuffer.token = outputSize > 0 ? output : null;
return new SecurityStatusPal(done ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.ContinueNeeded);
}
catch (Exception exc)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, exc);
}
}
private static SecurityStatusPal EncryptDecryptHelper(SafeDeleteContext securityContext, byte[] input, int offset, int size, bool encrypt, ref byte[] output, out int resultSize)
{
resultSize = 0;
try
{
Interop.Ssl.SslErrorCode errorCode = Interop.Ssl.SslErrorCode.SSL_ERROR_NONE;
SafeSslHandle scHandle = ((SafeDeleteSslContext)securityContext).SslContext;
if (encrypt)
{
resultSize = Interop.OpenSsl.Encrypt(scHandle, input, offset, size, ref output, out errorCode);
}
else
{
Debug.Assert(ReferenceEquals(input, output), "Expected input==output when decrypting");
resultSize = Interop.OpenSsl.Decrypt(scHandle, input, offset, size, out errorCode);
}
switch (errorCode)
{
case Interop.Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE:
return new SecurityStatusPal(SecurityStatusPalErrorCode.Renegotiate);
case Interop.Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
return new SecurityStatusPal(SecurityStatusPalErrorCode.ContextExpired);
case Interop.Ssl.SslErrorCode.SSL_ERROR_NONE:
case Interop.Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
default:
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, new Interop.OpenSsl.SslException((int)errorCode));
}
}
catch (Exception ex)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, ex);
}
}
public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage)
{
// There doesn't seem to be an exposed API for writing an alert,
// the API seems to assume that all alerts are generated internally by
// SSLHandshake.
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext)
{
SafeDeleteSslContext sslContext = ((SafeDeleteSslContext)securityContext);
// Unset the quiet shutdown option initially configured.
Interop.Ssl.SslSetQuietShutdown(sslContext.SslContext, 0);
int status = Interop.Ssl.SslShutdown(sslContext.SslContext);
if (status == 0)
{
// Call SSL_shutdown again for a bi-directional shutdown.
status = Interop.Ssl.SslShutdown(sslContext.SslContext);
}
if (status == 1)
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
Interop.Ssl.SslErrorCode code = Interop.Ssl.SslGetError(sslContext.SslContext, status);
if (code == Interop.Ssl.SslErrorCode.SSL_ERROR_WANT_READ ||
code == Interop.Ssl.SslErrorCode.SSL_ERROR_WANT_WRITE)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
else
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, new Interop.OpenSsl.SslException((int)code));
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.Engine
{
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.DocAsCode.MarkdownLite;
using Microsoft.DocAsCode.Plugins;
using Microsoft.DocAsCode.Common;
[Serializable]
public sealed class XRefDetails
{
/// <summary>
/// TODO: completely move into template
/// Must be consistent with template input.replace(/\W/g, '_');
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private static Regex HtmlEncodeRegex = new Regex(@"\W", RegexOptions.Compiled);
public string Uid { get; private set; }
public string Anchor { get; private set; }
public string Title { get; private set; }
public string Href { get; private set; }
public string Raw { get; private set; }
public string RawSource { get; private set; }
public string DisplayProperty { get; private set; }
public string AltProperty { get; private set; }
public string InnerHtml { get; private set; }
public string Text { get; private set; }
public string Alt { get; private set; }
public XRefSpec Spec { get; private set; }
public bool ThrowIfNotResolved { get; private set; }
public string SourceFile { get; private set; }
public int SourceStartLineNumber { get; private set; }
public int SourceEndLineNumber { get; private set; }
private XRefDetails() { }
public static XRefDetails From(HtmlAgilityPack.HtmlNode node)
{
if (node.Name != "xref") throw new NotSupportedException("Only xref node is supported!");
var xref = new XRefDetails();
var uid = node.GetAttributeValue("uid", null);
var rawHref = node.GetAttributeValue("href", null);
NameValueCollection queryString = null;
if (!string.IsNullOrEmpty(rawHref))
{
if (!string.IsNullOrEmpty(uid))
{
Logger.LogWarning($"Both href and uid attribute are defined for {node.OuterHtml}, use href instead of uid.");
}
string others;
var anchorIndex = rawHref.IndexOf("#");
if (anchorIndex == -1)
{
xref.Anchor = string.Empty;
others = rawHref;
}
else
{
xref.Anchor = rawHref.Substring(anchorIndex);
others = rawHref.Remove(anchorIndex);
}
var queryIndex = others.IndexOf("?");
if (queryIndex == -1)
{
xref.Uid = HttpUtility.UrlDecode(others);
}
else
{
xref.Uid = HttpUtility.UrlDecode(others.Remove(queryIndex));
queryString = HttpUtility.ParseQueryString(others.Substring(queryIndex));
}
}
else
{
xref.Uid = uid;
}
xref.InnerHtml = node.InnerHtml;
xref.DisplayProperty = node.GetAttributeValue("displayProperty", queryString?.Get("displayProperty") ?? XRefSpec.NameKey);
xref.AltProperty = node.GetAttributeValue("altProperty", queryString?.Get("altProperty") ?? "fullName");
xref.Text = node.GetAttributeValue("text", node.GetAttributeValue("name", StringHelper.HtmlEncode(queryString?.Get("text"))));
xref.Alt = node.GetAttributeValue("alt", node.GetAttributeValue("fullname", StringHelper.HtmlEncode(queryString?.Get("alt"))));
xref.Title = node.GetAttributeValue("title", queryString?.Get("title"));
xref.SourceFile = node.GetAttributeValue("sourceFile", null);
xref.SourceStartLineNumber = node.GetAttributeValue("sourceStartLineNumber", 0);
xref.SourceEndLineNumber = node.GetAttributeValue("sourceEndLineNumber", 0);
// Both `data-raw-html` and `data-raw-source` are html encoded. Use `data-raw-html` with higher priority.
// `data-raw-html` will be decoded then displayed, while `data-raw-source` will be displayed directly.
xref.RawSource = node.GetAttributeValue("data-raw-source", null);
var raw = node.GetAttributeValue("data-raw-html", null);
if (!string.IsNullOrEmpty(raw))
{
xref.Raw = StringHelper.HtmlDecode(raw);
}
else
{
xref.Raw = xref.RawSource;
}
xref.ThrowIfNotResolved = node.GetAttributeValue("data-throw-if-not-resolved", false);
return xref;
}
public void ApplyXrefSpec(XRefSpec spec)
{
if (spec == null)
{
return;
}
// TODO: What if href is not html?
if (!string.IsNullOrEmpty(spec.Href))
{
Href = UriUtility.GetNonFragment(spec.Href);
if (string.IsNullOrEmpty(Anchor))
{
Anchor = UriUtility.GetFragment(spec.Href);
}
}
Spec = spec;
}
/// <summary>
/// TODO: multi-lang support
/// </summary>
/// <returns></returns>
public HtmlAgilityPack.HtmlNode ConvertToHtmlNode(string language)
{
// If href exists, return anchor else return text
if (!string.IsNullOrEmpty(Href))
{
if (!string.IsNullOrEmpty(InnerHtml))
{
return GetAnchorNode(Href, Anchor, Title, InnerHtml, RawSource, SourceFile, SourceStartLineNumber, SourceEndLineNumber);
}
if (!string.IsNullOrEmpty(Text))
{
return GetAnchorNode(Href, Anchor, Title, Text, RawSource, SourceFile, SourceStartLineNumber, SourceEndLineNumber);
}
if (Spec != null)
{
var value = StringHelper.HtmlEncode(GetLanguageSpecificAttribute(Spec, language, DisplayProperty, "name"));
if (!string.IsNullOrEmpty(value))
{
return GetAnchorNode(Href, Anchor, Title, value, RawSource, SourceFile, SourceStartLineNumber, SourceEndLineNumber);
}
}
return GetAnchorNode(Href, Anchor, Title, Uid, RawSource, SourceFile, SourceStartLineNumber, SourceEndLineNumber);
}
else
{
if (!string.IsNullOrEmpty(Raw))
{
return HtmlAgilityPack.HtmlNode.CreateNode(Raw);
}
if (!string.IsNullOrEmpty(InnerHtml))
{
return GetDefaultPlainTextNode(InnerHtml);
}
if (!string.IsNullOrEmpty(Alt))
{
return GetDefaultPlainTextNode(Alt);
}
if (Spec != null)
{
var value = StringHelper.HtmlEncode(GetLanguageSpecificAttribute(Spec, language, AltProperty, "name"));
if (!string.IsNullOrEmpty(value))
{
return GetDefaultPlainTextNode(value);
}
}
return GetDefaultPlainTextNode(Uid);
}
}
private static HtmlAgilityPack.HtmlNode GetAnchorNode(string href, string anchor, string title, string value, string rawSource, string sourceFile, int sourceStartLineNumber, int sourceEndLineNumber)
{
var anchorNode = $"<a class=\"xref\" href=\"{href}\"";
if (!string.IsNullOrEmpty(anchor))
{
anchorNode += $" anchor=\"{anchor}\"";
}
if (!string.IsNullOrEmpty(title))
{
anchorNode += $" title=\"{title}\"";
}
if (!string.IsNullOrEmpty(rawSource))
{
anchorNode += $" data-raw-source=\"{rawSource}\"";
}
if (!string.IsNullOrEmpty(sourceFile))
{
anchorNode += $" sourceFile=\"{sourceFile}\"";
}
if (sourceStartLineNumber != 0)
{
anchorNode += $" sourceStartLineNumber={sourceStartLineNumber}";
}
if (sourceEndLineNumber != 0)
{
anchorNode += $" sourceEndLineNumber={sourceEndLineNumber}";
}
anchorNode += $">{value}</a>";
return HtmlAgilityPack.HtmlNode.CreateNode(anchorNode);
}
private static HtmlAgilityPack.HtmlNode GetDefaultPlainTextNode(string value)
{
var spanNode = $"<span class=\"xref\">{value}</span>";
return HtmlAgilityPack.HtmlNode.CreateNode(spanNode);
}
private static string GetLanguageSpecificAttribute(XRefSpec spec, string language, params string[] keyInFallbackOrder)
{
if (keyInFallbackOrder == null || keyInFallbackOrder.Length == 0)
{
throw new ArgumentException("key must be provided!", nameof(keyInFallbackOrder));
}
string suffix = string.Empty;
if (!string.IsNullOrEmpty(language))
{
suffix = "." + language;
}
foreach (var key in keyInFallbackOrder)
{
var keyWithSuffix = key + suffix;
if (spec.TryGetValue(keyWithSuffix, out string value))
{
return value;
}
if (spec.TryGetValue(key, out value))
{
return value;
}
}
return null;
}
public static HtmlAgilityPack.HtmlNode ConvertXrefLinkNodeToXrefNode(HtmlAgilityPack.HtmlNode node)
{
var href = node.GetAttributeValue("href", null);
if (node.Name != "a" || string.IsNullOrEmpty(href) || !href.StartsWith("xref:"))
{
throw new NotSupportedException("Only anchor node with href started with \"xref:\" is supported!");
}
href = href.Substring("xref:".Length);
var raw = StringHelper.HtmlEncode(node.OuterHtml);
var xrefNode = $"<xref href=\"{href}\" data-throw-if-not-resolved=\"True\" data-raw-html=\"{raw}\"";
foreach (var attr in node.Attributes ?? Enumerable.Empty<HtmlAgilityPack.HtmlAttribute>())
{
if (attr.Name == "href" || attr.Name == "data-throw-if-not-resolved" || attr.Name == "data-raw-html")
{
continue;
}
xrefNode += $" {attr.Name}=\"{attr.Value}\"";
}
xrefNode += $">{node.InnerHtml}</xref>";
return HtmlAgilityPack.HtmlNode.CreateNode(xrefNode);
}
}
}
| |
namespace CSharpCLI {
using System;
using System.Reflection;
/// <summary>
/// Statement class is used to prepare and execute selct statement
/// </summary>
///
public class Statement {
/// <summary>
/// Cleanup unreferenced statement
/// </summary>
///
public void finalize() {
if (con != null) {
close();
}
}
/// <summary>
/// Close the statement. This method release all resource assoiated with statement
/// at client and server. f close method will not be called, cleanup still
/// will be performed later when garbage collector call finilize method of this
/// object
/// </summary>
///
public void close() {
if (con == null) {
throw new CliError("Statement already closed");
}
ComBuffer buf = new ComBuffer(Connection.CLICommand.cli_cmd_free_statement, stmtId);
con.send(buf);
con = null;
}
internal class Parameter {
internal Parameter next;
internal string name;
internal Connection.CLIType type;
internal int ivalue;
internal long lvalue;
internal float fvalue;
internal double dvalue;
internal string svalue;
internal Rectangle rvalue;
internal Parameter(string name) {
this.name = name;
type = Connection.CLIType.cli_undefined;
}
}
/// <summary>
/// Set bool parameter
/// </summary>
/// <param name="name">name of the parameter started with <code>%</code> character</param>
/// <param name="value">value of the parameter</param>
///
public void setBool(string name, bool value) {
Parameter p = getParam(name);
p.ivalue = value ? 1 : 0;
p.type = Connection.CLIType.cli_bool;
}
/// <summary>
/// Set byte parameter
/// </summary>
/// <param name="name">name of the parameter started with <code>%</code> character</param>
/// <param name="value">value of the parameter</param>
///
public void setByte(string name, byte value) {
Parameter p = getParam(name);
p.ivalue = value;
p.type = Connection.CLIType.cli_int4;
}
/// <summary>
/// Set short parameter
/// </summary>
/// <param name="name">name of the parameter started with <code>%</code> character</param>
/// <param name="value">value of the parameter</param>
///
public void setShort(string name, short value) {
Parameter p = getParam(name);
p.ivalue = value;
p.type = Connection.CLIType.cli_int4;
}
/// <summary>
/// Set integer parameter
/// </summary>
/// <param name="name">name of the parameter started with <code>%</code> character</param>
/// <param name="value">value of the parameter</param>
///
public void setInt(string name, int value) {
Parameter p = getParam(name);
p.ivalue = value;
p.type = Connection.CLIType.cli_int4;
}
/// <summary>
/// Set long parameter
/// </summary>
/// <param name="name">name of the parameter started with <code>%</code> character</param>
/// <param name="value">value of the parameter</param>
///
public void setLong(string name, long value) {
Parameter p = getParam(name);
p.lvalue = value;
p.type = Connection.CLIType.cli_int8;
}
/// <summary>
/// Set double parameter
/// <param name="name">name of the parameter started with <code>%</code> character</param>
/// <param name="value">value of the parameter</param>
/// </summary>
///
public void setDouble(string name, double value) {
Parameter p = getParam(name);
p.dvalue = value;
p.type = Connection.CLIType.cli_real8;
}
/// <summary>
/// Set float parameter
/// </summary>
/// <param name="name">name of the parameter started with <code>%</code> character</param>
/// <param name="value">value of the parameter</param>
///
public void setFloat(string name, float value) {
Parameter p = getParam(name);
p.fvalue = value;
p.type = Connection.CLIType.cli_real4;
}
/// <summary>
/// Set string parameter
/// </summary>
/// <param name="name">name of the parameter started with <code>%</code> character</param>
/// <param name="value">value of the parameter</param>
///
public void setString(string name, string value) {
Parameter p = getParam(name);
p.svalue = value;
p.type = Connection.CLIType.cli_asciiz;
}
/// <summary>
/// Set reference parameter
/// </summary>
/// <param name="name">name of the parameter started with <code>%</code> character</param>
/// <param name="value">value of the parameter, <code>null</code> means null reference</param>
///
public void setRef(string name, Reference value) {
Parameter p = getParam(name);
p.ivalue = value != null ? value.oid : 0;
p.type = Connection.CLIType.cli_oid;
}
/// <summary>
/// Set rectangle parameter
/// </summary>
/// <param name="name">name of the parameter started with <code>%</code> character</param>
/// <param name="rect">value of the parameter</param>
///
public void setRectangle(string name, Rectangle rect) {
Parameter p = getParam(name);
p.rvalue = rect;
p.type = Connection.CLIType.cli_rectangle;
}
/// <summary>
/// Prepare (if needed) and execute select statement
/// </summary>
/// <returns>object set with the selected objects</returns>
///
public ObjectSet fetch() {
return fetch(false);
}
/// <summary>
/// Prepare (if needed) and execute select statement
/// Only object set returned by the select for updated statement allows
/// update and deletion of the objects.
/// </summary>
/// <param name="forUpdate">if cursor is opened in for update mode</param>
/// <returns>object set with the selected objects</returns>
///
public ObjectSet fetch(bool forUpdate) {
int i, n;
ComBuffer buf;
if (!prepared) {
buf = new ComBuffer(Connection.CLICommand.cli_cmd_prepare_and_execute, stmtId);
n = tableDesc.nColumns;
buf.putByte(nParams);
buf.putByte(n);
int len = stmtLen;
bool addNull = false;
if (len == 0 || stmt[len-1] != 0) {
addNull = true;
len += nParams;
buf.putShort(len+1);
} else {
len += nParams;
buf.putShort(len);
}
i = 0;
Parameter p = parameters;
do {
byte ch = stmt[i++];
buf.putByte(ch);
len -= 1;
if (ch == '\0') {
if (len != 0) {
if (p.type == Connection.CLIType.cli_undefined) {
throw new CliError("Unbound parameter " + p.name);
}
buf.putByte((int)p.type);
p = p.next;
len -= 1;
}
}
} while (len != 0);
if (addNull) {
buf.putByte('\0');
}
tableDesc.writeColumnDefs(buf);
} else { // statement was already prepared
buf = new ComBuffer(Connection.CLICommand.cli_cmd_execute, stmtId);
}
this.forUpdate = forUpdate;
buf.putByte(forUpdate ? 1 : 0);
for (Parameter p = parameters; p != null; p = p.next) {
switch (p.type) {
case Connection.CLIType.cli_oid:
case Connection.CLIType.cli_int4:
buf.putInt(p.ivalue);
break;
case Connection.CLIType.cli_int1:
case Connection.CLIType.cli_bool:
buf.putByte((byte)p.ivalue);
break;
case Connection.CLIType.cli_int2:
buf.putShort((short)p.ivalue);
break;
case Connection.CLIType.cli_int8:
buf.putLong(p.lvalue);
break;
case Connection.CLIType.cli_real4:
buf.putFloat(p.fvalue);
break;
case Connection.CLIType.cli_real8:
buf.putDouble(p.dvalue);
break;
case Connection.CLIType.cli_asciiz:
buf.putAsciiz(p.svalue);
break;
}
}
prepared = true;
return new ObjectSet(this, con.sendReceive(buf));
}
static bool FindTypeByName(Type t, object name)
{
return t.Name.Equals(name);
}
internal Statement(Connection con, string sql, int stmtId) {
this.stmtId = stmtId;
int src = 0, dst = 0, len = sql.Length;
int p = sql.IndexOf("from");
if (p < 0 && (p = sql.IndexOf("FROM")) < 0) {
throw new CliError("Bad statment: SELECT FROM expected");
}
p += 5;
while (p < len && sql[p] == ' ') {
p += 1;
}
int q = p;
while (++q < len && sql[q] != ' ');
if (p+1 == q) {
throw new CliError("Bad statment: table name expected after FROM");
}
string tableName = sql.Substring(p, q-p);
lock (Connection.tableHash) {
tableDesc = (TableDescriptor)Connection.tableHash[tableName];
if (tableDesc == null) {
Type tableClass = Type.GetType(tableName);
if (tableClass == null) {
if (con.pkgs != null)
{
foreach (string pkg in con.pkgs) {
tableClass = Type.GetType(pkg + '.' + tableName);
if (tableClass != null)
{
break;
}
}
}
if (tableClass == null)
{
foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Module mod in ass.GetModules())
{
foreach (Type t in mod.FindTypes(new TypeFilter(FindTypeByName), tableName))
{
if (tableClass != null)
{
throw new CliError("Class " + tableName + " exists in more than one scope");
}
tableClass = t;
}
}
}
}
if (tableClass == null) {
throw new CliError("Class " + tableName + " not found");
}
}
tableDesc = new TableDescriptor(tableClass);
Connection.tableHash[tableName] = tableDesc;
}
}
byte[] buf = new byte[len];
while (src < len) {
char ch = sql[src];
if (ch == '\'') {
do {
do {
buf[dst++] = (byte)sql[src++];
if (src == len) {
throw new CliError("Unterminated string constant in query");
}
} while (sql[src] != '\'');
buf[dst++] = (byte)'\'';
} while (++src < len && sql[src] == '\'');
} else if (ch == '%') {
int begin = src;
do {
if (++src == len) {
break;
}
ch = sql[src];
} while ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
|| (ch >= '0' && ch <= '9') || ch == '_');
if (ch == '%') {
throw new CliError("Invalid parameter name");
}
Parameter param = new Parameter(sql.Substring(begin, src-begin));
if (lastParam == null) {
parameters = param;
} else {
lastParam.next = param;
}
lastParam = param;
nParams += 1;
buf[dst++] = (byte)'\0';
} else {
buf[dst++]= (byte)sql[src++];
}
}
stmt = buf;
stmtLen = dst;
this.con = con;
}
internal Parameter getParam(string name) {
for (Parameter p = parameters; p != null; p = p.next) {
if (p.name.Equals(name)) {
return p;
}
}
throw new CliError("No such parameter");
}
internal byte[] stmt;
internal int stmtId;
internal int stmtLen;
internal Connection con;
internal Parameter parameters;
internal Parameter lastParam;
internal int nParams;
internal bool prepared;
internal bool forUpdate;
internal TableDescriptor tableDesc;
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics.SymbolStore;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Reflection;
using System.Collections;
using System.Windows.Forms;
using System.Diagnostics;
using PHP.Core;
using PHP.Core.Reflection;
using System.Web;
using System.Web.SessionState;
namespace PHP.Library
{
#if DEBUG
/// <exclude/>
public static class PhpDocumentation
{
private static bool FunctionsCallback(MethodInfo method, ImplementsFunctionAttribute ifa, object result)
{
if ((ifa.Options & FunctionImplOptions.Internal) == 0 && (ifa.Options & FunctionImplOptions.NotSupported) == 0)
{
PhpArray array = (PhpArray)result;
((PhpArray)array["name"]).Add(ifa.Name);
((PhpArray)array["type"]).Add(method.DeclaringType.FullName);
((PhpArray)array["method"]).Add(method.Name);
}
return true;
}
private static bool TypesCallback(Type type, object result)
{
PhpArray array = (PhpArray)result;
((PhpArray)array["name"]).Add(type.FullName);
((PhpArray)array["interface"]).Add(type.IsInterface);
return true;
}
private static bool ConstantsCallback(FieldInfo field, ImplementsConstantAttribute ica, object result)
{
PhpArray array = (PhpArray)result;
((PhpArray)array["name"]).Add(ica.Name);
((PhpArray)array["type"]).Add(field.DeclaringType.FullName);
((PhpArray)array["field"]).Add(field.Name);
((PhpArray)array["insensitive"]).Add(ica.CaseInsensitive);
return true;
}
/// <summary>
/// Prints documentation table for classes.
/// </summary>
[ImplementsFunction("phpnet_doc_functions", FunctionImplOptions.Internal)]
public static PhpArray PrintFunctions()
{
PhpArray result = new PhpArray();
result.Add("name", new PhpArray());
result.Add("type", new PhpArray());
result.Add("method", new PhpArray());
Assembly assembly = typeof(PhpDocumentation).Assembly;
//PhpLibraryModule.EnumerateFunctions(assembly, new PhpLibraryModule.FunctionsEnumCallback(FunctionsCallback), result);
return result;
}
/// <summary>
/// Prints documentation table for classes.
/// </summary>
[ImplementsFunction("phpnet_doc_types", FunctionImplOptions.Internal)]
public static PhpArray PrintTypes()
{
PhpArray result = new PhpArray();
result.Add("name", new PhpArray());
result.Add("interface", new PhpArray());
Assembly assembly = typeof(PhpDocumentation).Assembly;
//PhpLibraryModule.EnumerateTypes(assembly, new PhpLibraryModule.TypeEnumCallback(TypesCallback), result);
return result;
}
/// <summary>
/// Prints documentation table for classes.
/// </summary>
[ImplementsFunction("phpnet_doc_constants", FunctionImplOptions.Internal)]
public static PhpArray PrintConstants()
{
PhpArray result = new PhpArray();
result.Add("name", new PhpArray());
result.Add("type", new PhpArray());
result.Add("field", new PhpArray());
result.Add("insensitive", new PhpArray());
Assembly assembly = typeof(PhpDocumentation).Assembly;
//PhpLibraryModule.EnumerateConstants(assembly, new PhpLibraryModule.ConstantsEnumCallback(ConstantsCallback), result);
return result;
}
}
/// <summary>
/// Functions used for debugging class library.
/// </summary>
/// <exclude/>
public sealed class DebugTests
{
private DebugTests() { }
[ImplementsFunction("__break", FunctionImplOptions.Internal)]
public static void Break()
{
Debugger.Break();
}
[ImplementsFunction("__ddump", FunctionImplOptions.Internal)]
public static void DebugDump(object var)
{
StringWriter s = new StringWriter();
PhpVariable.Dump(s, var);
Debug.WriteLine("DEBUG", s.ToString());
}
[ImplementsFunction("__0", FunctionImplOptions.Internal)]
public static void f0(PhpReference arg)
{
PhpVariable.Dump(arg.value);
arg.value = "hello";
}
[ImplementsFunction("__1", FunctionImplOptions.Internal)]
public static void f1(params PhpReference[] args)
{
foreach (PhpReference arg in args)
{
PhpVariable.Dump(arg.value);
arg.value = "hello";
}
}
[ImplementsFunction("__2", FunctionImplOptions.Internal)]
public static void f2(params int[] args)
{
foreach (int arg in args)
PhpVariable.Dump(arg);
}
[ImplementsFunction("__3", FunctionImplOptions.Internal)]
public static void f3(params object[] args)
{
foreach (object arg in args)
PhpVariable.Dump(arg);
}
[ImplementsFunction("__4", FunctionImplOptions.Internal)]
public static void f4(params PhpArray[] args)
{
foreach (PhpArray arg in args)
PhpVariable.Dump(arg);
}
[ImplementsFunction("__5", FunctionImplOptions.Internal)]
public static void f5(params double[] args)
{
foreach (double arg in args)
PhpVariable.Dump(arg);
}
[ImplementsFunction("__6", FunctionImplOptions.Internal)]
public static void f6(ref PhpArray arg)
{
PhpVariable.Dump(arg);
}
[ImplementsFunction("__7", FunctionImplOptions.Internal)]
public static void f7(params PhpArray[] args)
{
foreach (PhpArray arg in args)
PhpVariable.Dump(arg);
}
[ImplementsFunction("__8", FunctionImplOptions.Internal)]
[return: CastToFalse]
public static string f8(PhpResource a, PhpResource b, PhpResource c)
{
return null;
}
[ImplementsFunction("__9", FunctionImplOptions.Internal)]
[return: CastToFalse]
public static int f9(PhpResource a)
{
return -1;
}
[ImplementsFunction("__readline", FunctionImplOptions.Internal)]
public static string ReadLine()
{
return Console.ReadLine();
}
[ImplementsFunction("__stacktrace", FunctionImplOptions.Internal)]
public static string ClrStackTrace()
{
StackTrace trace = new StackTrace(true);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < trace.FrameCount; i++)
{
StackFrame frame = trace.GetFrame(i);
MethodBase method = frame.GetMethod();
sb.AppendFormat("{0} {1} {2} {3} {4} {5}\n",
(method != null) ? method.DeclaringType + "." + method.Name : "NULL",
frame.GetFileName(),
frame.GetFileLineNumber(),
frame.GetFileColumnNumber(),
frame.GetNativeOffset(),
frame.GetILOffset());
}
return sb.ToString();
}
/// <summary>
/// Gets an array of headers of the current HTTP request.
/// </summary>
[ImplementsFunction("__headers", FunctionImplOptions.Internal)]
public static PhpArray GetHeaders()
{
PhpArray result = new PhpArray();
NameValueCollection headers = HttpContext.Current.Request.Headers;
string[] keys = headers.AllKeys;
for (int i = 0; i < keys.Length; i++)
{
string[] values = headers.GetValues(keys[i]);
if (values.Length > 1)
{
PhpArray keys_array = new PhpArray();
for (int j = 0; j < values.Length; j++)
{
keys_array.Add(values[j]);
}
result.Add(keys[i], keys_array);
}
else
{
result.Add(keys[i], values[0]);
}
}
return result;
}
[ImplementsFunction("__request_enc", FunctionImplOptions.Internal)]
public static string GetRequestEncoding()
{
return HttpContext.Current.Request.ContentEncoding.EncodingName;
}
[ImplementsFunction("__response_enc", FunctionImplOptions.Internal)]
public static string GetResponseEncoding()
{
return HttpContext.Current.Response.ContentEncoding.EncodingName;
}
[ImplementsFunction("__upper", FunctionImplOptions.Internal)]
public static PhpBytes GetUpperBytes()
{
byte[] result = new byte[30];
for (int i = 0; i < result.Length; i++)
result[i] = (byte)(i + 128);
return new PhpBytes(result);
}
[ImplementsFunction("__throw", FunctionImplOptions.Internal)]
public static PhpBytes __throw()
{
throw new ArgumentNullException("XXX", "Fake exception");
}
[ImplementsFunction("__dump_transient", FunctionImplOptions.Internal)]
public static void __dump_transient()
{
DynamicCode.Dump(ScriptContext.CurrentContext, ScriptContext.CurrentContext.Output);
}
[ImplementsFunction("__evalinfo", FunctionImplOptions.CaptureEvalInfo | FunctionImplOptions.Internal)]
public static PhpArray __evalinfo()
{
ScriptContext context = ScriptContext.CurrentContext;
return PhpArray.Keyed(
"file", context.EvalRelativeSourcePath,
"line", context.EvalLine,
"column", context.EvalColumn);
}
[ImplementsFunction("__dump_session", FunctionImplOptions.Internal)]
public static void __dump_session()
{
TextWriter o = ScriptContext.CurrentContext.Output;
HttpContext context = HttpContext.Current;
if (context == null) { o.WriteLine("HTTP CONTEXT NULL"); return; }
HttpSessionState state = context.Session;
if (context == null) { o.WriteLine("SESSION NULL"); return; }
PhpArray a = new PhpArray();
foreach (string name in state)
{
a[name] = state[name];
}
PhpVariable.Dump(o, a);
}
[ImplementsFunction("__dump_fdecls", FunctionImplOptions.Internal)]
public static PhpArray __dump_fdecls()
{
PhpArray result = new PhpArray();
foreach (KeyValuePair<string, DRoutineDesc> entry in ScriptContext.CurrentContext.DeclaredFunctions)
{
result.Add(entry.Key, entry.Value.MakeFullName());
}
return result;
}
[ImplementsFunction("__type", FunctionImplOptions.Internal)]
public static string PhpNetType(object o)
{
return o == null ? "null" : o.GetType().FullName;
}
[ImplementsFunction("__assemblies", FunctionImplOptions.Internal)]
public static PhpArray GetAssemblies()
{
PhpArray result = new PhpArray();
foreach (PhpLibraryAssembly a in ScriptContext.CurrentContext.ApplicationContext.GetLoadedLibraries())
result.Add(a.RealAssembly.FullName);
return result;
}
[ImplementsFunction("__descriptors", FunctionImplOptions.Internal)]
public static PhpArray GetDescriptors()
{
PhpArray result = new PhpArray();
foreach (PhpLibraryAssembly a in ScriptContext.CurrentContext.ApplicationContext.GetLoadedLibraries())
result.Add(a.Descriptor.GetType().FullName);
return result;
}
public sealed class Remoter : MarshalByRefObject
{
public string[] GetLoadedAssemblies()
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
string[] result = new string[assemblies.Length];
for (int i = 0; i < assemblies.Length; i++)
result[i] = assemblies[i].FullName;
return result;
}
public static Remoter CreateRemoteInstance(AppDomain domain)
{
Type t = typeof(Remoter);
return (Remoter)domain.CreateInstanceAndUnwrap(t.Assembly.FullName, t.FullName);
}
}
private static void AppDomainInfo(AppDomain domain, TextWriter output)
{
if (domain == null) return;
output.WriteLine("</PRE><H3>AppDomain info</H3><PRE>");
output.WriteLine("FriendlyName = {0}", domain.FriendlyName);
output.WriteLine("ApplicationBase = {0}", domain.SetupInformation.ApplicationBase);
output.WriteLine("ConfigurationFile = {0}", domain.SetupInformation.ConfigurationFile);
output.WriteLine("DynamicBase = {0}", domain.SetupInformation.DynamicBase);
output.WriteLine("PrivateBinPath = {0}", domain.SetupInformation.PrivateBinPath);
output.WriteLine("CachePath = {0}", domain.SetupInformation.CachePath);
output.WriteLine("ShadowCopyDirectories = {0}", domain.SetupInformation.ShadowCopyDirectories);
output.WriteLine("ShadowCopyFiles = {0}", domain.SetupInformation.ShadowCopyFiles);
if (domain == AppDomain.CurrentDomain)
{
foreach (Assembly assembly in domain.GetAssemblies())
output.WriteLine(" Assembly: {0}", assembly.FullName);
}
else
{
foreach (string name in Remoter.CreateRemoteInstance(domain).GetLoadedAssemblies())
output.WriteLine(" Assembly: {0}", name);
}
}
[ImplementsFunction("__info", FunctionImplOptions.Internal)]
public static void Info()
{
Info(ScriptContext.CurrentContext);
}
public static void Info(ScriptContext/*!*/ scriptContext)
{
TextWriter output = scriptContext.Output;
HttpContext ctx = HttpContext.Current;
output.WriteLine("<br><div style='background-color:oldlace'><H3>Phalanger debug info:</H3><PRE>");
output.WriteLine("</PRE><H3>HttpRuntime</H3><PRE>");
output.WriteLine("AppDomainAppId = {0}", HttpRuntime.AppDomainAppId);
output.WriteLine("AppDomainAppPath = {0}", HttpRuntime.AppDomainAppPath);
output.WriteLine("AppDomainAppVirtualPath = {0}", HttpRuntime.AppDomainAppVirtualPath);
output.WriteLine("AppDomainId = {0}", HttpRuntime.AppDomainId);
output.WriteLine("AspInstallDirectory = {0}", HttpRuntime.AspInstallDirectory);
output.WriteLine("BinDirectory = {0}", HttpRuntime.BinDirectory);
output.WriteLine("ClrInstallDirectory = {0}", HttpRuntime.ClrInstallDirectory);
try
{
output.WriteLine("CodegenDir = {0}", HttpRuntime.CodegenDir);
}
catch (Exception)
{
output.WriteLine("CodegenDir = N/A");
}
output.WriteLine("MachineConfigurationDirectory = {0}", HttpRuntime.MachineConfigurationDirectory);
output.WriteLine("</PRE><H3>Worker Process</H3><PRE>");
output.Write("Worker processes: ");
if (ctx != null)
{
foreach (ProcessInfo pi in ProcessModelInfo.GetHistory(20))
output.Write(pi.ProcessID + ";");
output.WriteLine();
output.WriteLine("Current Worker Process start time: {0}", ProcessModelInfo.GetCurrentProcessInfo().StartTime);
}
else
{
output.WriteLine("N/A");
}
Process proc = Process.GetCurrentProcess();
output.WriteLine("Current process: Id = {0}", proc.Id);
output.WriteLine("Current PrivateMemorySize: {0} MB", proc.PrivateMemorySize64 / (1024 * 1024));
output.WriteLine("Current WorkingSet: {0} MB", proc.WorkingSet64 / (1024 * 1024));
output.WriteLine("Current VirtualMemorySize: {0} MB", proc.VirtualMemorySize64 / (1024 * 1024));
output.WriteLine("Current thread: HashCode = {0}", Thread.CurrentThread.GetHashCode());
output.WriteLine("Current domain: {0}", Thread.GetDomain().FriendlyName);
AppDomainInfo(AppDomain.CurrentDomain, output);
if (ctx != null) AppDomainInfo(AppDomain.CurrentDomain, output);
output.WriteLine("</PRE><H3>Libraries</H3><PRE>");
foreach (PhpLibraryAssembly a in scriptContext.ApplicationContext.GetLoadedLibraries())
a.Descriptor.Dump(output);
//output.WriteLine("</PRE><H3>Invalidated Precompiled Scripts</H3><PRE>");
//foreach (string item in WebServerManagersDebug.GetInvalidatedScripts())
// output.WriteLine(item);
output.WriteLine("</PRE><H3>Cache</H3><PRE>");
foreach (DictionaryEntry item in HttpRuntime.Cache)
if (item.Value is string)
output.WriteLine("{0} => '{1}'", item.Key, item.Value);
else
output.WriteLine("{0} => instance of {1}", item.Key, item.Value.GetType().FullName);
if (ctx != null)
{
output.WriteLine("</PRE><H3>Query Variables</H3><PRE>");
String[] keys;
keys = ctx.Request.QueryString.AllKeys;
for (int i = 0; i < keys.Length; i++)
output.WriteLine("{0} = \"{1}\"", keys[i], ctx.Request.QueryString.GetValues(keys[i])[0]);
if (ctx.Session != null)
{
output.WriteLine("</PRE><H3>Session Variables</H3><PRE>");
output.WriteLine("IsCookieless = {0}", ctx.Session.IsCookieless);
output.WriteLine("IsNewSession = {0}", ctx.Session.IsNewSession);
output.WriteLine("SessionID = {0}", ctx.Session.SessionID);
foreach (string name in ctx.Session)
{
output.Write("{0} = ", name);
PhpVariable.Dump(ctx.Session[name]);
}
}
output.WriteLine("</PRE><H3>Cookies</H3><PRE>");
foreach (string cookie_name in ctx.Request.Cookies)
{
HttpCookie cookie = ctx.Request.Cookies[cookie_name];
Console.WriteLine("{0} = {1}", cookie.Name, cookie.Value);
}
output.WriteLine("</PRE><H3>Server Variables</H3><PRE>");
keys = ctx.Request.ServerVariables.AllKeys;
for (int i = 0; i < keys.Length; i++)
output.WriteLine("{0} = \"{1}\"", keys[i], ctx.Request.ServerVariables.GetValues(keys[i])[0]);
}
else
{
output.WriteLine("</PRE><H3>Missing HttpContext</H3><PRE>");
}
output.WriteLine("</PRE></DIV>");
}
}
#endif
}
| |
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing.Drawing2D;
namespace GodLesZ.Library.Controls {
/// <summary>
/// A windows vista like button.
/// </summary>
[DefaultEvent("Click")]
public class VistaButton : System.Windows.Forms.UserControl {
#region - Designer -
private System.ComponentModel.Container components = null;
/// <summary>
/// Initialize the component with it's
/// default settings.
/// </summary>
public VistaButton() {
InitializeComponent();
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.Selectable, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.BackColor = Color.Transparent;
mFadeIn.Interval = 30;
mFadeOut.Interval = 30;
}
/// <summary>
/// Release resources used by the control.
/// </summary>
protected override void Dispose(bool disposing) {
if (disposing) {
if (components != null) {
components.Dispose();
}
}
base.Dispose(disposing);
}
#region - Component Designer generated code -
private void InitializeComponent() {
//
// VistaButton
//
this.Name = "VistaButton";
this.Size = new System.Drawing.Size(100, 32);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.VistaButton_Paint);
this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.VistaButton_KeyUp);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.VistaButton_KeyDown);
this.MouseEnter += new System.EventHandler(this.VistaButton_MouseEnter);
this.MouseLeave += new System.EventHandler(this.VistaButton_MouseLeave);
this.MouseUp += new MouseEventHandler(VistaButton_MouseUp);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.VistaButton_MouseDown);
this.GotFocus += new EventHandler(VistaButton_MouseEnter);
this.LostFocus += new EventHandler(VistaButton_MouseLeave);
this.mFadeIn.Tick += new EventHandler(mFadeIn_Tick);
this.mFadeOut.Tick += new EventHandler(mFadeOut_Tick);
this.Resize += new EventHandler(VistaButton_Resize);
}
#endregion
#endregion
#region - Enums -
/// <summary>
/// A private enumeration that determines
/// the mouse state in relation to the
/// current instance of the control.
/// </summary>
enum State { None, Hover, Pressed };
/// <summary>
/// A public enumeration that determines whether
/// the button background is painted when the
/// mouse is not inside the ClientArea.
/// </summary>
public enum Style {
/// <summary>
/// Draw the button as normal
/// </summary>
Default,
/// <summary>
/// Only draw the background on mouse over.
/// </summary>
Flat
};
#endregion
#region - Properties -
#region - Private Variables -
private bool calledbykey = false;
private State mButtonState = State.None;
private Timer mFadeIn = new Timer();
private Timer mFadeOut = new Timer();
private int mGlowAlpha = 0;
#endregion
#region - Text -
private string mText;
/// <summary>
/// The text that is displayed on the button.
/// </summary>
[Category("Text"),
Description("The text that is displayed on the button.")]
public string ButtonText {
get { return mText; }
set { mText = value; this.Invalidate(); }
}
private Color mForeColor = Color.White;
/// <summary>
/// The color with which the text is drawn.
/// </summary>
[Category("Text"),
Browsable(true),
DefaultValue(typeof(Color), "White"),
Description("The color with which the text is drawn.")]
public override Color ForeColor {
get { return mForeColor; }
set { mForeColor = value; this.Invalidate(); }
}
private ContentAlignment mTextAlign = ContentAlignment.MiddleCenter;
/// <summary>
/// The alignment of the button text
/// that is displayed on the control.
/// </summary>
[Category("Text"),
DefaultValue(typeof(ContentAlignment), "MiddleCenter"),
Description("The alignment of the button text " +
"that is displayed on the control.")]
public ContentAlignment TextAlign {
get { return mTextAlign; }
set { mTextAlign = value; this.Invalidate(); }
}
#endregion
#region - Image -
private Image mImage;
/// <summary>
/// The image displayed on the button that
/// is used to help the user identify
/// it's function if the text is ambiguous.
/// </summary>
[Category("Image"),
DefaultValue(null),
Description("The image displayed on the button that " +
"is used to help the user identify" +
"it's function if the text is ambiguous.")]
public Image Image {
get { return mImage; }
set { mImage = value; this.Invalidate(); }
}
private ContentAlignment mImageAlign = ContentAlignment.MiddleLeft;
/// <summary>
/// The alignment of the image
/// in relation to the button.
/// </summary>
[Category("Image"),
DefaultValue(typeof(ContentAlignment), "MiddleLeft"),
Description("The alignment of the image " +
"in relation to the button.")]
public ContentAlignment ImageAlign {
get { return mImageAlign; }
set { mImageAlign = value; this.Invalidate(); }
}
private Size mImageSize = new Size(24, 24);
/// <summary>
/// The size of the image to be displayed on the
/// button. This property defaults to 24x24.
/// </summary>
[Category("Image"),
DefaultValue(typeof(Size), "24, 24"),
Description("The size of the image to be displayed on the" +
"button. This property defaults to 24x24.")]
public Size ImageSize {
get { return mImageSize; }
set { mImageSize = value; this.Invalidate(); }
}
#endregion
#region - Appearance -
private Style mButtonStyle = Style.Default;
/// <summary>
/// Sets whether the button background is drawn
/// while the mouse is outside of the client area.
/// </summary>
[Category("Appearance"),
DefaultValue(typeof(Style), "Default"),
Description("Sets whether the button background is drawn " +
"while the mouse is outside of the client area.")]
public Style ButtonStyle {
get { return mButtonStyle; }
set { mButtonStyle = value; this.Invalidate(); }
}
private int mCornerRadius = 8;
/// <summary>
/// The radius for the button corners. The
/// greater this value is, the more 'smooth'
/// the corners are. This property should
/// not be greater than half of the
/// controls height.
/// </summary>
[Category("Appearance"),
DefaultValue(8),
Description("The radius for the button corners. The " +
"greater this value is, the more 'smooth' " +
"the corners are. This property should " +
"not be greater than half of the " +
"controls height.")]
public int CornerRadius {
get { return mCornerRadius; }
set { mCornerRadius = value; this.Invalidate(); }
}
private Color mHighlightColor = Color.White;
/// <summary>
/// The colour of the highlight on the top of the button.
/// </summary>
[Category("Appearance"),
DefaultValue(typeof(Color), "White"),
Description("The colour of the highlight on the top of the button.")]
public Color HighlightColor {
get { return mHighlightColor; }
set { mHighlightColor = value; this.Invalidate(); }
}
private Color mButtonColor = Color.Black;
/// <summary>
/// The bottom color of the button that
/// will be drawn over the base color.
/// </summary>
[Category("Appearance"),
DefaultValue(typeof(Color), "Black"),
Description("The bottom color of the button that " +
"will be drawn over the base color.")]
public Color ButtonColor {
get { return mButtonColor; }
set { mButtonColor = value; this.Invalidate(); }
}
private Color mGlowColor = Color.FromArgb(141, 189, 255);
/// <summary>
/// The colour that the button glows when
/// the mouse is inside the client area.
/// </summary>
[Category("Appearance"),
DefaultValue(typeof(Color), "141,189,255"),
Description("The colour that the button glows when " +
"the mouse is inside the client area.")]
public Color GlowColor {
get { return mGlowColor; }
set { mGlowColor = value; this.Invalidate(); }
}
private Image mBackImage;
/// <summary>
/// The background image for the button,
/// this image is drawn over the base
/// color of the button.
/// </summary>
[Category("Appearance"),
DefaultValue(null),
Description("The background image for the button, " +
"this image is drawn over the base " +
"color of the button.")]
public Image BackImage {
get { return mBackImage; }
set { mBackImage = value; this.Invalidate(); }
}
private Color mBaseColor = Color.Black;
/// <summary>
/// The backing color that the rest of
/// the button is drawn. For a glassier
/// effect set this property to Transparent.
/// </summary>
[Category("Appearance"),
DefaultValue(typeof(Color), "Black"),
Description("The backing color that the rest of" +
"the button is drawn. For a glassier " +
"effect set this property to Transparent.")]
public Color BaseColor {
get { return mBaseColor; }
set { mBaseColor = value; this.Invalidate(); }
}
#endregion
#endregion
#region - Functions -
private GraphicsPath RoundRect(RectangleF r, float r1, float r2, float r3, float r4) {
float x = r.X, y = r.Y, w = r.Width, h = r.Height;
GraphicsPath rr = new GraphicsPath();
rr.AddBezier(x, y + r1, x, y, x + r1, y, x + r1, y);
rr.AddLine(x + r1, y, x + w - r2, y);
rr.AddBezier(x + w - r2, y, x + w, y, x + w, y + r2, x + w, y + r2);
rr.AddLine(x + w, y + r2, x + w, y + h - r3);
rr.AddBezier(x + w, y + h - r3, x + w, y + h, x + w - r3, y + h, x + w - r3, y + h);
rr.AddLine(x + w - r3, y + h, x + r4, y + h);
rr.AddBezier(x + r4, y + h, x, y + h, x, y + h - r4, x, y + h - r4);
rr.AddLine(x, y + h - r4, x, y + r1);
return rr;
}
private StringFormat StringFormatAlignment(ContentAlignment textalign) {
StringFormat sf = new StringFormat();
switch (textalign) {
case ContentAlignment.TopLeft:
case ContentAlignment.TopCenter:
case ContentAlignment.TopRight:
sf.LineAlignment = StringAlignment.Near;
break;
case ContentAlignment.MiddleLeft:
case ContentAlignment.MiddleCenter:
case ContentAlignment.MiddleRight:
sf.LineAlignment = StringAlignment.Center;
break;
case ContentAlignment.BottomLeft:
case ContentAlignment.BottomCenter:
case ContentAlignment.BottomRight:
sf.LineAlignment = StringAlignment.Far;
break;
}
switch (textalign) {
case ContentAlignment.TopLeft:
case ContentAlignment.MiddleLeft:
case ContentAlignment.BottomLeft:
sf.Alignment = StringAlignment.Near;
break;
case ContentAlignment.TopCenter:
case ContentAlignment.MiddleCenter:
case ContentAlignment.BottomCenter:
sf.Alignment = StringAlignment.Center;
break;
case ContentAlignment.TopRight:
case ContentAlignment.MiddleRight:
case ContentAlignment.BottomRight:
sf.Alignment = StringAlignment.Far;
break;
}
return sf;
}
#endregion
#region - Drawing -
/// <summary>
/// Draws the outer border for the control
/// using the ButtonColor property.
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawOuterStroke(Graphics g) {
if (this.ButtonStyle == Style.Flat && this.mButtonState == State.None) { return; }
Rectangle r = this.ClientRectangle;
r.Width -= 1;
r.Height -= 1;
using (GraphicsPath rr = RoundRect(r, CornerRadius, CornerRadius, CornerRadius, CornerRadius)) {
using (Pen p = new Pen(this.ButtonColor)) {
g.DrawPath(p, rr);
}
}
}
/// <summary>
/// Draws the inner border for the control
/// using the HighlightColor property.
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawInnerStroke(Graphics g) {
if (this.ButtonStyle == Style.Flat && this.mButtonState == State.None) { return; }
Rectangle r = this.ClientRectangle;
r.X++;
r.Y++;
r.Width -= 3;
r.Height -= 3;
using (GraphicsPath rr = RoundRect(r, CornerRadius, CornerRadius, CornerRadius, CornerRadius)) {
using (Pen p = new Pen(this.HighlightColor)) {
g.DrawPath(p, rr);
}
}
}
/// <summary>
/// Draws the background for the control
/// using the background image and the
/// BaseColor.
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawBackground(Graphics g) {
if (this.ButtonStyle == Style.Flat && this.mButtonState == State.None) { return; }
int alpha = (mButtonState == State.Pressed) ? 204 : 127;
Rectangle r = this.ClientRectangle;
r.Width--;
r.Height--;
using (GraphicsPath rr = RoundRect(r, CornerRadius, CornerRadius, CornerRadius, CornerRadius)) {
using (SolidBrush sb = new SolidBrush(this.BaseColor)) {
g.FillPath(sb, rr);
}
SetClip(g);
if (this.BackImage != null) { g.DrawImage(this.BackImage, this.ClientRectangle); }
g.ResetClip();
using (SolidBrush sb = new SolidBrush(Color.FromArgb(alpha, this.ButtonColor))) {
g.FillPath(sb, rr);
}
}
}
/// <summary>
/// Draws the Highlight over the top of the
/// control using the HightlightColor.
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawHighlight(Graphics g) {
if (this.ButtonStyle == Style.Flat && this.mButtonState == State.None) { return; }
int alpha = (mButtonState == State.Pressed) ? 60 : 150;
Rectangle rect = new Rectangle(0, 0, this.Width, this.Height / 2);
using (GraphicsPath r = RoundRect(rect, CornerRadius, CornerRadius, 0, 0)) {
using (LinearGradientBrush lg = new LinearGradientBrush(r.GetBounds(),
Color.FromArgb(alpha, this.HighlightColor),
Color.FromArgb(alpha / 3, this.HighlightColor),
LinearGradientMode.Vertical)) {
g.FillPath(lg, r);
}
}
}
/// <summary>
/// Draws the glow for the button when the
/// mouse is inside the client area using
/// the GlowColor property.
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawGlow(Graphics g) {
if (this.mButtonState == State.Pressed) { return; }
SetClip(g);
using (GraphicsPath glow = new GraphicsPath()) {
glow.AddEllipse(-5, this.Height / 2 - 10, this.Width + 11, this.Height + 11);
using (PathGradientBrush gl = new PathGradientBrush(glow)) {
gl.CenterColor = Color.FromArgb(mGlowAlpha, this.GlowColor);
gl.SurroundColors = new Color[] { Color.FromArgb(0, this.GlowColor) };
g.FillPath(gl, glow);
}
}
g.ResetClip();
}
/// <summary>
/// Draws the text for the button.
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawText(Graphics g) {
StringFormat sf = StringFormatAlignment(this.TextAlign);
Rectangle r = new Rectangle(8, 8, this.Width - 17, this.Height - 17);
g.DrawString(this.ButtonText, this.Font, new SolidBrush(this.ForeColor), r, sf);
}
/// <summary>
/// Draws the image for the button
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawImage(Graphics g) {
if (this.Image == null) { return; }
Rectangle r = new Rectangle(8, 8, this.ImageSize.Width, this.ImageSize.Height);
switch (this.ImageAlign) {
case ContentAlignment.TopCenter:
r = new Rectangle(this.Width / 2 - this.ImageSize.Width / 2, 8, this.ImageSize.Width, this.ImageSize.Height);
break;
case ContentAlignment.TopRight:
r = new Rectangle(this.Width - 8 - this.ImageSize.Width, 8, this.ImageSize.Width, this.ImageSize.Height);
break;
case ContentAlignment.MiddleLeft:
r = new Rectangle(8, this.Height / 2 - this.ImageSize.Height / 2, this.ImageSize.Width, this.ImageSize.Height);
break;
case ContentAlignment.MiddleCenter:
r = new Rectangle(this.Width / 2 - this.ImageSize.Width / 2, this.Height / 2 - this.ImageSize.Height / 2, this.ImageSize.Width, this.ImageSize.Height);
break;
case ContentAlignment.MiddleRight:
r = new Rectangle(this.Width - 8 - this.ImageSize.Width, this.Height / 2 - this.ImageSize.Height / 2, this.ImageSize.Width, this.ImageSize.Height);
break;
case ContentAlignment.BottomLeft:
r = new Rectangle(8, this.Height - 8 - this.ImageSize.Height, this.ImageSize.Width, this.ImageSize.Height);
break;
case ContentAlignment.BottomCenter:
r = new Rectangle(this.Width / 2 - this.ImageSize.Width / 2, this.Height - 8 - this.ImageSize.Height, this.ImageSize.Width, this.ImageSize.Height);
break;
case ContentAlignment.BottomRight:
r = new Rectangle(this.Width - 8 - this.ImageSize.Width, this.Height - 8 - this.ImageSize.Height, this.ImageSize.Width, this.ImageSize.Height);
break;
}
g.DrawImage(this.Image, r);
}
private void SetClip(Graphics g) {
Rectangle r = this.ClientRectangle;
r.X++;
r.Y++;
r.Width -= 3;
r.Height -= 3;
using (GraphicsPath rr = RoundRect(r, CornerRadius, CornerRadius, CornerRadius, CornerRadius)) {
g.SetClip(rr);
}
}
#endregion
#region - Private Subs -
private void VistaButton_Paint(object sender, PaintEventArgs e) {
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
DrawBackground(e.Graphics);
DrawHighlight(e.Graphics);
DrawImage(e.Graphics);
DrawText(e.Graphics);
DrawGlow(e.Graphics);
DrawOuterStroke(e.Graphics);
DrawInnerStroke(e.Graphics);
}
private void VistaButton_Resize(object sender, EventArgs e) {
Rectangle r = this.ClientRectangle;
r.X -= 1;
r.Y -= 1;
r.Width += 2;
r.Height += 2;
using (GraphicsPath rr = RoundRect(r, CornerRadius, CornerRadius, CornerRadius, CornerRadius)) {
this.Region = new Region(rr);
}
}
#region - Mouse and Keyboard Events -
private void VistaButton_MouseEnter(object sender, EventArgs e) {
mButtonState = State.Hover;
mFadeOut.Stop();
mFadeIn.Start();
}
private void VistaButton_MouseLeave(object sender, EventArgs e) {
mButtonState = State.None;
if (this.mButtonStyle == Style.Flat) { mGlowAlpha = 0; }
mFadeIn.Stop();
mFadeOut.Start();
}
private void VistaButton_MouseDown(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
mButtonState = State.Pressed;
if (this.mButtonStyle != Style.Flat) { mGlowAlpha = 255; }
mFadeIn.Stop();
mFadeOut.Stop();
this.Invalidate();
}
}
private void mFadeIn_Tick(object sender, EventArgs e) {
if (this.ButtonStyle == Style.Flat) { mGlowAlpha = 0; }
if (mGlowAlpha + 30 >= 255) {
mGlowAlpha = 255;
mFadeIn.Stop();
} else {
mGlowAlpha += 30;
}
this.Invalidate();
}
private void mFadeOut_Tick(object sender, EventArgs e) {
if (this.ButtonStyle == Style.Flat) { mGlowAlpha = 0; }
if (mGlowAlpha - 30 <= 0) {
mGlowAlpha = 0;
mFadeOut.Stop();
} else {
mGlowAlpha -= 30;
}
this.Invalidate();
}
private void VistaButton_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Space) {
MouseEventArgs m = new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0);
VistaButton_MouseDown(sender, m);
}
}
private void VistaButton_KeyUp(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Space) {
MouseEventArgs m = new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0);
calledbykey = true;
VistaButton_MouseUp(sender, m);
}
}
private void VistaButton_MouseUp(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
mButtonState = State.Hover;
mFadeIn.Stop();
mFadeOut.Stop();
this.Invalidate();
if (calledbykey == true) { this.OnClick(EventArgs.Empty); calledbykey = false; }
}
}
#endregion
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.TestForNaNCorrectlyAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.TestForNaNCorrectlyAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests
{
public class TestForNaNCorrectlyTests
{
[Fact]
public async Task CSharpDiagnosticForEqualityWithFloatNaN()
{
var code = @"
public class A
{
public bool Compare(float f)
{
return f == float.NaN;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(6, 16));
}
[Fact]
public async Task BasicDiagnosticForEqualityWithFloatNaN()
{
var code = @"
Public Class A
Public Function Compare(f As Single) As Boolean
Return f = Single.NaN
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code, GetBasicResultAt(4, 16));
}
[Fact]
public async Task CSharpDiagnosticForInequalityWithFloatNaN()
{
var code = @"
public class A
{
public bool Compare(float f)
{
return f != float.NaN;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(6, 16));
}
[Fact]
public async Task BasicDiagnosticForInEqualityWithFloatNaN()
{
var code = @"
Public Class A
Public Function Compare(f As Single) As Boolean
Return f <> Single.NaN
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code, GetBasicResultAt(4, 16));
}
[Fact]
public async Task CSharpDiagnosticForGreaterThanFloatNaN()
{
var code = @"
public class A
{
public bool Compare(float f)
{
return f > float.NaN;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(6, 16));
}
[Fact]
public async Task BasicDiagnosticForGreaterThanFloatNaN()
{
var code = @"
Public Class A
Public Function Compare(f As Single) As Boolean
Return f > Single.NaN
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code, GetBasicResultAt(4, 16));
}
[Fact]
public async Task CSharpDiagnosticForGreaterThanOrEqualToFloatNaN()
{
var code = @"
public class A
{
public bool Compare(float f)
{
return f >= float.NaN;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(6, 16));
}
[Fact]
public async Task BasicDiagnosticForGreaterThanOrEqualToFloatNaN()
{
var code = @"
Public Class A
Public Function Compare(f As Single) As Boolean
Return f >= Single.NaN
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code, GetBasicResultAt(4, 16));
}
[Fact]
public async Task CSharpDiagnosticForLessThanFloatNaN()
{
var code = @"
public class A
{
public bool Compare(float f)
{
return f < float.NaN;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(6, 16));
}
[Fact]
public async Task BasicDiagnosticForLessThanFloatNaN()
{
var code = @"
Public Class A
Public Function Compare(f As Single) As Boolean
Return f < Single.NaN
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code, GetBasicResultAt(4, 16));
}
[Fact]
public async Task CSharpDiagnosticForLessThanOrEqualToFloatNaN()
{
var code = @"
public class A
{
public bool Compare(float f)
{
return f <= float.NaN;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(6, 16));
}
[Fact]
public async Task BasicDiagnosticForLessThanOrEqualToFloatNaN()
{
var code = @"
Public Class A
Public Function Compare(f As Single) As Boolean
Return f <= Single.NaN
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code, GetBasicResultAt(4, 16));
}
[Fact]
public async Task CSharpDiagnosticForComparisonWithDoubleNaN()
{
var code = @"
public class A
{
public bool Compare(double d)
{
return d == double.NaN;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(6, 16));
}
[Fact]
public async Task BasicDiagnosticForComparisonWithDoubleNaN()
{
var code = @"
Public Class A
Public Function Compare(d As Double) As Boolean
Return d < Double.NaN
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code, GetBasicResultAt(4, 16));
}
[Fact]
public async Task CSharpDiagnosticForComparisonWithNaNOnLeft()
{
var code = @"
public class A
{
public bool Compare(double d)
{
return double.NaN == d;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(6, 16));
}
[Fact]
public async Task BasicDiagnosticForComparisonWithNaNOnLeft()
{
var code = @"
Public Class A
Public Function Compare(d As Double) As Boolean
Return Double.NaN = d
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code, GetBasicResultAt(4, 16));
}
[Fact]
public async Task CSharpNoDiagnosticForComparisonWithBadExpression()
{
var code = @"
public class A
{
public bool Compare(float f)
{
return f == float.{|CS0117:NbN|}; // Misspelled.
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task BasicNoDiagnosticForComparisonWithBadExpression()
{
var code = @"
Public Class A
Public Function Compare(f As Single) As Boolean
Return f = {|BC30456:Single.NbN|} ' Misspelled
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task CSharpNoDiagnosticForComparisonWithFunctionReturningNaN()
{
var code = @"
public class A
{
public bool Compare(float f)
{
return f == NaNFunc();
}
private float NaNFunc()
{
return float.NaN;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task BasicNoDiagnosticForComparisonWithFunctionReturningNaN()
{
var code = @"
Public Class A
Public Function Compare(f As Single) As Boolean
Return f = NaNFunc()
End Function
Private Function NaNFunc() As Single
Return Single.NaN
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task CSharpNoDiagnosticForEqualityWithNonNaN()
{
var code = @"
public class A
{
public bool Compare(float f)
{
return f == 1.0;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task BasicNoDiagnosticForEqualityWithNonNaN()
{
var code = @"
Public Class A
Public Function Compare(f As Single) As Boolean
Return f = 1.0
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task CSharpNoDiagnosticForNonComparisonOperationWithNaN()
{
var code = @"
public class A
{
public float OperateOn(float f)
{
return f + float.NaN;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task BasicNoDiagnosticForNonComparisonOperationWithNonNaN()
{
var code = @"
Public Class A
Public Function OperateOn(f As Single) As Single
Return f + Single.NaN
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task CSharpOnlyOneDiagnosticForComparisonWithNaNOnBothSides()
{
var code = @"
public class A
{
public bool Compare()
{
return float.NaN == float.NaN;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(6, 16));
}
[Fact]
public async Task BasicOnlyOneDiagnosticForComparisonWithNonNaNOnBothSides()
{
var code = @"
Public Class A
Public Function Compare() As Boolean
Return Single.NaN = Single.NaN
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code, GetBasicResultAt(4, 16));
}
// At @srivatsn's suggestion, here are a few tests that verify that the operation
// tree is correct when the comparison occurs in syntactic constructs other than
// a function return value. Of course we can't be exhaustive about this, and these
// tests are really more about the correctness of the operation tree -- ensuring
// that "binary operator expressions" are present in places we expect them to be --
// than they are about the correctness of our treatment of these expressions once
// we find them.
[Fact]
public async Task CSharpDiagnosticForComparisonWithNaNInFunctionArgument()
{
var code = @"
public class A
{
float _n = 42.0F;
public void F()
{
G(_n == float.NaN);
}
public void G(bool comparison) {}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(8, 11));
}
[Fact]
public async Task BasicDiagnosticForComparisonWithNaNInFunctionArgument()
{
var code = @"
Public Class A
Private _n As Single = 42.0F
Public Sub F()
G(_n = Single.NaN)
End Sub
Public Sub G(comparison As Boolean)
End Sub
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code, GetBasicResultAt(6, 11));
}
[Fact]
public async Task CSharpDiagnosticForComparisonWithNaNInTernaryOperator()
{
var code = @"
public class A
{
float _n = 42.0F;
public int F()
{
return _n == float.NaN ? 1 : 0;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(8, 16));
}
[Fact]
public async Task BasicDiagnosticForComparisonWithNaNInIfOperator()
{
// VB doesn't have the ternary operator, but we add this test for symmetry.
var code = @"
Public Class A
Private _n As Single = 42.0F
Public Function F() As Integer
Return If(_n = Single.NaN, 1, 0)
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code, GetBasicResultAt(6, 19));
}
[Fact]
public async Task CSharpDiagnosticForComparisonWithNaNInThrowStatement()
{
var code = @"
public class A
{
float _n = 42.0F;
public void F()
{
throw _n != float.NaN ? new System.Exception() : new System.ArgumentException();
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(8, 15));
}
[Fact]
public async Task CSharpDiagnosticForComparisonWithNaNInCatchFilterClause()
{
var code = @"
using System;
public class A
{
float _n = 42.0F;
public void F()
{
try
{
}
catch (Exception ex) when (_n != float.NaN)
{
}
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(13, 36));
}
[Fact]
public async Task CSharpDiagnosticForComparisonWithNaNInYieldReturnStatement()
{
var code = @"
using System.Collections.Generic;
public class A
{
float _n = 42.0F;
public IEnumerable<bool> F()
{
yield return _n != float.NaN;
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(10, 22));
}
[Fact]
public async Task CSharpDiagnosticForComparisonWithNaNInSwitchStatement()
{
var code = @"
public class A
{
float _n = 42.0F;
public void F()
{
switch (_n != float.NaN)
{
default:
throw new System.NotImplementedException();
}
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(8, 17));
}
[Fact]
public async Task CSharpDiagnosticForComparisonWithNaNInForLoop()
{
var code = @"
public class A
{
float _n = 42.0F;
public void F()
{
for (; _n != float.NaN; )
{
throw new System.Exception();
}
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(8, 16));
}
[Fact]
public async Task CSharpDiagnosticForComparisonWithNaNInWhileLoop()
{
var code = @"
public class A
{
float _n = 42.0F;
public void F()
{
while (_n != float.NaN)
{
}
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(8, 16));
}
[Fact]
public async Task CSharpDiagnosticForComparisonWithNaNInDoWhileLoop()
{
var code = @"
public class A
{
float _n = 42.0F;
public void F()
{
do
{
}
while (_n != float.NaN);
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpResultAt(11, 16));
}
private static DiagnosticResult GetCSharpResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic()
.WithLocation(line, column);
#pragma warning restore RS0030 // Do not used banned APIs
private static DiagnosticResult GetBasicResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic()
.WithLocation(line, column);
#pragma warning restore RS0030 // Do not used banned APIs
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.ComponentModel;
using Microsoft.PowerShell;
#if CORECLR
using System.Reflection;
#endif
namespace System.Management.Automation
{
/// <summary>
/// Implements Adapter for the COM objects.
/// </summary>
internal class ComAdapter : Adapter
{
private readonly ComTypeInfo _comTypeInfo;
/// <summary>
/// Constructor for the ComAdapter
/// </summary>
/// <param name="typeinfo">typeinfo for the com object we are adapting</param>
internal ComAdapter(ComTypeInfo typeinfo)
{
Diagnostics.Assert(typeinfo != null, "Caller to verify typeinfo is not null.");
_comTypeInfo = typeinfo;
}
internal static string GetComTypeName(string clsid)
{
StringBuilder firstType = new StringBuilder("System.__ComObject");
firstType.Append("#{");
firstType.Append(clsid);
firstType.Append("}");
return firstType.ToString();
}
/// <summary>
/// Returns the TypeNameHierarchy out of an object
/// </summary>
/// <param name="obj">object to get the TypeNameHierarchy from</param>
protected override IEnumerable<string> GetTypeNameHierarchy(object obj)
{
yield return GetComTypeName(_comTypeInfo.Clsid);
foreach (string baseType in GetDotNetTypeNameHierarchy(obj))
{
yield return baseType;
}
}
/// <summary>
/// Returns null if memberName is not a member in the adapter or
/// the corresponding PSMemberInfo
/// </summary>
/// <param name="obj">object to retrieve the PSMemberInfo from</param>
/// <param name="memberName">name of the member to be retrieved</param>
/// <returns>The PSMemberInfo corresponding to memberName from obj</returns>
protected override T GetMember<T>(object obj, string memberName)
{
ComProperty prop;
if (_comTypeInfo.Properties.TryGetValue(memberName, out prop))
{
if (prop.IsParameterized)
{
if (typeof(T).IsAssignableFrom(typeof(PSParameterizedProperty)))
{
return new PSParameterizedProperty(prop.Name, this, obj, prop) as T;
}
}
else if (typeof(T).IsAssignableFrom(typeof(PSProperty)))
{
return new PSProperty(prop.Name, this, obj, prop) as T;
}
}
ComMethod method;
if (typeof(T).IsAssignableFrom(typeof(PSMethod)) &&
(_comTypeInfo != null) && (_comTypeInfo.Methods.TryGetValue(memberName, out method)))
{
PSMethod mshMethod = new PSMethod(method.Name, this, obj, method);
return mshMethod as T;
}
return null;
}
/// <summary>
/// Retrieves all the members available in the object.
/// The adapter implementation is encouraged to cache all properties/methods available
/// in the first call to GetMember and GetMembers so that subsequent
/// calls can use the cache.
/// In the case of the .NET adapter that would be a cache from the .NET type to
/// the public properties and fields available in that type.
/// In the case of the DirectoryEntry adapter, this could be a cache of the objectClass
/// to the properties available in it.
/// </summary>
/// <param name="obj">object to get all the member information from</param>
/// <returns>all members in obj</returns>
protected override PSMemberInfoInternalCollection<T> GetMembers<T>(object obj)
{
PSMemberInfoInternalCollection<T> collection = new PSMemberInfoInternalCollection<T>();
bool lookingForProperties = typeof(T).IsAssignableFrom(typeof(PSProperty));
bool lookingForParameterizedProperties = typeof(T).IsAssignableFrom(typeof(PSParameterizedProperty));
if (lookingForProperties || lookingForParameterizedProperties)
{
foreach (ComProperty prop in _comTypeInfo.Properties.Values)
{
if (prop.IsParameterized)
{
if (lookingForParameterizedProperties)
{
collection.Add(new PSParameterizedProperty(prop.Name, this, obj, prop) as T);
}
}
else if (lookingForProperties)
{
collection.Add(new PSProperty(prop.Name, this, obj, prop) as T);
}
}
}
bool lookingForMethods = typeof(T).IsAssignableFrom(typeof(PSMethod));
if (lookingForMethods)
{
foreach (ComMethod method in _comTypeInfo.Methods.Values)
{
if (collection[method.Name] == null)
{
PSMethod mshmethod = new PSMethod(method.Name, this, obj, method);
collection.Add(mshmethod as T);
}
}
}
return collection;
}
/// <summary>
/// Returns an array with the property attributes
/// </summary>
/// <param name="property">property we want the attributes from</param>
/// <returns>an array with the property attributes</returns>
protected override AttributeCollection PropertyAttributes(PSProperty property)
{
return new AttributeCollection();
}
/// <summary>
/// Returns the value from a property coming from a previous call to DoGetProperty
/// </summary>
/// <param name="property">PSProperty coming from a previous call to DoGetProperty</param>
/// <returns>The value of the property</returns>
protected override object PropertyGet(PSProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.GetValue(property.baseObject);
}
/// <summary>
/// Sets the value of a property coming from a previous call to DoGetProperty
/// </summary>
/// <param name="property">PSProperty coming from a previous call to DoGetProperty</param>
/// <param name="setValue">value to set the property with</param>
/// <param name="convertIfPossible">instructs the adapter to convert before setting, if the adapter supports conversion</param>
protected override void PropertySet(PSProperty property, object setValue, bool convertIfPossible)
{
ComProperty prop = (ComProperty)property.adapterData;
prop.SetValue(property.baseObject, setValue);
}
/// <summary>
/// Returns true if the property is settable
/// </summary>
/// <param name="property">property to check</param>
/// <returns>true if the property is settable</returns>
protected override bool PropertyIsSettable(PSProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.IsSettable;
}
/// <summary>
/// Returns true if the property is gettable
/// </summary>
/// <param name="property">property to check</param>
/// <returns>true if the property is gettable</returns>
protected override bool PropertyIsGettable(PSProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.IsGettable;
}
/// <summary>
/// Returns the name of the type corresponding to the property
/// </summary>
/// <param name="property">PSProperty obtained in a previous DoGetProperty</param>
/// <param name="forDisplay">True if the result is for display purposes only</param>
/// <returns>the name of the type corresponding to the property</returns>
protected override string PropertyType(PSProperty property, bool forDisplay)
{
ComProperty prop = (ComProperty)property.adapterData;
return forDisplay ? ToStringCodeMethods.Type(prop.Type) : prop.Type.FullName;
}
/// <summary>
/// get the property signature.
/// </summary>
/// <param name="property">property object whose signature we want</param>
/// <returns>string representing the signature of the property</returns>
protected override string PropertyToString(PSProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.ToString();
}
#region Methods
/// <summary>
/// Called after a non null return from GetMethodData to try to call
/// the method with the arguments
/// </summary>
/// <param name="method">the non empty return from GetMethods</param>
/// <param name="arguments">the arguments to use</param>
/// <returns>the return value for the method</returns>
protected override object MethodInvoke(PSMethod method, object[] arguments)
{
ComMethod commethod = (ComMethod)method.adapterData;
return commethod.InvokeMethod(method, arguments);
}
/// <summary>
/// Called after a non null return from GetMethodData to return the overloads
/// </summary>
/// <param name="method">the return of GetMethodData</param>
/// <returns></returns>
protected override Collection<String> MethodDefinitions(PSMethod method)
{
ComMethod commethod = (ComMethod)method.adapterData;
return commethod.MethodDefinitions();
}
#endregion
#region parameterized property
/// <summary>
/// Returns the name of the type corresponding to the property's value
/// </summary>
/// <param name="property">property obtained in a previous GetMember</param>
/// <returns>the name of the type corresponding to the member</returns>
protected override string ParameterizedPropertyType(PSParameterizedProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.Type.FullName;
}
/// <summary>
/// Returns true if the property is settable
/// </summary>
/// <param name="property">property to check</param>
/// <returns>true if the property is settable</returns>
protected override bool ParameterizedPropertyIsSettable(PSParameterizedProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.IsSettable;
}
/// <summary>
/// Returns true if the property is gettable
/// </summary>
/// <param name="property">property to check</param>
/// <returns>true if the property is gettable</returns>
protected override bool ParameterizedPropertyIsGettable(PSParameterizedProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.IsGettable;
}
/// <summary>
/// Called after a non null return from GetMember to get the property value
/// </summary>
/// <param name="property">the non empty return from GetMember</param>
/// <param name="arguments">the arguments to use</param>
/// <returns>the return value for the property</returns>
protected override object ParameterizedPropertyGet(PSParameterizedProperty property, object[] arguments)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.GetValue(property.baseObject, arguments);
}
/// <summary>
/// Called after a non null return from GetMember to set the property value
/// </summary>
/// <param name="property">the non empty return from GetMember</param>
/// <param name="setValue">the value to set property with</param>
/// <param name="arguments">the arguments to use</param>
protected override void ParameterizedPropertySet(PSParameterizedProperty property, object setValue, object[] arguments)
{
ComProperty prop = (ComProperty)property.adapterData;
prop.SetValue(property.baseObject, setValue, arguments);
}
/// <summary>
/// Returns the string representation of the property in the object
/// </summary>
/// <param name="property">property obtained in a previous GetMember</param>
/// <returns>the string representation of the property in the object</returns>
protected override string ParameterizedPropertyToString(PSParameterizedProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
return prop.ToString();
}
/// <summary>
/// Called after a non null return from GetMember to return the overloads
/// </summary>
/// <param name="property">the return of GetMember</param>
protected override Collection<String> ParameterizedPropertyDefinitions(PSParameterizedProperty property)
{
ComProperty prop = (ComProperty)property.adapterData;
Collection<string> returnValue = new Collection<string> { prop.GetDefinition() };
return returnValue;
}
#endregion parameterized property
}
}
| |
// 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.Composition.Hosting.Core;
using System.Composition.Hosting;
namespace System.Composition
{
/// <summary>
/// Provides retrieval of exports from the composition.
/// </summary>
public abstract class CompositionContext
{
private const string ImportManyImportMetadataConstraintName = "IsImportMany";
/// <summary>
/// Retrieve the single <paramref name="contract"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <param name="contract">The contract to retrieve.</param>
/// <returns>An instance of the export.</returns>
/// <param name="export">The export if available, otherwise, null.</param>
/// <exception cref="CompositionFailedException" />
public abstract bool TryGetExport(CompositionContract contract, out object export);
/// <summary>
/// Retrieve the single <typeparamref name="TExport"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <typeparam name="TExport">The type of the export to retrieve.</typeparam>
/// <returns>An instance of the export.</returns>
/// <exception cref="CompositionFailedException" />
public TExport GetExport<TExport>()
{
return GetExport<TExport>((string)null);
}
/// <summary>
/// Retrieve the single <typeparamref name="TExport"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <typeparam name="TExport">The type of the export to retrieve.</typeparam>
/// <param name="contractName">Optionally, a discriminator that constrains the selection of the export.</param>
/// <returns>An instance of the export.</returns>
/// <exception cref="CompositionFailedException" />
public TExport GetExport<TExport>(string contractName)
{
return (TExport)GetExport(typeof(TExport), contractName);
}
/// <summary>
/// Retrieve the single <paramref name="exportType"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <param name="exportType">The type of the export to retrieve.</param>
/// <param name="contractName">Optionally, a discriminator that constrains the selection of the export.</param>
/// <returns>An instance of the export.</returns>
/// <param name="export">The export if available, otherwise, null.</param>
/// <exception cref="CompositionFailedException" />
public bool TryGetExport(Type exportType, string contractName, out object export)
{
return TryGetExport(new CompositionContract(exportType, contractName), out export);
}
/// <summary>
/// Retrieve the single <paramref name="exportType"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <param name="exportType">The type of the export to retrieve.</param>
/// <returns>An instance of the export.</returns>
/// <param name="export">The export if available, otherwise, null.</param>
/// <exception cref="CompositionFailedException" />
public bool TryGetExport(Type exportType, out object export)
{
return TryGetExport(exportType, null, out export);
}
/// <summary>
/// Retrieve the single <typeparamref name="TExport"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <typeparam name="TExport">The type of the export to retrieve.</typeparam>
/// <returns>An instance of the export.</returns>
/// <param name="export">The export if available, otherwise, null.</param>
/// <exception cref="CompositionFailedException" />
public bool TryGetExport<TExport>(out TExport export)
{
return TryGetExport<TExport>(null, out export);
}
/// <summary>
/// Retrieve the single <typeparamref name="TExport"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <typeparam name="TExport">The type of the export to retrieve.</typeparam>
/// <param name="contractName">Optionally, a discriminator that constrains the selection of the export.</param>
/// <returns>An instance of the export.</returns>
/// <param name="export">The export if available, otherwise, null.</param>
/// <exception cref="CompositionFailedException" />
public bool TryGetExport<TExport>(string contractName, out TExport export)
{
object untypedExport;
if (!TryGetExport(typeof(TExport), contractName, out untypedExport))
{
export = default(TExport);
return false;
}
export = (TExport)untypedExport;
return true;
}
/// <summary>
/// Retrieve the single <paramref name="exportType"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <param name="exportType">The type of the export to retrieve.</param>
/// <returns>An instance of the export.</returns>
/// <exception cref="CompositionFailedException" />
public object GetExport(Type exportType)
{
return GetExport(exportType, (string)null);
}
/// <summary>
/// Retrieve the single <paramref name="exportType"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <param name="exportType">The type of the export to retrieve.</param>
/// <param name="contractName">Optionally, a discriminator that constrains the selection of the export.</param>
/// <returns>An instance of the export.</returns>
/// <exception cref="CompositionFailedException" />
public object GetExport(Type exportType, string contractName)
{
return GetExport(new CompositionContract(exportType, contractName));
}
/// <summary>
/// Retrieve the single <paramref name="contract"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <param name="contract">The contract of the export to retrieve.</param>
/// <returns>An instance of the export.</returns>
/// <exception cref="CompositionFailedException" />
public object GetExport(CompositionContract contract)
{
object export;
if (!TryGetExport(contract, out export))
throw new CompositionFailedException(
string.Format(Properties.Resources.CompositionContext_NoExportFoundForContract, contract));
return export;
}
/// <summary>
/// Retrieve the single <paramref name="exportType"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <param name="exportType">The type of the export to retrieve.</param>
/// <exception cref="CompositionFailedException" />
public IEnumerable<object> GetExports(Type exportType)
{
return GetExports(exportType, (string)null);
}
/// <summary>
/// Retrieve the single <paramref name="exportType"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <param name="exportType">The type of the export to retrieve.</param>
/// <param name="contractName">The discriminator to apply when selecting the export.</param>
/// <returns>An instance of the export.</returns>
/// <exception cref="CompositionFailedException" />
public IEnumerable<object> GetExports(Type exportType, string contractName)
{
var manyContract = new CompositionContract(
exportType.MakeArrayType(),
contractName,
new Dictionary<string, object> { { ImportManyImportMetadataConstraintName, true } });
return (IEnumerable<object>)GetExport(manyContract);
}
/// <summary>
/// Retrieve the single <typeparamref name="TExport"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <typeparam name="TExport">The export type to retrieve.</typeparam>
/// <returns>An instance of the export.</returns>
/// <exception cref="CompositionFailedException" />
public IEnumerable<TExport> GetExports<TExport>()
{
return GetExports<TExport>((string)null);
}
/// <summary>
/// Retrieve the single <typeparamref name="TExport"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <typeparam name="TExport">The export type to retrieve.</typeparam>
/// <returns>An instance of the export.</returns>
/// <param name="contractName">The discriminator to apply when selecting the export.</param>
/// <exception cref="CompositionFailedException" />
public IEnumerable<TExport> GetExports<TExport>(string contractName)
{
return (IEnumerable<TExport>)GetExports(typeof(TExport), contractName);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Convenient wrapper for an array, an offset, and
** a count. Ideally used in streams & collections.
** Net Classes will consume an array of these.
**
**
===========================================================*/
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
{
// Note: users should make sure they copy the fields out of an ArraySegment onto their stack
// then validate that the fields describe valid bounds within the array. This must be done
// because assignments to value types are not atomic, and also because one thread reading
// three fields from an ArraySegment may not see the same ArraySegment from one call to another
// (ie, users could assign a new value to the old location).
public struct ArraySegment<T> : IList<T>, IReadOnlyList<T>
{
private readonly T[] _array;
private readonly int _offset;
private readonly int _count;
public ArraySegment(T[] array)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
Contract.EndContractBlock();
_array = array;
_offset = 0;
_count = array.Length;
}
public ArraySegment(T[] array, int offset, int count)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
_array = array;
_offset = offset;
_count = count;
}
public T[] Array
{
get
{
Debug.Assert((null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
return _array;
}
}
public int Offset
{
get
{
// Since copying value types is not atomic & callers cannot atomically
// read all three fields, we cannot guarantee that Offset is within
// the bounds of Array. That is our intent, but let's not specify
// it as a postcondition - force callers to re-verify this themselves
// after reading each field out of an ArraySegment into their stack.
Contract.Ensures(Contract.Result<int>() >= 0);
Debug.Assert((null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
return _offset;
}
}
public int Count
{
get
{
// Since copying value types is not atomic & callers cannot atomically
// read all three fields, we cannot guarantee that Count is within
// the bounds of Array. That's our intent, but let's not specify
// it as a postcondition - force callers to re-verify this themselves
// after reading each field out of an ArraySegment into their stack.
Contract.Ensures(Contract.Result<int>() >= 0);
Debug.Assert((null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
return _count;
}
}
public Enumerator GetEnumerator()
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
Contract.EndContractBlock();
return new Enumerator(this);
}
public override int GetHashCode()
{
if (_array == null)
{
return 0;
}
int hash = 5381;
hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset);
hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count);
// The array hash is expected to be an evenly-distributed mixture of bits,
// so rather than adding the cost of another rotation we just xor it.
hash ^= _array.GetHashCode();
return hash;
}
public override bool Equals(Object obj)
{
if (obj is ArraySegment<T>)
return Equals((ArraySegment<T>)obj);
else
return false;
}
public bool Equals(ArraySegment<T> obj)
{
return obj._array == _array && obj._offset == _offset && obj._count == _count;
}
public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b)
{
return a.Equals(b);
}
public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b)
{
return !(a == b);
}
#region IList<T>
T IList<T>.this[int index]
{
get
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
if (index < 0 || index >= _count)
throw new ArgumentOutOfRangeException(nameof(index));
Contract.EndContractBlock();
return _array[_offset + index];
}
set
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
if (index < 0 || index >= _count)
throw new ArgumentOutOfRangeException(nameof(index));
Contract.EndContractBlock();
_array[_offset + index] = value;
}
}
int IList<T>.IndexOf(T item)
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
Contract.EndContractBlock();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0 ? index - _offset : -1;
}
void IList<T>.Insert(int index, T item)
{
throw new NotSupportedException();
}
void IList<T>.RemoveAt(int index)
{
throw new NotSupportedException();
}
#endregion
#region IReadOnlyList<T>
T IReadOnlyList<T>.this[int index]
{
get
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
if (index < 0 || index >= _count)
throw new ArgumentOutOfRangeException(nameof(index));
Contract.EndContractBlock();
return _array[_offset + index];
}
}
#endregion IReadOnlyList<T>
#region ICollection<T>
bool ICollection<T>.IsReadOnly
{
get
{
// the indexer setter does not throw an exception although IsReadOnly is true.
// This is to match the behavior of arrays.
return true;
}
}
void ICollection<T>.Add(T item)
{
throw new NotSupportedException();
}
void ICollection<T>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<T>.Contains(T item)
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
Contract.EndContractBlock();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0;
}
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
System.Array.Copy(_array, _offset, array, arrayIndex, _count);
}
bool ICollection<T>.Remove(T item)
{
throw new NotSupportedException();
}
#endregion
#region IEnumerable<T>
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
public struct Enumerator : IEnumerator<T>
{
private readonly T[] _array;
private readonly int _start;
private readonly int _end; // cache Offset + Count, since it's a little slow
private int _current;
internal Enumerator(ArraySegment<T> arraySegment)
{
Debug.Assert(arraySegment.Array != null);
Debug.Assert(arraySegment.Offset >= 0);
Debug.Assert(arraySegment.Count >= 0);
Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length);
_array = arraySegment._array;
_start = arraySegment._offset;
_end = _start + arraySegment._count;
_current = _start - 1;
}
public bool MoveNext()
{
if (_current < _end)
{
_current++;
return (_current < _end);
}
return false;
}
public T Current
{
get
{
if (_current < _start)
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
if (_current >= _end)
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
return _array[_current];
}
}
object IEnumerator.Current => Current;
void IEnumerator.Reset()
{
_current = _start - 1;
}
public void Dispose()
{
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Concurrency;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Runtime.Utilities;
using UnitTests.GrainInterfaces;
using Xunit;
namespace UnitTests.Grains
{
[Serializable]
[GenerateSerializer]
public class EchoTaskGrainState
{
[Id(0)]
public int MyId { get; set; }
[Id(1)]
public string LastEcho { get; set; }
}
[StorageProvider(ProviderName = "MemoryStore")]
public class EchoGrain : Grain<EchoTaskGrainState>, IEchoGrain
{
private ILogger logger;
public EchoGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
logger.Info(GetType().FullName + " created");
return base.OnActivateAsync(cancellationToken);
}
public Task<string> GetLastEcho()
{
return Task.FromResult(State.LastEcho);
}
public Task<string> Echo(string data)
{
logger.Info("IEchoGrain.Echo=" + data);
State.LastEcho = data;
return Task.FromResult(data);
}
public Task<string> EchoError(string data)
{
logger.Info("IEchoGrain.EchoError=" + data);
State.LastEcho = data;
throw new Exception(data);
}
public Task<DateTime?> EchoNullable(DateTime? value) => Task.FromResult(value);
}
[StorageProvider(ProviderName = "MemoryStore")]
internal class EchoTaskGrain : Grain<EchoTaskGrainState>, IEchoTaskGrain, IDebuggerHelperTestGrain
{
private readonly IInternalGrainFactory internalGrainFactory;
private readonly IGrainContext _grainContext;
private ILogger logger;
public EchoTaskGrain(IInternalGrainFactory internalGrainFactory, ILogger<EchoTaskGrain> logger, IGrainContext grainContext)
{
this.internalGrainFactory = internalGrainFactory;
this.logger = logger;
_grainContext = grainContext;
}
public Task<int> GetMyIdAsync() { return Task.FromResult(State.MyId); }
public Task<string> GetLastEchoAsync() { return Task.FromResult(State.LastEcho); }
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
logger.Info(GetType().FullName + " created");
return base.OnActivateAsync(cancellationToken);
}
public Task<string> EchoAsync(string data)
{
logger.Info("IEchoGrainAsync.Echo=" + data);
State.LastEcho = data;
return Task.FromResult(data);
}
public Task<string> EchoErrorAsync(string data)
{
logger.Info("IEchoGrainAsync.EchoError=" + data);
State.LastEcho = data;
throw new Exception(data);
}
private Task<string> EchoErrorAV(string data)
{
logger.Info("IEchoGrainAsync.EchoErrorAV=" + data);
State.LastEcho = data;
throw new Exception(data);
}
public async Task<string> AwaitMethodErrorAsync(string data)
{
logger.Info("IEchoGrainAsync.CallMethodErrorAsync=" + data);
return await EchoErrorAsync(data);
}
public async Task<string> AwaitAVMethodErrorAsync(string data)
{
logger.Info("IEchoGrainAsync.CallMethodErrorAsync=" + data);
return await EchoErrorAV(data);
}
public async Task<string> AwaitAVGrainCallErrorAsync(string data)
{
logger.Info("IEchoGrainAsync.AwaitAVGrainErrorAsync=" + data);
IEchoGrain avGrain = GrainFactory.GetGrain<IEchoGrain>(this.GetPrimaryKey());
return await avGrain.EchoError(data);
}
public Task<int> BlockingCallTimeoutAsync(TimeSpan delay)
{
logger.Info("IEchoGrainAsync.BlockingCallTimeout Delay={0}", delay);
Stopwatch sw = new Stopwatch();
sw.Start();
Thread.Sleep(delay);
logger.Info("IEchoGrainAsync.BlockingCallTimeout Awoke from sleep after {0}", sw.Elapsed);
throw new InvalidOperationException("Timeout should have been returned to caller before " + delay);
}
public Task PingAsync()
{
logger.Info("IEchoGrainAsync.Ping");
return Task.CompletedTask;
}
public Task PingLocalSiloAsync()
{
logger.Info("IEchoGrainAsync.PingLocal");
SiloAddress mySilo = _grainContext.Address.SiloAddress;
return GetSiloControlReference(mySilo).Ping("PingLocal");
}
public Task PingRemoteSiloAsync(SiloAddress siloAddress)
{
logger.Info("IEchoGrainAsync.PingRemote");
return GetSiloControlReference(siloAddress).Ping("PingRemote");
}
public async Task PingOtherSiloAsync()
{
logger.Info("IEchoGrainAsync.PingOtherSilo");
SiloAddress mySilo = _grainContext.Address.SiloAddress;
IManagementGrain mgmtGrain = GrainFactory.GetGrain<IManagementGrain>(0);
var silos = await mgmtGrain.GetHosts();
SiloAddress siloAddress = silos.Where(pair => !pair.Key.Equals(mySilo)).Select(pair => pair.Key).First();
logger.Info("Sending Ping to remote silo {0}", siloAddress);
await GetSiloControlReference(siloAddress).Ping("PingOtherSilo-" + siloAddress);
logger.Info("Ping reply received for {0}", siloAddress);
}
public async Task PingClusterMemberAsync()
{
logger.Info("IEchoGrainAsync.PingClusterMemberAsync");
SiloAddress mySilo = _grainContext.Address.SiloAddress;
IManagementGrain mgmtGrain = GrainFactory.GetGrain<IManagementGrain>(0);
var silos = await mgmtGrain.GetHosts();
SiloAddress siloAddress = silos.Where(pair => !pair.Key.Equals(mySilo)).Select(pair => pair.Key).First();
logger.Info("Sending Ping to remote silo {0}", siloAddress);
var oracle = this.internalGrainFactory.GetSystemTarget<IMembershipService>(Constants.MembershipServiceType, siloAddress);
await oracle.Ping(1);
logger.Info("Ping reply received for {0}", siloAddress);
}
private ISiloControl GetSiloControlReference(SiloAddress silo)
{
return this.internalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlType, silo);
}
public Task OrleansDebuggerHelper_GetGrainInstance_Test()
{
var result = OrleansDebuggerHelper.GetGrainInstance(null);
Assert.Null(result);
result = OrleansDebuggerHelper.GetGrainInstance(this);
Assert.Same(this, result);
result = OrleansDebuggerHelper.GetGrainInstance(this.AsReference<IDebuggerHelperTestGrain>());
Assert.Same(this, result);
result = OrleansDebuggerHelper.GetGrainInstance(this.GrainFactory.GetGrain<IEchoGrain>(Guid.NewGuid()));
Assert.Null(result);
return Task.CompletedTask;
}
}
[StorageProvider(ProviderName = "MemoryStore")]
public class BlockingEchoTaskGrain : Grain<EchoTaskGrainState>, IBlockingEchoTaskGrain
{
private ILogger logger;
public BlockingEchoTaskGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
logger.Info(GetType().FullName + " created");
return base.OnActivateAsync(cancellationToken);
}
public Task<int> GetMyId()
{
return Task.FromResult(State.MyId);
}
public Task<string> GetLastEcho()
{
return Task.FromResult(State.LastEcho);
}
public Task<string> Echo(string data)
{
string name = GetType().Name + ".Echo";
logger.Info(name + " Data=" + data);
State.LastEcho = data;
var result = Task.FromResult(data);
logger.Info(name + " Result=" + result);
return result;
}
public async Task<string> CallMethodTask_Await(string data)
{
string name = GetType().Name + ".CallMethodTask_Await";
logger.Info(name + " Data=" + data);
IEchoTaskGrain avGrain = GrainFactory.GetGrain<IEchoTaskGrain>(this.GetPrimaryKey());
var result = await avGrain.EchoAsync(data);
logger.Info(name + " Result=" + result);
return result;
}
public async Task<string> CallMethodAV_Await(string data)
{
string name = GetType().Name + ".CallMethodAV_Await";
logger.Info(name + " Data=" + data);
IEchoGrain avGrain = GrainFactory.GetGrain<IEchoGrain>(this.GetPrimaryKey());
var result = await avGrain.Echo(data);
logger.Info(name + " Result=" + result);
return result;
}
#pragma warning disable 1998
public async Task<string> CallMethodTask_Block(string data)
{
string name = GetType().Name + ".CallMethodTask_Block";
logger.Info(name + " Data=" + data);
IEchoTaskGrain avGrain = GrainFactory.GetGrain<IEchoTaskGrain>(this.GetPrimaryKey());
// Note: We deliberately use .Result here in this test case to block current executing thread
var result = avGrain.EchoAsync(data).Result;
logger.Info(name + " Result=" + result);
return result;
}
#pragma warning restore 1998
#pragma warning disable 1998
public async Task<string> CallMethodAV_Block(string data)
{
string name = GetType().Name + ".CallMethodAV_Block";
logger.Info(name + " Data=" + data);
IEchoGrain avGrain = GrainFactory.GetGrain<IEchoGrain>(this.GetPrimaryKey());
// Note: We deliberately use .Result here in this test case to block current executing thread
var result = avGrain.Echo(data).Result;
logger.Info(name + " Result=" + result);
return result;
}
#pragma warning restore 1998
}
[Reentrant]
[StorageProvider(ProviderName = "MemoryStore")]
public class ReentrantBlockingEchoTaskGrain : Grain<EchoTaskGrainState>, IReentrantBlockingEchoTaskGrain
{
private ILogger logger;
public ReentrantBlockingEchoTaskGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
logger.Info(GetType().FullName + " created");
return base.OnActivateAsync(cancellationToken);
}
public Task<int> GetMyId()
{
return Task.FromResult(State.MyId);
}
public Task<string> GetLastEcho()
{
return Task.FromResult(State.LastEcho);
}
public Task<string> Echo(string data)
{
string name = GetType().Name + ".Echo";
logger.Info(name + " Data=" + data);
State.LastEcho = data;
var result = Task.FromResult(data);
logger.Info(name + " Result=" + result);
return result;
}
public async Task<string> CallMethodTask_Await(string data)
{
string name = GetType().Name + ".CallMethodTask_Await";
logger.Info(name + " Data=" + data);
IEchoTaskGrain avGrain = GrainFactory.GetGrain<IEchoTaskGrain>(this.GetPrimaryKey());
var result = await avGrain.EchoAsync(data);
logger.Info(name + " Result=" + result);
return result;
}
public async Task<string> CallMethodAV_Await(string data)
{
string name = GetType().Name + ".CallMethodAV_Await";
logger.Info(name + " Data=" + data);
IEchoGrain avGrain = GrainFactory.GetGrain<IEchoGrain>(this.GetPrimaryKey());
var result = await avGrain.Echo(data);
logger.Info(name + " Result=" + result);
return result;
}
#pragma warning disable 1998
public async Task<string> CallMethodTask_Block(string data)
{
string name = GetType().Name + ".CallMethodTask_Block";
logger.Info(name + " Data=" + data);
IEchoTaskGrain avGrain = GrainFactory.GetGrain<IEchoTaskGrain>(this.GetPrimaryKey());
// Note: We deliberately use .Result here in this test case to block current executing thread
var result = avGrain.EchoAsync(data).Result;
logger.Info(name + " Result=" + result);
return result;
}
#pragma warning restore 1998
#pragma warning disable 1998
public async Task<string> CallMethodAV_Block(string data)
{
string name = GetType().Name + ".CallMethodAV_Block";
logger.Info(name + " Data=" + data);
IEchoGrain avGrain = GrainFactory.GetGrain<IEchoGrain>(this.GetPrimaryKey());
// Note: We deliberately use .Result here in this test case to block current executing thread
var result = avGrain.Echo(data).Result;
logger.Info(name + " Result=" + result);
return result;
}
#pragma warning restore 1998
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class DynamicILInfoTests
{
private static string HelloWorld() => "hello, world".ToUpper();
[Fact]
public void GetTokenFor_String_Success()
{
DynamicMethod dynamicMethod = new DynamicMethod(nameof(HelloWorld), typeof(string), new Type[] { }, typeof(DynamicILInfoTests), false);
DynamicILInfo dynamicILInfo = dynamicMethod.GetDynamicILInfo();
SignatureHelper sigHelper = SignatureHelper.GetLocalVarSigHelper();
sigHelper.AddArgument(typeof(string), false);
dynamicILInfo.SetLocalSignature(sigHelper.GetSignature());
byte[] code = {
0x00, 0x72, 0x01, 0x00, 0x00, 0x70, 0x6f, 0x04, 0x00, 0x00, 0x0a, 0x0a, 0x2b, 0x00, 0x06, 0x2a
};
int token0 = dynamicILInfo.GetTokenFor("hello, world");
int token1 = dynamicILInfo.GetTokenFor(typeof(string).GetMethod("ToUpper", Type.EmptyTypes).MethodHandle);
PutInteger4(token0, 0x0002, code);
PutInteger4(token1, 0x0007, code);
dynamicILInfo.SetCode(code, 1);
string ret = (string)dynamicMethod.Invoke(null, null);
Assert.Equal(ret, HelloWorld());
}
private static long Fib(long value)
{
if (value == 0 || value == 1)
return value;
return Fib(value - 1) + Fib(value - 2);
}
[Fact]
public void GetTokenFor_DynamicMethod_Success()
{
// Calling DynamicMethod recursively
DynamicMethod dynamicMethod = new DynamicMethod(nameof(Fib), typeof(long), new Type[] { typeof(long) }, typeof(DynamicILInfoTests), false);
DynamicILInfo dynamicILInfo = dynamicMethod.GetDynamicILInfo();
SignatureHelper sigHelper = SignatureHelper.GetLocalVarSigHelper();
sigHelper.AddArgument(typeof(long), false);
sigHelper.AddArgument(typeof(bool), false);
dynamicILInfo.SetLocalSignature(sigHelper.GetSignature());
byte[] code = {
0x00, 0x02, 0x16, 0x6a, 0x2e, 0x0a, 0x02, 0x17, 0x6a, 0xfe, 0x01, 0x16, 0xfe, 0x01, 0x2b, 0x01,
0x16, 0x0b, 0x07, 0x2d, 0x04, 0x02, 0x0a, 0x2b, 0x16, 0x02, 0x17, 0x6a, 0x59, 0x28, 0x02, 0x00,
0x00, 0x06, 0x02, 0x18, 0x6a, 0x59, 0x28, 0x02, 0x00, 0x00, 0x06, 0x58, 0x0a, 0x2b, 0x00, 0x06,
0x2a
};
int token0 = dynamicILInfo.GetTokenFor(dynamicMethod);
PutInteger4(token0, 0x001e, code);
PutInteger4(token0, 0x0027, code);
dynamicILInfo.SetCode(code, 3);
long ret = (long)dynamicMethod.Invoke(null, new object[] { 20 });
Assert.Equal(ret, Fib(20));
}
private static Person Mock()
{
Person p = new Person("Bill", 50, 30000f);
p.m_name = "Bill Gates";
p.Age++;
p.IncSalary(300);
return p;
}
private class Person
{
int m_age;
float m_salary;
public string m_name;
public int Age { get { return m_age; } set { m_age = value; } }
public float Salary { get { return m_salary; } }
public Person(string name, int age, float salary)
{
m_name = name;
m_age = age;
m_salary = salary;
}
public void IncSalary(float percentage)
{
m_salary = m_salary * percentage;
}
public override bool Equals(object other)
{
Person other2 = other as Person;
if (other2 == null) return false;
if (m_name != other2.m_name) return false;
if (m_age != other2.m_age) return false;
if (m_salary != other2.m_salary) return false;
return true;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
[Fact]
public void GetTokenFor_CtorMethodAndField_Success()
{
DynamicMethod dynamicMethod = new DynamicMethod(nameof(Mock), typeof(Person), new Type[] { }, typeof(DynamicILInfoTests), false);
DynamicILInfo dynamicILInfo = dynamicMethod.GetDynamicILInfo();
SignatureHelper sigHelper = SignatureHelper.GetLocalVarSigHelper();
sigHelper.AddArgument(typeof(Person), false);
sigHelper.AddArgument(typeof(Person), false);
dynamicILInfo.SetLocalSignature(sigHelper.GetSignature());
byte[] code = {
0x00, 0x72, 0x49, 0x00, 0x00, 0x70, 0x1f, 0x32, 0x22, 0x00, 0x60, 0xea, 0x46, 0x73, 0x0f, 0x00,
0x00, 0x06, 0x0a, 0x06, 0x72, 0x53, 0x00, 0x00, 0x70, 0x7d, 0x04, 0x00, 0x00, 0x04, 0x06, 0x25,
0x6f, 0x0c, 0x00, 0x00, 0x06, 0x17, 0x58, 0x6f, 0x0d, 0x00, 0x00, 0x06, 0x00, 0x06, 0x22, 0x00,
0x00, 0x96, 0x43, 0x6f, 0x10, 0x00, 0x00, 0x06, 0x00, 0x06, 0x0b, 0x2b, 0x00, 0x07, 0x2a
};
int token0 = dynamicILInfo.GetTokenFor("Bill");
int token1 = dynamicILInfo.GetTokenFor(typeof(Person).GetConstructor(new Type[] { typeof(string), typeof(int), typeof(float) }).MethodHandle);
int token2 = dynamicILInfo.GetTokenFor("Bill Gates");
int token3 = dynamicILInfo.GetTokenFor(typeof(Person).GetField("m_name").FieldHandle);
int token4 = dynamicILInfo.GetTokenFor(typeof(Person).GetMethod("get_Age").MethodHandle);
int token5 = dynamicILInfo.GetTokenFor(typeof(Person).GetMethod("set_Age").MethodHandle);
int token6 = dynamicILInfo.GetTokenFor(typeof(Person).GetMethod("IncSalary").MethodHandle);
PutInteger4(token0, 0x0002, code);
PutInteger4(token1, 0x000e, code);
PutInteger4(token2, 0x0015, code);
PutInteger4(token3, 0x001a, code);
PutInteger4(token4, 0x0021, code);
PutInteger4(token5, 0x0028, code);
PutInteger4(token6, 0x0034, code);
dynamicILInfo.SetCode(code, 4);
Person ret = (Person)dynamicMethod.Invoke(null, null);
Assert.Equal(ret, Mock());
}
private class MyList<T> : IEnumerable<T>
{
List<T> list;
public MyList() { list = new List<T>(); }
public void Add(T val) { list.Add(val); }
public IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); }
}
private static int SumInteger()
{
MyList<int> list = new MyList<int>();
list.Add(100);
list.Add(200);
list.Add(300);
int sum = 0;
foreach (int item in list)
{
sum += item;
}
return sum;
}
[Fact]
public void GetTokenFor_IntGenerics_Success()
{
DynamicMethod dynamicMethod = new DynamicMethod(nameof(SumInteger), typeof(int), new Type[] { }, typeof(DynamicILInfoTests), false);
DynamicILInfo dynamicILInfo = dynamicMethod.GetDynamicILInfo();
SignatureHelper sigHelper = SignatureHelper.GetLocalVarSigHelper();
sigHelper.AddArgument(typeof(MyList<int>), false);
sigHelper.AddArgument(typeof(int), false);
sigHelper.AddArgument(typeof(int), false);
sigHelper.AddArgument(typeof(int), false);
sigHelper.AddArgument(typeof(System.Collections.Generic.IEnumerator<int>), false);
sigHelper.AddArgument(typeof(bool), false);
dynamicILInfo.SetLocalSignature(sigHelper.GetSignature());
byte[] code = {
0x00, 0x73, 0x1c, 0x00, 0x00, 0x0a, 0x0a, 0x06, 0x1f, 0x64, 0x6f, 0x1d, 0x00, 0x00, 0x0a, 0x00,
0x06, 0x20, 0xc8, 0x00, 0x00, 0x00, 0x6f, 0x1d, 0x00, 0x00, 0x0a, 0x00, 0x06, 0x20, 0x2c, 0x01,
0x00, 0x00, 0x6f, 0x1d, 0x00, 0x00, 0x0a, 0x00, 0x16, 0x0b, 0x00, 0x06, 0x6f, 0x1e, 0x00, 0x00,
0x0a, 0x13, 0x04, 0x2b, 0x0e, 0x11, 0x04, 0x6f, 0x1f, 0x00, 0x00, 0x0a, 0x0c, 0x00, 0x07, 0x08,
0x58, 0x0b, 0x00, 0x11, 0x04, 0x6f, 0x20, 0x00, 0x00, 0x0a, 0x13, 0x05, 0x11, 0x05, 0x2d, 0xe5,
0xde, 0x14, 0x11, 0x04, 0x14, 0xfe, 0x01, 0x13, 0x05, 0x11, 0x05, 0x2d, 0x08, 0x11, 0x04, 0x6f,
0x21, 0x00, 0x00, 0x0a, 0x00, 0xdc, 0x00, 0x07, 0x0d, 0x2b, 0x00, 0x09, 0x2a
};
int token0 = dynamicILInfo.GetTokenFor(typeof(MyList<int>).GetConstructors()[0].MethodHandle, typeof(MyList<int>).TypeHandle);
int token1 = dynamicILInfo.GetTokenFor(typeof(MyList<int>).GetMethod("Add").MethodHandle, typeof(MyList<int>).TypeHandle);
int token2 = dynamicILInfo.GetTokenFor(typeof(MyList<int>).GetMethod("GetEnumerator").MethodHandle, typeof(MyList<int>).TypeHandle);
int token3 = dynamicILInfo.GetTokenFor(typeof(System.Collections.Generic.IEnumerator<int>).GetMethod("get_Current").MethodHandle, typeof(System.Collections.Generic.IEnumerator<int>).TypeHandle);
int token4 = dynamicILInfo.GetTokenFor(typeof(System.Collections.IEnumerator).GetMethod("MoveNext").MethodHandle);
int token5 = dynamicILInfo.GetTokenFor(typeof(System.IDisposable).GetMethod("Dispose").MethodHandle);
PutInteger4(token0, 0x0002, code);
PutInteger4(token1, 0x000b, code);
PutInteger4(token1, 0x0017, code);
PutInteger4(token1, 0x0023, code);
PutInteger4(token2, 0x002d, code);
PutInteger4(token3, 0x0038, code);
PutInteger4(token4, 0x0046, code);
PutInteger4(token5, 0x0060, code);
dynamicILInfo.SetCode(code, 2);
byte[] exceptions = {
0x41, 0x1c, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00,
0x52, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
dynamicILInfo.SetExceptions(exceptions);
int ret = (int)dynamicMethod.Invoke(null, null);
Assert.Equal(ret, SumInteger());
}
private static string ContactString()
{
MyList<string> list = new MyList<string>();
list.Add("Hello~");
list.Add("World!");
string sum = string.Empty;
foreach (string item in list)
{
sum += item;
}
return sum;
}
[Fact]
public void GetTokenFor_StringGenerics_Success()
{
DynamicMethod dynamicMethod = new DynamicMethod(nameof(ContactString), typeof(string), Type.EmptyTypes, typeof(DynamicILInfoTests), false);
DynamicILInfo dynamicILInfo = dynamicMethod.GetDynamicILInfo();
SignatureHelper sigHelper = SignatureHelper.GetLocalVarSigHelper();
sigHelper.AddArgument(typeof(MyList<string>), false);
sigHelper.AddArgument(typeof(string), false);
sigHelper.AddArgument(typeof(string), false);
sigHelper.AddArgument(typeof(string), false);
sigHelper.AddArgument(typeof(System.Collections.Generic.IEnumerator<string>), false);
sigHelper.AddArgument(typeof(bool), false);
dynamicILInfo.SetLocalSignature(sigHelper.GetSignature());
byte[] code = {
0x00, 0x73, 0x26, 0x00, 0x00, 0x0a, 0x0a, 0x06, 0x72, 0x29, 0x01, 0x00, 0x70, 0x6f, 0x27, 0x00,
0x00, 0x0a, 0x00, 0x06, 0x72, 0x37, 0x01, 0x00, 0x70, 0x6f, 0x27, 0x00, 0x00, 0x0a, 0x00, 0x7e,
0x28, 0x00, 0x00, 0x0a, 0x0b, 0x00, 0x06, 0x6f, 0x29, 0x00, 0x00, 0x0a, 0x13, 0x04, 0x2b, 0x12,
0x11, 0x04, 0x6f, 0x2a, 0x00, 0x00, 0x0a, 0x0c, 0x00, 0x07, 0x08, 0x28, 0x2b, 0x00, 0x00, 0x0a,
0x0b, 0x00, 0x11, 0x04, 0x6f, 0x20, 0x00, 0x00, 0x0a, 0x13, 0x05, 0x11, 0x05, 0x2d, 0xe1, 0xde,
0x14, 0x11, 0x04, 0x14, 0xfe, 0x01, 0x13, 0x05, 0x11, 0x05, 0x2d, 0x08, 0x11, 0x04, 0x6f, 0x21,
0x00, 0x00, 0x0a, 0x00, 0xdc, 0x00, 0x07, 0x0d, 0x2b, 0x00, 0x09, 0x2a
};
int token0 = dynamicILInfo.GetTokenFor(typeof(MyList<string>).GetConstructor(Type.EmptyTypes).MethodHandle, typeof(MyList<string>).TypeHandle);
int token1 = dynamicILInfo.GetTokenFor("Hello~");
int token2 = dynamicILInfo.GetTokenFor(typeof(MyList<string>).GetMethod("Add").MethodHandle, typeof(MyList<string>).TypeHandle);
int token3 = dynamicILInfo.GetTokenFor("World!");
int token4 = dynamicILInfo.GetTokenFor(typeof(string).GetField("Empty").FieldHandle);
int token5 = dynamicILInfo.GetTokenFor(typeof(MyList<string>).GetMethod("GetEnumerator").MethodHandle, typeof(MyList<string>).TypeHandle);
int token6 = dynamicILInfo.GetTokenFor(typeof(System.Collections.Generic.IEnumerator<string>).GetMethod("get_Current").MethodHandle, typeof(System.Collections.Generic.IEnumerator<string>).TypeHandle);
int token7 = dynamicILInfo.GetTokenFor(typeof(string).GetMethod("Concat", new Type[] { typeof(string), typeof(string) }).MethodHandle);
int token8 = dynamicILInfo.GetTokenFor(typeof(System.Collections.IEnumerator).GetMethod("MoveNext").MethodHandle);
int token9 = dynamicILInfo.GetTokenFor(typeof(System.IDisposable).GetMethod("Dispose").MethodHandle);
PutInteger4(token0, 0x0002, code);
PutInteger4(token1, 0x0009, code);
PutInteger4(token2, 0x000e, code);
PutInteger4(token3, 0x0015, code);
PutInteger4(token2, 0x001a, code);
PutInteger4(token4, 0x0020, code);
PutInteger4(token5, 0x0028, code);
PutInteger4(token6, 0x0033, code);
PutInteger4(token7, 0x003c, code);
PutInteger4(token8, 0x0045, code);
PutInteger4(token9, 0x005f, code);
dynamicILInfo.SetCode(code, 2);
byte[] exceptions = {
0x41, 0x1c, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00,
0x51, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
dynamicILInfo.SetExceptions(exceptions);
string ret = (string)dynamicMethod.Invoke(null, null);
Assert.Equal(ret, ContactString());
}
private static int ExceptionTest()
{
int caught = 0;
try
{
try
{
int j = 0;
int i = 1 / j;
}
catch
{
caught++;
}
try
{
Type.GetType("A.B", true);
}
catch (Exception)
{
caught++;
}
string s = null;
s.ToUpper();
}
catch (NullReferenceException)
{
caught++;
}
finally
{
caught += 2;
}
return caught;
}
[Fact]
public void GetTokenFor_Exception_Success()
{
DynamicMethod dynamicMethod = new DynamicMethod(nameof(ExceptionTest), typeof(int), Type.EmptyTypes, typeof(DynamicILInfoTests), false);
DynamicILInfo dynamicILInfo = dynamicMethod.GetDynamicILInfo();
SignatureHelper sigHelper = SignatureHelper.GetLocalVarSigHelper();
sigHelper.AddArgument(typeof(int), false);
sigHelper.AddArgument(typeof(int), false);
sigHelper.AddArgument(typeof(int), false);
sigHelper.AddArgument(typeof(string), false);
sigHelper.AddArgument(typeof(int), false);
dynamicILInfo.SetLocalSignature(sigHelper.GetSignature());
byte[] code = {
0x00, 0x16, 0x0a, 0x00, 0x00, 0x16, 0x0b, 0x17, 0x07, 0x5b, 0x0c, 0x00, 0xde, 0x09, 0x26, 0x00,
0x06, 0x17, 0x58, 0x0a, 0x00, 0xde, 0x00, 0x00, 0x00, 0x72, 0xed, 0x01, 0x00, 0x70, 0x17, 0x28,
0x32, 0x00, 0x00, 0x0a, 0x26, 0x00, 0xde, 0x09, 0x26, 0x00, 0x06, 0x17, 0x58, 0x0a, 0x00, 0xde,
0x00, 0x00, 0x14, 0x0d, 0x09, 0x6f, 0x05, 0x00, 0x00, 0x0a, 0x26, 0x00, 0xde, 0x09, 0x26, 0x00,
0x06, 0x17, 0x58, 0x0a, 0x00, 0xde, 0x00, 0x00, 0xde, 0x07, 0x00, 0x06, 0x18, 0x58, 0x0a, 0x00,
0xdc, 0x00, 0x06, 0x13, 0x04, 0x2b, 0x00, 0x11, 0x04, 0x2a
};
int token0 = dynamicILInfo.GetTokenFor("A.B");
int token1 = dynamicILInfo.GetTokenFor(typeof(System.Type).GetMethod("GetType", new Type[] { typeof(string), typeof(bool) }).MethodHandle);
int token2 = dynamicILInfo.GetTokenFor(typeof(string).GetMethod("ToUpper", Type.EmptyTypes).MethodHandle);
PutInteger4(token0, 0x001a, code);
PutInteger4(token1, 0x0020, code);
PutInteger4(token2, 0x0036, code);
dynamicILInfo.SetCode(code, 2);
int token3 = dynamicILInfo.GetTokenFor(typeof(System.Object).TypeHandle);
int token4 = dynamicILInfo.GetTokenFor(typeof(System.Exception).TypeHandle);
int token5 = dynamicILInfo.GetTokenFor(typeof(System.NullReferenceException).TypeHandle);
byte[] exceptions = {
0x41, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x0e, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x47, 0x00, 0x00, 0x00, 0x4a, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
PutInteger4(token3, 0x0018, exceptions);
PutInteger4(token4, 0x0030, exceptions);
PutInteger4(token5, 0x0048, exceptions);
dynamicILInfo.SetExceptions(exceptions);
int ret = (int)dynamicMethod.Invoke(null, null);
Assert.Equal(ret, ExceptionTest());
}
private static bool MyRule(int value) => value > 10;
private bool MyRule(string value) => value.Length > 10;
private delegate bool Satisfy<T>(T item);
private class Finder
{
public static T Find<T>(T[] items, Satisfy<T> standard)
{
foreach (T item in items)
if (standard(item)) return item;
return default(T);
}
}
private static bool GenericMethod()
{
int[] intarray = new int[6];
intarray[0] = 2;
intarray[1] = 9;
intarray[2] = -1;
intarray[3] = 14;
intarray[4] = 3;
intarray[5] = 55;
int i = Finder.Find(intarray, MyRule);
string[] strarray = new string[] { "Hello", "1", "world", "dynamicmethod", "find it already" };
string s = Finder.Find(strarray, new DynamicILInfoTests().MyRule);
return (i == intarray[3] && s == strarray[3]);
}
[Fact]
public void Test_GenericMethod()
{
DynamicMethod dynamicMethod = new DynamicMethod(nameof(GenericMethod), typeof(bool), Type.EmptyTypes, typeof(DynamicILInfoTests), false);
DynamicILInfo dynamicILInfo = dynamicMethod.GetDynamicILInfo();
SignatureHelper sigHelper = SignatureHelper.GetLocalVarSigHelper();
sigHelper.AddArgument(typeof(System.Int32[]), false);
sigHelper.AddArgument(typeof(int), false);
sigHelper.AddArgument(typeof(System.String[]), false);
sigHelper.AddArgument(typeof(string), false);
sigHelper.AddArgument(typeof(bool), false);
sigHelper.AddArgument(typeof(System.String[]), false);
dynamicILInfo.SetLocalSignature(sigHelper.GetSignature());
byte[] code = {
0x00, 0x1c, 0x8d, 0x1f, 0x00, 0x00, 0x01, 0x0a, 0x06, 0x16, 0x18, 0x9e, 0x06, 0x17, 0x1f, 0x09,
0x9e, 0x06, 0x18, 0x15, 0x9e, 0x06, 0x19, 0x1f, 0x0e, 0x9e, 0x06, 0x1a, 0x19, 0x9e, 0x06, 0x1b,
0x1f, 0x37, 0x9e, 0x06, 0x14, 0xfe, 0x06, 0x12, 0x00, 0x00, 0x06, 0x73, 0x3a, 0x00, 0x00, 0x0a,
0x28, 0x06, 0x00, 0x00, 0x2b, 0x0b, 0x1b, 0x8d, 0x0e, 0x00, 0x00, 0x01, 0x13, 0x05, 0x11, 0x05,
0x16, 0x72, 0x85, 0x02, 0x00, 0x70, 0xa2, 0x11, 0x05, 0x17, 0x72, 0x91, 0x02, 0x00, 0x70, 0xa2,
0x11, 0x05, 0x18, 0x72, 0x95, 0x02, 0x00, 0x70, 0xa2, 0x11, 0x05, 0x19, 0x72, 0xa1, 0x02, 0x00,
0x70, 0xa2, 0x11, 0x05, 0x1a, 0x72, 0xbd, 0x02, 0x00, 0x70, 0xa2, 0x11, 0x05, 0x0c, 0x08, 0x73,
0x18, 0x00, 0x00, 0x06, 0xfe, 0x06, 0x13, 0x00, 0x00, 0x06, 0x73, 0x3b, 0x00, 0x00, 0x0a, 0x28,
0x07, 0x00, 0x00, 0x2b, 0x0d, 0x07, 0x06, 0x19, 0x94, 0x33, 0x0b, 0x09, 0x08, 0x19, 0x9a, 0x28,
0x3c, 0x00, 0x00, 0x0a, 0x2b, 0x01, 0x16, 0x13, 0x04, 0x2b, 0x00, 0x11, 0x04, 0x2a
};
int token0 = dynamicILInfo.GetTokenFor(typeof(int).TypeHandle);
int token1 = dynamicILInfo.GetTokenFor(typeof(DynamicILInfoTests).GetMethod("MyRule", BindingFlags.NonPublic | BindingFlags.Static).MethodHandle);
int token2 = dynamicILInfo.GetTokenFor(typeof(Satisfy<int>).GetConstructor(new Type[] { typeof(System.Object), typeof(System.IntPtr) }).MethodHandle, typeof(Satisfy<int>).TypeHandle);
int token3 = dynamicILInfo.GetTokenFor(typeof(Finder).GetMethod("Find").MakeGenericMethod(typeof(int)).MethodHandle);
int token4 = dynamicILInfo.GetTokenFor(typeof(string).TypeHandle);
int token5 = dynamicILInfo.GetTokenFor("Hello");
int token6 = dynamicILInfo.GetTokenFor("1");
int token7 = dynamicILInfo.GetTokenFor("world");
int token8 = dynamicILInfo.GetTokenFor("dynamicmethod");
int token9 = dynamicILInfo.GetTokenFor("find it already");
int token10 = dynamicILInfo.GetTokenFor(typeof(DynamicILInfoTests).GetConstructor(Type.EmptyTypes).MethodHandle);
int token11 = dynamicILInfo.GetTokenFor(typeof(DynamicILInfoTests).GetMethod("MyRule", BindingFlags.NonPublic | BindingFlags.Instance).MethodHandle);
int token12 = dynamicILInfo.GetTokenFor(typeof(Satisfy<string>).GetConstructor(new Type[] { typeof(System.Object), typeof(System.IntPtr) }).MethodHandle, typeof(Satisfy<string>).TypeHandle);
int token13 = dynamicILInfo.GetTokenFor(typeof(Finder).GetMethod("Find").MakeGenericMethod(typeof(string)).MethodHandle);
int token14 = dynamicILInfo.GetTokenFor(typeof(string).GetMethod("op_Equality").MethodHandle);
PutInteger4(token0, 0x0003, code);
PutInteger4(token1, 0x0027, code);
PutInteger4(token2, 0x002c, code);
PutInteger4(token3, 0x0031, code);
PutInteger4(token4, 0x0038, code);
PutInteger4(token5, 0x0042, code);
PutInteger4(token6, 0x004b, code);
PutInteger4(token7, 0x0054, code);
PutInteger4(token8, 0x005d, code);
PutInteger4(token9, 0x0066, code);
PutInteger4(token10, 0x0070, code);
PutInteger4(token11, 0x0076, code);
PutInteger4(token12, 0x007b, code);
PutInteger4(token13, 0x0080, code);
PutInteger4(token14, 0x0090, code);
dynamicILInfo.SetCode(code, 4);
bool ret = (bool)dynamicMethod.Invoke(null, null);
Assert.Equal(ret, GenericMethod());
}
private static int TwoDimTest()
{
int a = 6;
int b = 8;
int[,] array = new int[a, b];
for (int i = 0; i < a; i++)
for (int j = 0; j < b; j++)
array[i, j] = i * j;
for (int i = 1; i < a; i++)
for (int j = 1; j < b; j++)
array[i, j] += array[i - 1, j - 1];
return array[a - 1, b - 1];
}
[Fact]
public void Test_TwoDimTest()
{
// 2-D array (set/address/get)
DynamicMethod dynamicMethod = new DynamicMethod(nameof(TwoDimTest), typeof(int), Type.EmptyTypes, typeof(DynamicILInfoTests), false);
DynamicILInfo dynamicILInfo = dynamicMethod.GetDynamicILInfo();
SignatureHelper sigHelper = SignatureHelper.GetLocalVarSigHelper();
sigHelper.AddArgument(typeof(int), false);
sigHelper.AddArgument(typeof(int), false);
sigHelper.AddArgument(typeof(System.Int32[,]), false);
sigHelper.AddArgument(typeof(int), false);
sigHelper.AddArgument(typeof(int), false);
sigHelper.AddArgument(typeof(int), false);
sigHelper.AddArgument(typeof(bool), false);
dynamicILInfo.SetLocalSignature(sigHelper.GetSignature());
byte[] code = {
0x00, 0x1c, 0x0a, 0x1e, 0x0b, 0x06, 0x07, 0x73, 0x3e, 0x00, 0x00, 0x0a, 0x0c, 0x16, 0x0d, 0x2b,
0x27, 0x16, 0x13, 0x04, 0x2b, 0x13, 0x08, 0x09, 0x11, 0x04, 0x09, 0x11, 0x04, 0x5a, 0x28, 0x3f,
0x00, 0x00, 0x0a, 0x11, 0x04, 0x17, 0x58, 0x13, 0x04, 0x11, 0x04, 0x07, 0xfe, 0x04, 0x13, 0x06,
0x11, 0x06, 0x2d, 0xe2, 0x09, 0x17, 0x58, 0x0d, 0x09, 0x06, 0xfe, 0x04, 0x13, 0x06, 0x11, 0x06,
0x2d, 0xcf, 0x17, 0x0d, 0x2b, 0x3c, 0x17, 0x13, 0x04, 0x2b, 0x28, 0x08, 0x09, 0x11, 0x04, 0x28,
0x40, 0x00, 0x00, 0x0a, 0x25, 0x71, 0x1f, 0x00, 0x00, 0x01, 0x08, 0x09, 0x17, 0x59, 0x11, 0x04,
0x17, 0x59, 0x28, 0x41, 0x00, 0x00, 0x0a, 0x58, 0x81, 0x1f, 0x00, 0x00, 0x01, 0x11, 0x04, 0x17,
0x58, 0x13, 0x04, 0x11, 0x04, 0x07, 0xfe, 0x04, 0x13, 0x06, 0x11, 0x06, 0x2d, 0xcd, 0x09, 0x17,
0x58, 0x0d, 0x09, 0x06, 0xfe, 0x04, 0x13, 0x06, 0x11, 0x06, 0x2d, 0xba, 0x08, 0x06, 0x17, 0x59,
0x07, 0x17, 0x59, 0x28, 0x41, 0x00, 0x00, 0x0a, 0x13, 0x05, 0x2b, 0x00, 0x11, 0x05, 0x2a
};
int token0 = dynamicILInfo.GetTokenFor(typeof(System.Int32[,]).GetConstructor(new Type[] { typeof(int), typeof(int) }).MethodHandle);
int token1 = dynamicILInfo.GetTokenFor(typeof(System.Int32[,]).GetMethod("Set").MethodHandle);
int token2 = dynamicILInfo.GetTokenFor(typeof(System.Int32[,]).GetMethod("Address").MethodHandle);
int token3 = dynamicILInfo.GetTokenFor(typeof(int).TypeHandle);
int token4 = dynamicILInfo.GetTokenFor(typeof(System.Int32[,]).GetMethod("Get").MethodHandle);
PutInteger4(token0, 0x0008, code);
PutInteger4(token1, 0x001f, code);
PutInteger4(token2, 0x0050, code);
PutInteger4(token3, 0x0056, code);
PutInteger4(token4, 0x0063, code);
PutInteger4(token3, 0x0069, code);
PutInteger4(token4, 0x0094, code);
dynamicILInfo.SetCode(code, 6);
int ret = (int)dynamicMethod.Invoke(null, null);
Assert.Equal(ret, TwoDimTest());
}
private class G<T>
{
public string M<K>(K arg)
{
return typeof(T).ToString() + typeof(K).ToString();
}
}
private static string CallGM()
{
string s = null;
G<int> g = new G<int>();
s += g.M(100);
s += g.M("hello");
G<string> g2 = new G<string>();
s += g2.M(100);
s += g2.M("world");
G<Type> g3 = new G<Type>();
s += g3.M(100L);
s += g3.M(new object());
return s;
}
[Fact]
public void Test_CallGM()
{
// GenericMethod inside GenericType
DynamicMethod dynamicMethod = new DynamicMethod(nameof(CallGM), typeof(string), Type.EmptyTypes, typeof(DynamicILInfoTests), false);
DynamicILInfo dynamicILInfo = dynamicMethod.GetDynamicILInfo();
SignatureHelper sigHelper = SignatureHelper.GetLocalVarSigHelper();
sigHelper.AddArgument(typeof(string), false);
sigHelper.AddArgument(typeof(G<int>), false);
sigHelper.AddArgument(typeof(G<string>), false);
sigHelper.AddArgument(typeof(G<System.Type>), false);
sigHelper.AddArgument(typeof(string), false);
dynamicILInfo.SetLocalSignature(sigHelper.GetSignature());
byte[] code = {
0x00, 0x14, 0x0a, 0x73, 0x42, 0x00, 0x00, 0x0a, 0x0b, 0x06, 0x07, 0x1f, 0x64, 0x6f, 0x09, 0x00,
0x00, 0x2b, 0x28, 0x2b, 0x00, 0x00, 0x0a, 0x0a, 0x06, 0x07, 0x72, 0x5f, 0x03, 0x00, 0x70, 0x6f,
0x0a, 0x00, 0x00, 0x2b, 0x28, 0x2b, 0x00, 0x00, 0x0a, 0x0a, 0x73, 0x44, 0x00, 0x00, 0x0a, 0x0c,
0x06, 0x08, 0x1f, 0x64, 0x6f, 0x0b, 0x00, 0x00, 0x2b, 0x28, 0x2b, 0x00, 0x00, 0x0a, 0x0a, 0x06,
0x08, 0x72, 0x95, 0x02, 0x00, 0x70, 0x6f, 0x0c, 0x00, 0x00, 0x2b, 0x28, 0x2b, 0x00, 0x00, 0x0a,
0x0a, 0x73, 0x46, 0x00, 0x00, 0x0a, 0x0d, 0x06, 0x09, 0x1f, 0x64, 0x6a, 0x6f, 0x0d, 0x00, 0x00,
0x2b, 0x28, 0x2b, 0x00, 0x00, 0x0a, 0x0a, 0x06, 0x09, 0x73, 0x2c, 0x00, 0x00, 0x0a, 0x6f, 0x0e,
0x00, 0x00, 0x2b, 0x28, 0x2b, 0x00, 0x00, 0x0a, 0x0a, 0x06, 0x13, 0x04, 0x2b, 0x00, 0x11, 0x04,
0x2a
};
int token0 = dynamicILInfo.GetTokenFor(typeof(G<int>).GetConstructor(Type.EmptyTypes).MethodHandle, typeof(G<int>).TypeHandle);
int token1 = dynamicILInfo.GetTokenFor(typeof(G<int>).GetMethod("M").MakeGenericMethod(typeof(int)).MethodHandle, typeof(G<int>).TypeHandle);
int token2 = dynamicILInfo.GetTokenFor(typeof(string).GetMethod("Concat", new Type[] { typeof(string), typeof(string) }).MethodHandle);
int token3 = dynamicILInfo.GetTokenFor("hello");
int token4 = dynamicILInfo.GetTokenFor(typeof(G<int>).GetMethod("M").MakeGenericMethod(typeof(string)).MethodHandle, typeof(G<int>).TypeHandle);
int token5 = dynamicILInfo.GetTokenFor(typeof(G<string>).GetConstructor(Type.EmptyTypes).MethodHandle, typeof(G<string>).TypeHandle);
int token6 = dynamicILInfo.GetTokenFor(typeof(G<string>).GetMethod("M").MakeGenericMethod(typeof(int)).MethodHandle, typeof(G<string>).TypeHandle);
int token7 = dynamicILInfo.GetTokenFor("world");
int token8 = dynamicILInfo.GetTokenFor(typeof(G<string>).GetMethod("M").MakeGenericMethod(typeof(string)).MethodHandle, typeof(G<string>).TypeHandle);
int token9 = dynamicILInfo.GetTokenFor(typeof(G<System.Type>).GetConstructor(Type.EmptyTypes).MethodHandle, typeof(G<System.Type>).TypeHandle);
int token10 = dynamicILInfo.GetTokenFor(typeof(G<System.Type>).GetMethod("M").MakeGenericMethod(typeof(long)).MethodHandle, typeof(G<System.Type>).TypeHandle);
int token11 = dynamicILInfo.GetTokenFor(typeof(System.Object).GetConstructor(Type.EmptyTypes).MethodHandle);
int token12 = dynamicILInfo.GetTokenFor(typeof(G<System.Type>).GetMethod("M").MakeGenericMethod(typeof(System.Object)).MethodHandle, typeof(G<System.Type>).TypeHandle);
PutInteger4(token0, 0x0004, code);
PutInteger4(token1, 0x000e, code);
PutInteger4(token2, 0x0013, code);
PutInteger4(token3, 0x001b, code);
PutInteger4(token4, 0x0020, code);
PutInteger4(token2, 0x0025, code);
PutInteger4(token5, 0x002b, code);
PutInteger4(token6, 0x0035, code);
PutInteger4(token2, 0x003a, code);
PutInteger4(token7, 0x0042, code);
PutInteger4(token8, 0x0047, code);
PutInteger4(token2, 0x004c, code);
PutInteger4(token9, 0x0052, code);
PutInteger4(token10, 0x005d, code);
PutInteger4(token2, 0x0062, code);
PutInteger4(token11, 0x006a, code);
PutInteger4(token12, 0x006f, code);
PutInteger4(token2, 0x0074, code);
dynamicILInfo.SetCode(code, 3);
string ret = (string)dynamicMethod.Invoke(null, null);
Assert.Equal(ret, CallGM());
}
private static void PutInteger4(int value, int startPos, byte[] array)
{
array[startPos++] = (byte)value;
array[startPos++] = (byte)(value >> 8);
array[startPos++] = (byte)(value >> 16);
array[startPos++] = (byte)(value >> 24);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public unsafe void SetX_NullInput_ThrowsArgumentNullException(bool skipVisibility)
{
DynamicMethod method = GetDynamicMethod(skipVisibility);
DynamicILInfo dynamicILInfo = method.GetDynamicILInfo();
Assert.Throws<ArgumentNullException>(() => dynamicILInfo.SetCode(null, 1, 8));
Assert.Throws<ArgumentNullException>(() => dynamicILInfo.SetExceptions(null, 1));
Assert.Throws<ArgumentNullException>(() => dynamicILInfo.SetLocalSignature(null, 1));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public unsafe void SetX_NegativeInputSize_ThrowsArgumentOutOfRangeException(bool skipVisibility)
{
DynamicMethod method = GetDynamicMethod(skipVisibility);
DynamicILInfo dynamicILInfo = method.GetDynamicILInfo();
var bytes = new byte[] { 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };
Assert.Throws<ArgumentOutOfRangeException>(() => {fixed (byte* bytesPtr = bytes) { dynamicILInfo.SetCode(bytesPtr, -1, 8); }});
Assert.Throws<ArgumentOutOfRangeException>(() => {fixed (byte* bytesPtr = bytes) { dynamicILInfo.SetExceptions(bytesPtr, -1); }});
Assert.Throws<ArgumentOutOfRangeException>(() => {fixed (byte* bytesPtr = bytes) { dynamicILInfo.SetLocalSignature(bytesPtr, -1); }});
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void GetDynamicILInfo_NotSameNotNull(bool skipVisibility)
{
DynamicMethod method = GetDynamicMethod(skipVisibility);
DynamicILInfo dynamicILInfo = method.GetDynamicILInfo();
Assert.NotNull(dynamicILInfo);
Assert.Equal(dynamicILInfo, method.GetDynamicILInfo());
Assert.Equal(method, dynamicILInfo.DynamicMethod);
}
private DynamicMethod GetDynamicMethod(bool skipVisibility)
{
return new DynamicMethod(nameof(DynamicMethod), typeof(void),
new Type[] { typeof(object), typeof(int), typeof(string) },
typeof(Object),
skipVisibility);
}
}
}
| |
using System;
using JetBrains.Annotations;
using Mod;
using Mod.Exceptions;
using Mod.Keybinds;
using Photon;
using Photon.Enums;
using UnityEngine;
// ReSharper disable once CheckNamespace
public class Cannon : Photon.MonoBehaviour
{
public Transform ballPoint;
public Transform barrel;
private Quaternion correctBarrelRot = Quaternion.identity;
private Vector3 correctPlayerPos = Vector3.zero;
private Quaternion correctPlayerRot = Quaternion.identity;
public float currentRot = 0f;
public Transform firingPoint;
public bool isCannonGround;
public GameObject myCannonBall;
public LineRenderer myCannonLine;
public HERO myHero;
public string settings;
public float SmoothingDelay = 5f;
public void Awake()
{
if (photonView != null)
{
photonView.observed = this;
this.barrel = transform.Find("Barrel");
this.correctPlayerPos = transform.position;
this.correctPlayerRot = transform.rotation;
this.correctBarrelRot = this.barrel.rotation;
if (photonView.isMine)
{
this.firingPoint = this.barrel.Find("FiringPoint");
this.ballPoint = this.barrel.Find("BallPoint");
this.myCannonLine = this.ballPoint.GetComponent<LineRenderer>();
if (gameObject.name.Contains("CannonGround"))
{
this.isCannonGround = true;
}
}
if (PhotonNetwork.isMasterClient)
{
Player owner = photonView.owner;
if (GameManager.instance.allowedToCannon.ContainsKey(owner.ID))
{
this.settings = GameManager.instance.allowedToCannon[owner.ID].settings;
photonView.RPC(Rpc.SetSize, PhotonTargets.All, this.settings);
int viewID = GameManager.instance.allowedToCannon[owner.ID].viewID;
GameManager.instance.allowedToCannon.Remove(owner.ID);
CannonPropRegion component = PhotonView.Find(viewID).gameObject.GetComponent<CannonPropRegion>();
if (component != null)
{
component.disabled = true;
component.destroyed = true;
PhotonNetwork.Destroy(component.gameObject);
}
}
else if (!(owner.IsLocal || GameManager.instance.restartingMC))
{
GameManager.instance.KickPlayerRC(owner, false, "spawning cannon without request.");
}
}
}
}
public void CannonFire()
{
if (this.myHero.skillCDDuration <= 0f)
{
foreach (EnemyCheckCollider c in PhotonNetwork.Instantiate("FX/boom2", this.firingPoint.position, this.firingPoint.rotation, 0).GetComponentsInChildren<EnemyCheckCollider>())
c.dmg = 0;
this.myCannonBall = PhotonNetwork.Instantiate("RCAsset/CannonBallObject", this.ballPoint.position, this.firingPoint.rotation, 0);
this.myCannonBall.rigidbody.velocity = this.firingPoint.forward * 300f;
this.myCannonBall.GetComponent<CannonBall>().myHero = this.myHero;
this.myHero.skillCDDuration = 3.5f;
}
}
public void OnDestroy()
{
if (PhotonNetwork.isMasterClient && !GameManager.instance.isRestarting)
{
string[] strArray = this.settings.Split(',');
if (strArray[0] == "photon")
{
if (strArray.Length > 15)
{
GameObject go = PhotonNetwork.Instantiate("RCAsset/" + strArray[1] + "Prop", new Vector3(float.Parse(strArray[12]), float.Parse(strArray[13]), float.Parse(strArray[14])), new Quaternion(float.Parse(strArray[15]), float.Parse(strArray[16]), float.Parse(strArray[17]), float.Parse(strArray[18])), 0);
go.GetComponent<CannonPropRegion>().settings = this.settings;
go.GetPhotonView().RPC(Rpc.SetSize, PhotonTargets.AllBuffered, this.settings);
}
else
{
PhotonNetwork.Instantiate("RCAsset/" + strArray[1] + "Prop", new Vector3(float.Parse(strArray[2]), float.Parse(strArray[3]), float.Parse(strArray[4])), new Quaternion(float.Parse(strArray[5]), float.Parse(strArray[6]), float.Parse(strArray[7]), float.Parse(strArray[8])), 0).GetComponent<CannonPropRegion>().settings = this.settings;
}
}
}
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.isWriting)
{
stream.SendNext(transform.position);
stream.SendNext(transform.rotation);
stream.SendNext(this.barrel.rotation);
}
else
{
this.correctPlayerPos = (Vector3) stream.ReceiveNext();
this.correctPlayerRot = (Quaternion) stream.ReceiveNext();
this.correctBarrelRot = (Quaternion) stream.ReceiveNext();
}
}
[RPC]
[UsedImplicitly]
public void SetSize(string settings, PhotonMessageInfo info)
{
if (!info.sender.IsMasterClient)
throw new NotAllowedException(nameof(SetSize), info);
string[] strArray = settings.Split(',');
if (strArray.Length > 15)
{
float a = 1f;
GameObject gameObject;
gameObject = this.gameObject;
if (strArray[2] != "default")
{
if (strArray[2].EqualsIgnoreCase("transparent"))
{
if (float.TryParse(strArray[2].Substring(11), out var num2))
{
a = num2;
}
foreach (Renderer renderer in gameObject.GetComponentsInChildren<Renderer>())
{
renderer.material = (Material) GameManager.RCassets.Load("transparent");
if (float.Parse(strArray[10]) != 1f || float.Parse(strArray[11]) != 1f)
{
renderer.material.mainTextureScale = new Vector2(renderer.material.mainTextureScale.x * float.Parse(strArray[10]), renderer.material.mainTextureScale.y * float.Parse(strArray[11]));
}
}
}
else
{
foreach (Renderer renderer in gameObject.GetComponentsInChildren<Renderer>())
{
if (!renderer.name.Contains("Line Renderer"))
{
renderer.material = (Material) GameManager.RCassets.Load(strArray[2]);
if (float.Parse(strArray[10]) != 1f || float.Parse(strArray[11]) != 1f)
{
renderer.material.mainTextureScale = new Vector2(renderer.material.mainTextureScale.x * float.Parse(strArray[10]), renderer.material.mainTextureScale.y * float.Parse(strArray[11]));
}
}
}
}
}
Vector3 localScale = gameObject.transform.localScale;
gameObject.transform.localScale = new Vector3(
localScale.x * float.Parse(strArray[3]) - 0.001f,
localScale.y * float.Parse(strArray[4]),
localScale.z * float.Parse(strArray[5]));
if (strArray[6] != "0")
{
Color color = new Color(float.Parse(strArray[7]), float.Parse(strArray[8]), float.Parse(strArray[9]), a);
foreach (MeshFilter filter in gameObject.GetComponentsInChildren<MeshFilter>())
{
Mesh mesh = filter.mesh;
Color[] colorArray = new Color[mesh.vertexCount];
for (int i = 0; i < mesh.vertexCount; i++)
colorArray[i] = color;
mesh.colors = colorArray;
}
}
}
}
public void Update()
{
if (!photonView.isMine)
{
transform.position = Vector3.Lerp(transform.position, this.correctPlayerPos, Time.deltaTime * this.SmoothingDelay);
transform.rotation = Quaternion.Lerp(transform.rotation, this.correctPlayerRot, Time.deltaTime * this.SmoothingDelay);
this.barrel.rotation = Quaternion.Lerp(this.barrel.rotation, this.correctBarrelRot, Time.deltaTime * this.SmoothingDelay);
return;
}
Vector3 vector = new Vector3(0f, -30f, 0f);
Vector3 position = this.ballPoint.position;
Vector3 vector3 = this.ballPoint.forward * 300f;
float num = 40f / vector3.magnitude;
this.myCannonLine.SetWidth(0.5f, 40f);
this.myCannonLine.SetVertexCount(100);
for (int i = 0; i < 100; i++)
{
this.myCannonLine.SetPosition(i, position);
position += vector3 * num + 0.5f * vector * num * num;
vector3 += vector * num;
}
const float speed = 20f;
if (this.isCannonGround)
{
if (Shelter.InputManager.IsKeyPressed(InputAction.Forward))
{
if (this.currentRot <= 32f)
{
this.currentRot += Time.deltaTime * speed;
this.barrel.Rotate(new Vector3(0f, 0f, Time.deltaTime * speed));
}
}
else if (Shelter.InputManager.IsKeyPressed(InputAction.Back) && this.currentRot >= -18f)
{
this.currentRot += Time.deltaTime * -speed;
this.barrel.Rotate(new Vector3(0f, 0f, Time.deltaTime * -speed));
}
}
else
{
if (Shelter.InputManager.IsKeyPressed(InputAction.Forward))
{
if (this.currentRot >= -50f)
{
this.currentRot += Time.deltaTime * -speed;
this.barrel.Rotate(new Vector3(Time.deltaTime * -speed, 0f, 0f));
}
}
else if (Shelter.InputManager.IsKeyPressed(InputAction.Back) && this.currentRot <= 40f)
{
this.currentRot += Time.deltaTime * speed;
this.barrel.Rotate(new Vector3(Time.deltaTime * speed, 0f, 0f));
}
}
if (Shelter.InputManager.IsKeyPressed(InputAction.Left))
transform.Rotate(new Vector3(0f, Time.deltaTime * -speed, 0f));
else if (Shelter.InputManager.IsKeyPressed(InputAction.Right))
transform.Rotate(new Vector3(0f, Time.deltaTime * speed, 0f));
if (Shelter.InputManager.IsDown(InputAction.Attack))
{
CannonFire();
}
else if (Shelter.InputManager.IsDown(InputAction.EnterCannon))
{
if (myHero != null)
myHero.ExitCannon();
PhotonNetwork.Destroy(gameObject);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="LBQueues.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <disclaimer>
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
// </disclaimer>
//------------------------------------------------------------------------------
using System;
using System.Threading;
using System.Diagnostics;
namespace Microsoft.Research.Joins.LockBased {
internal interface IQueue<A> {
void Init();
void Add(A a);
A Get();
bool Empty { get; }
}
internal struct LibQueue<A> : IQueue<A> {
internal System.Collections.Generic.Queue<A> mQ;
public void Init() {
mQ = new System.Collections.Generic.Queue<A>();
}
public void Add(A a) {
mQ.Enqueue(a);
}
public A Get() {
return mQ.Dequeue();
}
public bool Empty {
get { return mQ.Count == 0; }
}
}
internal struct Queue<A> : IQueue<A> {
internal class CyclicList {
internal A mHead;
internal CyclicList mTail;
internal CyclicList(A head, CyclicList context) {
mHead = head;
mTail = context.mTail;
context.mTail = this;
}
internal CyclicList(A head) {
mHead = head; mTail = this;
}
}
private CyclicList mLast;
void IQueue<A>.Init() { mLast = null; }
void IQueue<A>.Add(A a) {
if (mLast == null) mLast = new CyclicList(a);
else {
new CyclicList(a, mLast);
mLast = mLast.mTail;
}
}
A IQueue<A>.Get() {
A a = mLast.mTail.mHead;
if ((mLast.mTail) == mLast)
mLast = null;
else mLast.mTail = mLast.mTail.mTail;
return a;
}
bool IQueue<A>.Empty { get { return mLast == null; } }
public override string ToString() {
return (mLast == null) ? "empty" :
(mLast.mTail == mLast) ? mLast.mTail.mHead.ToString() :
mLast.mTail.mHead + ",...," + mLast.mHead;
}
}
internal struct UnitQueue : IQueue<Unit> {
private int mCount;
void IQueue<Unit>.Init() { this.mCount = 0; }
void IQueue<Unit>.Add(Unit u) {
if (this.mCount == System.Int32.MaxValue)
JoinException.AsynchronousChannelOverflow();
else mCount++;
}
Unit IQueue<Unit>.Get() { mCount--; return Unit.Null; }
bool IQueue<Unit>.Empty { get { return mCount == 0; } }
public override string ToString() {
return mCount.ToString();
}
}
internal class ThreadQueue {
private bool mSignalled = false;
private int mCount = 0;
internal bool Empty { get { return (mCount == 0); } }
[DebuggerNonUserCode]
internal void Yield(object myCurrentLock) {
mCount++;
Monitor.Exit(myCurrentLock);
lock (this) {
while (!mSignalled) {
Monitor.Wait(this);
}
mSignalled = false;
}
Monitor.Enter(myCurrentLock);
mCount--;
}
internal void WakeUp() {
lock (this) {
if (!mSignalled) {
mSignalled = true;
Monitor.Pulse(this);
}
}
}
public override string ToString() {
return mCount.ToString();
}
}
/*
This version tries to cache a single lock in a thread-local, but may not buy us anything...
internal class ThreadLocals {
[ThreadStatic]
static internal object Lock;
}
internal class Waiter<R> {
enum Status { Pending, Done, Failed, Continue }
private Status mStatus = Status.Pending;
R m_res;
Exception m_exn;
object m_lock;
internal Waiter() {
var l = ThreadLocals.Lock;
if (l == null) {
l = new object();
ThreadLocals.Lock = l;
}
m_lock = l;
}
internal bool Wait(ref R res) {
lock (m_lock) {
while (mStatus == Status.Pending) {
Monitor.Wait(m_lock);
};
switch (mStatus) {
case Status.Done: {
res = m_res;
return true;
}
case Status.Failed: {
throw m_exn;
}
case Status.Continue:
default: {
return false;
}
}
}
}
internal void WakeUp() {
lock (m_lock) {
if (this.mStatus == Status.Pending) {
this.mStatus = Status.Continue;
Monitor.Pulse(m_lock);
}
}
}
internal void Fail(Exception e) {
lock (m_lock) {
if (this.mStatus == Status.Pending) {
this.m_exn = e;
this.mStatus = Status.Failed;
Monitor.Pulse(m_lock);
}
}
if (mNext != null) mNext.Fail(e);
}
internal void Succeed(R res) {
lock (m_lock) {
if (this.mStatus == Status.Pending) {
this.m_res = res;
this.mStatus = Status.Done;
Monitor.Pulse(m_lock);
}
}
if (mNext != null) mNext.Succeed(res);
}
internal Waiter<R> mNext;
public void AddTo(ref Waiter<R> waiters) {
this.mNext = waiters;
waiters = this;
}
}
*/
internal abstract class Waiter {
internal enum Status { Pending, Done, Failed, Continue }
internal Status mStatus = Status.Pending;
internal Exception m_exn;
protected abstract void Schedule();
protected abstract void WaitWhilePending();
internal void WakeUp() {
lock (this) {
if (this.mStatus == Status.Pending) {
this.mStatus = Status.Continue;
Schedule();
}
}
}
internal void Fail(Exception e) {
lock (this) {
if (this.mStatus == Status.Pending) {
this.m_exn = e;
this.mStatus = Status.Failed;
Schedule();
}
}
if (mNext != null) mNext.Fail(e);
}
internal Waiter mNext;
public void AddTo(ref Waiter waiters) {
this.mNext = waiters;
waiters = this;
}
}
internal abstract class Waiter<R> : Waiter {
internal R m_res;
internal bool Wait(ref R res) {
lock (this) {
/*
while (mStatus == Status.Pending) {
Monitor.Wait(this);
};
*/
WaitWhilePending();
switch (mStatus) {
case Status.Pending:
{
Debug.Assert(false);
throw new System.Exception();
}
case Status.Done: {
res = m_res;
return true;
}
case Status.Failed: {
throw m_exn;
}
case Status.Continue:
default: {
return false;
}
}
}
}
internal void Succeed(R res) {
lock (this) {
if (this.mStatus == Status.Pending)
{
this.m_res = res;
this.mStatus = Status.Done;
Schedule();
}
}
if (mNext != null) ((Waiter<R>) mNext).Succeed(res);
}
}
internal abstract class AbstractWaiter<A,R> : Waiter<R> {
public readonly A m_arg;
internal AbstractWaiter(A arg) {
this.m_arg = arg;
}
}
internal class Waiter<A,R> : AbstractWaiter<A,R> {
protected override void WaitWhilePending()
{
while (mStatus == Status.Pending)
{
Monitor.Wait(this);
};
}
protected override void Schedule()
{
Monitor.Pulse(this);
}
internal Waiter(A arg): base(arg) {
}
}
internal class AsyncWaiter<A,R> : AbstractWaiter<A,R> {
Action<bool, Waiter<R>> k;
protected override void WaitWhilePending()
{
#warning: "Async:check me"
Debug.Assert(this.mStatus != Status.Pending);
return;
}
protected override void Schedule()
{
#warning: "Async:optimize me"
Debug.Assert(this.mStatus != Status.Pending);
System.Threading.Tasks.Task.Factory.StartNew(() => k(mStatus != Status.Continue,this));
//Run()
}
internal AsyncWaiter(A arg,Action<bool,Waiter<R>> k): base(arg) {
this.k = k;
}
}
internal class ThreadQueue<R,A> {
// todo: add Node<R> superclass with appropriate methods and
// links to other nodes...
internal System.Collections.Generic.Queue<AbstractWaiter<A, R>> mQ
= new System.Collections.Generic.Queue<AbstractWaiter<A, R>>();
internal bool Empty { get { return (mQ.Count == 0); } }
[DebuggerNonUserCode]
internal bool Yield(A a, object myCurrentLock, ref R r) {
var n = new Waiter<A,R>(a);
mQ.Enqueue(n);
Monitor.Exit(myCurrentLock);
var s = n.Wait(ref r);
if (s) return true;
else {
Monitor.Enter(myCurrentLock);
return false;
}
}
internal void WakeUp() {
var n = mQ.Dequeue();
n.WakeUp();
}
internal void AsyncYield( A t, object myCurrentLock, Action<bool,Waiter<R>> k)
{
var n = new AsyncWaiter<A, R>(t,k);
mQ.Enqueue(n);
Monitor.Exit(myCurrentLock);
/*
var s = n.Wait(ref a.result);
if (s) return true;
else
{
Monitor.Enter(myCurrentLock);
return false;
}
* */
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.RuleEngine
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
/// <summary>
/// Helper class to query the global rule respository for applicable rules
/// </summary>
public static class RuleSelector
{
/// <summary>
/// Gets all applicable rules to a specific context
/// </summary>
/// <param name="contextTrait">the current interop request context these rules are applicable</param>
/// <returns>rules applicable to the specified request context</returns>
public static IEnumerable<Rule> GetRules(this ServiceContextCore contextTrait)
{
if (contextTrait == null)
{
throw new ArgumentNullException("contextTrait");
}
return RuleCatalogCollection.Instance.SelectRulesOfCategory(contextTrait.Category)
.SelectRules(contextTrait.PayloadType, contextTrait.IsMediaLinkEntry, contextTrait.Projection)
.SelectRules(contextTrait.PayloadFormat)
.SelectRulesByMetadataFlag(contextTrait.OdataMetadataType)
.SelectRulesByConformanceType(contextTrait.ServiceType, contextTrait.LevelTypes)
.SelectRules(contextTrait.Version)
.SelectRulesByMetadata(contextTrait.HasMetadata)
.SelectRulesByServiceDocument(contextTrait.HasServiceDocument)
.SelectRulesByOfflineFlag(contextTrait.IsOffline);
}
/// <summary>
/// Filters rules based on rule category.
/// </summary>
/// <param name="rules">The collection of input rules</param>
/// <param name="category">Rule category</param>
/// <returns>The subset of input rules that meet the condition of category</returns>
public static IEnumerable<Rule> SelectRulesOfCategory(this IEnumerable<Rule> rules, string category)
{
if (rules == null)
{
throw new ArgumentNullException("rules");
}
return from r in rules
where r.Category.Equals(category, System.StringComparison.OrdinalIgnoreCase)
select r;
}
/// <summary>
/// Filters rules based on payload type and flag of media link entry.
/// </summary>
/// <param name="rules">The collection of input rules</param>
/// <param name="payloadType">Payload type</param>
/// <param name="isMediaLinkEntry">Flag of media link entry</param>
/// <param name="projection">Flag of projected request</param>
/// <returns>The subset of input rules that meet the conditions of payload type and media link entry flag</returns>
private static IEnumerable<Rule> SelectRules(this IEnumerable<Rule> rules, PayloadType payloadType, bool isMediaLinkEntry, bool projection)
{
rules = from r in rules
where !r.PayloadType.HasValue || r.PayloadType == payloadType
select r;
if (payloadType == PayloadType.Entry)
{
rules = from r in rules
where !r.IsMediaLinkEntry.HasValue || r.IsMediaLinkEntry.Value == isMediaLinkEntry
select r;
}
if (payloadType == PayloadType.Entry || payloadType == PayloadType.Feed)
{
rules = from r in rules
where !r.Projection.HasValue || r.Projection.Value == projection
select r;
}
return rules;
}
/// <summary>
/// Filters rules based on payload format.
/// </summary>
/// <param name="rules">The collection of input rules</param>
/// <param name="payloadFormat">Payload format</param>
/// <returns>The subset of input rules that meet the condition of payload format</returns>
private static IEnumerable<Rule> SelectRules(this IEnumerable<Rule> rules, PayloadFormat payloadFormat)
{
return from r in rules
where !r.PayloadFormat.HasValue || r.PayloadFormat == payloadFormat
select r;
}
/// <summary>
/// Filters rules based on OData version.
/// </summary>
/// <param name="rules">The collection of input rules</param>
/// <param name="version">OData version</param>
/// <returns>The subset of input rules that meet the condition of OData version</returns>
public static IEnumerable<Rule> SelectRules(this IEnumerable<Rule> rules, ODataVersion version)
{
return from r in rules
where (!r.Version.HasValue && (version == ODataVersion.V1 || version == ODataVersion.V2 || version == ODataVersion.V3 || version == ODataVersion.V1_V2) || version == ODataVersion.V1_V2_V3)
|| r.Version == version
|| (r.Version == ODataVersion.V1_V2 && (version == ODataVersion.V1 || version == ODataVersion.V2))
|| (version == ODataVersion.V1_V2 && (r.Version == ODataVersion.V1 || r.Version == ODataVersion.V2))
|| (version == ODataVersion.V3_V4 && (r.Version == ODataVersion.V3 || r.Version == ODataVersion.V4))
|| (r.Version == ODataVersion.V3_V4 && (version == ODataVersion.V3 || version == ODataVersion.V4))
|| (version == ODataVersion.V4 && (r.Version == ODataVersion.V4 || r.Version == ODataVersion.V3_V4))
|| (r.Version == ODataVersion.V1_V2_V3 && (version == ODataVersion.V1 || version == ODataVersion.V2 || version == ODataVersion.V3 || version == ODataVersion.V1_V2))
|| (version == ODataVersion.V_All && r.Version != ODataVersion.UNKNOWN)
select r;
}
/// <summary>
/// Filters rules based on whether metadata document is available.
/// </summary>
/// <param name="rules">The collection of input rules</param>
/// <param name="hasMetadata">Flag of metadata document availability</param>
/// <returns>The subset of input rules that meet the condition of metadata document availability</returns>
private static IEnumerable<Rule> SelectRulesByMetadata(this IEnumerable<Rule> rules, bool hasMetadata)
{
return from r in rules
where !r.RequireMetadata.HasValue || r.RequireMetadata.Value == hasMetadata || (r.RequireMetadata.HasValue && r.RequireMetadata.Value == false)
select r;
}
/// <summary>
/// Filters rules based on whether service document is available.
/// </summary>
/// <param name="rules">The collection of input rules</param>
/// <param name="hasServiceDocument">Flag of service document availability</param>
/// <returns>The subset of input rules that meet the condition of service document availability</returns>
private static IEnumerable<Rule> SelectRulesByServiceDocument(this IEnumerable<Rule> rules, bool hasServiceDocument)
{
return from r in rules
where !r.RequireServiceDocument.HasValue || r.RequireServiceDocument.Value == hasServiceDocument
select r;
}
/// <summary>
/// Filters rules based on offline context or live context
/// </summary>
/// <param name="rules">The collection of input rules</param>
/// <param name="isOfflineContext">Flag of context being offline or live</param>
/// <returns>The subset of input rules that applies to the context</returns>
private static IEnumerable<Rule> SelectRulesByOfflineFlag(this IEnumerable<Rule> rules, bool isOfflineContext)
{
if (isOfflineContext)
{
return from r in rules
where !r.Offline.HasValue || r.Offline.Value == true
select r;
}
else
{
return rules;
}
}
/// <summary>
/// Filters rules based on odata metadata type
/// </summary>
/// <param name="rules">The collection of input rules</param>
/// <param name="ODataMetadataType">OData metadata type</param>
/// <returns>The subset of input rules that applies to the context</returns>
private static IEnumerable<Rule> SelectRulesByMetadataFlag(this IEnumerable<Rule> rules, ODataMetadataType odataMetadataType)
{
return from r in rules
where !r.OdataMetadataType.HasValue || r.OdataMetadataType.Value == odataMetadataType
select r;
}
/// <summary>
/// Filters rules based on resource type
/// </summary>
/// <param name="rules">The collection of input rules</param>
/// <param name="resourceType">resource type</param>
/// <returns>The subset of input rules that applies to the context</returns>
private static IEnumerable<Rule> SelectRulesByConformanceType(this IEnumerable<Rule> rules, ConformanceServiceType resourceType, ConformanceLevelType[] levelTypes = null)
{
rules = from r in rules
where !r.ResourceType.HasValue || r.ResourceType.Value == resourceType
select r;
if (null != levelTypes && levelTypes.Count() > 0)
{
rules = from r in rules
where !r.LevelType.HasValue || levelTypes.Contains(r.LevelType.Value)
select r;
}
return rules;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2012-2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using NUnit.Common;
using NUnit.Framework.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
namespace NUnit.Framework.Api
{
/// <summary>
/// DefaultTestAssemblyBuilder loads a single assembly and builds a TestSuite
/// containing test fixtures present in the assembly.
/// </summary>
public class DefaultTestAssemblyBuilder : ITestAssemblyBuilder
{
static Logger log = InternalTrace.GetLogger(typeof(DefaultTestAssemblyBuilder));
#region Instance Fields
/// <summary>
/// The default suite builder used by the test assembly builder.
/// </summary>
ISuiteBuilder _defaultSuiteBuilder;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DefaultTestAssemblyBuilder"/> class.
/// </summary>
public DefaultTestAssemblyBuilder()
{
_defaultSuiteBuilder = new DefaultSuiteBuilder();
}
#endregion
#region Build Methods
/// <summary>
/// Build a suite of tests from a provided assembly
/// </summary>
/// <param name="assembly">The assembly from which tests are to be built</param>
/// <param name="options">A dictionary of options to use in building the suite</param>
/// <returns>
/// A TestSuite containing the tests found in the assembly
/// </returns>
public ITest Build(Assembly assembly, IDictionary options)
{
#if PORTABLE
log.Debug("Loading {0}", assembly.FullName);
#else
log.Debug("Loading {0} in AppDomain {1}", assembly.FullName, AppDomain.CurrentDomain.FriendlyName);
#endif
#if SILVERLIGHT
string assemblyPath = AssemblyHelper.GetAssemblyName(assembly).Name;
#elif PORTABLE
string assemblyPath = AssemblyHelper.GetAssemblyName(assembly).FullName;
#else
string assemblyPath = AssemblyHelper.GetAssemblyPath(assembly);
#endif
return Build(assembly, assemblyPath, options);
}
/// <summary>
/// Build a suite of tests given the filename of an assembly
/// </summary>
/// <param name="assemblyName">The filename of the assembly from which tests are to be built</param>
/// <param name="options">A dictionary of options to use in building the suite</param>
/// <returns>
/// A TestSuite containing the tests found in the assembly
/// </returns>
public ITest Build(string assemblyName, IDictionary options)
{
#if PORTABLE
log.Debug("Loading {0}", assemblyName);
#else
log.Debug("Loading {0} in AppDomain {1}", assemblyName, AppDomain.CurrentDomain.FriendlyName);
#endif
TestSuite testAssembly = null;
try
{
var assembly = AssemblyHelper.Load(assemblyName);
testAssembly = Build(assembly, assemblyName, options);
}
catch (Exception ex)
{
testAssembly = new TestAssembly(assemblyName);
testAssembly.RunState = RunState.NotRunnable;
testAssembly.Properties.Set(PropertyNames.SkipReason, ex.Message);
}
return testAssembly;
}
private TestSuite Build(Assembly assembly, string assemblyPath, IDictionary options)
{
TestSuite testAssembly = null;
try
{
IList fixtureNames = options[PackageSettings.LOAD] as IList;
var fixtures = GetFixtures(assembly, fixtureNames);
testAssembly = BuildTestAssembly(assembly, assemblyPath, fixtures);
}
catch (Exception ex)
{
testAssembly = new TestAssembly(assemblyPath);
testAssembly.RunState = RunState.NotRunnable;
testAssembly.Properties.Set(PropertyNames.SkipReason, ex.Message);
}
return testAssembly;
}
#endregion
#region Helper Methods
private IList<Test> GetFixtures(Assembly assembly, IList names)
{
var fixtures = new List<Test>();
log.Debug("Examining assembly for test fixtures");
var testTypes = GetCandidateFixtureTypes(assembly, names);
log.Debug("Found {0} classes to examine", testTypes.Count);
#if LOAD_TIMING
System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
timer.Start();
#endif
int testcases = 0;
foreach (Type testType in testTypes)
{
var typeInfo = new TypeWrapper(testType);
try
{
if (_defaultSuiteBuilder.CanBuildFrom(typeInfo))
{
Test fixture = _defaultSuiteBuilder.BuildFrom(typeInfo);
fixtures.Add(fixture);
testcases += fixture.TestCaseCount;
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
#if LOAD_TIMING
log.Debug("Found {0} fixtures with {1} test cases in {2} seconds", fixtures.Count, testcases, timer.Elapsed);
#else
log.Debug("Found {0} fixtures with {1} test cases", fixtures.Count, testcases);
#endif
return fixtures;
}
private IList<Type> GetCandidateFixtureTypes(Assembly assembly, IList names)
{
var types = assembly.GetTypes();
if (names == null || names.Count == 0)
return types;
var result = new List<Type>();
foreach (string name in names)
{
Type fixtureType = assembly.GetType(name);
if (fixtureType != null)
result.Add(fixtureType);
else
{
string prefix = name + ".";
foreach (Type type in types)
if (type.FullName.StartsWith(prefix))
result.Add(type);
}
}
return result;
}
private TestSuite BuildTestAssembly(Assembly assembly, string assemblyName, IList<Test> fixtures)
{
TestSuite testAssembly = new TestAssembly(assembly, assemblyName);
if (fixtures.Count == 0)
{
testAssembly.RunState = RunState.NotRunnable;
testAssembly.Properties.Set(PropertyNames.SkipReason, "Has no TestFixtures");
}
else
{
NamespaceTreeBuilder treeBuilder =
new NamespaceTreeBuilder(testAssembly);
treeBuilder.Add(fixtures);
testAssembly = treeBuilder.RootSuite;
}
testAssembly.ApplyAttributesToTest(assembly);
#if !PORTABLE
#if !SILVERLIGHT
testAssembly.Properties.Set(PropertyNames.ProcessID, System.Diagnostics.Process.GetCurrentProcess().Id);
#endif
testAssembly.Properties.Set(PropertyNames.AppDomain, AppDomain.CurrentDomain.FriendlyName);
#endif
// TODO: Make this an option? Add Option to sort assemblies as well?
testAssembly.Sort();
return testAssembly;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Batch
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LocationOperations operations.
/// </summary>
internal partial class LocationOperations : IServiceOperations<BatchManagementClient>, ILocationOperations
{
/// <summary>
/// Initializes a new instance of the LocationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LocationOperations(BatchManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the BatchManagementClient
/// </summary>
public BatchManagementClient Client { get; private set; }
/// <summary>
/// Gets the Batch service quotas for the specified subscription at the given
/// location.
/// </summary>
/// <param name='locationName'>
/// The desired region for the quotas.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<BatchLocationQuota>> GetQuotasWithHttpMessagesAsync(string locationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (locationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "locationName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("locationName", locationName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetQuotas", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/quotas").ToString();
_url = _url.Replace("{locationName}", System.Uri.EscapeDataString(locationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<BatchLocationQuota>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchLocationQuota>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System.Globalization;
using System.Text;
namespace System
{
internal static class UriHelper
{
private static readonly char[] HexUpperChars = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
// http://host/Path/Path/File?Query is the base of
// - http://host/Path/Path/File/ ... (those "File" words may be different in semantic but anyway)
// - http://host/Path/Path/#Fragment
// - http://host/Path/Path/?Query
// - http://host/Path/Path/MoreDir/ ...
// - http://host/Path/Path/OtherFile?Query
// - http://host/Path/Path/Fl
// - http://host/Path/Path/
//
// It is not a base for
// - http://host/Path/Path (that last "Path" is not considered as a directory)
// - http://host/Path/Path?Query
// - http://host/Path/Path#Fragment
// - http://host/Path/Path2/
// - http://host/Path/Path2/MoreDir
// - http://host/Path/File
//
// ASSUMES that strings like http://host/Path/Path/MoreDir/../../ have been canonicalized before going to this method.
// ASSUMES that back slashes already have been converted if applicable.
//
internal static unsafe bool TestForSubPath( char* pMe, ushort meLength, char* pShe, ushort sheLength,
bool ignoreCase)
{
ushort i = 0;
char chMe;
char chShe;
bool AllSameBeforeSlash = true;
for( ;i < meLength && i < sheLength; ++i)
{
chMe = *(pMe+i);
chShe = *(pShe+i);
if (chMe == '?' || chMe == '#')
{
// survived so far and pMe does not have any more path segments
return true;
}
// If pMe terminates a path segment, so must pShe
if (chMe == '/')
{
if (chShe != '/')
{
// comparison has falied
return false;
}
// plus the segments must be the same
if (!AllSameBeforeSlash)
{
// comparison has falied
return false;
}
//so far so good
AllSameBeforeSlash = true;
continue;
}
// if pShe terminates then pMe must not have any more path segments
if (chShe == '?' || chShe == '#')
{
break;
}
if (!ignoreCase)
{
if (chMe != chShe)
{
AllSameBeforeSlash = false;
}
}
else
{
if (Char.ToLower(chMe, CultureInfo.InvariantCulture) != Char.ToLower(chShe, CultureInfo.InvariantCulture))
{
AllSameBeforeSlash = false;
}
}
}
// If me is longer then it must not have any more path segments
for (; i < meLength; ++i)
{
if ((chMe = *(pMe+i)) == '?' || chMe == '#')
{
return true;
}
if (chMe == '/')
{
return false;
}
}
//survived by getting to the end of pMe
return true;
}
// - forceX characters are always escaped if found
// - rsvd character will remain unescaped
//
// start - starting offset from input
// end - the exclusive ending offset in input
// destPos - starting offset in dest for output, on return this will be an exclusive "end" in the output.
//
// In case "dest" has lack of space it will be reallocated by preserving the _whole_ content up to current destPos
//
// Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos
//
const short c_MaxAsciiCharsReallocate = 40;
const short c_MaxUnicodeCharsReallocate = 40;
const short c_MaxUTF_8BytesPerUnicodeChar = 4;
const short c_EncodedCharsPerByte = 3;
internal unsafe static char[] EscapeString(string input, int start, int end, char[] dest, ref int destPos,
bool isUriString, char force1, char force2, char rsvd)
{
if (end - start >= Uri.c_MaxUriBufferSize)
throw new UriFormatException(SR.GetString(SR.net_uri_SizeLimit));
int i = start;
int prevInputPos = start;
byte *bytes = stackalloc byte[c_MaxUnicodeCharsReallocate*c_MaxUTF_8BytesPerUnicodeChar]; // 40*4=160
fixed (char* pStr = input)
{
for(; i < end; ++i)
{
char ch = pStr[i];
// a Unicode ?
if (ch > '\x7F')
{
short maxSize = (short)Math.Min(end - i, (int)c_MaxUnicodeCharsReallocate-1);
short count = 1;
for (; count < maxSize && pStr[i + count] > '\x7f'; ++count)
;
// Is the last a high surrogate?
if (pStr[i + count-1] >= 0xD800 && pStr[i + count-1] <= 0xDBFF)
{
// Should be a rare case where the app tries to feed an invalid Unicode surrogates pair
if (count == 1 || count == end - i)
throw new UriFormatException(SR.GetString(SR.net_uri_BadString));
// need to grab one more char as a Surrogate except when it's a bogus input
++count;
}
dest = EnsureDestinationSize(pStr, dest, i,
(short)(count * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte),
c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte,
ref destPos, prevInputPos);
short numberOfBytes = (short)Encoding.UTF8.GetBytes(pStr+i, count, bytes,
c_MaxUnicodeCharsReallocate*c_MaxUTF_8BytesPerUnicodeChar);
// This is the only exception that built in UriParser can throw after a Uri ctor.
// Should not happen unless the app tries to feed an invalid Unicode String
if (numberOfBytes == 0)
throw new UriFormatException(SR.GetString(SR.net_uri_BadString));
i += (count-1);
for (count = 0 ; count < numberOfBytes; ++count)
EscapeAsciiChar((char)bytes[count], dest, ref destPos);
prevInputPos = i+1;
}
else if (ch == '%' && rsvd == '%')
{
// Means we don't reEncode '%' but check for the possible escaped sequence
dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte,
c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos);
if(i + 2 < end && EscapedAscii(pStr[i+1], pStr[i+2]) != Uri.c_DummyChar)
{
// leave it escaped
dest[destPos++] = '%';
dest[destPos++] = pStr[i+1];
dest[destPos++] = pStr[i+2];
i += 2;
}
else
{
EscapeAsciiChar('%', dest, ref destPos);
}
prevInputPos = i+1;
}
else if (ch == force1 || ch == force2)
{
dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte,
c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos);
EscapeAsciiChar(ch, dest, ref destPos);
prevInputPos = i+1;
}
else if (ch != rsvd && (isUriString ? !IsReservedUnreservedOrHash(ch) : !IsUnreserved(ch)))
{
dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte,
c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos);
EscapeAsciiChar(ch, dest, ref destPos);
prevInputPos = i+1;
}
}
if (prevInputPos != i)
{
// need to fill up the dest array ?
if (prevInputPos != start || dest != null)
dest = EnsureDestinationSize(pStr, dest, i, 0, 0, ref destPos, prevInputPos);
}
}
return dest;
}
//
// ensure destination array has enough space and contains all the needed input stuff
//
private unsafe static char[] EnsureDestinationSize(char* pStr, char[] dest, int currentInputPos,
short charsToAdd, short minReallocateChars, ref int destPos, int prevInputPos)
{
if ((object) dest == null || dest.Length < destPos + (currentInputPos-prevInputPos) + charsToAdd)
{
// allocating or reallocating array by ensuring enough space based on maxCharsToAdd.
char[] newresult = new char[destPos + (currentInputPos-prevInputPos) + minReallocateChars];
if ((object) dest != null && destPos != 0)
Buffer.BlockCopy(dest, 0, newresult, 0, destPos<<1);
dest = newresult;
}
// ensuring we copied everything form the input string left before last escaping
while (prevInputPos != currentInputPos)
dest[destPos++] = pStr[prevInputPos++];
return dest;
}
//
// This method will assume that any good Escaped Sequence will be unescaped in the output
// - Assumes Dest.Length - detPosition >= end-start
// - UnescapeLevel controls various modes of opearion
// - Any "bad" escape sequence will remain as is or '%' will be escaped.
// - destPosition tells the starting index in dest for placing the result.
// On return destPosition tells the last character + 1 postion in the "dest" array.
// - The control chars and chars passed in rsdvX parameters may be re-escaped depending on UnescapeLevel
// - It is a RARE case when Unescape actually needs escaping some characteres mentioned above.
// For this reason it returns a char[] that is usually the same ref as the input "dest" value.
//
internal unsafe static char[] UnescapeString(string input, int start, int end, char[] dest,
ref int destPosition, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser syntax,
bool isQuery)
{
fixed (char *pStr = input)
{
return UnescapeString(pStr, start, end, dest, ref destPosition, rsvd1, rsvd2, rsvd3, unescapeMode,
syntax, isQuery);
}
}
internal unsafe static char[] UnescapeString(char* pStr, int start, int end, char[] dest, ref int destPosition,
char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser syntax, bool isQuery)
{
byte [] bytes = null;
byte escapedReallocations = 0;
bool escapeReserved = false;
int next = start;
bool iriParsing = Uri.IriParsingStatic(syntax)
&& ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.EscapeUnescape);
while (true)
{
// we may need to re-pin dest[]
fixed (char* pDest = dest)
{
if ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.CopyOnly)
{
while (start < end)
pDest[destPosition++] = pStr[start++];
return dest;
}
while (true)
{
char ch = (char)0;
for (;next < end; ++next)
{
if ((ch = pStr[next]) == '%')
{
if ((unescapeMode & UnescapeMode.Unescape) == 0)
{
// re-escape, don't check anything else
escapeReserved = true;
}
else if (next+2 < end)
{
ch = EscapedAscii(pStr[next+1], pStr[next+2]);
// Unescape a good sequence if full unescape is requested
if (unescapeMode >= UnescapeMode.UnescapeAll)
{
if (ch == Uri.c_DummyChar)
{
if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow)
{
// Should be a rare case where the app tries to feed an invalid escaped sequence
throw new UriFormatException(SR.GetString(SR.net_uri_BadString));
}
continue;
}
}
// re-escape % from an invalid sequence
else if (ch == Uri.c_DummyChar)
{
if ((unescapeMode & UnescapeMode.Escape) != 0)
escapeReserved = true;
else
continue; // we should throw instead but since v1.0 woudl just print '%'
}
// Do not unescape '%' itself unless full unescape is requested
else if (ch == '%')
{
next += 2;
continue;
}
// Do not unescape a reserved char unless full unescape is requested
else if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3)
{
next += 2;
continue;
}
// Do not unescape a dangerous char unless it's V1ToStringFlags mode
else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0 && IsNotSafeForUnescape(ch))
{
next += 2;
continue;
}
else if (iriParsing && ((ch <='\x9F' && IsNotSafeForUnescape(ch)) ||
(ch >'\x9F' &&!Uri.CheckIriUnicodeRange(ch, isQuery))))
{
// check if unenscaping gives a char ouside iri range
// if it does then keep it escaped
next += 2;
continue;
}
// unescape escaped char or escape %
break;
}
else if (unescapeMode >= UnescapeMode.UnescapeAll)
{
if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow)
{
// Should be a rare case where the app tries to feed an invalid escaped sequence
throw new UriFormatException(SR.GetString(SR.net_uri_BadString));
}
// keep a '%' as part of a bogus sequence
continue;
}
else
{
escapeReserved = true;
}
// escape (escapeReserved==ture) or otheriwse unescape the sequence
break;
}
else if ((unescapeMode & (UnescapeMode.Unescape | UnescapeMode.UnescapeAll))
== (UnescapeMode.Unescape | UnescapeMode.UnescapeAll))
{
continue;
}
else if ((unescapeMode & UnescapeMode.Escape) != 0)
{
// Could actually escape some of the characters
if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3)
{
// found an unescaped reserved character -> escape it
escapeReserved = true;
break;
}
else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0
&& (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F')))
{
// found an unescaped reserved character -> escape it
escapeReserved = true;
break;
}
}
}
//copy off previous characters from input
while (start < next)
pDest[destPosition++] = pStr[start++];
if (next != end)
{
//VsWhidbey#87423
if (escapeReserved)
{
//escape that char
// Since this should be _really_ rare case, reallocate with constant size increase of 30 rsvd-type characters.
if (escapedReallocations == 0)
{
escapedReallocations = 30;
char[] newDest = new char[dest.Length + escapedReallocations*3];
fixed (char *pNewDest = newDest)
{
for (int i = 0; i < destPosition; ++i)
pNewDest[i] = pDest[i];
}
dest = newDest;
// re-pin new dest[] array
goto dest_fixed_loop_break;
}
else
{
--escapedReallocations;
EscapeAsciiChar(pStr[next], dest, ref destPosition);
escapeReserved = false;
start = ++next;
continue;
}
}
// unescaping either one Ascii or possibly multiple Unicode
if (ch <= '\x7F')
{
//ASCII
dest[destPosition++] = ch;
next+=3;
start = next;
continue;
}
// Unicode
int byteCount = 1;
// lazy initialization of max size, will reuse the array for next sequences
if ((object) bytes == null)
bytes = new byte[end - next];
bytes[0] = (byte)ch;
next+=3;
while (next < end)
{
// Check on exit criterion
if ((ch = pStr[next]) != '%' || next+2 >= end)
break;
// already made sure we have 3 characters in str
ch = EscapedAscii(pStr[next+1], pStr[next+2]);
//invalid hex sequence ?
if (ch == Uri.c_DummyChar)
break;
// character is not part of a UTF-8 sequence ?
else if (ch < '\x80')
break;
else
{
//a UTF-8 sequence
bytes[byteCount++] = (byte)ch;
next += 3;
}
}
Encoding noFallbackCharUTF8 = (Encoding)Encoding.UTF8.Clone();
noFallbackCharUTF8.EncoderFallback = new EncoderReplacementFallback("");
noFallbackCharUTF8.DecoderFallback = new DecoderReplacementFallback("");
char[] unescapedChars = new char[bytes.Length];
int charCount = noFallbackCharUTF8.GetChars(bytes, 0, byteCount, unescapedChars, 0);
start = next;
// match exact bytes
// Do not unescape chars not allowed by Iri
// need to check for invalid utf sequences that may not have given any chars
MatchUTF8Sequence(pDest, dest, ref destPosition, unescapedChars, charCount, bytes,
byteCount, isQuery, iriParsing);
}
if (next == end)
goto done;
}
dest_fixed_loop_break: ;
}
}
done: return dest;
}
//
// Need to check for invalid utf sequences that may not have given any chars.
// We got the unescaped chars, we then reencode them and match off the bytes
// to get the invalid sequence bytes that we just copy off
//
internal static unsafe void MatchUTF8Sequence(char* pDest, char[] dest, ref int destOffset, char[] unescapedChars,
int charCount, byte[] bytes, int byteCount, bool isQuery, bool iriParsing)
{
int count = 0;
fixed (char* unescapedCharsPtr = unescapedChars)
{
for (int j = 0; j < charCount; ++j)
{
bool isHighSurr = Char.IsHighSurrogate(unescapedCharsPtr[j]);
byte[] encodedBytes = Encoding.UTF8.GetBytes(unescapedChars, j, isHighSurr ? 2 : 1);
int encodedBytesLength = encodedBytes.Length;
// we have to keep unicode chars outside Iri range escaped
bool inIriRange = false;
if (iriParsing)
{
if (!isHighSurr)
inIriRange = Uri.CheckIriUnicodeRange(unescapedChars[j], isQuery);
else
{
bool surrPair = false;
inIriRange = Uri.CheckIriUnicodeRange(unescapedChars[j], unescapedChars[j + 1],
ref surrPair, isQuery);
}
}
while (true)
{
// Escape any invalid bytes that were before this character
while (bytes[count] != encodedBytes[0])
{
EscapeAsciiChar((char)bytes[count++], dest, ref destOffset);
}
// check if all bytes match
bool allBytesMatch = true;
int k = 0;
for (; k < encodedBytesLength; ++k)
{
if (bytes[count + k] != encodedBytes[k])
{
allBytesMatch = false;
break;
}
}
if (allBytesMatch)
{
count += encodedBytesLength;
if (iriParsing)
{
if (!inIriRange)
{
// need to keep chars not allowed as escaped
for (int l = 0; l < encodedBytes.Length; ++l)
{
EscapeAsciiChar((char)encodedBytes[l], dest, ref destOffset);
}
}
else if (!Uri.IsBidiControlCharacter(unescapedCharsPtr[j]))
{
//copy chars
pDest[destOffset++] = unescapedCharsPtr[j];
}
if (isHighSurr)
pDest[destOffset++] = unescapedCharsPtr[j + 1];
}
else
{
//copy chars
pDest[destOffset++] = unescapedCharsPtr[j];
if (isHighSurr)
pDest[destOffset++] = unescapedCharsPtr[j + 1];
}
break; // break out of while (true) since we've matched this char bytes
}
else
{
// copy bytes till place where bytes dont match
for (int l = 0; l < k; ++l)
{
EscapeAsciiChar((char)bytes[count++], dest, ref destOffset);
}
}
}
if (isHighSurr) j++;
}
}
// Include any trailing invalid sequences
while (count < byteCount)
{
EscapeAsciiChar((char)bytes[count++], dest, ref destOffset);
}
}
internal static void EscapeAsciiChar(char ch, char[] to, ref int pos)
{
to[pos++] = '%';
to[pos++] = HexUpperChars[(ch & 0xf0) >> 4];
to[pos++] = HexUpperChars[ch & 0xf];
}
internal static char EscapedAscii(char digit, char next)
{
if (!(((digit >= '0') && (digit <= '9'))
|| ((digit >= 'A') && (digit <= 'F'))
|| ((digit >= 'a') && (digit <= 'f'))))
{
return Uri.c_DummyChar;
}
int res = (digit <= '9')
? ((int)digit - (int)'0')
: (((digit <= 'F')
? ((int)digit - (int)'A')
: ((int)digit - (int)'a'))
+ 10);
if (!(((next >= '0') && (next <= '9'))
|| ((next >= 'A') && (next <= 'F'))
|| ((next >= 'a') && (next <= 'f'))))
{
return Uri.c_DummyChar;
}
return (char)((res << 4) + ((next <= '9')
? ((int)next - (int)'0')
: (((next <= 'F')
? ((int)next - (int)'A')
: ((int)next - (int)'a'))
+ 10)));
}
// Do not unescape these in safe mode:
// 1) reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
// 2) excluded = control | "#" | "%" | "\"
//
// That will still give plenty characters unescaped by SafeUnesced mode such as
// 1) Unicode characters
// 2) Unreserved = alphanum | "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
// 3) DelimitersAndUnwise = "<" | ">" | <"> | "{" | "}" | "|" | "^" | "[" | "]" | "`"
internal static bool IsNotSafeForUnescape(char ch)
{
if (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F'))
return true;
else if ((ch >= ';' && ch <= '@' && (ch | '\x2') != '>') ||
(ch >= '#' && ch <= '&') ||
ch == '+' || ch == ',' || ch == '/' || ch == '\\')
return true;
return false;
}
private const string RFC2396ReservedMarks = @";/?:@&=+$,";
private const string RFC3986ReservedMarks = @":/?#[]@!$&'()*+,;=";
private const string RFC2396UnreservedMarks = @"-_.!~*'()";
private const string RFC3986UnreservedMarks = @"-._~";
private static unsafe bool IsReservedUnreservedOrHash(char c)
{
if (IsUnreserved(c))
{
return true;
}
if (UriParser.ShouldUseLegacyV2Quirks)
{
return ((RFC2396ReservedMarks.IndexOf(c) >= 0) || c == '#');
}
return (RFC3986ReservedMarks.IndexOf(c) >= 0);
}
internal static unsafe bool IsUnreserved(char c)
{
if (Uri.IsAsciiLetterOrDigit(c))
{
return true;
}
if (UriParser.ShouldUseLegacyV2Quirks)
{
return (RFC2396UnreservedMarks.IndexOf(c) >= 0);
}
return (RFC3986UnreservedMarks.IndexOf(c) >= 0);
}
internal static bool Is3986Unreserved(char c)
{
if (Uri.IsAsciiLetterOrDigit(c))
{
return true;
}
return (RFC3986UnreservedMarks.IndexOf(c) >= 0);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Palaso.Code;
using Palaso.Migration;
namespace Palaso.WritingSystems.Migration.WritingSystemsLdmlV0To1Migration
{
/// <summary>
/// This class is used to migrate an LdmlFile from LDML palaso version 0 (or 1) to 2. It takes any LDML file and transforms
/// a non-conformant rfc5646 tag contained therein into a conformant one. Note that the constructor expects a callback
/// to help a consumer perform changes to its own files where necassary.
/// Also note that the files are not written until all writing systems have been migrated in order to deal correctly
/// with duplicate Rfc5646 tags that might result from migration.
/// </summary>
public class LdmlVersion0MigrationStrategy : MigrationStrategyBase
{
public class MigrationInfo
{
public string FileName;
public string RfcTagBeforeMigration;
public string RfcTagAfterMigration;
}
public delegate void MigrationHandler(IEnumerable<MigrationInfo> migrationInfo);
private readonly List<MigrationInfo> _migrationInfo;
private readonly Dictionary<string, WritingSystemDefinitionV1> _writingSystemsV1;
private readonly MigrationHandler _migrationHandler;
private readonly IAuditTrail _auditLog;
private readonly WritingSystemCompatibility _roundTripBogusFlex70PrivateUse;
public LdmlVersion0MigrationStrategy(
MigrationHandler migrationHandler,
IAuditTrail auditLog,
int fromVersion,
WritingSystemCompatibility roundtripBogusFlex70PrivateUse) :
this(migrationHandler, auditLog, fromVersion)
{
_roundTripBogusFlex70PrivateUse = roundtripBogusFlex70PrivateUse;
}
public LdmlVersion0MigrationStrategy(MigrationHandler migrationHandler, IAuditTrail auditLog, int fromVersion) :
base(fromVersion, 2)
{
Guard.AgainstNull(migrationHandler, "migrationCallback must be set");
_migrationInfo = new List<MigrationInfo>();
_writingSystemsV1 = new Dictionary<string, WritingSystemDefinitionV1>();
_migrationHandler = migrationHandler;
_auditLog = auditLog;
}
public override void Migrate(string sourceFilePath, string destinationFilePath)
{
string sourceFileName = Path.GetFileName(sourceFilePath);
var writingSystemDefinitionV0 = new WritingSystemDefinitionV0();
new LdmlAdaptorV0().Read(sourceFilePath, writingSystemDefinitionV0);
var rfcHelper = new Rfc5646TagCleaner(
writingSystemDefinitionV0.ISO639,
writingSystemDefinitionV0.Script,
writingSystemDefinitionV0.Region,
writingSystemDefinitionV0.Variant,
"");
rfcHelper.Clean();
var writingSystemDefinitionV1 = new WritingSystemDefinitionV1
{
DefaultFontName = writingSystemDefinitionV0.DefaultFontName,
Abbreviation = writingSystemDefinitionV0.Abbreviation,
DefaultFontSize = writingSystemDefinitionV0.DefaultFontSize,
IsUnicodeEncoded = !writingSystemDefinitionV0.IsLegacyEncoded,
Keyboard = writingSystemDefinitionV0.Keyboard,
LanguageName = writingSystemDefinitionV0.LanguageName,
RightToLeftScript = writingSystemDefinitionV0.RightToLeftScript,
SortRules = writingSystemDefinitionV0.SortRules,
SortUsing = (WritingSystemDefinitionV1.SortRulesType)writingSystemDefinitionV0.SortUsing,
SpellCheckingId = writingSystemDefinitionV0.SpellCheckingId,
VersionDescription = writingSystemDefinitionV0.VersionDescription,
DateModified = DateTime.Now
};
writingSystemDefinitionV1.SetAllComponents(
rfcHelper.Language,
rfcHelper.Script,
rfcHelper.Region,
ConcatenateVariantAndPrivateUse(rfcHelper.Variant, rfcHelper.PrivateUse)
);
_writingSystemsV1[sourceFileName] = writingSystemDefinitionV1;
//_migratedWs.VerboseDescription //not written out by LdmlAdaptorV1 - flex?
//_migratedWs.NativeName //not written out by LdmlAdaptorV1 - flex?);
// Record the details for use in PostMigrate where we change the file name to match the rfc tag where we can.
var migrationInfo = new MigrationInfo
{
FileName = sourceFileName,
RfcTagBeforeMigration = writingSystemDefinitionV0.Rfc5646,
RfcTagAfterMigration = writingSystemDefinitionV1.Bcp47Tag
};
_migrationInfo.Add(migrationInfo);
}
private static string ConcatenateVariantAndPrivateUse(string variant, string privateUse)
{
string concatenatedTags = variant;
if (!String.IsNullOrEmpty(concatenatedTags))
{
concatenatedTags += "-";
}
if (!String.IsNullOrEmpty(privateUse))
{
concatenatedTags += "x-";
concatenatedTags += privateUse;
}
return concatenatedTags;
}
#region FolderMigrationCode
public override void PostMigrate(string sourcePath, string destinationPath)
{
EnsureRfcTagsUnique(_migrationInfo);
// Write them back, with their new file name.
foreach (var migrationInfo in _migrationInfo)
{
var writingSystemDefinitionV1 = _writingSystemsV1[migrationInfo.FileName];
string sourceFilePath = Path.Combine(sourcePath, migrationInfo.FileName);
string destinationFilePath = Path.Combine(destinationPath, migrationInfo.RfcTagAfterMigration + ".ldml");
if (migrationInfo.RfcTagBeforeMigration != migrationInfo.RfcTagAfterMigration)
{
_auditLog.LogChange(migrationInfo.RfcTagBeforeMigration, migrationInfo.RfcTagAfterMigration);
}
WriteLdml(writingSystemDefinitionV1, sourceFilePath, destinationFilePath);
}
if (_migrationHandler != null)
{
_migrationHandler(_migrationInfo);
}
}
private void WriteLdml(WritingSystemDefinitionV1 writingSystemDefinitionV1, string sourceFilePath, string destinationFilePath)
{
using (Stream sourceStream = new FileStream(sourceFilePath, FileMode.Open))
{
var ldmlDataMapper = new LdmlAdaptorV1();
ldmlDataMapper.Write(destinationFilePath, writingSystemDefinitionV1, sourceStream, _roundTripBogusFlex70PrivateUse);
sourceStream.Close();
}
}
internal void EnsureRfcTagsUnique(IEnumerable<MigrationInfo> migrationInfo)
{
var uniqueRfcTags = new HashSet<string>();
foreach (var info in migrationInfo)
{
MigrationInfo currentInfo = info;
if (uniqueRfcTags.Any(rfcTag => rfcTag.Equals(currentInfo.RfcTagAfterMigration, StringComparison.OrdinalIgnoreCase)))
{
if (currentInfo.RfcTagBeforeMigration.Equals(currentInfo.RfcTagAfterMigration, StringComparison.OrdinalIgnoreCase))
{
// We want to change the other, because we are the same. Even if the other is the same, we'll change it anyway.
MigrationInfo otherInfo = _migrationInfo.First(
i => i.RfcTagAfterMigration.Equals(currentInfo.RfcTagAfterMigration, StringComparison.OrdinalIgnoreCase)
);
otherInfo.RfcTagAfterMigration = UniqueTagForDuplicate(otherInfo.RfcTagAfterMigration, uniqueRfcTags);
uniqueRfcTags.Add(otherInfo.RfcTagAfterMigration);
var writingSystemV1 = _writingSystemsV1[otherInfo.FileName];
writingSystemV1.SetTagFromString(otherInfo.RfcTagAfterMigration);
}
else
{
currentInfo.RfcTagAfterMigration = UniqueTagForDuplicate(currentInfo.RfcTagAfterMigration, uniqueRfcTags);
uniqueRfcTags.Add(currentInfo.RfcTagAfterMigration);
var writingSystemV1 = _writingSystemsV1[currentInfo.FileName];
writingSystemV1.SetTagFromString(currentInfo.RfcTagAfterMigration);
}
}
else
{
uniqueRfcTags.Add(currentInfo.RfcTagAfterMigration);
}
}
}
private static string UniqueTagForDuplicate(string rfcTag, IEnumerable<string> uniqueRfcTags)
{
RFC5646Tag tag = RFC5646Tag.Parse(rfcTag);
string originalPrivateUse = tag.PrivateUse;
int duplicateNumber = 0;
do
{
duplicateNumber++;
tag.PrivateUse = originalPrivateUse;
tag.AddToPrivateUse(String.Format("dupl{0}", duplicateNumber));
} while (uniqueRfcTags.Any(s => s.Equals(tag.CompleteTag, StringComparison.OrdinalIgnoreCase)));
return tag.CompleteTag;
}
#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;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class ParameterBlockTests : SharedBlockTests
{
private static IEnumerable<ParameterExpression> SingleParameter
{
get { return Enumerable.Repeat(Expression.Variable(typeof(int)), 1); }
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void SingleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
SingleParameter,
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void DoubleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
SingleParameter,
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void NullExpicitType()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Block(null, SingleParameter, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Block(null, SingleParameter, Enumerable.Repeat(Expression.Constant(0), 1)));
}
[Fact]
public void NullExpressionList()
{
AssertExtensions.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, default(Expression[])));
AssertExtensions.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, default(IEnumerable<Expression>)));
AssertExtensions.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, default(Expression[])));
AssertExtensions.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, default(IEnumerable<Expression>)));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void NullExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i < expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = null;
AssertExtensions.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions));
AssertExtensions.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions.Skip(0)));
AssertExtensions.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions));
AssertExtensions.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions.Skip(0)));
}
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void UnreadableExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i != expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = UnreadableExpression;
AssertExtensions.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions));
AssertExtensions.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions.Skip(0)));
AssertExtensions.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions));
AssertExtensions.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions.Skip(0)));
}
}
[Theory]
[PerCompilationType(nameof(ObjectAssignableConstantValuesAndSizes))]
public void BlockExplicitType(object value, int blockSize, bool useInterpreter)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
BlockExpression block = Expression.Block(typeof(object), SingleParameter, PadBlock(blockSize - 1, constant));
Assert.Equal(typeof(object), block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void BlockInvalidExplicitType(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Block(typeof(string), SingleParameter, expressions));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Block(typeof(string), SingleParameter, expressions.ToArray()));
}
[Theory]
[PerCompilationType(nameof(ConstantValuesAndSizes))]
public void BlockFromEmptyParametersSameAsFromParams(object value, int blockSize, bool useInterpreter)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression fromParamsBlock = Expression.Block(SingleParameter, expressions.ToArray());
BlockExpression fromEnumBlock = Expression.Block(SingleParameter, expressions);
Assert.Equal(fromParamsBlock.GetType(), fromEnumBlock.GetType());
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(constant, fromParamsBlock)).Compile(useInterpreter)());
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(constant, fromEnumBlock)).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void InvalidExpressionIndex(object value, int blockSize)
{
BlockExpression block = Expression.Block(SingleParameter, PadBlock(blockSize - 1, Expression.Constant(value, value.GetType())));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[-1]);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[blockSize]);
}
[Fact]
public void EmptyBlockWithParametersAndNonVoidTypeNotAllowed()
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Block(typeof(int), SingleParameter));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Block(typeof(int), SingleParameter, Enumerable.Empty<Expression>()));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromParams(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions.ToArray());
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromEnumerable(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void VariableCountCorrect(object value, int blockSize)
{
IEnumerable<ParameterExpression> vars = Enumerable.Range(0, blockSize).Select(i => Expression.Variable(value.GetType()));
BlockExpression block = Expression.Block(vars, Expression.Constant(value, value.GetType()));
Assert.Equal(blockSize, block.Variables.Count);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void RewriteToSameWithSameValues(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Same(block, block.Update(block.Variables.ToArray(), expressions));
Assert.Same(block, block.Update(block.Variables.ToArray(), expressions));
Assert.Same(block, NoOpVisitor.Instance.Visit(block));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void CanFindItems(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(SingleParameter, values);
IList<Expression> expressions = block.Expressions;
for (int i = 0; i != values.Length; ++i)
Assert.Equal(i, expressions.IndexOf(values[i]));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void IdentifyNonAbsentItemAsAbsent(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Equal(-1, block.Expressions.IndexOf(Expression.Default(typeof(long))));
Assert.False(block.Expressions.Contains(null));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ExpressionsEnumerable(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(SingleParameter, values);
Assert.True(values.SequenceEqual(block.Expressions));
int index = 0;
foreach (Expression exp in ((IEnumerable)block.Expressions))
Assert.Same(exp, values[index++]);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void UpdateWithExpressionsReturnsSame(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Same(block, block.Update(block.Variables, block.Expressions));
Assert.Same(block, NoOpVisitor.Instance.Visit(block));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void Visit(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory]
[MemberData(nameof(ObjectAssignableConstantValuesAndSizes))]
public void VisitTyped(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(typeof(object), SingleParameter, expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void NullVariables(int blockSize)
{
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
IEnumerable<ParameterExpression> vars = Enumerable.Repeat(default(ParameterExpression), 1);
AssertExtensions.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(vars, expressions));
AssertExtensions.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(vars, expressions.ToArray()));
AssertExtensions.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions));
AssertExtensions.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions.ToArray()));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void ByRefVariables(int blockSize)
{
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
IEnumerable<ParameterExpression> vars = Enumerable.Repeat(Expression.Parameter(typeof(int).MakeByRefType()), 1);
AssertExtensions.Throws<ArgumentException>("variables[0]", () => Expression.Block(vars, expressions));
AssertExtensions.Throws<ArgumentException>("variables[0]", () => Expression.Block(vars, expressions.ToArray()));
AssertExtensions.Throws<ArgumentException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions));
AssertExtensions.Throws<ArgumentException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions.ToArray()));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void RepeatedVariables(int blockSize)
{
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
ParameterExpression variable = Expression.Variable(typeof(int));
IEnumerable<ParameterExpression> vars = Enumerable.Repeat(variable, 2);
AssertExtensions.Throws<ArgumentException>("variables[1]", () => Expression.Block(vars, expressions));
AssertExtensions.Throws<ArgumentException>("variables[1]", () => Expression.Block(vars, expressions.ToArray()));
AssertExtensions.Throws<ArgumentException>("variables[1]", () => Expression.Block(typeof(object), vars, expressions));
AssertExtensions.Throws<ArgumentException>("variables[1]", () => Expression.Block(typeof(object), vars, expressions.ToArray()));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateDoesntRepeatEnumeration(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
ParameterExpression[] vars = {Expression.Variable(typeof(int)), Expression.Variable(typeof(string))};
BlockExpression block = Expression.Block(vars, expressions);
Assert.Same(block, block.Update(new RunOnceEnumerable<ParameterExpression>(vars), block.Expressions));
vars = new[] {Expression.Variable(typeof(int)), Expression.Variable(typeof(string))};
Assert.NotSame(block, block.Update(new RunOnceEnumerable<ParameterExpression>(vars), block.Expressions));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateDifferentSizeReturnsDifferent(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
ParameterExpression[] vars = { Expression.Variable(typeof(int)), Expression.Variable(typeof(string)) };
BlockExpression block = Expression.Block(vars, expressions);
Assert.NotSame(block, block.Update(vars, block.Expressions.Prepend(Expression.Empty())));
}
}
}
| |
using System;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using System.Xml;
using System.Collections;
using System.Runtime.InteropServices;
using System.Diagnostics;
using CSScriptLibrary;
namespace CLRDebugger
{
class Script
{
static string usage = "Usage: cscscript debugCLR [file]|[/i|/u] ...\nLoads C# script compiled executable into MS CLR Debugger (DbgCLR.exe).\n</i> / </u> - command switch to install/uninstall shell extension\n";
static public void Main(string[] args)
{
if (CLRDE.GetAvailableIDE() == null)
{
MessageBox.Show("CLR Debugger cannot be found.");
return;
}
if (args.Length == 0 || (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")))
{
Console.WriteLine(usage);
}
else if (args[0].Trim().ToLower() == "/i")
{
CLRDE.InstallShellExtension();
}
else if (args[0].Trim().ToLower() == "/u")
{
CLRDE.UninstallShellExtension();
}
else
{
try
{
FileInfo info = new FileInfo(args[0]);
string scriptFile = info.FullName;
string outputFile = Path.Combine(Path.GetDirectoryName(scriptFile), Path.GetFileNameWithoutExtension(scriptFile) + ".exe");
bool existed = File.Exists(outputFile);
RunScript(" /e /dbg \"" + info.FullName + "\"");
if (File.Exists(outputFile))
{
//open executable
Environment.CurrentDirectory = Path.GetDirectoryName(scriptFile);
Process myProcess = new Process();
myProcess.StartInfo.FileName = CLRDE.GetIDEFile();
myProcess.StartInfo.Arguments = "\"" + outputFile + "\" ";
myProcess.Start();
myProcess.WaitForExit();
//do clean up
if (!existed)
{
if (File.Exists(outputFile))
File.Delete(outputFile);
if (File.Exists(Path.GetFileNameWithoutExtension(outputFile) + ".pdb"))
File.Delete(Path.GetFileNameWithoutExtension(outputFile) + ".pdb");
}
}
else
{
if (File.Exists(Path.GetFileNameWithoutExtension(outputFile) + ".pdb"))
File.Delete(Path.GetFileNameWithoutExtension(outputFile) + ".pdb");
MessageBox.Show("Script cannot be compiled into excutable.");
}
}
catch (Exception e)
{
MessageBox.Show("Specified file could not be opened\n" + e.Message);
}
}
}
static void RunScript(string scriptFileCmd)
{
Process myProcess = new Process();
myProcess.StartInfo.FileName = "cscs.exe";
myProcess.StartInfo.Arguments = "/nl " + scriptFileCmd;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
string line = null;
while (null != (line = myProcess.StandardOutput.ReadLine()))
{
Console.WriteLine(line);
}
myProcess.WaitForExit();
}
public class CLRDE
{
static public string GetIDEFile()
{
string retval = "<not defined>";
try
{
RegistryKey DbgClr = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\DbgClr");
if (DbgClr == null)
return retval;
double ver = 0.0;
string subKeyStr = "";
foreach (string keyStr in DbgClr.GetSubKeyNames())
{
subKeyStr = keyStr;
double currVer = Convert.ToDouble(keyStr, System.Globalization.CultureInfo.InvariantCulture);
ver = Math.Max(currVer, ver);
}
if (ver != 0.0)
{
string debuggerDir = DbgClr.OpenSubKey(subKeyStr).GetValue("InstallDir").ToString();
retval = Path.Combine(debuggerDir, "DbgCLR.exe");
}
}
catch
{
}
return retval;
}
static public string[] GetAvailableIDE()
{
if (GetIDEFile() != "<not defined>")
{
string scHomeDir = GetEnvironmentVariable("CSSCRIPT_DIR");
return new string[] {
"Open (CLRDebug)",
"\t- Open with MS CLR Debugger",
"\"" + scHomeDir + "\\csws.exe\" /c \"" + scHomeDir + "\\lib\\debugCLR.cs\" \"%1\""};
}
return null;
}
static public void InstallShellExtension()
{
string fileTypeName = null;
RegistryKey csFile = Registry.ClassesRoot.OpenSubKey(".cs");
if (csFile != null)
{
fileTypeName = (string)csFile.GetValue("");
}
if (fileTypeName != null)
{
//Shell extensions
Console.WriteLine("Create 'Open as script (CLR Debgger)' shell extension...");
RegistryKey shell = Registry.ClassesRoot.CreateSubKey(fileTypeName + "\\shell\\Open as script(CLR Debgger)\\command");
string scHomeDir = GetEnvironmentVariable("CSSCRIPT_DIR");
if (scHomeDir != null)
{
string regValue = "\"" + Path.Combine(scHomeDir, "csws.exe") + "\"" +
" /c " +
"\"" + Path.Combine(scHomeDir, "lib\\DebugCLR.cs") + "\" " +
"\"%1\"";
shell.SetValue("", regValue);
shell.Close();
}
else
Console.WriteLine("\n" +
"The Environment variable CSSCRIPT_DIR is not set.\n" +
"This can be the result of running the script from the Total Commander or similar utility.\n" +
"Please rerun install.bat from Windows Explorer or from the new instance of Total Commander.");
}
}
static public string GetEnvironmentVariable(string name)
{
//It is important in the all "installation" scripts to have reliable GetEnvironmentVariable().
//Under some circumstances freshly set environment variable CSSCRIPT_DIR cannot be obtained with
//Environment.GetEnvironmentVariable(). For example when running under Total Commander or similar
//shell utility. Even SendMessageTimeout does not help in all cases. That is why GetEnvironmentVariable
//is reimplemented here.
object value = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment").GetValue(name);
return value == null ? null : value.ToString();
}
static public void UninstallShellExtension()
{
string fileTypeName = null;
RegistryKey csFile = Registry.ClassesRoot.OpenSubKey(".cs");
if (csFile != null)
{
fileTypeName = (string)csFile.GetValue("");
}
if (fileTypeName != null)
{
try
{
if (Registry.ClassesRoot.OpenSubKey(fileTypeName + "\\shell\\Open as script(CLR Debgger)") != null)
{
Console.WriteLine("Remove 'Open as script (CLR Debgger)' shell extension...");
Registry.ClassesRoot.DeleteSubKeyTree(fileTypeName + "\\shell\\Open as script(CLR Debgger)");
}
}
catch { }
}
}
}
}
}
| |
//
// FontBackendHandler.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt.Drawing;
using MonoMac.AppKit;
using MonoMac.Foundation;
using System.Collections.Generic;
namespace Xwt.Mac
{
public class MacFontBackendHandler: FontBackendHandler
{
public override object GetSystemDefaultFont ()
{
return FontData.FromFont (NSFont.SystemFontOfSize (0));
}
public override object GetSystemDefaultMonospaceFont ()
{
var font = NSFont.SystemFontOfSize (0);
return Create ("Menlo", font.PointSize, FontStyle.Normal, FontWeight.Normal, FontStretch.Normal);
}
public override IEnumerable<string> GetInstalledFonts ()
{
return NSFontManager.SharedFontManager.AvailableFontFamilies;
}
public override IEnumerable<KeyValuePair<string, object>> GetAvailableFamilyFaces (string family)
{
foreach (var nsFace in NSFontManager.SharedFontManager.AvailableMembersOfFontFamily(family)) {
var name = (string)new NSString(nsFace.ValueAt(1));
var weight = new NSNumber (nsFace.ValueAt (2)).Int32Value;
var traits = (NSFontTraitMask)new NSNumber (nsFace.ValueAt (3)).Int32Value;
yield return new KeyValuePair<string, object>(name, FontData.FromFamily(family, traits, weight, 0));
}
yield break;
}
public override object Create (string fontName, double size, FontStyle style, FontWeight weight, FontStretch stretch)
{
var t = GetStretchTrait (stretch) | GetStyleTrait (style);
var f = NSFontManager.SharedFontManager.FontWithFamily (fontName, t, GetWeightValue (weight), (float)size);
var fd = FontData.FromFont (NSFontManager.SharedFontManager.ConvertFont (f, t));
fd.Style = style;
fd.Weight = weight;
fd.Stretch = stretch;
return fd;
}
#region IFontBackendHandler implementation
public override object Copy (object handle)
{
FontData f = (FontData) handle;
f = f.Copy ();
f.Font = (NSFont) f.Font.Copy ();
return f;
}
public override object SetSize (object handle, double size)
{
FontData f = (FontData) handle;
f = f.Copy ();
f.Font = NSFontManager.SharedFontManager.ConvertFont (f.Font, (float)size);
return f;
}
public override object SetFamily (object handle, string family)
{
FontData f = (FontData) handle;
f = f.Copy ();
f.Font = NSFontManager.SharedFontManager.ConvertFontToFamily (f.Font, family);
return f;
}
public override object SetStyle (object handle, FontStyle style)
{
FontData f = (FontData) handle;
f = f.Copy ();
NSFontTraitMask mask;
if (style == FontStyle.Italic || style == FontStyle.Oblique)
mask = NSFontTraitMask.Italic;
else
mask = NSFontTraitMask.Unitalic;
f.Font = NSFontManager.SharedFontManager.ConvertFont (f.Font, mask);
f.Style = style;
return f;
}
static int GetWeightValue (FontWeight weight)
{
switch (weight) {
case FontWeight.Thin:
return 1;
case FontWeight.Ultralight:
return 2;
case FontWeight.Light:
return 3;
case FontWeight.Book:
return 4;
case FontWeight.Normal:
return 5;
case FontWeight.Medium:
return 6;
case FontWeight.Semibold:
return 8;
case FontWeight.Bold:
return 9;
case FontWeight.Ultrabold:
return 10;
case FontWeight.Heavy:
return 11;
case FontWeight.Ultraheavy:
return 12;
default:
return 13;
}
}
internal static FontWeight GetWeightFromValue (int w)
{
if (w <= 1)
return FontWeight.Thin;
if (w == 2)
return FontWeight.Ultralight;
if (w == 3)
return FontWeight.Light;
if (w == 4)
return FontWeight.Book;
if (w == 5)
return FontWeight.Normal;
if (w == 6)
return FontWeight.Medium;
if (w <= 8)
return FontWeight.Semibold;
if (w == 9)
return FontWeight.Bold;
if (w == 10)
return FontWeight.Ultrabold;
if (w == 11)
return FontWeight.Heavy;
return FontWeight.Ultraheavy;
}
NSFontTraitMask GetStretchTrait (FontStretch stretch)
{
switch (stretch) {
case FontStretch.Condensed:
case FontStretch.ExtraCondensed:
case FontStretch.SemiCondensed:
return NSFontTraitMask.Condensed;
case FontStretch.Normal:
return default (NSFontTraitMask);
default:
return NSFontTraitMask.Expanded;
}
}
NSFontTraitMask GetStyleTrait (FontStyle style)
{
switch (style) {
case FontStyle.Italic:
case FontStyle.Oblique:
return NSFontTraitMask.Italic;
default:
return default (NSFontTraitMask);
}
}
public override object SetWeight (object handle, FontWeight weight)
{
FontData f = (FontData) handle;
f = f.Copy ();
int w = GetWeightValue (weight);
var traits = NSFontManager.SharedFontManager.TraitsOfFont (f.Font);
traits |= weight >= FontWeight.Bold ? NSFontTraitMask.Bold : NSFontTraitMask.Unbold;
traits &= weight >= FontWeight.Bold ? ~NSFontTraitMask.Unbold : ~NSFontTraitMask.Bold;
f.Font = NSFontManager.SharedFontManager.FontWithFamily (f.Font.FamilyName, traits, w, f.Font.PointSize);
f.Weight = weight;
return f;
}
public override object SetStretch (object handle, FontStretch stretch)
{
FontData f = (FontData) handle;
f = f.Copy ();
NSFont font = f.Font;
if (stretch < FontStretch.SemiCondensed) {
font = NSFontManager.SharedFontManager.ConvertFont (font, NSFontTraitMask.Condensed);
font = NSFontManager.SharedFontManager.ConvertFontToNotHaveTrait (font, NSFontTraitMask.Compressed | NSFontTraitMask.Expanded | NSFontTraitMask.Narrow);
}
if (stretch == FontStretch.SemiCondensed) {
font = NSFontManager.SharedFontManager.ConvertFont (font, NSFontTraitMask.Narrow);
font = NSFontManager.SharedFontManager.ConvertFontToNotHaveTrait (font, NSFontTraitMask.Compressed | NSFontTraitMask.Expanded | NSFontTraitMask.Condensed);
}
else if (stretch > FontStretch.Normal) {
font = NSFontManager.SharedFontManager.ConvertFont (font, NSFontTraitMask.Expanded);
font = NSFontManager.SharedFontManager.ConvertFontToNotHaveTrait (font, NSFontTraitMask.Compressed | NSFontTraitMask.Narrow | NSFontTraitMask.Condensed);
}
else {
font = NSFontManager.SharedFontManager.ConvertFontToNotHaveTrait (font, NSFontTraitMask.Condensed | NSFontTraitMask.Expanded | NSFontTraitMask.Narrow | NSFontTraitMask.Compressed);
}
f.Font = font;
f.Stretch = stretch;
return f;
}
public override double GetSize (object handle)
{
FontData f = (FontData) handle;
return f.Font.PointSize;
}
public override string GetFamily (object handle)
{
FontData f = (FontData) handle;
return f.Font.FamilyName;
}
public override FontStyle GetStyle (object handle)
{
FontData f = (FontData) handle;
return f.Style;
}
public override FontWeight GetWeight (object handle)
{
FontData f = (FontData) handle;
return f.Weight;
}
public override FontStretch GetStretch (object handle)
{
FontData f = (FontData) handle;
return f.Stretch;
}
#endregion
}
public class FontData
{
public NSFont Font;
public FontStyle Style;
public FontWeight Weight;
public FontStretch Stretch;
public FontData ()
{
}
public static FontData FromFamily (string family, NSFontTraitMask traits, int weight, float size)
{
var font = NSFontManager.SharedFontManager.FontWithFamily (family, traits, weight, size);
var gentraits = NSFontManager.SharedFontManager.TraitsOfFont (font);
// NSFontManager may loose the traits, restore them here
if (traits > 0 && gentraits == 0)
font = NSFontManager.SharedFontManager.ConvertFont (font, traits);
return FromFont (font);
}
public static FontData FromFont (NSFont font)
{
var traits = NSFontManager.SharedFontManager.TraitsOfFont (font);
FontStretch stretch;
if ((traits & NSFontTraitMask.Condensed) != 0)
stretch = FontStretch.Condensed;
else if ((traits & NSFontTraitMask.Narrow) != 0)
stretch = FontStretch.SemiCondensed;
else if ((traits & NSFontTraitMask.Compressed) != 0)
stretch = FontStretch.ExtraCondensed;
else if ((traits & NSFontTraitMask.Expanded) != 0)
stretch = FontStretch.Expanded;
else
stretch = FontStretch.Normal;
FontStyle style;
if ((traits & NSFontTraitMask.Italic) != 0)
style = FontStyle.Italic;
else
style = FontStyle.Normal;
return new FontData {
Font = font,
Style = style,
Weight = MacFontBackendHandler.GetWeightFromValue (NSFontManager.SharedFontManager.WeightOfFont (font)),
Stretch = stretch
};
}
public FontData Copy ()
{
return new FontData {
Font = Font,
Style = Style,
Weight = Weight,
Stretch = Stretch
};
}
}
}
| |
//
// UnityOSC - Open Sound Control interface for the Unity3d game engine
//
// Copyright (c) 2012 Jorge Garcia Martin
//
// 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.
//
// Inspired by http://www.unifycommunity.com/wiki/index.php?title=AManagerClass
using System;
using System.Net;
using System.Collections.Generic;
using UnityEngine;
namespace UnityOSC
{
/// <summary>
/// Models a log of a server composed by an OSCServer, a List of OSCPacket and a List of
/// strings that represent the current messages in the log.
/// </summary>
public struct ServerLog
{
public OSCServer server;
public List<OSCPacket> packets;
public List<string> log;
}
/// <summary>
/// Models a log of a client composed by an OSCClient, a List of OSCMessage and a List of
/// strings that represent the current messages in the log.
/// </summary>
public struct ClientLog
{
public OSCClient client;
public List<OSCMessage> messages;
public List<string> log;
}
/// <summary>
/// Handles all the OSC servers and clients of the current Unity game/application.
/// Tracks incoming and outgoing messages.
/// </summary>
public class OSCHandler : MonoBehaviour
{
#region Singleton Constructors
static OSCHandler ()
{
}
OSCHandler ()
{
}
public static OSCHandler Instance {
get {
if (_instance == null) {
_instance = new GameObject ("OSCHandler").AddComponent<OSCHandler> ();
}
return _instance;
}
}
#endregion
#region Member Variables
private static OSCHandler _instance = null;
private Dictionary<string, ClientLog> _clients = new Dictionary<string, ClientLog> ();
private Dictionary<string, ServerLog> _servers = new Dictionary<string, ServerLog> ();
private const int _loglength = 25;
#endregion
/// <summary>
/// Initializes the OSC Handler.
/// Here you can create the OSC servers and clientes.
/// </summary>
public void Init ()
{
//Initialize OSC clients (transmitters)
//Example:
//CreateClient("leapDrawing", IPAddress.Parse("127.0.0.1"), 57121);
//Initialize OSC servers (listeners)
//Example:
//CreateServer("AndroidPhone", 6666);
}
#region Properties
public Dictionary<string, ClientLog> Clients {
get {
return _clients;
}
}
public Dictionary<string, ServerLog> Servers {
get {
return _servers;
}
}
#endregion
#region Methods
/// <summary>
/// Ensure that the instance is destroyed when the game is stopped in the Unity editor
/// Close all the OSC clients and servers
/// </summary>
void OnApplicationQuit ()
{
foreach (KeyValuePair<string,ClientLog> pair in _clients) {
pair.Value.client.Close ();
}
foreach (KeyValuePair<string,ServerLog> pair in _servers) {
pair.Value.server.Close ();
}
_instance = null;
}
/// <summary>
/// Creates an OSC Client (sends OSC messages) given an outgoing port and address.
/// </summary>
/// <param name="clientId">
/// A <see cref="System.String"/>
/// </param>
/// <param name="destination">
/// A <see cref="IPAddress"/>
/// </param>
/// <param name="port">
/// A <see cref="System.Int32"/>
/// </param>
public void CreateClient (string clientId, IPAddress destination, int port)
{
ClientLog clientitem = new ClientLog ();
clientitem.client = new OSCClient (destination, port);
clientitem.log = new List<string> ();
clientitem.messages = new List<OSCMessage> ();
_clients.Add (clientId, clientitem);
// Send test message
string testaddress = "/test/alive/";
OSCMessage message = new OSCMessage (testaddress, destination.ToString ());
message.Append (port);
message.Append ("OK");
_clients [clientId].log.Add (String.Concat (DateTime.UtcNow.ToString (), ".",
FormatMilliseconds (DateTime.Now.Millisecond), " : ",
testaddress, " ", DataToString (message.Data)));
_clients [clientId].messages.Add (message);
_clients [clientId].client.Send (message);
}
/// <summary>
/// Creates an OSC Server (listens to upcoming OSC messages) given an incoming port.
/// </summary>
/// <param name="serverId">
/// A <see cref="System.String"/>
/// </param>
/// <param name="port">
/// A <see cref="System.Int32"/>
/// </param>
public void CreateServer (string serverId, int port, PacketReceivedEventHandler _PacketReceivedEvent)
{
OSCServer server = new OSCServer (port, _PacketReceivedEvent);
//server.PacketReceivedEvent += OnPacketReceived;
ServerLog serveritem = new ServerLog ();
serveritem.server = server;
serveritem.log = new List<string> ();
serveritem.packets = new List<OSCPacket> ();
_servers.Add (serverId, serveritem);
}
void OnPacketReceived (OSCServer server, OSCPacket packet)
{
}
/// <summary>
/// Sends an OSC message to a specified client, given its clientId (defined at the OSC client construction),
/// OSC address and a single value. Also updates the client log.
/// </summary>
/// <param name="clientId">
/// A <see cref="System.String"/>
/// </param>
/// <param name="address">
/// A <see cref="System.String"/>
/// </param>
/// <param name="value">
/// A <see cref="T"/>
/// </param>
public void SendMessageToClient<T> (string clientId, string address, T value)
{
List<object> temp = new List<object> ();
temp.Add (value);
SendMessageToClient (clientId, address, temp);
}
/// <summary>
/// Sends an OSC message to a specified client, given its clientId (defined at the OSC client construction),
/// OSC address and a list of values. Also updates the client log.
/// </summary>
/// <param name="clientId">
/// A <see cref="System.String"/>
/// </param>
/// <param name="address">
/// A <see cref="System.String"/>
/// </param>
/// <param name="values">
/// A <see cref="List<T>"/>
/// </param>
public void SendMessageToClient<T> (string clientId, string address, List<T> values)
{
if (_clients.ContainsKey (clientId)) {
OSCMessage message = new OSCMessage (address);
foreach (T msgvalue in values) {
message.Append (msgvalue);
}
if (_clients [clientId].log.Count < _loglength) {
_clients [clientId].log.Add (String.Concat (DateTime.UtcNow.ToString (), ".",
FormatMilliseconds (DateTime.Now.Millisecond),
" : ", address, " ", DataToString (message.Data)));
_clients [clientId].messages.Add (message);
} else {
_clients [clientId].log.RemoveAt (0);
_clients [clientId].messages.RemoveAt (0);
_clients [clientId].log.Add (String.Concat (DateTime.UtcNow.ToString (), ".",
FormatMilliseconds (DateTime.Now.Millisecond),
" : ", address, " ", DataToString (message.Data)));
_clients [clientId].messages.Add (message);
}
_clients [clientId].client.Send (message);
} else {
Debug.LogError (string.Format ("Can't send OSC messages to {0}. Client doesn't exist.", clientId));
}
}
/// <summary>
/// Updates clients and servers logs.
/// </summary>
public void UpdateLogs ()
{
foreach (KeyValuePair<string,ServerLog> pair in _servers) {
_servers [pair.Key].packets.Clear ();
if (_servers [pair.Key].server.LastReceivedPacket != null) {
//Initialization for the first packet received
if (true || _servers [pair.Key].log.Count == 0) {
_servers [pair.Key].packets.Add (_servers [pair.Key].server.LastReceivedPacket);
_servers [pair.Key].log.Add (String.Concat (DateTime.UtcNow.ToString (), ".",
FormatMilliseconds (DateTime.Now.Millisecond), " : ",
_servers [pair.Key].server.LastReceivedPacket.Address, " ",
DataToString (_servers [pair.Key].server.LastReceivedPacket.Data)));
break;
}
if (_servers [pair.Key].server.LastReceivedPacket.TimeStamp
!= _servers [pair.Key].packets [_servers [pair.Key].packets.Count - 1].TimeStamp) {
if (_servers [pair.Key].log.Count > _loglength - 1) {
_servers [pair.Key].log.RemoveAt (0);
_servers [pair.Key].packets.RemoveAt (0);
}
_servers [pair.Key].packets.Add (_servers [pair.Key].server.LastReceivedPacket);
_servers [pair.Key].log.Add (String.Concat (DateTime.UtcNow.ToString (), ".",
FormatMilliseconds (DateTime.Now.Millisecond), " : ",
_servers [pair.Key].server.LastReceivedPacket.Address, " ",
DataToString (_servers [pair.Key].server.LastReceivedPacket.Data)));
}
}
}
}
/// <summary>
/// Converts a collection of object values to a concatenated string.
/// </summary>
/// <param name="data">
/// A <see cref="List<System.Object>"/>
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
private string DataToString (List<object> data)
{
string buffer = "";
for (int i = 0; i < data.Count; i++) {
buffer += data [i].ToString () + " ";
}
buffer += "\n";
return buffer;
}
/// <summary>
/// Formats a milliseconds number to a 000 format. E.g. given 50, it outputs 050. Given 5, it outputs 005
/// </summary>
/// <param name="milliseconds">
/// A <see cref="System.Int32"/>
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
private string FormatMilliseconds (int milliseconds)
{
if (milliseconds < 100) {
if (milliseconds < 10)
return String.Concat ("00", milliseconds.ToString ());
return String.Concat ("0", milliseconds.ToString ());
}
return milliseconds.ToString ();
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <license file="Node.cs">
//
// The use and distribution terms for this software are contained in the file
// named 'LICENSE', which can be found in the resources directory of this
// distribution.
//
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// </license>
//------------------------------------------------------------------------------
using System;
using EcmaScript.NET.Collections;
namespace EcmaScript.NET
{
/// <summary> This class implements the root of the intermediate representation.
///
/// </summary>
public class Node
{
internal class GetterPropertyLiteral
{
internal object Property;
public GetterPropertyLiteral (object property)
{
Property = property;
}
}
internal class SetterPropertyLiteral
{
internal object Property;
public SetterPropertyLiteral (object property)
{
Property = property;
}
}
public Node FirstChild
{
get
{
return first;
}
}
public Node LastChild
{
get
{
return last;
}
}
public Node Next
{
get
{
return next;
}
}
public Node LastSibling
{
get
{
Node n = this;
while (n.next != null) {
n = n.next;
}
return n;
}
}
public int Lineno
{
get
{
return lineno;
}
}
/// <summary>Can only be called when <tt>getType() == Token.NUMBER</tt> </summary>
public double Double
{
get
{
return ((NumberNode)this).number;
}
set
{
((NumberNode)this).number = value;
}
}
/// <summary>Can only be called when node has String context. </summary>
public string String
{
get
{
return ((StringNode)this).str;
}
set
{
if (value == null)
Context.CodeBug ();
((StringNode)this).str = value;
}
}
public const int FUNCTION_PROP = 1;
public const int LOCAL_PROP = 2;
public const int LOCAL_BLOCK_PROP = 3;
public const int REGEXP_PROP = 4;
public const int CASEARRAY_PROP = 5;
public const int TARGETBLOCK_PROP = 6;
public const int VARIABLE_PROP = 7;
public const int ISNUMBER_PROP = 8;
public const int DIRECTCALL_PROP = 9;
public const int SPECIALCALL_PROP = 10;
public const int SKIP_INDEXES_PROP = 11;
public const int OBJECT_IDS_PROP = 12;
public const int INCRDECR_PROP = 13;
public const int CATCH_SCOPE_PROP = 14;
public const int LABEL_ID_PROP = 15;
public const int MEMBER_TYPE_PROP = 16;
public const int NAME_PROP = 17;
public const int LAST_PROP = NAME_PROP;
// values of ISNUMBER_PROP to specify
// which of the children are Number Types
public const int BOTH = 0;
public const int LEFT = 1;
public const int RIGHT = 2;
public const int NON_SPECIALCALL = 0;
public const int SPECIALCALL_EVAL = 1;
public const int SPECIALCALL_WITH = 2;
public const int DECR_FLAG = 0x1;
public const int POST_FLAG = 0x2;
public const int PROPERTY_FLAG = 0x1;
public const int ATTRIBUTE_FLAG = 0x2;
public const int DESCENDANTS_FLAG = 0x4; // x..y or x..@i
private class NumberNode : Node
{
internal NumberNode (double number)
: base (Token.NUMBER)
{
this.number = number;
}
internal double number;
}
private class StringNode : Node
{
internal StringNode (int Type, string str)
: base (Type)
{
this.str = str;
}
internal string str;
}
public class Jump : Node
{
public Jump JumpStatement
{
get
{
if (!(Type == Token.BREAK || Type == Token.CONTINUE))
Context.CodeBug ();
return jumpNode;
}
set
{
if (!(Type == Token.BREAK || Type == Token.CONTINUE))
Context.CodeBug ();
if (value == null)
Context.CodeBug ();
if (this.jumpNode != null)
Context.CodeBug (); //only once
this.jumpNode = value;
}
}
public Node Default
{
get
{
if (!(Type == Token.SWITCH))
Context.CodeBug ();
return target2;
}
set
{
if (!(Type == Token.SWITCH))
Context.CodeBug ();
if (value.Type != Token.TARGET)
Context.CodeBug ();
if (target2 != null)
Context.CodeBug (); //only once
target2 = value;
}
}
public Node Finally
{
get
{
if (!(Type == Token.TRY))
Context.CodeBug ();
return target2;
}
set
{
if (!(Type == Token.TRY))
Context.CodeBug ();
if (value.Type != Token.TARGET)
Context.CodeBug ();
if (target2 != null)
Context.CodeBug (); //only once
target2 = value;
}
}
public Jump Loop
{
get
{
if (!(Type == Token.LABEL))
Context.CodeBug ();
return jumpNode;
}
set
{
if (!(Type == Token.LABEL))
Context.CodeBug ();
if (value == null)
Context.CodeBug ();
if (jumpNode != null)
Context.CodeBug (); //only once
jumpNode = value;
}
}
public Node Continue
{
get
{
if (Type != Token.LOOP)
Context.CodeBug ();
return target2;
}
set
{
if (Type != Token.LOOP)
Context.CodeBug ();
if (value.Type != Token.TARGET)
Context.CodeBug ();
if (target2 != null)
Context.CodeBug (); //only once
target2 = value;
}
}
public Jump (int Type)
: base (Type)
{
}
internal Jump (int Type, int lineno)
: base (Type, lineno)
{
}
internal Jump (int Type, Node child)
: base (Type, child)
{
}
internal Jump (int Type, Node child, int lineno)
: base (Type, child, lineno)
{
}
public Node target;
private Node target2;
private Jump jumpNode;
}
private class PropListItem
{
internal PropListItem next;
internal int Type;
internal int intValue;
internal object objectValue;
}
public Node (int nodeType)
{
Type = nodeType;
}
public Node (int nodeType, Node child)
{
Type = nodeType;
first = last = child;
child.next = null;
}
public Node (int nodeType, Node left, Node right)
{
Type = nodeType;
first = left;
last = right;
left.next = right;
right.next = null;
}
public Node (int nodeType, Node left, Node mid, Node right)
{
Type = nodeType;
first = left;
last = right;
left.next = mid;
mid.next = right;
right.next = null;
}
public Node (int nodeType, int line)
{
Type = nodeType;
lineno = line;
}
public Node (int nodeType, Node child, int line)
: this (nodeType, child)
{
lineno = line;
}
public Node (int nodeType, Node left, Node right, int line)
: this (nodeType, left, right)
{
lineno = line;
}
public Node (int nodeType, Node left, Node mid, Node right, int line)
: this (nodeType, left, mid, right)
{
lineno = line;
}
public static Node newNumber (double number)
{
return new NumberNode (number);
}
public static Node newString (string str)
{
return new StringNode (Token.STRING, str);
}
public static Node newString (int Type, string str)
{
return new StringNode (Type, str);
}
public bool hasChildren ()
{
return first != null;
}
public Node getChildBefore (Node child)
{
if (child == first)
return null;
Node n = first;
while (n.next != child) {
n = n.next;
if (n == null)
throw new ApplicationException ("node is not a child");
}
return n;
}
public void addChildToFront (Node child)
{
child.next = first;
first = child;
if (last == null) {
last = child;
}
}
public void addChildToBack (Node child)
{
child.next = null;
if (last == null) {
first = last = child;
return;
}
last.next = child;
last = child;
}
public void addChildrenToFront (Node children)
{
Node lastSib = children.LastSibling;
lastSib.next = first;
first = children;
if (last == null) {
last = lastSib;
}
}
public void addChildrenToBack (Node children)
{
if (last != null) {
last.next = children;
}
last = children.LastSibling;
if (first == null) {
first = children;
}
}
/// <summary> Add 'child' before 'node'.</summary>
public void addChildBefore (Node newChild, Node node)
{
if (newChild.next != null)
throw new ApplicationException ("newChild had siblings in addChildBefore");
if (first == node) {
newChild.next = first;
first = newChild;
return;
}
Node prev = getChildBefore (node);
addChildAfter (newChild, prev);
}
/// <summary> Add 'child' after 'node'.</summary>
public void addChildAfter (Node newChild, Node node)
{
if (newChild.next != null)
throw new ApplicationException ("newChild had siblings in addChildAfter");
newChild.next = node.next;
node.next = newChild;
if (last == node)
last = newChild;
}
public void removeChild (Node child)
{
Node prev = getChildBefore (child);
if (prev == null)
first = first.next;
else
prev.next = child.next;
if (child == last)
last = prev;
child.next = null;
}
public void replaceChild (Node child, Node newChild)
{
newChild.next = child.next;
if (child == first) {
first = newChild;
}
else {
Node prev = getChildBefore (child);
prev.next = newChild;
}
if (child == last)
last = newChild;
child.next = null;
}
public void replaceChildAfter (Node prevChild, Node newChild)
{
Node child = prevChild.next;
newChild.next = child.next;
prevChild.next = newChild;
if (child == last)
last = newChild;
child.next = null;
}
private static string propToString (int propType)
{
if (Token.printTrees) {
// If Context.printTrees is false, the compiler
// can remove all these strings.
switch (propType) {
case FUNCTION_PROP:
return "function";
case LOCAL_PROP:
return "local";
case LOCAL_BLOCK_PROP:
return "local_block";
case REGEXP_PROP:
return "regexp";
case CASEARRAY_PROP:
return "casearray";
case TARGETBLOCK_PROP:
return "targetblock";
case VARIABLE_PROP:
return "variable";
case ISNUMBER_PROP:
return "isnumber";
case DIRECTCALL_PROP:
return "directcall";
case SPECIALCALL_PROP:
return "specialcall";
case SKIP_INDEXES_PROP:
return "skip_indexes";
case OBJECT_IDS_PROP:
return "object_ids_prop";
case INCRDECR_PROP:
return "incrdecr_prop";
case CATCH_SCOPE_PROP:
return "catch_scope_prop";
case LABEL_ID_PROP:
return "label_id_prop";
case MEMBER_TYPE_PROP:
return "member_Type_prop";
case NAME_PROP:
return "name_prop";
default:
Context.CodeBug ();
break;
}
}
return null;
}
private PropListItem lookupProperty (int propType)
{
PropListItem x = propListHead;
while (x != null && propType != x.Type) {
x = x.next;
}
return x;
}
private PropListItem ensureProperty (int propType)
{
PropListItem item = lookupProperty (propType);
if (item == null) {
item = new PropListItem ();
item.Type = propType;
item.next = propListHead;
propListHead = item;
}
return item;
}
public void removeProp (int propType)
{
PropListItem x = propListHead;
if (x != null) {
PropListItem prev = null;
while (x.Type != propType) {
prev = x;
x = x.next;
if (x == null) {
return;
}
}
if (prev == null) {
propListHead = x.next;
}
else {
prev.next = x.next;
}
}
}
public object getProp (int propType)
{
PropListItem item = lookupProperty (propType);
if (item == null) {
return null;
}
return item.objectValue;
}
public int getIntProp (int propType, int defaultValue)
{
PropListItem item = lookupProperty (propType);
if (item == null) {
return defaultValue;
}
return item.intValue;
}
public int getExistingIntProp (int propType)
{
PropListItem item = lookupProperty (propType);
if (item == null) {
Context.CodeBug ();
}
return item.intValue;
}
public void putProp (int propType, object prop)
{
if (prop == null) {
removeProp (propType);
}
else {
PropListItem item = ensureProperty (propType);
item.objectValue = prop;
}
}
public void putIntProp (int propType, int prop)
{
PropListItem item = ensureProperty (propType);
item.intValue = prop;
}
public static Node newTarget ()
{
return new Node (Token.TARGET);
}
public int labelId ()
{
if (Type != Token.TARGET)
Context.CodeBug ();
return getIntProp (LABEL_ID_PROP, -1);
}
public void labelId (int labelId)
{
if (Type != Token.TARGET)
Context.CodeBug ();
putIntProp (LABEL_ID_PROP, labelId);
}
public override string ToString ()
{
if (Token.printTrees) {
System.Text.StringBuilder sb = new System.Text.StringBuilder ();
toString (new ObjToIntMap (), sb);
return sb.ToString ();
}
return Convert.ToString (Type);
}
private void toString (ObjToIntMap printIds, System.Text.StringBuilder sb)
{
if (Token.printTrees) {
sb.Append (Token.name (this.Type));
if (this is StringNode) {
sb.Append (' ');
sb.Append (String);
}
else if (this is ScriptOrFnNode) {
ScriptOrFnNode sof = (ScriptOrFnNode)this;
if (this is FunctionNode) {
FunctionNode fn = (FunctionNode)this;
sb.Append (' ');
sb.Append (fn.FunctionName);
}
sb.Append (" [source name: ");
sb.Append (sof.SourceName);
sb.Append ("] [encoded source length: ");
sb.Append (sof.EncodedSourceEnd - sof.EncodedSourceStart);
sb.Append ("] [base line: ");
sb.Append (sof.BaseLineno);
sb.Append ("] [end line: ");
sb.Append (sof.EndLineno);
sb.Append (']');
}
else if (this is Jump) {
Jump jump = (Jump)this;
if (this.Type == Token.BREAK || this.Type == Token.CONTINUE) {
sb.Append (" [label: ");
appendPrintId (jump.JumpStatement, printIds, sb);
sb.Append (']');
}
else if (this.Type == Token.TRY) {
Node catchNode = jump.target;
Node finallyTarget = jump.Finally;
if (catchNode != null) {
sb.Append (" [catch: ");
appendPrintId (catchNode, printIds, sb);
sb.Append (']');
}
if (finallyTarget != null) {
sb.Append (" [finally: ");
appendPrintId (finallyTarget, printIds, sb);
sb.Append (']');
}
}
else if (this.Type == Token.LABEL || this.Type == Token.LOOP || this.Type == Token.SWITCH) {
sb.Append (" [break: ");
appendPrintId (jump.target, printIds, sb);
sb.Append (']');
if (this.Type == Token.LOOP) {
sb.Append (" [continue: ");
appendPrintId (jump.Continue, printIds, sb);
sb.Append (']');
}
}
else {
sb.Append (" [target: ");
appendPrintId (jump.target, printIds, sb);
sb.Append (']');
}
}
else if (this.Type == Token.NUMBER) {
sb.Append (' ');
sb.Append (Double);
}
else if (this.Type == Token.TARGET) {
sb.Append (' ');
appendPrintId (this, printIds, sb);
}
if (lineno != -1) {
sb.Append (' ');
sb.Append (lineno);
}
for (PropListItem x = propListHead; x != null; x = x.next) {
int Type = x.Type;
sb.Append (" [");
sb.Append (propToString (Type));
sb.Append (": ");
string value;
switch (Type) {
case TARGETBLOCK_PROP: // can't add this as it recurses
value = "target block property";
break;
case LOCAL_BLOCK_PROP: // can't add this as it is dull
value = "last local block";
break;
case ISNUMBER_PROP:
switch (x.intValue) {
case BOTH:
value = "both";
break;
case RIGHT:
value = "right";
break;
case LEFT:
value = "left";
break;
default:
throw Context.CodeBug ();
}
break;
case SPECIALCALL_PROP:
switch (x.intValue) {
case SPECIALCALL_EVAL:
value = "eval";
break;
case SPECIALCALL_WITH:
value = "with";
break;
default:
// NON_SPECIALCALL should not be stored
throw Context.CodeBug ();
}
break;
default:
object obj = x.objectValue;
if (obj != null) {
value = obj.ToString ();
}
else {
value = Convert.ToString (x.intValue);
}
break;
}
sb.Append (value);
sb.Append (']');
}
}
}
public string toStringTree (ScriptOrFnNode treeTop)
{
if (Token.printTrees) {
System.Text.StringBuilder sb = new System.Text.StringBuilder ();
toStringTreeHelper (treeTop, this, null, 0, sb);
return sb.ToString ();
}
return null;
}
private static void toStringTreeHelper (ScriptOrFnNode treeTop, Node n, ObjToIntMap printIds, int level, System.Text.StringBuilder sb)
{
if (Token.printTrees) {
if (printIds == null) {
printIds = new ObjToIntMap ();
generatePrintIds (treeTop, printIds);
}
for (int i = 0; i != level; ++i) {
sb.Append (" ");
}
n.toString (printIds, sb);
sb.Append ('\n');
for (Node cursor = n.FirstChild; cursor != null; cursor = cursor.Next) {
if (cursor.Type == Token.FUNCTION) {
int fnIndex = cursor.getExistingIntProp (Node.FUNCTION_PROP);
FunctionNode fn = treeTop.getFunctionNode (fnIndex);
toStringTreeHelper (fn, fn, null, level + 1, sb);
}
else {
toStringTreeHelper (treeTop, cursor, printIds, level + 1, sb);
}
}
}
}
private static void generatePrintIds (Node n, ObjToIntMap map)
{
if (Token.printTrees) {
map.put (n, map.size ());
for (Node cursor = n.FirstChild; cursor != null; cursor = cursor.Next) {
generatePrintIds (cursor, map);
}
}
}
private static void appendPrintId (Node n, ObjToIntMap printIds, System.Text.StringBuilder sb)
{
if (Token.printTrees) {
if (n != null) {
int id = printIds.Get (n, -1);
sb.Append ('#');
if (id != -1) {
sb.Append (id + 1);
}
else {
sb.Append ("<not_available>");
}
}
}
}
internal int Type; // Type of the node; Token.NAME for example
internal Node next; // next sibling
private Node first; // first element of a linked list of children
private Node last; // last element of a linked list of children
private int lineno = -1; // encapsulated int data; depends on Type
/// <summary> Linked list of properties. Since vast majority of nodes would have
/// no more then 2 properties, linked list saves memory and provides
/// fast lookup. If this does not holds, propListHead can be replaced
/// by UintMap.
/// </summary>
private PropListItem propListHead;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;
namespace CoreEditor.Utils
{
public static class WhereUsed
{
[MenuItem( "Assets/Find Reference(s)", true, 21 ),MenuItem( "Assets/Safe Delete %#\b", true, 20 )]
public static bool IsSelectionAssets()
{
if ( Selection.objects.Length == 0 )
return false;
foreach ( var selectedObject in Selection.objects )
{
if ( !EditorUtility.IsPersistent( selectedObject ) )
return false;
}
return true;
}
[MenuItem( "Assets/Find Reference(s)", false, 21 )]
public static void Print()
{
PrintReferences( Selection.objects );
}
public static void PrintReferences( params Object[] objects )
{
var references = new HashSet<string>();
var directReferences = new HashSet<string>();
var indirectReferences = new HashSet<string>();
var sb = new StringBuilder();
sb.AppendLine( "[ Selected File(s) ]" );
foreach ( var selectedObject in objects )
{
sb.AppendLine( AssetDatabase.GetAssetPath( selectedObject ) );
references.UnionWith( ExtractDirectAndIndirect( FindReferences( selectedObject ), ref directReferences, ref indirectReferences ) );
}
sb.AppendLine();
if ( references.Count == 0 )
sb.AppendLine( "No reference" );
else
{
AppendReferencesToStringBuilder( directReferences, indirectReferences, ref sb );
}
Log( sb.ToString() );
EditorUtility.ClearProgressBar();
}
[MenuItem( "Edit/Find Unreferenced Asset(s)", false, 0 )]
public static void FindUnreferencedAssets()
{
Log( GetUnreferencedAssets().ToSortedLines() );
}
[MenuItem( "Edit/Select Unreferenced Asset(s)", false, 1 )]
public static void SelectUnreferencedAssets()
{
var assets = new List<Object>();
foreach ( var asset in GetUnreferencedAssets() )
assets.Add( AssetDatabase.LoadAssetAtPath( asset, typeof( Object ) ) );
Selection.objects = assets.ToArray();
}
static HashSet<string> GetUnreferencedAssets()
{
var referencesOutsideResources = new HashSet<string>();
var otherAssets = new HashSet<string>();
var ignoreExtensions = new HashSet<string>( new [] {
".asset",
".prefs" ,
".cs",
".boo",
".js",
".rsp",
".m",
".mm",
".py",
".h",
".plist",
".a",
".dll",
".pyc",
".scpt",
".userprefs",
".jar" ,
".json",
".zip",
".xib",
".c",
".o" ,
".patch",
".icns",
""
} );
var assets = AssetDatabase.GetAllAssetPaths().Where( file => !ignoreExtensions.Contains( Path.GetExtension( file ).ToLower() ) ).ToArray();
int total = assets.Length;
float invTotal = 1.0f / total;
int count = 0;
var totalString = " / " + total;
foreach ( var asset in assets )
{
if ( count % 20 == 0 && EditorUtility.DisplayCancelableProgressBar( "Find Unreferenced Asset(s)", "Processing... " + count + totalString, ( count * invTotal ) ) )
break;
if ( IsResourceOrScene( asset ) )
{
var dependencies = AssetDatabase.GetDependencies( new []{ asset } )
.Where( dependency => !dependency.StartsWith( "Assets/Resources" ) && dependency != asset );
referencesOutsideResources.UnionWith( dependencies );
}
else
{
otherAssets.Add( asset );
}
}
otherAssets.ExceptWith( referencesOutsideResources );
otherAssets.ExceptWith( LibraryReferences() );
EditorUtility.ClearProgressBar();
return otherAssets;
}
static void AppendReferencesToStringBuilder( HashSet<string> directReferences, HashSet<string> indirectReferences, ref StringBuilder sb )
{
sb.AppendLine( "[ Direct Reference(s) ] " );
sb.AppendLine( directReferences.ToSortedLines() );
if ( indirectReferences.Count > 0 )
{
sb.AppendLine( "[ Indirect Reference(s) or Rare Assets that have both direct AND indirect reference on the selected asset(s) ]" );
sb.AppendLine( indirectReferences.ToSortedLines() );
}
}
static HashSet<string> ExtractDirectAndIndirect( HashSet<string> references, ref HashSet<string> directReferences, ref HashSet<string> indirectReferences )
{
int total = references.Count;
float invTotal = 1.0f / total;
int count = 0;
var totalString = " / " + total;
foreach ( var reference in references )
{
count++;
if ( count % 20 == 0 && EditorUtility.DisplayCancelableProgressBar( "Find Reference(s)", "Splitting direct and indirect reference(s)" + count + totalString, ( count * invTotal ) ) )
break;
if ( ( references.Intersect( AssetDatabase.GetDependencies( new string[ ]{ reference } ) ).Count() <= 1 ) )
directReferences.Add( reference );
else
indirectReferences.Add( reference );
}
return references;
}
static HashSet<string> ExtractSelfAndParents( string path )
{
var selfAndParents = new HashSet<string>();
var parent = path;
while ( parent != "Assets" )
{
selfAndParents.Add( parent );
parent = Path.GetDirectoryName( parent );
}
;
return selfAndParents;
}
static HashSet<string> FindReferences( Object obj )
{
var path = AssetDatabase.GetAssetPath( obj );
var selfAndParents = ExtractSelfAndParents( path );
var pathAsDir = path;
bool isDir = Directory.Exists( "./" + path );
if ( isDir )
pathAsDir += "/";
var referencedBy = new HashSet<string>();
var assets = AssetDatabase.GetAllAssetPaths().Where( file => !file.StartsWith( pathAsDir ) && file != path ).ToArray();
var total = assets.Length;
var invTotal = 1f / total;
var count = 0;
var totalString = " / " + total;
foreach ( var asset in assets )
{
count++;
if ( count % 20 == 0 && EditorUtility.DisplayCancelableProgressBar( "Find Reference(s)", "Looking for reference(s) " + count + totalString, ( count * invTotal ) ) )
break;
var dependencies = AssetDatabase.GetDependencies( new string[ ]{ asset } );
Func<string,bool> referenceSelfParentOrChildren = (dep ) => ( ( selfAndParents.Contains( dep ) && dep != asset ) || ( isDir && dep.StartsWith( pathAsDir ) ) );
if ( dependencies.FirstOrDefault( referenceSelfParentOrChildren ) != null )
referencedBy.Add( asset );
}
referencedBy.UnionWith( LibraryReferences( obj ) );
return referencedBy;
}
static HashSet<string> LibraryReferences( Object obj )
{
const string libraryPath = "ProjectSettings/ProjectSettings.asset";
var foundLibraryReferences = new HashSet<string>();
var type = typeof( PlayerSettings );
foreach ( var property in type.GetProperties( BindingFlags.Static | BindingFlags.Public ) )
{
if ( property.PropertyType == typeof( Object ) || property.PropertyType.IsSubclassOf( typeof( Object ) ) )
{
var val = type.InvokeMember( property.Name, BindingFlags.Public | BindingFlags.Static | BindingFlags.GetProperty, null, property.PropertyType, null ) as Object;
if ( val == obj )
{
foundLibraryReferences.Add( libraryPath + "/" + type.Name + "/" + property.Name );
}
}
}
foreach ( var nestedClass in type.GetNestedTypes( BindingFlags.Static | BindingFlags.Public ) )
{
foreach ( var property in nestedClass.GetProperties( BindingFlags.Static | BindingFlags.Public ) )
{
if ( property.PropertyType == typeof( Object ) || property.PropertyType.IsSubclassOf( typeof( Object ) ) )
{
var val = nestedClass.InvokeMember( property.Name, BindingFlags.Public | BindingFlags.Static | BindingFlags.GetProperty, null, property.PropertyType, null ) as Object;
if ( val == obj )
{
foundLibraryReferences.Add( libraryPath + "/" + type.Name + "/" + nestedClass.Name + "/" + property.Name );
}
}
}
}
if ( obj is Texture2D )
{
foreach ( var target in EnumUtil.GetValues<BuildTargetGroup>() )
{
foreach ( var icon in PlayerSettings.GetIconsForTargetGroup( target ) )
{
if ( obj == icon )
{
foundLibraryReferences.Add( libraryPath + "/" + target + "/Icons" );
}
}
}
}
var editor = PlayerSettingsEditor;
foreach ( var field in editor.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance ) )
{
if ( field.FieldType == typeof( SerializedProperty ) )
{
var prop = field.GetValue( editor ) as SerializedProperty;
if ( prop != null )
{
if ( prop.type.StartsWith( "PPtr" ) && prop.objectReferenceValue == obj )
{
foundLibraryReferences.Add( libraryPath + "/PlayerSettings/" + field.Name.Replace( "m_", "" ) );
}
}
}
}
Object.DestroyImmediate( editor );
return foundLibraryReferences;
}
static Editor PlayerSettingsEditor
{
get {
var playerSettings = Unsupported.GetSerializedAssetInterfaceSingleton( "PlayerSettings" );
return Editor.CreateEditor( playerSettings );
}
}
static HashSet<string> LibraryReferences()
{
var libraryReferences = new HashSet<string>();
var type = typeof( PlayerSettings );
foreach ( var property in type.GetProperties( BindingFlags.Static | BindingFlags.Public ) )
{
if ( property.PropertyType == typeof( Object ) || property.PropertyType.IsSubclassOf( typeof( Object ) ) )
{
var val = type.InvokeMember( property.Name, BindingFlags.Public | BindingFlags.Static | BindingFlags.GetProperty, null, property.PropertyType, null ) as Object;
if ( val != null )
libraryReferences.Add( AssetDatabase.GetAssetPath( val ) );
}
}
foreach ( var nestedClass in type.GetNestedTypes( BindingFlags.Static | BindingFlags.Public ) )
{
foreach ( var property in nestedClass.GetProperties( BindingFlags.Static | BindingFlags.Public ) )
{
if ( property.PropertyType == typeof( Object ) || property.PropertyType.IsSubclassOf( typeof( Object ) ) )
{
var val = nestedClass.InvokeMember( property.Name, BindingFlags.Public | BindingFlags.Static | BindingFlags.GetProperty, null, property.PropertyType, null ) as Object;
if ( val != null )
libraryReferences.Add( AssetDatabase.GetAssetPath( val ) );
}
}
}
foreach ( var target in EnumUtil.GetValues<BuildTargetGroup>() )
{
foreach ( var icon in PlayerSettings.GetIconsForTargetGroup( target ) )
{
if ( icon != null )
libraryReferences.Add( AssetDatabase.GetAssetPath( icon ) );
}
}
var editor = PlayerSettingsEditor;
foreach ( var field in editor.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance ) )
{
if ( field.FieldType == typeof( SerializedProperty ) )
{
var prop = field.GetValue( editor ) as SerializedProperty;
if ( prop != null )
{
if ( prop.type.StartsWith( "PPtr" ) && prop.objectReferenceValue != null )
libraryReferences.Add( AssetDatabase.GetAssetPath( prop.objectReferenceValue ) );
}
}
}
Object.DestroyImmediate( editor );
return libraryReferences;
}
static void Log( string content, bool error = false )
{
Action<string> log;
if ( error )
log = Debug.LogError;
else
log = Debug.Log;
const int unityLogMaxSize = 16092;
if ( content.Length > unityLogMaxSize )
{
var filepath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + FileUtil.GetUniqueTempPathInProject() + ".txt";
if ( string.IsNullOrEmpty( filepath ) == false )
{
File.WriteAllText( filepath, content );
Process.Start( filepath );
content = "Content is too big for the Console. See full content in the opened file: \n" + filepath + "\n...\n\n" + content;
log( content );
}
}
else
{
log( content );
}
}
static bool IsResourceOrScene(string path)
{
return path.StartsWith( "Assets/Resources" ) || path.EndsWith( ".unity" );
}
}
static class EnumUtil
{
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues( typeof( T ) ).Cast<T>();
}
}
static class HashsetExtensions
{
public static string ToSortedLines( this HashSet<string> references )
{
var sortedReferences = references.ToList();
sortedReferences.Sort();
var sb = new StringBuilder();
foreach ( var depends in sortedReferences )
sb.AppendLine( depends );
return sb.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Diagnostics {
using System;
using System.Collections;
using System.Text;
using System.Threading;
using System.Security;
using System.Security.Permissions;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
// READ ME:
// Modifying the order or fields of this object may require other changes
// to the unmanaged definition of the StackFrameHelper class, in
// VM\DebugDebugger.h. The binder will catch some of these layout problems.
#if FEATURE_SERIALIZATION
[Serializable]
#endif
internal class StackFrameHelper : IDisposable
{
[NonSerialized]
private Thread targetThread;
private int[] rgiOffset;
private int[] rgiILOffset;
// this field is here only for backwards compatibility of serialization format
private MethodBase[] rgMethodBase;
#pragma warning disable 414
// dynamicMethods is an array of System.Resolver objects, used to keep
// DynamicMethodDescs alive for the lifetime of StackFrameHelper.
private Object dynamicMethods; // Field is not used from managed.
[NonSerialized]
private IntPtr[] rgMethodHandle;
private String[] rgAssemblyPath;
private IntPtr[] rgLoadedPeAddress;
private int[] rgiLoadedPeSize;
private IntPtr[] rgInMemoryPdbAddress;
private int[] rgiInMemoryPdbSize;
// if rgiMethodToken[i] == 0, then don't attempt to get the portable PDB source/info
private int[] rgiMethodToken;
private String[] rgFilename;
private int[] rgiLineNumber;
private int[] rgiColumnNumber;
#if FEATURE_EXCEPTIONDISPATCHINFO
[OptionalField]
private bool[] rgiLastFrameFromForeignExceptionStackTrace;
#endif // FEATURE_EXCEPTIONDISPATCHINFO
private GetSourceLineInfoDelegate getSourceLineInfo;
private int iFrameCount;
#pragma warning restore 414
private delegate void GetSourceLineInfoDelegate(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize,
IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset,
out string sourceFile, out int sourceLine, out int sourceColumn);
#if FEATURE_CORECLR
private static Type s_symbolsType = null;
private static MethodInfo s_symbolsMethodInfo = null;
[ThreadStatic]
private static int t_reentrancy = 0;
#endif
public StackFrameHelper(Thread target)
{
targetThread = target;
rgMethodBase = null;
rgMethodHandle = null;
rgiMethodToken = null;
rgiOffset = null;
rgiILOffset = null;
rgAssemblyPath = null;
rgLoadedPeAddress = null;
rgiLoadedPeSize = null;
rgInMemoryPdbAddress = null;
rgiInMemoryPdbSize = null;
dynamicMethods = null;
rgFilename = null;
rgiLineNumber = null;
rgiColumnNumber = null;
getSourceLineInfo = null;
#if FEATURE_EXCEPTIONDISPATCHINFO
rgiLastFrameFromForeignExceptionStackTrace = null;
#endif // FEATURE_EXCEPTIONDISPATCHINFO
// 0 means capture all frames. For StackTraces from an Exception, the EE always
// captures all frames. For other uses of StackTraces, we can abort stack walking after
// some limit if we want to by setting this to a non-zero value. In Whidbey this was
// hard-coded to 512, but some customers complained. There shouldn't be any need to limit
// this as memory/CPU is no longer allocated up front. If there is some reason to provide a
// limit in the future, then we should expose it in the managed API so applications can
// override it.
iFrameCount = 0;
}
//
// Initializes the stack trace helper. If fNeedFileInfo is true, initializes rgFilename,
// rgiLineNumber and rgiColumnNumber fields using the portable PDB reader if not already
// done by GetStackFramesInternal (on Windows for old PDB format).
//
internal void InitializeSourceInfo(int iSkip, bool fNeedFileInfo, Exception exception)
{
StackTrace.GetStackFramesInternal(this, iSkip, fNeedFileInfo, exception);
#if FEATURE_CORECLR
if (!fNeedFileInfo)
return;
// Check if this function is being reentered because of an exception in the code below
if (t_reentrancy > 0)
return;
t_reentrancy++;
try
{
if (s_symbolsMethodInfo == null)
{
s_symbolsType = Type.GetType(
"System.Diagnostics.StackTraceSymbols, System.Diagnostics.StackTrace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
throwOnError: false);
if (s_symbolsType == null)
return;
s_symbolsMethodInfo = s_symbolsType.GetMethod("GetSourceLineInfo");
if (s_symbolsMethodInfo == null)
return;
}
if (getSourceLineInfo == null)
{
// Create an instance of System.Diagnostics.Stacktrace.Symbols
object target = Activator.CreateInstance(s_symbolsType);
// Create an instance delegate for the GetSourceLineInfo method
getSourceLineInfo = (GetSourceLineInfoDelegate)s_symbolsMethodInfo.CreateDelegate(typeof(GetSourceLineInfoDelegate), target);
}
for (int index = 0; index < iFrameCount; index++)
{
// If there was some reason not to try get get the symbols from the portable PDB reader like the module was
// ENC or the source/line info was already retrieved, the method token is 0.
if (rgiMethodToken[index] != 0)
{
getSourceLineInfo(rgAssemblyPath[index], rgLoadedPeAddress[index], rgiLoadedPeSize[index],
rgInMemoryPdbAddress[index], rgiInMemoryPdbSize[index], rgiMethodToken[index],
rgiILOffset[index], out rgFilename[index], out rgiLineNumber[index], out rgiColumnNumber[index]);
}
}
}
catch
{
}
finally
{
t_reentrancy--;
}
#endif
}
void IDisposable.Dispose()
{
#if FEATURE_CORECLR
if (getSourceLineInfo != null)
{
IDisposable disposable = getSourceLineInfo.Target as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
#endif
}
[System.Security.SecuritySafeCritical]
public virtual MethodBase GetMethodBase(int i)
{
// There may be a better way to do this.
// we got RuntimeMethodHandles here and we need to go to MethodBase
// but we don't know whether the reflection info has been initialized
// or not. So we call GetMethods and GetConstructors on the type
// and then we fetch the proper MethodBase!!
IntPtr mh = rgMethodHandle[i];
if (mh.IsNull())
return null;
IRuntimeMethodInfo mhReal = RuntimeMethodHandle.GetTypicalMethodDefinition(new RuntimeMethodInfoStub(mh, this));
return RuntimeType.GetMethodBase(mhReal);
}
public virtual int GetOffset(int i) { return rgiOffset[i];}
public virtual int GetILOffset(int i) { return rgiILOffset[i];}
public virtual String GetFilename(int i) { return rgFilename == null ? null : rgFilename[i];}
public virtual int GetLineNumber(int i) { return rgiLineNumber == null ? 0 : rgiLineNumber[i];}
public virtual int GetColumnNumber(int i) { return rgiColumnNumber == null ? 0 : rgiColumnNumber[i];}
#if FEATURE_EXCEPTIONDISPATCHINFO
public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i)
{
return (rgiLastFrameFromForeignExceptionStackTrace == null)?false:rgiLastFrameFromForeignExceptionStackTrace[i];
}
#endif // FEATURE_EXCEPTIONDISPATCHINFO
public virtual int GetNumberOfFrames() { return iFrameCount;}
public virtual void SetNumberOfFrames(int i) { iFrameCount = i;}
//
// serialization implementation
//
[OnSerializing]
[SecuritySafeCritical]
void OnSerializing(StreamingContext context)
{
// this is called in the process of serializing this object.
// For compatibility with Everett we need to assign the rgMethodBase field as that is the field
// that will be serialized
rgMethodBase = (rgMethodHandle == null) ? null : new MethodBase[rgMethodHandle.Length];
if (rgMethodHandle != null)
{
for (int i = 0; i < rgMethodHandle.Length; i++)
{
if (!rgMethodHandle[i].IsNull())
rgMethodBase[i] = RuntimeType.GetMethodBase(new RuntimeMethodInfoStub(rgMethodHandle[i], this));
}
}
}
[OnSerialized]
void OnSerialized(StreamingContext context)
{
// after we are done serializing null the rgMethodBase field
rgMethodBase = null;
}
[OnDeserialized]
[SecuritySafeCritical]
void OnDeserialized(StreamingContext context)
{
// after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle
rgMethodHandle = (rgMethodBase == null) ? null : new IntPtr[rgMethodBase.Length];
if (rgMethodBase != null)
{
for (int i = 0; i < rgMethodBase.Length; i++)
{
if (rgMethodBase[i] != null)
rgMethodHandle[i] = rgMethodBase[i].MethodHandle.Value;
}
}
rgMethodBase = null;
}
}
// Class which represents a description of a stack trace
// There is no good reason for the methods of this class to be virtual.
// In order to ensure trusted code can trust the data it gets from a
// StackTrace, we use an InheritanceDemand to prevent partially-trusted
// subclasses.
#if !FEATURE_CORECLR
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
#endif
#if FEATURE_SERIALIZATION
[Serializable]
#endif
[System.Runtime.InteropServices.ComVisible(true)]
public class StackTrace
{
private StackFrame[] frames;
private int m_iNumOfFrames;
public const int METHODS_TO_SKIP = 0;
private int m_iMethodsToSkip;
// Constructs a stack trace from the current location.
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
public StackTrace()
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, false, null, null);
}
// Constructs a stack trace from the current location.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(bool fNeedFileInfo)
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, null);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(int skipFrames)
{
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, null);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(int skipFrames, bool fNeedFileInfo)
{
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, null);
}
// Constructs a stack trace from the current location.
public StackTrace(Exception e)
{
if (e == null)
throw new ArgumentNullException("e");
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, false, null, e);
}
// Constructs a stack trace from the current location.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(Exception e, bool fNeedFileInfo)
{
if (e == null)
throw new ArgumentNullException("e");
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, e);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(Exception e, int skipFrames)
{
if (e == null)
throw new ArgumentNullException("e");
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, e);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo)
{
if (e == null)
throw new ArgumentNullException("e");
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, e);
}
// Constructs a "fake" stack trace, just containing a single frame.
// Does not have the overhead of a full stack trace.
//
public StackTrace(StackFrame frame)
{
frames = new StackFrame[1];
frames[0] = frame;
m_iMethodsToSkip = 0;
m_iNumOfFrames = 1;
}
// Constructs a stack trace for the given thread
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
[Obsolete("This constructor has been deprecated. Please use a constructor that does not require a Thread parameter. http://go.microsoft.com/fwlink/?linkid=14202")]
public StackTrace(Thread targetThread, bool needFileInfo)
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, needFileInfo, targetThread, null);
}
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, bool fNeedFileInfo, Exception e);
internal static int CalculateFramesToSkip(StackFrameHelper StackF, int iNumFrames)
{
int iRetVal = 0;
String PackageName = "System.Diagnostics";
// Check if this method is part of the System.Diagnostics
// package. If so, increment counter keeping track of
// System.Diagnostics functions
for (int i = 0; i < iNumFrames; i++)
{
MethodBase mb = StackF.GetMethodBase(i);
if (mb != null)
{
Type t = mb.DeclaringType;
if (t == null)
break;
String ns = t.Namespace;
if (ns == null)
break;
if (String.Compare(ns, PackageName, StringComparison.Ordinal) != 0)
break;
}
iRetVal++;
}
return iRetVal;
}
// Retrieves an object with stack trace information encoded.
// It leaves out the first "iSkip" lines of the stacktrace.
//
private void CaptureStackTrace(int iSkip, bool fNeedFileInfo, Thread targetThread, Exception e)
{
m_iMethodsToSkip += iSkip;
using (StackFrameHelper StackF = new StackFrameHelper(targetThread))
{
StackF.InitializeSourceInfo(0, fNeedFileInfo, e);
m_iNumOfFrames = StackF.GetNumberOfFrames();
if (m_iMethodsToSkip > m_iNumOfFrames)
m_iMethodsToSkip = m_iNumOfFrames;
if (m_iNumOfFrames != 0)
{
frames = new StackFrame[m_iNumOfFrames];
for (int i = 0; i < m_iNumOfFrames; i++)
{
bool fDummy1 = true;
bool fDummy2 = true;
StackFrame sfTemp = new StackFrame(fDummy1, fDummy2);
sfTemp.SetMethodBase(StackF.GetMethodBase(i));
sfTemp.SetOffset(StackF.GetOffset(i));
sfTemp.SetILOffset(StackF.GetILOffset(i));
#if FEATURE_EXCEPTIONDISPATCHINFO
sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i));
#endif // FEATURE_EXCEPTIONDISPATCHINFO
if (fNeedFileInfo)
{
sfTemp.SetFileName(StackF.GetFilename(i));
sfTemp.SetLineNumber(StackF.GetLineNumber(i));
sfTemp.SetColumnNumber(StackF.GetColumnNumber(i));
}
frames[i] = sfTemp;
}
// CalculateFramesToSkip skips all frames in the System.Diagnostics namespace,
// but this is not desired if building a stack trace from an exception.
if (e == null)
m_iMethodsToSkip += CalculateFramesToSkip(StackF, m_iNumOfFrames);
m_iNumOfFrames -= m_iMethodsToSkip;
if (m_iNumOfFrames < 0)
{
m_iNumOfFrames = 0;
}
}
// In case this is the same object being re-used, set frames to null
else
frames = null;
}
}
// Property to get the number of frames in the stack trace
//
public virtual int FrameCount
{
get { return m_iNumOfFrames;}
}
// Returns a given stack frame. Stack frames are numbered starting at
// zero, which is the last stack frame pushed.
//
public virtual StackFrame GetFrame(int index)
{
if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0))
return frames[index+m_iMethodsToSkip];
return null;
}
// Returns an array of all stack frames for this stacktrace.
// The array is ordered and sized such that GetFrames()[i] == GetFrame(i)
// The nth element of this array is the same as GetFrame(n).
// The length of the array is the same as FrameCount.
//
[ComVisible(false)]
public virtual StackFrame [] GetFrames()
{
if (frames == null || m_iNumOfFrames <= 0)
return null;
// We have to return a subset of the array. Unfortunately this
// means we have to allocate a new array and copy over.
StackFrame [] array = new StackFrame[m_iNumOfFrames];
Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames);
return array;
}
// Builds a readable representation of the stack trace
//
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
public override String ToString()
{
// Include a trailing newline for backwards compatibility
return ToString(TraceFormat.TrailingNewLine);
}
// TraceFormat is Used to specify options for how the
// string-representation of a StackTrace should be generated.
internal enum TraceFormat
{
Normal,
TrailingNewLine, // include a trailing new line character
NoResourceLookup // to prevent infinite resource recusion
}
// Builds a readable representation of the stack trace, specifying
// the format for backwards compatibility.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal String ToString(TraceFormat traceFormat)
{
bool displayFilenames = true; // we'll try, but demand may fail
String word_At = "at";
String inFileLineNum = "in {0}:line {1}";
if(traceFormat != TraceFormat.NoResourceLookup)
{
word_At = Environment.GetResourceString("Word_At");
inFileLineNum = Environment.GetResourceString("StackTrace_InFileLineNumber");
}
bool fFirstFrame = true;
StringBuilder sb = new StringBuilder(255);
for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++)
{
StackFrame sf = GetFrame(iFrameIndex);
MethodBase mb = sf.GetMethod();
if (mb != null)
{
// We want a newline at the end of every line except for the last
if (fFirstFrame)
fFirstFrame = false;
else
sb.Append(Environment.NewLine);
sb.AppendFormat(CultureInfo.InvariantCulture, " {0} ", word_At);
Type t = mb.DeclaringType;
// if there is a type (non global method) print it
if (t != null)
{
// Append t.FullName, replacing '+' with '.'
string fullName = t.FullName;
for (int i = 0; i < fullName.Length; i++)
{
char ch = fullName[i];
sb.Append(ch == '+' ? '.' : ch);
}
sb.Append('.');
}
sb.Append(mb.Name);
// deal with the generic portion of the method
if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod)
{
Type[] typars = ((MethodInfo)mb).GetGenericArguments();
sb.Append('[');
int k=0;
bool fFirstTyParam = true;
while (k < typars.Length)
{
if (fFirstTyParam == false)
sb.Append(',');
else
fFirstTyParam = false;
sb.Append(typars[k].Name);
k++;
}
sb.Append(']');
}
ParameterInfo[] pi = null;
#if FEATURE_CORECLR
try
{
#endif
pi = mb.GetParameters();
#if FEATURE_CORECLR
}
catch
{
// The parameter info cannot be loaded, so we don't
// append the parameter list.
}
#endif
if (pi != null)
{
// arguments printing
sb.Append('(');
bool fFirstParam = true;
for (int j = 0; j < pi.Length; j++)
{
if (fFirstParam == false)
sb.Append(", ");
else
fFirstParam = false;
String typeName = "<UnknownType>";
if (pi[j].ParameterType != null)
typeName = pi[j].ParameterType.Name;
sb.Append(typeName);
sb.Append(' ');
sb.Append(pi[j].Name);
}
sb.Append(')');
}
// source location printing
if (displayFilenames && (sf.GetILOffset() != -1))
{
// If we don't have a PDB or PDB-reading is disabled for the module,
// then the file name will be null.
String fileName = null;
// Getting the filename from a StackFrame is a privileged operation - we won't want
// to disclose full path names to arbitrarily untrusted code. Rather than just omit
// this we could probably trim to just the filename so it's still mostly usefull.
try
{
fileName = sf.GetFileName();
}
#if FEATURE_CAS_POLICY
catch (NotSupportedException)
{
// Having a deprecated stack modifier on the callstack (such as Deny) will cause
// a NotSupportedException to be thrown. Since we don't know if the app can
// access the file names, we'll conservatively hide them.
displayFilenames = false;
}
#endif // FEATURE_CAS_POLICY
catch (SecurityException)
{
// If the demand for displaying filenames fails, then it won't
// succeed later in the loop. Avoid repeated exceptions by not trying again.
displayFilenames = false;
}
if (fileName != null)
{
// tack on " in c:\tmp\MyFile.cs:line 5"
sb.Append(' ');
sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber());
}
}
#if FEATURE_EXCEPTIONDISPATCHINFO
if (sf.GetIsLastFrameFromForeignExceptionStackTrace())
{
sb.Append(Environment.NewLine);
sb.Append(Environment.GetResourceString("Exception_EndStackTraceFromPreviousThrow"));
}
#endif // FEATURE_EXCEPTIONDISPATCHINFO
}
}
if(traceFormat == TraceFormat.TrailingNewLine)
sb.Append(Environment.NewLine);
return sb.ToString();
}
// This helper is called from within the EE to construct a string representation
// of the current stack trace.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
private static String GetManagedStackTraceStringHelper(bool fNeedFileInfo)
{
// Note all the frames in System.Diagnostics will be skipped when capturing
// a normal stack trace (not from an exception) so we don't need to explicitly
// skip the GetManagedStackTraceStringHelper frame.
StackTrace st = new StackTrace(0, fNeedFileInfo);
return st.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Diagnostics;
namespace System.Reflection
{
#if CORERT
[System.Runtime.CompilerServices.ReflectionBlocked]
public // Needs to be public so that Reflection.Core can see it.
#else
internal
#endif
static class SignatureTypeExtensions
{
/// <summary>
/// This is semantically identical to
///
/// parameter.ParameterType == pattern.TryResolveAgainstGenericMethod(parameter.Member)
///
/// but without the allocation overhead of TryResolve.
/// </summary>
public static bool MatchesParameterTypeExactly(this Type pattern, ParameterInfo parameter)
{
if (pattern is SignatureType signatureType)
return signatureType.MatchesExactly(parameter.ParameterType);
else
return pattern == (object)(parameter.ParameterType);
}
/// <summary>
/// This is semantically identical to
///
/// actual == pattern.TryResolveAgainstGenericMethod(parameterMember)
///
/// but without the allocation overhead of TryResolve.
/// </summary>
internal static bool MatchesExactly(this SignatureType pattern, Type actual)
{
if (pattern.IsSZArray)
{
return actual.IsSZArray && pattern.ElementType.MatchesExactly(actual.GetElementType());
}
else if (pattern.IsVariableBoundArray)
{
return actual.IsVariableBoundArray && pattern.GetArrayRank() == actual.GetArrayRank() && pattern.ElementType.MatchesExactly(actual.GetElementType());
}
else if (pattern.IsByRef)
{
return actual.IsByRef && pattern.ElementType.MatchesExactly(actual.GetElementType());
}
else if (pattern.IsPointer)
{
return actual.IsPointer && pattern.ElementType.MatchesExactly(actual.GetElementType());
}
else if (pattern.IsConstructedGenericType)
{
if (!actual.IsConstructedGenericType)
return false;
if (!(pattern.GetGenericTypeDefinition() == actual.GetGenericTypeDefinition()))
return false;
Type[] patternGenericTypeArguments = pattern.GenericTypeArguments;
Type[] actualGenericTypeArguments = actual.GenericTypeArguments;
int count = patternGenericTypeArguments.Length;
if (count != actualGenericTypeArguments.Length)
return false;
for (int i = 0; i < count; i++)
{
Type patternGenericTypeArgument = patternGenericTypeArguments[i];
if (patternGenericTypeArgument is SignatureType signatureType)
{
if (!signatureType.MatchesExactly(actualGenericTypeArguments[i]))
return false;
}
else
{
if (patternGenericTypeArgument != actualGenericTypeArguments[i])
return false;
}
}
return true;
}
else if (pattern.IsGenericMethodParameter)
{
if (!actual.IsGenericMethodParameter)
return false;
if (pattern.GenericParameterPosition != actual.GenericParameterPosition)
return false;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Translates a SignatureType into its equivalent resolved Type by recursively substituting all generic parameter references
/// with its corresponding generic parameter definition. This is slow so MatchesExactly or MatchesParameterTypeExactly should be
/// substituted instead whenever possible. This is only used by the DefaultBinder when its fast-path checks have been exhausted and
/// it needs to call non-trivial methods like IsAssignableFrom which SignatureTypes will never support.
///
/// Because this method is used to eliminate method candidates in a GetMethod() lookup, it is entirely possible that the Type
/// might not be creatable due to conflicting generic constraints. Since this merely implies that this candidate is not
/// the method we're looking for, we return null rather than let the TypeLoadException bubble up. The DefaultBinder will catch
/// the null and continue its search for a better candidate.
/// </summary>
internal static Type TryResolveAgainstGenericMethod(this SignatureType signatureType, MethodInfo genericMethod)
{
return signatureType.TryResolve(genericMethod.GetGenericArguments());
}
private static Type TryResolve(this SignatureType signatureType, Type[] genericMethodParameters)
{
if (signatureType.IsSZArray)
{
return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakeArrayType();
}
else if (signatureType.IsVariableBoundArray)
{
return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakeArrayType(signatureType.GetArrayRank());
}
else if (signatureType.IsByRef)
{
return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakeByRefType();
}
else if (signatureType.IsPointer)
{
return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakePointerType();
}
else if (signatureType.IsConstructedGenericType)
{
Type[] genericTypeArguments = signatureType.GenericTypeArguments;
int count = genericTypeArguments.Length;
Type[] newGenericTypeArguments = new Type[count];
for (int i = 0; i < count; i++)
{
Type genericTypeArgument = genericTypeArguments[i];
if (genericTypeArgument is SignatureType signatureGenericTypeArgument)
{
newGenericTypeArguments[i] = signatureGenericTypeArgument.TryResolve(genericMethodParameters);
if (newGenericTypeArguments[i] == null)
return null;
}
else
{
newGenericTypeArguments[i] = genericTypeArgument;
}
}
return signatureType.GetGenericTypeDefinition().TryMakeGenericType(newGenericTypeArguments);
}
else if (signatureType.IsGenericMethodParameter)
{
int position = signatureType.GenericParameterPosition;
if (position >= genericMethodParameters.Length)
return null;
return genericMethodParameters[position];
}
else
{
return null;
}
}
private static Type TryMakeArrayType(this Type type)
{
try
{
return type.MakeArrayType();
}
catch
{
return null;
}
}
private static Type TryMakeArrayType(this Type type, int rank)
{
try
{
return type.MakeArrayType(rank);
}
catch
{
return null;
}
}
private static Type TryMakeByRefType(this Type type)
{
try
{
return type.MakeByRefType();
}
catch
{
return null;
}
}
private static Type TryMakePointerType(this Type type)
{
try
{
return type.MakePointerType();
}
catch
{
return null;
}
}
private static Type TryMakeGenericType(this Type type, Type[] instantiation)
{
try
{
return type.MakeGenericType(instantiation);
}
catch
{
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 Polacca.Api.Areas.HelpPage.ModelDescriptions;
using Polacca.Api.Areas.HelpPage.Models;
namespace Polacca.Api.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 UnityEngine;
[AddComponentMenu("NGUI/UI/Anchor"), ExecuteInEditMode]
public class UIAnchor : MonoBehaviour
{
public enum Side
{
BottomLeft,
Left,
TopLeft,
Top,
TopRight,
Right,
BottomRight,
Bottom,
Center
}
public Camera uiCamera;
public GameObject container;
public UIAnchor.Side side = UIAnchor.Side.Center;
public bool runOnlyOnce = true;
public Vector2 relativeOffset = Vector2.zero;
public Vector2 pixelOffset = Vector2.zero;
[HideInInspector, SerializeField]
private UIWidget widgetContainer;
private Transform mTrans;
private Animation mAnim;
private Rect mRect = default(Rect);
private UIRoot mRoot;
private bool mStarted;
private void Awake()
{
this.mTrans = base.transform;
this.mAnim = base.animation;
UICamera.mOnScreenReSize.Add(new UICamera.OnScreenResize(this.ScreenSizeChanged));
}
private void OnDestroy()
{
UICamera.mOnScreenReSize.Remove(new UICamera.OnScreenResize(this.ScreenSizeChanged));
this.mTrans = null;
this.mAnim = null;
this.mRoot = null;
}
private void ScreenSizeChanged()
{
if (this.mStarted && this.runOnlyOnce)
{
this.Update();
}
}
private void Start()
{
if (this.container == null && this.widgetContainer != null)
{
this.container = this.widgetContainer.gameObject;
this.widgetContainer = null;
}
this.mRoot = NGUITools.FindInParents<UIRoot>(base.gameObject);
if (this.uiCamera == null)
{
this.uiCamera = NGUITools.FindCameraForLayer(base.gameObject.layer);
}
if (this.uiCamera == null)
{
this.uiCamera = UICamera.currentCamera;
}
this.Update();
this.mStarted = true;
}
private void Update()
{
if (this.mAnim != null && this.mAnim.enabled && this.mAnim.isPlaying)
{
return;
}
bool flag = false;
UIWidget uIWidget = (!(this.container == null)) ? this.container.GetComponent<UIWidget>() : null;
UIPanel uIPanel = (!(this.container == null) || !(uIWidget == null)) ? this.container.GetComponent<UIPanel>() : null;
if (uIWidget != null)
{
Bounds bounds = uIWidget.CalculateBounds(this.container.transform.parent);
this.mRect.x = bounds.min.x;
this.mRect.y = bounds.min.y;
this.mRect.width = bounds.size.x;
this.mRect.height = bounds.size.y;
}
else if (uIPanel != null)
{
if (uIPanel.clipping == UIDrawCall.Clipping.None)
{
float num = (!(this.mRoot != null)) ? 0.5f : ((float)this.mRoot.activeHeight / (float)ResolutionConstrain.Instance.height * 0.5f);
this.mRect.xMin = (float)(-(float)ResolutionConstrain.Instance.width) * num;
this.mRect.yMin = (float)(-(float)ResolutionConstrain.Instance.height) * num;
this.mRect.xMax = -this.mRect.xMin;
this.mRect.yMax = -this.mRect.yMin;
}
else
{
Vector4 finalClipRegion = uIPanel.finalClipRegion;
this.mRect.x = finalClipRegion.x - finalClipRegion.z * 0.5f;
this.mRect.y = finalClipRegion.y - finalClipRegion.w * 0.5f;
this.mRect.width = finalClipRegion.z;
this.mRect.height = finalClipRegion.w;
}
}
else if (this.container != null)
{
Transform parent = this.container.transform.parent;
Bounds bounds2 = (!(parent != null)) ? NGUIMath.CalculateRelativeWidgetBounds(this.container.transform) : NGUIMath.CalculateRelativeWidgetBounds(parent, this.container.transform);
this.mRect.x = bounds2.min.x;
this.mRect.y = bounds2.min.y;
this.mRect.width = bounds2.size.x;
this.mRect.height = bounds2.size.y;
}
else
{
if (!(this.uiCamera != null))
{
return;
}
flag = true;
this.mRect = this.uiCamera.pixelRect;
}
float x = (this.mRect.xMin + this.mRect.xMax) * 0.5f;
float y = (this.mRect.yMin + this.mRect.yMax) * 0.5f;
Vector3 vector = Vector3.zero;
vector.x = x;
vector.y = y;
if (this.side != UIAnchor.Side.Center)
{
if (this.side == UIAnchor.Side.Right || this.side == UIAnchor.Side.TopRight || this.side == UIAnchor.Side.BottomRight)
{
vector.x = this.mRect.xMax;
}
else if (this.side == UIAnchor.Side.Top || this.side == UIAnchor.Side.Center || this.side == UIAnchor.Side.Bottom)
{
vector.x = x;
}
else
{
vector.x = this.mRect.xMin;
}
if (this.side == UIAnchor.Side.Top || this.side == UIAnchor.Side.TopRight || this.side == UIAnchor.Side.TopLeft)
{
vector.y = this.mRect.yMax;
}
else if (this.side == UIAnchor.Side.Left || this.side == UIAnchor.Side.Center || this.side == UIAnchor.Side.Right)
{
vector.y = y;
}
else
{
vector.y = this.mRect.yMin;
}
}
float width = this.mRect.width;
float height = this.mRect.height;
vector.x += this.pixelOffset.x + this.relativeOffset.x * width;
vector.y += this.pixelOffset.y + this.relativeOffset.y * height;
if (flag)
{
if (this.uiCamera.orthographic)
{
vector.x = Mathf.Round(vector.x);
vector.y = Mathf.Round(vector.y);
}
vector.z = this.uiCamera.WorldToScreenPoint(this.mTrans.position).z;
vector = this.uiCamera.ScreenToWorldPoint(vector);
}
else
{
vector.x = Mathf.Round(vector.x);
vector.y = Mathf.Round(vector.y);
if (uIPanel != null)
{
vector = uIPanel.cachedTransform.TransformPoint(vector);
}
else if (this.container != null)
{
Transform parent2 = this.container.transform.parent;
if (parent2 != null)
{
vector = parent2.TransformPoint(vector);
}
}
vector.z = this.mTrans.position.z;
}
if (this.mTrans.position != vector)
{
this.mTrans.position = vector;
}
if (this.runOnlyOnce && Application.isPlaying)
{
base.enabled = false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class UnionTests : EnumerableTests
{
private sealed class Modulo100EqualityComparer : IEqualityComparer<int?>
{
public bool Equals(int? x, int? y)
{
if (!x.HasValue) return !y.HasValue;
if (!y.HasValue) return false;
return x.GetValueOrDefault() % 100 == y.GetValueOrDefault() % 100;
}
public int GetHashCode(int? obj)
{
return obj.HasValue ? obj.GetValueOrDefault() % 100 + 1 : 0;
}
public override bool Equals(object obj)
{
// Equal to all other instances.
return obj is Modulo100EqualityComparer;
}
public override int GetHashCode()
{
return 0xAFFAB1E; // Any number as long as it's constant.
}
}
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q1 = from x1 in new int?[] { 2, 3, null, 2, null, 4, 5 }
select x1;
var q2 = from x2 in new int?[] { 1, 9, null, 4 }
select x2;
Assert.Equal(q1.Union(q2), q1.Union(q2));
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q1 = from x1 in new[] { "AAA", String.Empty, "q", "C", "#", "!@#$%^", "0987654321", "Calling Twice" }
select x1;
var q2 = from x2 in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS" }
select x2;
Assert.Equal(q1.Union(q2), q1.Union(q2));
}
[Fact]
public void SameResultsRepeatCallsMultipleUnions()
{
var q1 = from x1 in new int?[] { 2, 3, null, 2, null, 4, 5 }
select x1;
var q2 = from x2 in new int?[] { 1, 9, null, 4 }
select x2;
var q3 = from x3 in new int?[] { null, 8, 2, 2, 3 }
select x3;
Assert.Equal(q1.Union(q2).Union(q3), q1.Union(q2).Union(q3));
}
[Fact]
public void BothEmpty()
{
int[] first = { };
int[] second = { };
Assert.Empty(first.Union(second));
}
[Fact]
public void ManyEmpty()
{
int[] first = { };
int[] second = { };
int[] third = { };
int[] fourth = { };
Assert.Empty(first.Union(second).Union(third).Union(fourth));
}
[Fact]
public void CustomComparer()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = { "ttaM", "Charlie", "Bbo" };
string[] expected = { "Bob", "Robert", "Tim", "Matt", "Charlie" };
var comparer = new AnagramEqualityComparer();
Assert.Equal(expected, first.Union(second, comparer), comparer);
}
[Fact]
public void FirstNullCustomComparer()
{
string[] first = null;
string[] second = { "ttaM", "Charlie", "Bbo" };
var ane = Assert.Throws<ArgumentNullException>("first", () => first.Union(second, new AnagramEqualityComparer()));
}
[Fact]
public void SecondNullCustomComparer()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = null;
var ane = Assert.Throws<ArgumentNullException>("second", () => first.Union(second, new AnagramEqualityComparer()));
}
[Fact]
public void FirstNullNoComparer()
{
string[] first = null;
string[] second = { "ttaM", "Charlie", "Bbo" };
var ane = Assert.Throws<ArgumentNullException>("first", () => first.Union(second));
}
[Fact]
public void SecondNullNoComparer()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = null;
var ane = Assert.Throws<ArgumentNullException>("second", () => first.Union(second));
}
[Fact]
public void SingleNullWithEmpty()
{
string[] first = { null };
string[] second = new string[0];
string[] expected = { null };
Assert.Equal(expected, first.Union(second, EqualityComparer<string>.Default));
}
[Fact]
public void NullEmptyStringMix()
{
string[] first = { null, null, string.Empty };
string[] second = { null, null };
string[] expected = { null, string.Empty };
Assert.Equal(expected, first.Union(second, EqualityComparer<string>.Default));
}
[Fact]
public void DoubleNullWithEmpty()
{
string[] first = { null, null };
string[] second = new string[0];
string[] expected = { null };
Assert.Equal(expected, first.Union(second, EqualityComparer<string>.Default));
}
[Fact]
public void EmptyWithNonEmpty()
{
int[] first = { };
int[] second = { 2, 4, 5, 3, 2, 3, 9 };
int[] expected = { 2, 4, 5, 3, 9 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void NonEmptyWithEmpty()
{
int[] first = { 2, 4, 5, 3, 2, 3, 9 };
int[] second = { };
int[] expected = { 2, 4, 5, 3, 9 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void CommonElementsShared()
{
int[] first = { 1, 2, 3, 4, 5, 6 };
int[] second = { 6, 7, 7, 7, 8, 1 };
int[] expected = { 1, 2, 3, 4, 5, 6, 7, 8 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void SameElementRepeated()
{
int[] first = { 1, 1, 1, 1, 1, 1 };
int[] second = { 1, 1, 1, 1, 1, 1 };
int[] expected = { 1 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void RepeatedElementsWithSingleElement()
{
int[] first = { 1, 2, 3, 5, 3, 6 };
int[] second = { 7 };
int[] expected = { 1, 2, 3, 5, 6, 7 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void SingleWithAllUnique()
{
int?[] first = { 2 };
int?[] second = { 3, null, 4, 5 };
int?[] expected = { 2, 3, null, 4, 5 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void EachHasRepeatsBetweenAndAmongstThemselves()
{
int?[] first = { 1, 2, 3, 4, null, 5, 1 };
int?[] second = { 6, 2, 3, 4, 5, 6 };
int?[] expected = { 1, 2, 3, 4, null, 5, 6 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void EachHasRepeatsBetweenAndAmongstThemselvesMultipleUnions()
{
int?[] first = { 1, 2, 3, 4, null, 5, 1 };
int?[] second = { 6, 2, 3, 4, 5, 6 };
int?[] third = { 2, 8, 2, 3, 2, 8 };
int?[] fourth = { null, 1, 7, 2, 7 };
int?[] expected = { 1, 2, 3, 4, null, 5, 6, 8, 7 };
Assert.Equal(expected, first.Union(second).Union(third).Union(fourth));
}
[Fact]
public void MultipleUnionsCustomComparer()
{
int?[] first = { 1, 102, 903, 204, null, 5, 601 };
int?[] second = { 6, 202, 903, 204, 5, 106 };
int?[] third = { 2, 308, 2, 103, 802, 308 };
int?[] fourth = { null, 101, 207, 202, 207 };
int?[] expected = { 1, 102, 903, 204, null, 5, 6, 308, 207 };
Assert.Equal(expected, first.Union(second, new Modulo100EqualityComparer()).Union(third, new Modulo100EqualityComparer()).Union(fourth, new Modulo100EqualityComparer()));
}
[Fact]
public void MultipleUnionsDifferentComparers()
{
string[] first = { "Alpha", "Bravo", "Charlie", "Bravo", "Delta", "atleD", "ovarB" };
string[] second = { "Charlie", "Delta", "Echo", "Foxtrot", "Foxtrot", "choE" };
string[] third = { "trotFox", "Golf", "Alpha", "choE", "Tango" };
string[] plainThenAnagram = { "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Tango" };
string[] anagramThenPlain = { "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "trotFox", "Golf", "choE", "Tango" };
Assert.Equal(plainThenAnagram, first.Union(second).Union(third, new AnagramEqualityComparer()));
Assert.Equal(anagramThenPlain, first.Union(second, new AnagramEqualityComparer()).Union(third));
}
[Fact]
public void NullEqualityComparer()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = { "ttaM", "Charlie", "Bbo" };
string[] expected = { "Bob", "Robert", "Tim", "Matt", "miT", "ttaM", "Charlie", "Bbo" };
Assert.Equal(expected, first.Union(second, null));
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Union(Enumerable.Range(0, 3));
// Don't insist on this behaviour, but check its correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateMultipleUnions()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Union(Enumerable.Range(0, 3)).Union(Enumerable.Range(2, 4)).Union(new[] { 9, 2, 4 });
// Don't insist on this behaviour, but check its correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ToArray()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = { "ttaM", "Charlie", "Bbo" };
string[] expected = { "Bob", "Robert", "Tim", "Matt", "miT", "ttaM", "Charlie", "Bbo" };
Assert.Equal(expected, first.Union(second).ToArray());
}
[Fact]
public void ToArrayMultipleUnion()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = { "ttaM", "Charlie", "Bbo" };
string[] third = { "Bob", "Albert", "Tim" };
string[] expected = { "Bob", "Robert", "Tim", "Matt", "miT", "ttaM", "Charlie", "Bbo", "Albert" };
Assert.Equal(expected, first.Union(second).Union(third).ToArray());
}
[Fact]
public void ToList()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = { "ttaM", "Charlie", "Bbo" };
string[] expected = { "Bob", "Robert", "Tim", "Matt", "miT", "ttaM", "Charlie", "Bbo" };
Assert.Equal(expected, first.Union(second).ToList());
}
[Fact]
public void ToListMultipleUnion()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = { "ttaM", "Charlie", "Bbo" };
string[] third = { "Bob", "Albert", "Tim" };
string[] expected = { "Bob", "Robert", "Tim", "Matt", "miT", "ttaM", "Charlie", "Bbo", "Albert" };
Assert.Equal(expected, first.Union(second).Union(third).ToList());
}
[Fact]
public void Count()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = { "ttaM", "Charlie", "Bbo" };
Assert.Equal(8, first.Union(second).Count());
}
[Fact]
public void CountMultipleUnion()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = { "ttaM", "Charlie", "Bbo" };
string[] third = { "Bob", "Albert", "Tim" };
Assert.Equal(9, first.Union(second).Union(third).Count());
}
[Fact]
public void RepeatEnumerating()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = { "ttaM", "Charlie", "Bbo" };
var result = first.Union(second);
Assert.Equal(result, result);
}
[Fact]
public void RepeatEnumeratingMultipleUnions()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = { "ttaM", "Charlie", "Bbo" };
string[] third = { "Matt", "Albert", "Ichabod" };
var result = first.Union(second).Union(third);
Assert.Equal(result, result);
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudioTools.Project.Automation {
/// <summary>
/// Contains all of the properties of a given object that are contained in a generic collection of properties.
/// </summary>
[ComVisible(true)]
public class OAProperties : EnvDTE.Properties {
private NodeProperties target;
private Dictionary<string, EnvDTE.Property> properties = new Dictionary<string, EnvDTE.Property>();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public OAProperties(NodeProperties target) {
Utilities.ArgumentNotNull("target", target);
this.target = target;
this.AddPropertiesFromType(target.GetType());
}
/// <summary>
/// Defines the NodeProperties object that contains the defines the properties.
/// </summary>
public NodeProperties Target {
get {
return this.target;
}
}
#region EnvDTE.Properties
/// <summary>
/// Microsoft Internal Use Only.
/// </summary>
public virtual object Application {
get { return null; }
}
/// <summary>
/// Gets a value indicating the number of objects in the collection.
/// </summary>
public int Count {
get { return properties.Count; }
}
/// <summary>
/// Gets the top-level extensibility object.
/// </summary>
public virtual EnvDTE.DTE DTE {
get {
if (this.target.HierarchyNode == null || this.target.HierarchyNode.ProjectMgr == null || this.target.HierarchyNode.ProjectMgr.IsClosed ||
this.target.HierarchyNode.ProjectMgr.Site == null) {
throw new InvalidOperationException();
}
return this.target.HierarchyNode.ProjectMgr.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
}
}
/// <summary>
/// Gets an enumeration for items in a collection.
/// </summary>
/// <returns>An enumerator. </returns>
public IEnumerator GetEnumerator() {
if (this.properties.Count == 0) {
yield return new OANullProperty(this);
}
IEnumerator enumerator = this.properties.Values.GetEnumerator();
while (enumerator.MoveNext()) {
yield return enumerator.Current;
}
}
/// <summary>
/// Returns an indexed member of a Properties collection.
/// </summary>
/// <param name="index">The index at which to return a member.</param>
/// <returns>A Property object.</returns>
public virtual EnvDTE.Property Item(object index) {
if (index is string) {
string indexAsString = (string)index;
if (this.properties.ContainsKey(indexAsString)) {
return this.properties[indexAsString];
}
} else if (index is int) {
int realIndex = (int)index - 1;
if (realIndex >= 0 && realIndex < this.properties.Count) {
IEnumerator enumerator = this.properties.Values.GetEnumerator();
int i = 0;
while (enumerator.MoveNext()) {
if (i++ == realIndex) {
return (EnvDTE.Property)enumerator.Current;
}
}
}
}
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "index");
}
/// <summary>
/// Gets the immediate parent object of a Properties collection.
/// </summary>
public virtual object Parent {
get { return null; }
}
#endregion
#region methods
/// <summary>
/// Add properties to the collection of properties filtering only those properties which are com-visible and AutomationBrowsable
/// </summary>
/// <param name="targetType">The type of NodeProperties the we should filter on</param>
private void AddPropertiesFromType(Type targetType) {
Utilities.ArgumentNotNull("targetType", targetType);
// If the type is not COM visible, we do not expose any of the properties
if (!IsComVisible(targetType)) {
return;
}
// Add all properties being ComVisible and AutomationVisible
PropertyInfo[] propertyInfos = targetType.GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos) {
if (!IsInMap(propertyInfo) && IsComVisible(propertyInfo) && IsAutomationVisible(propertyInfo)) {
AddProperty(propertyInfo);
}
}
}
#endregion
#region virtual methods
/// <summary>
/// Creates a new OAProperty object and adds it to the current list of properties
/// </summary>
/// <param name="propertyInfo">The property to be associated with an OAProperty object</param>
private void AddProperty(PropertyInfo propertyInfo) {
var attrs = propertyInfo.GetCustomAttributes(typeof(PropertyNameAttribute), false);
string name = propertyInfo.Name;
if (attrs.Length > 0) {
name = ((PropertyNameAttribute)attrs[0]).Name;
}
this.properties.Add(name, new OAProperty(this, propertyInfo));
}
#endregion
#region helper methods
private bool IsInMap(PropertyInfo propertyInfo) {
return this.properties.ContainsKey(propertyInfo.Name);
}
private static bool IsAutomationVisible(PropertyInfo propertyInfo) {
object[] customAttributesOnProperty = propertyInfo.GetCustomAttributes(typeof(AutomationBrowsableAttribute), true);
foreach (AutomationBrowsableAttribute attr in customAttributesOnProperty) {
if (!attr.Browsable) {
return false;
}
}
return true;
}
private static bool IsComVisible(Type targetType) {
object[] customAttributesOnProperty = targetType.GetCustomAttributes(typeof(ComVisibleAttribute), true);
foreach (ComVisibleAttribute attr in customAttributesOnProperty) {
if (!attr.Value) {
return false;
}
}
return true;
}
private static bool IsComVisible(PropertyInfo propertyInfo) {
object[] customAttributesOnProperty = propertyInfo.GetCustomAttributes(typeof(ComVisibleAttribute), true);
foreach (ComVisibleAttribute attr in customAttributesOnProperty) {
if (!attr.Value) {
return false;
}
}
return true;
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Contexts
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
[Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
public class MappedDiagnosticsLogicalContextTests
{
public MappedDiagnosticsLogicalContextTests()
{
MappedDiagnosticsLogicalContext.Clear();
}
[Fact]
public void given_item_exists_when_getting_item_should_return_item_for_objecttype_2()
{
string key = "testKey1";
object value = 5;
MappedDiagnosticsLogicalContext.Set(key, value);
string expected = "5";
string actual = MappedDiagnosticsLogicalContext.Get(key);
Assert.Equal(expected, actual);
}
[Fact]
public void given_item_exists_when_getting_item_should_return_item_for_objecttype()
{
string key = "testKey2";
object value = DateTime.Now;
MappedDiagnosticsLogicalContext.Set(key, value);
object actual = MappedDiagnosticsLogicalContext.GetObject(key);
Assert.Equal(value, actual);
}
[Fact]
public void given_no_item_exists_when_getting_item_should_return_null()
{
Assert.Null(MappedDiagnosticsLogicalContext.GetObject("itemThatShouldNotExist"));
}
[Fact]
public void given_no_item_exists_when_getting_item_should_return_empty_string()
{
Assert.Empty(MappedDiagnosticsLogicalContext.Get("itemThatShouldNotExist"));
}
[Fact]
public void given_item_exists_when_getting_item_should_return_item()
{
const string key = "Key";
const string item = "Item";
MappedDiagnosticsLogicalContext.Set(key, item);
Assert.Equal(item, MappedDiagnosticsLogicalContext.Get(key));
}
[Fact]
public void given_item_does_not_exist_when_setting_item_should_contain_item()
{
const string key = "Key";
const string item = "Item";
MappedDiagnosticsLogicalContext.Set(key, item);
Assert.True(MappedDiagnosticsLogicalContext.Contains(key));
}
[Fact]
public void given_item_exists_when_setting_item_should_not_throw()
{
const string key = "Key";
const string item = "Item";
MappedDiagnosticsLogicalContext.Set(key, item);
var exRecorded = Record.Exception(() => MappedDiagnosticsLogicalContext.Set(key, item));
Assert.Null(exRecorded);
}
[Fact]
public void given_item_exists_when_setting_item_should_update_item()
{
const string key = "Key";
const string item = "Item";
const string newItem = "NewItem";
MappedDiagnosticsLogicalContext.Set(key, item);
MappedDiagnosticsLogicalContext.Set(key, newItem);
Assert.Equal(newItem, MappedDiagnosticsLogicalContext.Get(key));
}
[Fact]
public void given_no_item_exists_when_getting_items_should_return_empty_collection()
{
Assert.Equal(0, MappedDiagnosticsLogicalContext.GetNames().Count);
}
[Fact]
public void given_item_exists_when_getting_items_should_return_that_item()
{
const string key = "Key";
MappedDiagnosticsLogicalContext.Set(key, "Item");
Assert.Equal(1, MappedDiagnosticsLogicalContext.GetNames().Count);
Assert.True(MappedDiagnosticsLogicalContext.GetNames().Contains("Key"));
}
[Fact]
public void given_item_exists_after_removing_item_when_getting_items_should_not_contain_item()
{
const string keyThatRemains1 = "Key1";
const string keyThatRemains2 = "Key2";
const string keyThatIsRemoved = "KeyR";
MappedDiagnosticsLogicalContext.Set(keyThatRemains1, "7");
MappedDiagnosticsLogicalContext.Set(keyThatIsRemoved, 7);
MappedDiagnosticsLogicalContext.Set(keyThatRemains2, 8);
MappedDiagnosticsLogicalContext.Remove(keyThatIsRemoved);
Assert.Equal(2, MappedDiagnosticsLogicalContext.GetNames().Count);
Assert.False(MappedDiagnosticsLogicalContext.GetNames().Contains(keyThatIsRemoved));
}
[Fact]
public void given_item_does_not_exist_when_checking_if_context_contains_should_return_false()
{
Assert.False(MappedDiagnosticsLogicalContext.Contains("keyForItemThatDoesNotExist"));
}
[Fact]
public void given_item_exists_when_checking_if_context_contains_should_return_true()
{
const string key = "Key";
MappedDiagnosticsLogicalContext.Set(key, "Item");
Assert.True(MappedDiagnosticsLogicalContext.Contains(key));
}
[Fact]
public void given_item_exists_when_removing_item_should_not_contain_item()
{
const string keyForItemThatShouldExist = "Key";
const string itemThatShouldExist = "Item";
MappedDiagnosticsLogicalContext.Set(keyForItemThatShouldExist, itemThatShouldExist);
MappedDiagnosticsLogicalContext.Remove(keyForItemThatShouldExist);
Assert.False(MappedDiagnosticsLogicalContext.Contains(keyForItemThatShouldExist));
}
[Fact]
public void given_item_does_not_exist_when_removing_item_should_not_throw()
{
const string keyForItemThatShouldExist = "Key";
var exRecorded = Record.Exception(() => MappedDiagnosticsLogicalContext.Remove(keyForItemThatShouldExist));
Assert.Null(exRecorded);
}
[Fact]
public void given_item_does_not_exist_when_clearing_should_not_throw()
{
var exRecorded = Record.Exception(() => MappedDiagnosticsLogicalContext.Clear());
Assert.Null(exRecorded);
}
[Fact]
public void given_item_exists_when_clearing_should_not_contain_item()
{
const string key = "Key";
MappedDiagnosticsLogicalContext.Set(key, "Item");
MappedDiagnosticsLogicalContext.Clear();
Assert.False(MappedDiagnosticsLogicalContext.Contains(key));
}
[Fact]
public void given_multiple_threads_running_asynchronously_when_setting_and_getting_values_should_return_thread_specific_values()
{
const string key = "Key";
const string valueForLogicalThread1 = "ValueForTask1";
const string valueForLogicalThread2 = "ValueForTask2";
const string valueForLogicalThread3 = "ValueForTask3";
MappedDiagnosticsLogicalContext.Clear(true);
var task1 = Task.Factory.StartNew(() => {
MappedDiagnosticsLogicalContext.Set(key, valueForLogicalThread1);
return MappedDiagnosticsLogicalContext.Get(key);
});
var task2 = Task.Factory.StartNew(() => {
MappedDiagnosticsLogicalContext.Set(key, valueForLogicalThread2);
return MappedDiagnosticsLogicalContext.Get(key);
});
var task3 = Task.Factory.StartNew(() => {
MappedDiagnosticsLogicalContext.Set(key, valueForLogicalThread3);
return MappedDiagnosticsLogicalContext.Get(key);
});
Task.WaitAll(task1, task2, task3);
Assert.Equal(valueForLogicalThread1, task1.Result);
Assert.Equal(valueForLogicalThread2, task2.Result);
Assert.Equal(valueForLogicalThread3, task3.Result);
}
[Fact]
public void parent_thread_assigns_different_values_to_childs()
{
const string parentKey = "ParentKey";
const string parentValueForLogicalThread1 = "Parent1";
const string parentValueForLogicalThread2 = "Parent2";
const string childKey = "ChildKey";
const string valueForChildThread1 = "Child1";
const string valueForChildThread2 = "Child2";
MappedDiagnosticsLogicalContext.Clear(true);
var exitAllTasks = new ManualResetEvent(false);
MappedDiagnosticsLogicalContext.Set(parentKey, parentValueForLogicalThread1);
var task1 = Task.Factory.StartNew(() =>
{
MappedDiagnosticsLogicalContext.Set(childKey, valueForChildThread1);
exitAllTasks.WaitOne();
return MappedDiagnosticsLogicalContext.Get(parentKey) + "," + MappedDiagnosticsLogicalContext.Get(childKey);
});
MappedDiagnosticsLogicalContext.Set(parentKey, parentValueForLogicalThread2);
var task2 = Task.Factory.StartNew(() =>
{
MappedDiagnosticsLogicalContext.Set(childKey, valueForChildThread2);
exitAllTasks.WaitOne();
return MappedDiagnosticsLogicalContext.Get(parentKey) + "," + MappedDiagnosticsLogicalContext.Get(childKey);
});
exitAllTasks.Set();
Task.WaitAll(task1, task2);
Assert.Equal(parentValueForLogicalThread1 + "," + valueForChildThread1, task1.Result);
Assert.Equal(parentValueForLogicalThread2 + "," + valueForChildThread2, task2.Result);
}
[Fact]
public void timer_cannot_inherit_mappedcontext()
{
const string parentKey = nameof(timer_cannot_inherit_mappedcontext);
const string parentValueForLogicalThread1 = "Parent1";
object getObject = null;
string getValue = null;
var mre = new ManualResetEvent(false);
Timer thread = new Timer((s) =>
{
try
{
getObject = MappedDiagnosticsLogicalContext.GetObject(parentKey);
getValue = MappedDiagnosticsLogicalContext.Get(parentKey);
}
finally
{
mre.Set();
}
});
MappedDiagnosticsLogicalContext.Clear(true);
MappedDiagnosticsLogicalContext.Set(parentKey, parentValueForLogicalThread1);
thread.Change(0, Timeout.Infinite);
mre.WaitOne();
Assert.Null(getObject);
Assert.Empty(getValue);
}
[Fact]
public void disposable_removes_item()
{
const string itemNotRemovedKey = "itemNotRemovedKey";
const string itemRemovedKey = "itemRemovedKey";
MappedDiagnosticsLogicalContext.Clear();
MappedDiagnosticsLogicalContext.Set(itemNotRemovedKey, "itemNotRemoved");
using (MappedDiagnosticsLogicalContext.SetScoped(itemRemovedKey, "itemRemoved"))
{
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, itemRemovedKey });
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey });
}
[Fact]
public void dispose_is_idempotent()
{
const string itemKey = "itemKey";
MappedDiagnosticsLogicalContext.Clear();
IDisposable disposable = MappedDiagnosticsLogicalContext.SetScoped(itemKey, "item1");
disposable.Dispose();
Assert.False(MappedDiagnosticsLogicalContext.Contains(itemKey));
//This item shouldn't be removed since it is not the disposable one
MappedDiagnosticsLogicalContext.Set(itemKey, "item2");
disposable.Dispose();
Assert.True(MappedDiagnosticsLogicalContext.Contains(itemKey));
}
#if !NET35 && !NET40
[Fact]
public void disposable_multiple_items()
{
const string itemNotRemovedKey = "itemNotRemovedKey";
const string item1Key = "item1Key";
const string item2Key = "item2Key";
const string item3Key = "item3Key";
const string item4Key = "item4Key";
MappedDiagnosticsLogicalContext.Clear();
MappedDiagnosticsLogicalContext.Set(itemNotRemovedKey, "itemNotRemoved");
using (MappedDiagnosticsLogicalContext.SetScoped(new[]
{
new KeyValuePair<string, object>(item1Key, "1"),
new KeyValuePair<string, object>(item2Key, "2")
}))
{
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, item1Key, item2Key });
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey });
using (MappedDiagnosticsLogicalContext.SetScoped(new[]
{
new KeyValuePair<string, object>(item1Key, "1"),
new KeyValuePair<string, object>(item2Key, "2"),
new KeyValuePair<string, object>(item3Key, "3"),
new KeyValuePair<string, object>(item4Key, "4")
}))
{
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, item1Key, item2Key, item3Key, item4Key });
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey });
}
[Fact]
public void disposable_multiple_items_with_restore()
{
const string itemNotRemovedKey = "itemNotRemovedKey";
const string item1Key = "item1Key";
const string item2Key = "item2Key";
const string item3Key = "item3Key";
const string item4Key = "item4Key";
MappedDiagnosticsLogicalContext.Clear();
MappedDiagnosticsLogicalContext.Set(itemNotRemovedKey, "itemNotRemoved");
using (MappedDiagnosticsLogicalContext.SetScoped(new[]
{
new KeyValuePair<string, object>(item1Key, "1"),
new KeyValuePair<string, object>(item2Key, "2")
}))
{
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, item1Key, item2Key });
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey });
using (MappedDiagnosticsLogicalContext.SetScoped(new[]
{
new KeyValuePair<string, object>(item1Key, "1"),
new KeyValuePair<string, object>(item2Key, "2"),
new KeyValuePair<string, object>(item3Key, "3"),
new KeyValuePair<string, object>(item4Key, "4")
}))
{
using (var itemRemover = MappedDiagnosticsLogicalContext.SetScoped(new[]
{
new KeyValuePair<string, object>(item1Key, "111")
}))
{
Assert.Equal("111", MappedDiagnosticsLogicalContext.Get(item1Key));
}
using (MappedDiagnosticsLogicalContext.SetScoped(new[]
{
new KeyValuePair<string, object>(item1Key, "01"),
new KeyValuePair<string, object>(item2Key, "02"),
new KeyValuePair<string, object>(item3Key, "03"),
new KeyValuePair<string, object>(item4Key, "04")
}))
{
Assert.Equal("itemNotRemoved", MappedDiagnosticsLogicalContext.Get(itemNotRemovedKey));
Assert.Equal("01", MappedDiagnosticsLogicalContext.Get(item1Key));
Assert.Equal("02", MappedDiagnosticsLogicalContext.Get(item2Key));
Assert.Equal("03", MappedDiagnosticsLogicalContext.Get(item3Key));
Assert.Equal("04", MappedDiagnosticsLogicalContext.Get(item4Key));
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[]
{
itemNotRemovedKey, item1Key, item2Key, item3Key, item4Key
});
Assert.Equal("itemNotRemoved", MappedDiagnosticsLogicalContext.Get(itemNotRemovedKey));
Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(item1Key));
Assert.Equal("2", MappedDiagnosticsLogicalContext.Get(item2Key));
Assert.Equal("3", MappedDiagnosticsLogicalContext.Get(item3Key));
Assert.Equal("4", MappedDiagnosticsLogicalContext.Get(item4Key));
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey });
}
[Fact]
public void disposable_fast_clear_multiple_items()
{
const string item1Key = "item1Key";
const string item2Key = "item2Key";
const string item3Key = "item3Key";
const string item4Key = "item4Key";
MappedDiagnosticsLogicalContext.Clear();
using (MappedDiagnosticsLogicalContext.SetScoped(new[]
{
new KeyValuePair<string, object>(item1Key, "1"),
new KeyValuePair<string, object>(item2Key, "2")
}))
{
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { item1Key, item2Key });
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new string[] { });
using (MappedDiagnosticsLogicalContext.SetScoped(new[]
{
new KeyValuePair<string, object>(item1Key, "1"),
new KeyValuePair<string, object>(item2Key, "2"),
new KeyValuePair<string, object>(item3Key, "3"),
new KeyValuePair<string, object>(item4Key, "4")
}))
{
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { item1Key, item2Key, item3Key, item4Key });
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new string[] { });
}
#endif
[Fact]
public void given_multiple_set_invocations_mdlc_persists_only_last_value()
{
const string key = "key";
MappedDiagnosticsLogicalContext.Set(key, "1");
Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key));
MappedDiagnosticsLogicalContext.Set(key, 2);
MappedDiagnosticsLogicalContext.Set(key, "3");
Assert.Equal("3", MappedDiagnosticsLogicalContext.Get(key));
MappedDiagnosticsLogicalContext.Remove(key);
Assert.True(string.IsNullOrEmpty(MappedDiagnosticsLogicalContext.Get(key)));
}
[Fact]
public void given_multiple_setscoped_with_restore_invocations_mdlc_persists_all_values()
{
const string key = "key";
using (MappedDiagnosticsLogicalContext.SetScoped(key, "1"))
{
Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key));
using (MappedDiagnosticsLogicalContext.SetScoped(key, 2))
{
Assert.Equal(2.ToString(), MappedDiagnosticsLogicalContext.Get(key));
using (MappedDiagnosticsLogicalContext.SetScoped(key, null))
{
Assert.True(string.IsNullOrEmpty(MappedDiagnosticsLogicalContext.Get(key)));
}
Assert.Equal(2.ToString(), MappedDiagnosticsLogicalContext.Get(key));
}
Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key));
}
Assert.True(string.IsNullOrEmpty(MappedDiagnosticsLogicalContext.Get(key)));
}
[Fact]
public void given_multiple_multikey_setscoped_with_restore_invocations_mdlc_persists_all_values()
{
const string key1 = "key1";
const string key2 = "key2";
const string key3 = "key3";
using (MappedDiagnosticsLogicalContext.SetScoped(key1, "1"))
{
Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key1));
using (MappedDiagnosticsLogicalContext.SetScoped(key2, 2))
{
using (MappedDiagnosticsLogicalContext.SetScoped(key3, 3))
{
using (MappedDiagnosticsLogicalContext.SetScoped(key2, 22))
{
Assert.Equal(22.ToString(), MappedDiagnosticsLogicalContext.Get(key2));
}
Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key1));
Assert.Equal(2.ToString(), MappedDiagnosticsLogicalContext.Get(key2));
Assert.Equal(3.ToString(), MappedDiagnosticsLogicalContext.Get(key3));
}
}
Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key1));
}
Assert.True(string.IsNullOrEmpty(MappedDiagnosticsLogicalContext.Get(key1)));
}
[Fact]
public void given_multiple_multikey_setscoped_with_restore_invocations_dispose_differs_than_remove()
{
const string key1 = "key1";
const string key2 = "key2";
const string key3 = "key3";
var k1d = MappedDiagnosticsLogicalContext.SetScoped(key1, "1");
Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key1));
var k2d = MappedDiagnosticsLogicalContext.SetScoped(key2, 2);
var k3d = MappedDiagnosticsLogicalContext.SetScoped(key3, 3);
var k2d2 = MappedDiagnosticsLogicalContext.SetScoped(key2, 22);
Assert.Equal(22.ToString(), MappedDiagnosticsLogicalContext.Get(key2));
MappedDiagnosticsLogicalContext.Remove(key2);
Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key1));
Assert.NotEqual(2.ToString(), MappedDiagnosticsLogicalContext.Get(key2));
Assert.Equal(3.ToString(), MappedDiagnosticsLogicalContext.Get(key3));
MappedDiagnosticsLogicalContext.Remove(key3);
MappedDiagnosticsLogicalContext.Remove(key2);
Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key1));
MappedDiagnosticsLogicalContext.Remove(key1);
Assert.True(string.IsNullOrEmpty(MappedDiagnosticsLogicalContext.Get(key1)));
}
[Fact]
public void given_multiple_setscoped_with_restore_invocations_set_reset_value_stack()
{
const string key = "key";
using (MappedDiagnosticsLogicalContext.SetScoped(key, "1"))
{
using (MappedDiagnosticsLogicalContext.SetScoped(key, 2))
{
using (MappedDiagnosticsLogicalContext.SetScoped(key, 3))
{
Assert.Equal(3.ToString(), MappedDiagnosticsLogicalContext.Get(key));
}
// 'Set' does not reset that history of 'SetScoped'
MappedDiagnosticsLogicalContext.Set(key, "x");
Assert.Equal("x", MappedDiagnosticsLogicalContext.Get(key));
}
// Disposing will bring back previous value despite being overriden by 'Set'
Assert.Equal(1.ToString(), MappedDiagnosticsLogicalContext.Get(key));
}
Assert.True(string.IsNullOrEmpty(MappedDiagnosticsLogicalContext.Get(key)));
}
[Fact]
public void given_multiple_threads_running_asynchronously_when_setting_and_getting_values_setscoped_with_restore_should_return_thread_specific_values()
{
const string key = "Key";
const string initValue = "InitValue";
const string valueForLogicalThread1 = "ValueForTask1";
const string valueForLogicalThread1Next = "ValueForTask1Next";
const string valueForLogicalThread2 = "ValueForTask2";
const string valueForLogicalThread3 = "ValueForTask3";
MappedDiagnosticsLogicalContext.Clear(true);
MappedDiagnosticsLogicalContext.Set(key, initValue);
Assert.Equal(initValue, MappedDiagnosticsLogicalContext.Get(key));
var task1 = Task.Factory.StartNew(async () => {
MappedDiagnosticsLogicalContext.SetScoped(key, valueForLogicalThread1);
await Task.Delay(0).ConfigureAwait(false);
MappedDiagnosticsLogicalContext.SetScoped(key, valueForLogicalThread1Next);
return MappedDiagnosticsLogicalContext.Get(key);
});
var task2 = Task.Factory.StartNew(() => {
MappedDiagnosticsLogicalContext.SetScoped(key, valueForLogicalThread2);
return MappedDiagnosticsLogicalContext.Get(key);
});
var task3 = Task.Factory.StartNew(() => {
MappedDiagnosticsLogicalContext.SetScoped(key, valueForLogicalThread3);
return MappedDiagnosticsLogicalContext.Get(key);
});
Task.WaitAll(task1, task2, task3);
Assert.Equal(valueForLogicalThread1Next, task1.Result.Result);
Assert.Equal(valueForLogicalThread2, task2.Result);
Assert.Equal(valueForLogicalThread3, task3.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;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class TransactionTest
{
[Fact]
public void TestYukon()
{
new TransactionTestWorker(DataTestClass.SQL2005_Northwind + ";multipleactiveresultsets=true;").StartTest();
}
[Fact]
public void TestKatmai()
{
new TransactionTestWorker(DataTestClass.SQL2008_Northwind + ";multipleactiveresultsets=true;").StartTest();
}
}
internal class TransactionTestWorker
{
private static string s_tempTableName1 = string.Format("TEST_{0}{1}{2}", Environment.GetEnvironmentVariable("ComputerName"), Environment.TickCount, Guid.NewGuid()).Replace('-', '_');
private static string s_tempTableName2 = s_tempTableName1 + "_2";
private string _connectionString;
public TransactionTestWorker(string connectionString)
{
_connectionString = connectionString;
}
public void StartTest()
{
try
{
PrepareTables();
CommitTransactionTest();
ResetTables();
RollbackTransactionTest();
ResetTables();
ScopedTransactionTest();
ResetTables();
ExceptionTest();
ResetTables();
ReadUncommitedIsolationLevel_ShouldReturnUncommitedData();
ResetTables();
ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction();
ResetTables();
}
finally
{
//make sure to clean up
DropTempTables();
}
}
private void PrepareTables()
{
using (var conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand command = new SqlCommand(string.Format("CREATE TABLE [{0}]([CustomerID] [nchar](5) NOT NULL PRIMARY KEY, [CompanyName] [nvarchar](40) NOT NULL, [ContactName] [nvarchar](30) NULL)", s_tempTableName1), conn);
command.ExecuteNonQuery();
command.CommandText = "create table " + s_tempTableName2 + "(col1 int, col2 varchar(32))";
command.ExecuteNonQuery();
}
}
private void DropTempTables()
{
using (var conn = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand(
string.Format("DROP TABLE [{0}]; DROP TABLE [{1}]", s_tempTableName1, s_tempTableName2), conn);
conn.Open();
command.ExecuteNonQuery();
}
}
public void ResetTables()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(string.Format("TRUNCATE TABLE [{0}]; TRUNCATE TABLE [{1}]", s_tempTableName1, s_tempTableName2), connection))
{
command.ExecuteNonQuery();
}
}
}
private void CommitTransactionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand("select * from " + s_tempTableName1 + " where CustomerID='ZYXWV'", connection);
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
command.Transaction = tx;
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
}
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + s_tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command2.ExecuteNonQuery();
}
tx.Commit();
using (SqlDataReader reader = command.ExecuteReader())
{
int count = 0;
while (reader.Read()) { count++; }
Assert.True(count == 1, "Error: incorrect number of rows in table after update.");
Assert.Equal(count, 1);
}
}
}
private void RollbackTransactionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand("select * from " + s_tempTableName1 + " where CustomerID='ZYXWV'",
connection);
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
command.Transaction = tx;
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
}
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + s_tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command2.ExecuteNonQuery();
}
tx.Rollback();
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error Rollback Test : incorrect number of rows in table after rollback.");
int count = 0;
while (reader.Read()) count++;
Assert.Equal(count, 0);
}
connection.Close();
}
}
private void ScopedTransactionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand("select * from " + s_tempTableName1 + " where CustomerID='ZYXWV'",
connection);
connection.Open();
SqlTransaction tx = connection.BeginTransaction("transName");
command.Transaction = tx;
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
}
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + s_tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command2.ExecuteNonQuery();
}
tx.Save("saveName");
//insert another one
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + s_tempTableName1 + " VALUES ( 'ZYXW2', 'XY2', 'KK' );";
command2.ExecuteNonQuery();
}
tx.Rollback("saveName");
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.True(reader.HasRows, "Error Scoped Transaction Test : incorrect number of rows in table after rollback to save state one.");
int count = 0;
while (reader.Read()) count++;
Assert.Equal(count, 1);
}
tx.Rollback();
connection.Close();
}
}
private void ExceptionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
string invalidSaveStateMessage = SystemDataResourceManager.Instance.SQL_NullEmptyTransactionName;
string executeCommandWithoutTransactionMessage = SystemDataResourceManager.Instance.ADP_TransactionRequired("ExecuteNonQuery");
string transactionConflictErrorMessage = SystemDataResourceManager.Instance.ADP_TransactionConnectionMismatch;
string parallelTransactionErrorMessage = SystemDataResourceManager.Instance.ADP_ParallelTransactionsNotSupported("SqlConnection");
AssertException<InvalidOperationException>(() =>
{
SqlCommand command = new SqlCommand("sql", connection);
command.ExecuteNonQuery();
}, executeCommandWithoutTransactionMessage);
AssertException<InvalidOperationException>(() =>
{
SqlConnection con1 = new SqlConnection(_connectionString);
con1.Open();
SqlCommand command = new SqlCommand("sql", con1);
command.Transaction = tx;
command.ExecuteNonQuery();
}, transactionConflictErrorMessage);
AssertException<InvalidOperationException>(() =>
{
connection.BeginTransaction(null);
}, parallelTransactionErrorMessage);
AssertException<InvalidOperationException>(() =>
{
connection.BeginTransaction("");
}, parallelTransactionErrorMessage);
AssertException<ArgumentException>(() =>
{
tx.Rollback(null);
}, invalidSaveStateMessage);
AssertException<ArgumentException>(() =>
{
tx.Rollback("");
}, invalidSaveStateMessage);
AssertException<ArgumentException>(() =>
{
tx.Save(null);
}, invalidSaveStateMessage);
AssertException<ArgumentException>(() =>
{
tx.Save("");
}, invalidSaveStateMessage);
}
}
public static void AssertException<T>(Action action, string expectedErrorMessage) where T : Exception
{
var exception = Assert.Throws<T>(action);
Assert.Equal(exception.Message, expectedErrorMessage);
}
private void ReadUncommitedIsolationLevel_ShouldReturnUncommitedData()
{
using (SqlConnection connection1 = new SqlConnection(_connectionString))
{
connection1.Open();
SqlTransaction tx1 = connection1.BeginTransaction();
using (SqlCommand command1 = connection1.CreateCommand())
{
command1.Transaction = tx1;
command1.CommandText = "INSERT INTO " + s_tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command1.ExecuteNonQuery();
}
using (SqlConnection connection2 = new SqlConnection(_connectionString))
{
SqlCommand command2 =
new SqlCommand("select * from " + s_tempTableName1 + " where CustomerID='ZYXWV'",
connection2);
connection2.Open();
SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadUncommitted);
command2.Transaction = tx2;
using (SqlDataReader reader = command2.ExecuteReader())
{
int count = 0;
while (reader.Read()) count++;
Assert.True(count == 1, "Should Expected 1 row because Isolation Level is read uncommitted which should return uncommitted data.");
}
tx2.Rollback();
connection2.Close();
}
tx1.Rollback();
connection1.Close();
}
}
private void ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction()
{
using (SqlConnection connection1 = new SqlConnection(_connectionString))
{
connection1.Open();
SqlTransaction tx1 = connection1.BeginTransaction();
using (SqlCommand command1 = connection1.CreateCommand())
{
command1.Transaction = tx1;
command1.CommandText = "INSERT INTO " + s_tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command1.ExecuteNonQuery();
}
using (SqlConnection connection2 = new SqlConnection(_connectionString))
{
SqlCommand command2 =
new SqlCommand("select * from " + s_tempTableName1 + " where CustomerID='ZYXWV'",
connection2);
connection2.Open();
SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadCommitted);
command2.Transaction = tx2;
AssertException<SqlException>(() => command2.ExecuteReader(), SystemDataResourceManager.Instance.SQL_Timeout as string);
tx2.Rollback();
connection2.Close();
}
tx1.Rollback();
connection1.Close();
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Security;
using System.Windows;
using MS.Internal;
namespace System.Windows.Controls
{
/// <summary>
/// Converts instances of various types to and from DataGridLength.
/// </summary>
public class DataGridLengthConverter : TypeConverter
{
/// <summary>
/// Checks whether or not this class can convert from a given type.
/// </summary>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
// We can only handle strings, integral and floating types
TypeCode tc = Type.GetTypeCode(sourceType);
switch (tc)
{
case TypeCode.String:
case TypeCode.Decimal:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Byte:
return true;
default:
return false;
}
}
/// <summary>
/// Checks whether or not this class can convert to a given type.
/// </summary>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return (destinationType == typeof(string)) || (destinationType == typeof(InstanceDescriptor));
}
/// <summary>
/// Attempts to convert to a DataGridLength from the given object.
/// </summary>
/// <param name="context">The ITypeDescriptorContext for this call.</param>
/// <param name="culture">The CultureInfo which is respected when converting.</param>
/// <param name="value">The object to convert to a DataGridLength.</param>
/// <returns>The DataGridLength instance which was constructed.</returns>
/// <exception cref="ArgumentNullException">
/// An ArgumentNullException is thrown if the source is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An ArgumentException is thrown if the source is not null
/// and is not a valid type which can be converted to a DataGridLength.
/// </exception>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value != null)
{
string stringSource = value as string;
if (stringSource != null)
{
// Convert from string
return ConvertFromString(stringSource, culture);
}
else
{
// Conversion from numeric type
DataGridLengthUnitType type;
double doubleValue = Convert.ToDouble(value, culture);
if (DoubleUtil.IsNaN(doubleValue))
{
// This allows for conversion from Width / Height = "Auto"
doubleValue = 1.0;
type = DataGridLengthUnitType.Auto;
}
else
{
type = DataGridLengthUnitType.Pixel;
}
if (!Double.IsInfinity(doubleValue))
{
return new DataGridLength(doubleValue, type);
}
}
}
// The default exception to throw in ConvertFrom
throw GetConvertFromException(value);
}
/// <summary>
/// Attempts to convert a DataGridLength instance to the given type.
/// </summary>
/// <param name="context">The ITypeDescriptorContext for this call.</param>
/// <param name="culture">The CultureInfo which is respected when converting.</param>
/// <param name="value">The DataGridLength to convert.</param>
/// <param name="destinationType">The type to which to convert the DataGridLength instance.</param>
/// <returns>
/// The object which was constructed.
/// </returns>
/// <exception cref="ArgumentNullException">
/// An ArgumentNullException is thrown if the value is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An ArgumentException is thrown if the value is not null and is not a DataGridLength,
/// or if the destinationType isn't one of the valid destination types.
/// </exception>
/// <SecurityNote>
/// Critical: calls InstanceDescriptor ctor which LinkDemands
/// PublicOK: can only make an InstanceDescriptor for DataGridLength, not an arbitrary class
/// </SecurityNote>
[SecurityCritical]
public override object ConvertTo(
ITypeDescriptorContext context,
CultureInfo culture,
object value,
Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException("destinationType");
}
if ((value != null) && (value is DataGridLength))
{
DataGridLength length = (DataGridLength)value;
if (destinationType == typeof(string))
{
return ConvertToString(length, culture);
}
if (destinationType == typeof(InstanceDescriptor))
{
ConstructorInfo ci = typeof(DataGridLength).GetConstructor(new Type[] { typeof(double), typeof(DataGridLengthUnitType) });
return new InstanceDescriptor(ci, new object[] { length.Value, length.UnitType });
}
}
// The default exception to throw from ConvertTo
throw GetConvertToException(value, destinationType);
}
/// <summary>
/// Converts a DataGridLength instance to a String given the CultureInfo.
/// </summary>
/// <param name="gl">DataGridLength instance to convert.</param>
/// <param name="cultureInfo">The culture to use.</param>
/// <returns>String representation of the object.</returns>
internal static string ConvertToString(DataGridLength length, CultureInfo cultureInfo)
{
switch (length.UnitType)
{
case DataGridLengthUnitType.Auto:
case DataGridLengthUnitType.SizeToCells:
case DataGridLengthUnitType.SizeToHeader:
return length.UnitType.ToString();
// Star has one special case when value is "1.0" in which the value can be dropped.
case DataGridLengthUnitType.Star:
return DoubleUtil.IsOne(length.Value) ? "*" : Convert.ToString(length.Value, cultureInfo) + "*";
// Print out the numeric value. "px" can be omitted.
default:
return Convert.ToString(length.Value, cultureInfo);
}
}
/// <summary>
/// Parses a DataGridLength from a string given the CultureInfo.
/// </summary>
/// <param name="s">String to parse from.</param>
/// <param name="cultureInfo">Culture Info.</param>
/// <returns>Newly created DataGridLength instance.</returns>
/// <remarks>
/// Formats:
/// "[value][unit]"
/// [value] is a double
/// [unit] is a string in DataGridLength._unitTypes connected to a DataGridLengthUnitType
/// "[value]"
/// As above, but the DataGridLengthUnitType is assumed to be DataGridLengthUnitType.Pixel
/// "[unit]"
/// As above, but the value is assumed to be 1.0
/// This is only acceptable for a subset of DataGridLengthUnitType: Auto
/// </remarks>
private static DataGridLength ConvertFromString(string s, CultureInfo cultureInfo)
{
string goodString = s.Trim().ToLowerInvariant();
// Check if the string matches any of the descriptive unit types.
// In these cases, there is no need to parse a value.
for (int i = 0; i < NumDescriptiveUnits; i++)
{
string unitString = _unitStrings[i];
if (goodString == unitString)
{
return new DataGridLength(1.0, (DataGridLengthUnitType)i);
}
}
double value = 0.0;
DataGridLengthUnitType unit = DataGridLengthUnitType.Pixel;
int strLen = goodString.Length;
int strLenUnit = 0;
double unitFactor = 1.0;
// Check if the string contains a non-descriptive unit at the end.
int numUnitStrings = _unitStrings.Length;
for (int i = NumDescriptiveUnits; i < numUnitStrings; i++)
{
string unitString = _unitStrings[i];
// Note: This is NOT a culture specific comparison.
// This is by design: we want the same unit string table to work across all cultures.
if (goodString.EndsWith(unitString, StringComparison.Ordinal))
{
strLenUnit = unitString.Length;
unit = (DataGridLengthUnitType)i;
break;
}
}
// Couldn't match a standard unit type, try a non-standard unit type.
if (strLenUnit == 0)
{
numUnitStrings = _nonStandardUnitStrings.Length;
for (int i = 0; i < numUnitStrings; i++)
{
string unitString = _nonStandardUnitStrings[i];
// Note: This is NOT a culture specific comparison.
// This is by design: we want the same unit string table to work across all cultures.
if (goodString.EndsWith(unitString, StringComparison.Ordinal))
{
strLenUnit = unitString.Length;
unitFactor = _pixelUnitFactors[i];
break;
}
}
}
// Check if there is a numerical value to parse
if (strLen == strLenUnit)
{
// There is no numerical value to parse
if (unit == DataGridLengthUnitType.Star)
{
// Star's value defaults to 1. Anyone else would be 0.
value = 1.0;
}
}
else
{
// Parse a numerical value
Debug.Assert(
(unit == DataGridLengthUnitType.Pixel) || DoubleUtil.AreClose(unitFactor, 1.0),
"unitFactor should not be other than 1.0 unless the unit type is Pixel.");
string valueString = goodString.Substring(0, strLen - strLenUnit);
value = Convert.ToDouble(valueString, cultureInfo) * unitFactor;
}
return new DataGridLength(value, unit);
}
private static string[] _unitStrings = { "auto", "px", "sizetocells", "sizetoheader", "*" };
private const int NumDescriptiveUnits = 3;
// This array contains strings for unit types not included in the standard set
private static string[] _nonStandardUnitStrings = { "in", "cm", "pt" };
// These are conversion factors to transform other units to pixels
private static double[] _pixelUnitFactors =
{
96.0, // Pixels per Inch
96.0 / 2.54, // Pixels per Centimeter
96.0 / 72.0, // Pixels per Point
};
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: BinaryWriter
**
** <OWNER>gpaperin</OWNER>
**
** Purpose: Provides a way to write primitives types in
** binary from a Stream, while also supporting writing Strings
** in a particular encoding.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.Serialization;
using System.Text;
using System.Diagnostics.Contracts;
namespace System.IO {
// This abstract base class represents a writer that can write
// primitives to an arbitrary stream. A subclass can override methods to
// give unique encodings.
//
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class BinaryWriter : IDisposable
{
public static readonly BinaryWriter Null = new BinaryWriter();
protected Stream OutStream;
private byte[] _buffer; // temp space for writing primitives to.
private Encoding _encoding;
private Encoder _encoder;
[OptionalField] // New in .NET FX 4.5. False is the right default value.
private bool _leaveOpen;
// This field should never have been serialized and has not been used since before v2.0.
// However, this type is serializable, and we need to keep the field name around when deserializing.
// Also, we'll make .NET FX 4.5 not break if it's missing.
#pragma warning disable 169
[OptionalField]
private char[] _tmpOneCharBuffer;
#pragma warning restore 169
// Perf optimization stuff
private byte[] _largeByteBuffer; // temp space for writing chars.
private int _maxChars; // max # of chars we can put in _largeByteBuffer
// Size should be around the max number of chars/string * Encoding's max bytes/char
private const int LargeByteBufferSize = 256;
// Protected default constructor that sets the output stream
// to a null stream (a bit bucket).
protected BinaryWriter()
{
OutStream = Stream.Null;
_buffer = new byte[16];
_encoding = new UTF8Encoding(false, true);
_encoder = _encoding.GetEncoder();
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public BinaryWriter(Stream output) : this(output, new UTF8Encoding(false, true), false)
{
}
public BinaryWriter(Stream output, Encoding encoding) : this(output, encoding, false)
{
}
public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen)
{
if (output==null)
throw new ArgumentNullException("output");
if (encoding==null)
throw new ArgumentNullException("encoding");
if (!output.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
Contract.EndContractBlock();
OutStream = output;
_buffer = new byte[16];
_encoding = encoding;
_encoder = _encoding.GetEncoder();
_leaveOpen = leaveOpen;
}
// Closes this writer and releases any system resources associated with the
// writer. Following a call to Close, any operations on the writer
// may raise exceptions.
public virtual void Close()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing) {
if (_leaveOpen)
OutStream.Flush();
else
OutStream.Close();
}
}
public void Dispose()
{
Dispose(true);
}
/*
* Returns the stream associate with the writer. It flushes all pending
* writes before returning. All subclasses should override Flush to
* ensure that all buffered data is sent to the stream.
*/
public virtual Stream BaseStream {
get {
Flush();
return OutStream;
}
}
// Clears all buffers for this writer and causes any buffered data to be
// written to the underlying device.
public virtual void Flush()
{
OutStream.Flush();
}
public virtual long Seek(int offset, SeekOrigin origin)
{
return OutStream.Seek(offset, origin);
}
// Writes a boolean to this stream. A single byte is written to the stream
// with the value 0 representing false or the value 1 representing true.
//
public virtual void Write(bool value) {
_buffer[0] = (byte) (value ? 1 : 0);
OutStream.Write(_buffer, 0, 1);
}
// Writes a byte to this stream. The current position of the stream is
// advanced by one.
//
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public virtual void Write(byte value)
{
OutStream.WriteByte(value);
}
// Writes a signed byte to this stream. The current position of the stream
// is advanced by one.
//
[CLSCompliant(false)]
public virtual void Write(sbyte value)
{
OutStream.WriteByte((byte) value);
}
// Writes a byte array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the byte array.
//
public virtual void Write(byte[] buffer) {
if (buffer == null)
throw new ArgumentNullException("buffer");
Contract.EndContractBlock();
OutStream.Write(buffer, 0, buffer.Length);
}
// Writes a section of a byte array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the byte array.
//
public virtual void Write(byte[] buffer, int index, int count) {
OutStream.Write(buffer, index, count);
}
// Writes a character to this stream. The current position of the stream is
// advanced by two.
// Note this method cannot handle surrogates properly in UTF-8.
//
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual void Write(char ch) {
if (Char.IsSurrogate(ch))
throw new ArgumentException(Environment.GetResourceString("Arg_SurrogatesNotAllowedAsSingleChar"));
Contract.EndContractBlock();
Contract.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
int numBytes = 0;
fixed(byte * pBytes = _buffer) {
numBytes = _encoder.GetBytes(&ch, 1, pBytes, 16, true);
}
OutStream.Write(_buffer, 0, numBytes);
}
// Writes a character array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the character array.
//
public virtual void Write(char[] chars)
{
if (chars == null)
throw new ArgumentNullException("chars");
Contract.EndContractBlock();
byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length);
OutStream.Write(bytes, 0, bytes.Length);
}
// Writes a section of a character array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the character array.
//
public virtual void Write(char[] chars, int index, int count)
{
byte[] bytes = _encoding.GetBytes(chars, index, count);
OutStream.Write(bytes, 0, bytes.Length);
}
// Writes a double to this stream. The current position of the stream is
// advanced by eight.
//
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual void Write(double value)
{
#if MONO
OutStream.Write (Mono.Security.BitConverterLE.GetBytes (value), 0, 8);
#else
ulong TmpValue = *(ulong *)&value;
_buffer[0] = (byte) TmpValue;
_buffer[1] = (byte) (TmpValue >> 8);
_buffer[2] = (byte) (TmpValue >> 16);
_buffer[3] = (byte) (TmpValue >> 24);
_buffer[4] = (byte) (TmpValue >> 32);
_buffer[5] = (byte) (TmpValue >> 40);
_buffer[6] = (byte) (TmpValue >> 48);
_buffer[7] = (byte) (TmpValue >> 56);
OutStream.Write(_buffer, 0, 8);
#endif
}
public virtual void Write(decimal value)
{
Decimal.GetBytes(value,_buffer);
OutStream.Write(_buffer, 0, 16);
}
// Writes a two-byte signed integer to this stream. The current position of
// the stream is advanced by two.
//
public virtual void Write(short value)
{
_buffer[0] = (byte) value;
_buffer[1] = (byte) (value >> 8);
OutStream.Write(_buffer, 0, 2);
}
// Writes a two-byte unsigned integer to this stream. The current position
// of the stream is advanced by two.
//
[CLSCompliant(false)]
public virtual void Write(ushort value)
{
_buffer[0] = (byte) value;
_buffer[1] = (byte) (value >> 8);
OutStream.Write(_buffer, 0, 2);
}
// Writes a four-byte signed integer to this stream. The current position
// of the stream is advanced by four.
//
public virtual void Write(int value)
{
_buffer[0] = (byte) value;
_buffer[1] = (byte) (value >> 8);
_buffer[2] = (byte) (value >> 16);
_buffer[3] = (byte) (value >> 24);
OutStream.Write(_buffer, 0, 4);
}
// Writes a four-byte unsigned integer to this stream. The current position
// of the stream is advanced by four.
//
[CLSCompliant(false)]
public virtual void Write(uint value)
{
_buffer[0] = (byte) value;
_buffer[1] = (byte) (value >> 8);
_buffer[2] = (byte) (value >> 16);
_buffer[3] = (byte) (value >> 24);
OutStream.Write(_buffer, 0, 4);
}
// Writes an eight-byte signed integer to this stream. The current position
// of the stream is advanced by eight.
//
public virtual void Write(long value)
{
_buffer[0] = (byte) value;
_buffer[1] = (byte) (value >> 8);
_buffer[2] = (byte) (value >> 16);
_buffer[3] = (byte) (value >> 24);
_buffer[4] = (byte) (value >> 32);
_buffer[5] = (byte) (value >> 40);
_buffer[6] = (byte) (value >> 48);
_buffer[7] = (byte) (value >> 56);
OutStream.Write(_buffer, 0, 8);
}
// Writes an eight-byte unsigned integer to this stream. The current
// position of the stream is advanced by eight.
//
[CLSCompliant(false)]
public virtual void Write(ulong value)
{
_buffer[0] = (byte) value;
_buffer[1] = (byte) (value >> 8);
_buffer[2] = (byte) (value >> 16);
_buffer[3] = (byte) (value >> 24);
_buffer[4] = (byte) (value >> 32);
_buffer[5] = (byte) (value >> 40);
_buffer[6] = (byte) (value >> 48);
_buffer[7] = (byte) (value >> 56);
OutStream.Write(_buffer, 0, 8);
}
// Writes a float to this stream. The current position of the stream is
// advanced by four.
//
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual void Write(float value)
{
#if MONO
OutStream.Write (Mono.Security.BitConverterLE.GetBytes (value), 0, 4);
#else
uint TmpValue = *(uint *)&value;
_buffer[0] = (byte) TmpValue;
_buffer[1] = (byte) (TmpValue >> 8);
_buffer[2] = (byte) (TmpValue >> 16);
_buffer[3] = (byte) (TmpValue >> 24);
OutStream.Write(_buffer, 0, 4);
#endif
}
// Writes a length-prefixed string to this stream in the BinaryWriter's
// current Encoding. This method first writes the length of the string as
// a four-byte unsigned integer, and then writes that many characters
// to the stream.
//
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual void Write(String value)
{
if (value==null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
int len = _encoding.GetByteCount(value);
Write7BitEncodedInt(len);
if (_largeByteBuffer == null) {
_largeByteBuffer = new byte[LargeByteBufferSize];
_maxChars = LargeByteBufferSize / _encoding.GetMaxByteCount(1);
}
if (len <= LargeByteBufferSize) {
//Contract.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name);
_encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0);
OutStream.Write(_largeByteBuffer, 0, len);
}
else {
// Aggressively try to not allocate memory in this loop for
// runtime performance reasons. Use an Encoder to write out
// the string correctly (handling surrogates crossing buffer
// boundaries properly).
int charStart = 0;
int numLeft = value.Length;
#if _DEBUG
int totalBytes = 0;
#endif
while (numLeft > 0) {
// Figure out how many chars to process this round.
int charCount = (numLeft > _maxChars) ? _maxChars : numLeft;
int byteLen;
fixed(char* pChars = value) {
fixed(byte* pBytes = _largeByteBuffer) {
byteLen = _encoder.GetBytes(pChars + charStart, charCount, pBytes, LargeByteBufferSize, charCount == numLeft);
}
}
#if _DEBUG
totalBytes += byteLen;
Contract.Assert (totalBytes <= len && byteLen <= LargeByteBufferSize, "BinaryWriter::Write(String) - More bytes encoded than expected!");
#endif
OutStream.Write(_largeByteBuffer, 0, byteLen);
charStart += charCount;
numLeft -= charCount;
}
#if _DEBUG
Contract.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!");
#endif
}
}
protected void Write7BitEncodedInt(int value) {
// Write out an int 7 bits at a time. The high bit of the byte,
// when on, tells reader to continue reading more bytes.
uint v = (uint) value; // support negative numbers
while (v >= 0x80) {
Write((byte) (v | 0x80));
v >>= 7;
}
Write((byte)v);
}
}
}
| |
/*
* MSR Tools - tools for mining software repositories
*
* Copyright (C) 2010 Semyon Kirnosenko
*/
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using SharpTestsEx;
using Rhino.Mocks;
using MSR.Data.VersionControl;
using MSR.Data.Entities.DSL.Selection;
using MSR.Data.Entities.DSL.Mapping;
namespace MSR.Data.Entities.Mapping
{
[TestFixture]
public class CodeBlockMapperTest : BaseMapperTest
{
private CodeBlockMapper mapper;
private List<int> addedLines;
private List<int> removedLines;
[SetUp]
public override void SetUp()
{
base.SetUp();
addedLines = new List<int>();
removedLines = new List<int>();
diffStub.Stub(x => x.AddedLines)
.Return(addedLines);
diffStub.Stub(x => x.RemovedLines)
.Return(removedLines);
scmData.Stub(x => x.PreviousRevision(null))
.IgnoreArguments()
.Do((Func<string,string>)(r =>
{
return (Convert.ToInt32(r) - 1).ToString();
}));
mapper = new CodeBlockMapper(scmData);
}
[Test]
public void Should_map_nothing_if_there_are_no_added_or_removed_lines()
{
scmData.Stub(x => x.Diff("10", "file1"))
.Return(diffStub);
mapper.Map(
mappingDSL.AddCommit("10")
.AddFile("file1").Modified()
);
SubmitChanges();
Queryable<CodeBlock>().Count()
.Should().Be.EqualTo(0);
}
[Test]
public void Should_add_separate_blocks_for_added_and_removed_code()
{
mappingDSL
.AddCommit("9")
.AddFile("file1").Modified()
.Code(100)
.Submit();
scmData.Stub(x => x.Diff("10", "file1"))
.Return(diffStub);
addedLines.AddRange(new int[] { 20, 21, 22 });
removedLines.Add(5);
scmData.Stub(x => x.Blame("9", "file1"))
.Return(new BlameStub(x => "9"));
mapper.Map(
mappingDSL.AddCommit("10")
.File("file1").Modified()
);
SubmitChanges();
Queryable<CodeBlock>().Count()
.Should().Be.EqualTo(3);
Queryable<CodeBlock>()
.Select(x => x.Size).ToArray()
.Should().Have.SameSequenceAs(
new double[] { 100, 3, -1 }
);
}
[Test]
public void Should_set_commit_code_block_was_added_in()
{
mappingDSL
.AddCommit("9")
.AddFile("file1").Modified()
.Code(100)
.Submit();
scmData.Stub(x => x.Diff("10", "file1"))
.Return(diffStub);
removedLines.Add(10);
addedLines.Add(10);
scmData.Stub(x => x.Blame("9", "file1"))
.Return(new BlameStub(x => "9"));
mapper.Map(
mappingDSL.AddCommit("10")
.File("file1").Modified()
);
SubmitChanges();
Queryable<CodeBlock>().Single(x => x.Size == 1).AddedInitiallyInCommit.Revision
.Should().Be("10");
Queryable<CodeBlock>().Single(x => x.Size == -1).AddedInitiallyInCommit
.Should().Be.Null();
}
[Test]
public void Should_set_target_code_block_for_deleted_code_block()
{
mappingDSL
.AddCommit("1")
.AddFile("file1").Modified()
.Code(100)
.Submit()
.AddCommit("2")
.File("file1").Modified()
.Code(50)
.Submit()
.AddCommit("9")
.Submit();
scmData.Stub(x => x.Diff("10", "file1"))
.Return(diffStub);
removedLines.Add(5);
scmData.Stub(x => x.Blame("9", "file1"))
.Return(new BlameStub()
{
{ 5, "1" }
});
mapper.Map(
mappingDSL.AddCommit("10")
.File("file1").Modified()
);
SubmitChanges();
Queryable<CodeBlock>().Single(x => x.Modification.Commit.Revision == "10").TargetCodeBlock.Size
.Should().Be(100);
}
[Test]
public void Should_add_codeblocks_by_source_commit_for_copied_file()
{
mappingDSL
.AddCommit("6")
.AddFile("file1").Modified()
.Code(20)
.Submit()
.AddCommit("7")
.File("file1").Modified()
.Code(-5).ForCodeAddedInitiallyInRevision("6")
.Code(3)
.Submit()
.AddCommit("8")
.File("file1").Modified()
.Code(5)
.Submit();
scmData.Stub(x => x.Diff("10", "file2"))
.Return(diffStub);
addedLines.AddRange(Enumerable.Range(1,18));
scmData.Stub(x => x.Blame("7", "file1"))
.Return(new BlameStub(x => "6")
{
{ 10, "7" },
{ 11, "7" },
{ 12, "7" },
});
scmData.Stub(x => x.Diff("file2", "10", "file1", "7"))
.Return(FileUniDiff.Empty);
mapper.Map(
mappingDSL.AddCommit("10")
.AddFile("file2").CopiedFrom("file1", "7").Modified()
);
SubmitChanges();
var code = Queryable<CodeBlock>()
.Where(cb => cb.Modification.Commit.Revision == "10");
code.Count()
.Should().Be(2);
code.Select(cb => cb.Size).ToArray()
.Should().Have.SameSequenceAs(new double[] { 15, 3 });
code.Select(cb => cb.AddedInitiallyInCommit.Revision).ToArray()
.Should().Have.SameSequenceAs(new string[] { "6", "7" });
}
[Test]
public void Should_add_codeblocks_for_file_during_partial_mapping()
{
mappingDSL
.AddCommit("6")
.AddFile("file1").Modified()
.Code(20)
.AddFile("file2").Modified()
.Code(25)
.Submit()
.AddCommit("7")
.File("file1").Modified()
.Code(30)
.Submit()
.AddCommit("8")
.File("file1").Modified()
.Code(40)
.Submit();
scmData.Stub(x => x.Diff("7", "file2"))
.Return(diffStub);
addedLines.AddRange(new int[] { 10, 11 });
removedLines.AddRange(new int[] { 10, 11 });
scmData.Stub(x => x.Blame("6", "file2"))
.Return(new BlameStub(x => "6"));
mapper.Map(
mappingDSL.Commit("7")
.File("file2").Modified()
);
SubmitChanges();
var code = Queryable<CodeBlock>()
.Where(cb => cb.Modification.Commit.Revision == "7");
code.Count()
.Should().Be(3);
code.Select(cb => cb.Size).ToArray()
.Should().Have.SameSequenceAs(new double[] { 30, 2, -2 });
}
[Test]
public void Should_not_take_diff_for_copied_file()
{
mappingDSL
.AddCommit("1")
.AddFile("file1").Modified()
.Code(100)
.Submit();
scmData.Stub(x => x.Diff("file2", "10", "file1", "1"))
.Return(FileUniDiff.Empty);
mapper.Map(
mappingDSL.AddCommit("10")
.AddFile("file2").CopiedFrom("file1", "1").Modified()
);
SubmitChanges();
scmData.AssertWasNotCalled(x => x.Diff("10", "file2"));
}
[Test]
public void Should_use_diff_and_blame_for_copied_and_modified_file()
{
mappingDSL
.AddCommit("1")
.AddFile("file1").Modified()
.Code(100)
.Submit()
.AddCommit("2")
.File("file1").Modified()
.Code(20)
.Submit();
scmData.Stub(x => x.Diff("file2", "10", "file1", "2"))
.Return(diffStub);
removedLines.Add(120);
addedLines.Add(120);
IBlame blame = new BlameStub();
for (int i = 1; i <= 100; i++)
{
blame.Add(i, "1");
}
for (int i = 101; i <= 119; i++)
{
blame.Add(i, "2");
}
blame.Add(120, "10");
scmData.Stub(x => x.Blame("10", "file2"))
.Return(blame);
mapper.Map(
mappingDSL.AddCommit("10")
.AddFile("file2").CopiedFrom("file1", "2").Modified()
);
SubmitChanges();
var codeBlocks = Queryable<CodeBlock>()
.Where(cb => cb.Modification.Commit.Revision == "10");
codeBlocks.Count()
.Should().Be(3);
codeBlocks.Select(cb => cb.Size)
.Should().Have.SameSequenceAs(
new double[] { 100, 19, 1 }
);
codeBlocks.Select(cb => cb.AddedInitiallyInCommit.Revision)
.Should().Have.SameSequenceAs(
new string[] { "1", "2", "10" }
);
}
[Test]
public void Should_not_take_blame_for_copied_and_modified_file_without_deleted_code()
{
mappingDSL
.AddCommit("1")
.AddFile("file1").Modified()
.Code(100)
.Submit();
scmData.Stub(x => x.Diff("file2", "10", "file1", "1"))
.Return(diffStub);
addedLines.Add(10);
mapper.Map(
mappingDSL.AddCommit("10")
.AddFile("file2").CopiedFrom("file1", "1").Modified()
);
SubmitChanges();
scmData.AssertWasNotCalled(x => x.Blame("10", "file2"));
}
[Test]
public void Should_not_take_diff_for_deleted_file()
{
mappingDSL
.AddCommit("1")
.AddFile("file1").Modified()
.Code(100)
.Submit();
mapper.Map(
mappingDSL.AddCommit("10")
.File("file1").Delete().Modified()
);
SubmitChanges();
scmData.AssertWasNotCalled(x => x.Diff("10", "file1"));
}
[Test]
public void Should_not_take_blame_for_file_without_removed_code()
{
mappingDSL
.AddCommit("1")
.AddFile("file1").Modified()
.Code(100)
.Submit();
scmData.Stub(x => x.Diff("10", "file1"))
.Return(diffStub);
addedLines.AddRange(Enumerable.Range(10,20));
mapper.Map(
mappingDSL.AddCommit("10")
.File("file1").Modified()
);
SubmitChanges();
scmData.AssertWasNotCalled(x => x.Blame("9","file1"));
}
}
}
| |
/*! Achordeon - MIT License
Copyright (c) 2017 tiamatix / Wolf Robben
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
!*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Achordeon.Common.Helpers;
using Achordeon.Lib.DataModel;
using Achordeon.Lib.SongOptions;
using DryIoc;
using DryIoc.Experimental;
namespace Achordeon.Rendering.Ascii
{
public class AsciiRenderer : Renderer
{
private int m_CurrentLineLen = 0;
private int m_MaxLineLen = 0;
private StringBuilder m_Builder1 = new StringBuilder();
private void Append(char AChar)
{
m_CurrentLineLen++;
m_Builder1.Append(AChar);
}
private void Append(string AText)
{
m_CurrentLineLen += AText.Length;
m_Builder1.Append(AText);
}
private void AppendLine(string AText)
{
Append(AText);
AppendLine();
}
private void AppendLine()
{
if (m_CurrentLineLen > m_MaxLineLen)
m_MaxLineLen = m_CurrentLineLen;
m_CurrentLineLen = 0;
m_Builder1.AppendLine();
}
private void RenderLine(Line ALine, int AIndent)
{
/*
* Map chords and text accordingly:
*
* Well A child arrived [G]just [Amaj7/G]the [C]other day
*
* =>
*
* G Amaj7/C G
* Well A child arrived just the other day
*/
var ChordPositions = new Dictionary<LineChord, int>();
var TextPositions = new Dictionary<LineText, int>();
var CurrentPosition = AIndent;
foreach (var Run in ALine.Runs)
{
if (Run is LineText)
{
var Text = (LineText) Run;
TextPositions[Text] = CurrentPosition;
//If the previous chord needs more (or equal) space than the text
//we have to reserve extra space for the chord and one extra blank
var PreviousChordLength = ALine.GetPreviousElementOrNullOfType<LineChord>(Text)?.TextLength ?? 0;
if (PreviousChordLength >= Text.TextLength)
CurrentPosition += PreviousChordLength + 1;
else
CurrentPosition += Text.TextLength;
}
if (Run is LineChord)
{
if (!SongOptions.LyricsOnly)
{
var Chord = (LineChord) Run;
ChordPositions[Chord] = CurrentPosition;
}
}
}
if (ChordPositions.Any() && !SongOptions.LyricsOnly)
{
CurrentPosition = 0;
foreach (var Chord in ALine.Runs.OfType<LineChord>())
{
var ChordPos = ChordPositions[Chord];
while (CurrentPosition < ChordPos)
{
Append(' ');
CurrentPosition++;
}
Append(Chord.Name);
CurrentPosition += Chord.TextLength;
}
AppendLine();
}
CurrentPosition = 0;
foreach (var Text in ALine.Runs.OfType<LineText>())
{
var TextPos = TextPositions[Text];
while (CurrentPosition < TextPos)
{
Append(' ');
CurrentPosition++;
}
Append(Text.Text);
CurrentPosition += Text.TextLength;
}
AppendLine();
}
private string GetIndentString(int AIndent, char AChar = ' ')
{
return new string(AChar, AIndent);
}
private void RenderLineRange(LineRange ARange, int AIndent)
{
foreach (var obj in ARange.Lines)
{
if (obj is Line)
RenderLine((Line) obj, AIndent);
else if (obj is Comment)
{
Append(GetIndentString(AIndent));
AppendLine(((Comment) obj).Text);
}
else if (obj is Tab)
{
if (!SongOptions.LyricsOnly)
RenderLineRange((LineRange)obj, AIndent);
}
else if (obj is Chorus)
RenderLineRange((Chorus) obj, AIndent + 2);
else if (obj is LineRange)
RenderLineRange((LineRange) obj, AIndent);
}
}
private void RenderSong(Song ASong, int AIndent)
{
m_MaxLineLen = 0;
var StartPos = m_Builder1.Length;
foreach (var Subtitle in ASong.Subtitles)
{
Append(GetIndentString(AIndent));
AppendLine(Subtitle);
}
RenderLineRange(ASong, AIndent);
var Indent = Math.Max(0, m_MaxLineLen/2 - ASong.Title.Length/2);
m_Builder1.Insert(StartPos,
GetIndentString(Indent) +
ASong.Title.ToUpper() +
Environment.NewLine +
GetIndentString(Indent) +
GetIndentString(ASong.Title.Length, '=') +
Environment.NewLine);
}
public override void Render(Stream ATargetStream)
{
BeginRender();
try
{
m_MaxLineLen = 0;
m_Builder1 = new StringBuilder();
foreach (var Song in Book.Songs)
{
RenderSong(Song, 0);
if (Song != Book.Songs.LastOrDefault())
AppendLine();
}
var Encoding = IoC.Get<Encoding>() ?? System.Text.Encoding.Default;
using (TextWriter tw = new StreamWriter(ATargetStream, Encoding, 1, true))
{
tw.WriteLine(m_Builder1.ToString());
}
}
finally
{
EndRender();
}
}
public string Render()
{
using (var Stream = new StringStream())
{
Render(Stream);
return Stream.ToString();
}
}
public AsciiRenderer(Container AIoC, SongBook ABook, ISongOptions ASongOptions) : base(AIoC, ABook, ASongOptions)
{
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// VirtualNetworksOperations operations.
/// </summary>
internal partial class VirtualNetworksOperations : IServiceOperations<NetworkManagementClient>, IVirtualNetworksOperations
{
/// <summary>
/// Initializes a new instance of the VirtualNetworksOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal VirtualNetworksOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// The Delete VirtualNetwork operation deletes the specifed virtual network
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(
resourceGroupName, virtualNetworkName, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// The Delete VirtualNetwork operation deletes the specifed virtual network
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 204 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The Get VirtualNetwork operation retrieves information about the specified
/// virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetwork>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetwork>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The Put VirtualNetwork operation creates/updates a virtual network in the
/// specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update Virtual Network operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<VirtualNetwork>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<VirtualNetwork> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(
resourceGroupName, virtualNetworkName, parameters, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// The Put VirtualNetwork operation creates/updates a virtual network in the
/// specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update Virtual Network operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetwork>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetwork>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The list VirtualNetwork returns all Virtual Networks in a subscription
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworks").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetwork>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The list VirtualNetwork returns all Virtual Networks in a resource group
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetwork>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The list VirtualNetwork returns all Virtual Networks in a subscription
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetwork>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The list VirtualNetwork returns all Virtual Networks in a resource group
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetwork>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Net;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using OpenSource.UPnP;
namespace UPnPSniffer
{
/// <summary>
/// Summary description for GetForm.
/// </summary>
public class HttpRequestor : System.Windows.Forms.Form
{
private Queue RequestQ = new Queue();
private HTTPSession s;
private HTTPSessionWatcher SW;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.TextBox SniffText;
private System.Windows.Forms.TextBox GetText;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.ComboBox MethodBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button RequestButton;
private System.Windows.Forms.TextBox addressTextBox;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.ContextMenu networkContextMenu;
private System.Windows.Forms.MenuItem networkSeparatorMenuItem;
private System.Windows.Forms.MenuItem networkCopyMenuItem;
private System.Windows.Forms.Panel customRequestPanel;
private System.Windows.Forms.ComboBox versionComboBox;
private System.Windows.Forms.TextBox fieldsTextBox;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox directiveTextBox;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox directiveObjTextBox;
private System.Windows.Forms.TextBox bodyTextBox;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ContextMenu requestContextMenu;
private System.Windows.Forms.MenuItem RequestQueueMenuItem;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public HttpRequestor()
{
InitializeComponent();
MethodBox.SelectedIndex = 0;
versionComboBox.SelectedIndex = 1;
}
private void Request(object msg, IPEndPoint dest)
{
if (dest == null) return;
s = new HTTPSession(new IPEndPoint(IPAddress.Any, 0), dest,
new HTTPSession.SessionHandler(CreateSink),
new HTTPSession.SessionHandler(FailSink),
msg);
}
public string Address
{
get { return addressTextBox.Text; }
}
private HTTPMessage Request(Uri GetUri, bool isGetRequest, bool isHttp1_1)
{
directiveObjTextBox.Text = GetUri.PathAndQuery;
IPAddress Addr = null;
try
{
if (GetUri.HostNameType == UriHostNameType.Dns)
{
Addr = Dns.GetHostEntry(GetUri.Host).AddressList[0];
}
else
{
Addr = IPAddress.Parse(GetUri.Host);
}
}
catch (Exception)
{
return null;
}
if (Addr == null) return null;
IPEndPoint ep = new IPEndPoint(Addr, GetUri.Port);
// NKIDD - ADDED support for requesting GET/HEAD 1.0/1.1
HTTPMessage req = null;
if (isHttp1_1)
{
req = new HTTPMessage();
}
else
{
req = new HTTPMessage("1.0");
}
if (isGetRequest)
{
req.Directive = "GET";
}
else
{
req.Directive = "HEAD";
}
req.DirectiveObj = HTTPMessage.UnEscapeString(GetUri.PathAndQuery);
req.AddTag("Host", ep.ToString());
this.Text = "Device Sniffer - " + GetUri.AbsoluteUri;
SniffText.Text = "";
GetText.Text = "";
return (req);
}
private void FailSink(HTTPSession FS)
{
SniffText.Text = "Could not connect to resouce.";
GetText.Text = "Could not connect to resouce.";
}
private void CloseSink(HTTPSession CS)
{
}
private void CreateSink(HTTPSession CS)
{
CS.OnClosed += new HTTPSession.SessionHandler(CloseSink);
SW = new HTTPSessionWatcher(CS);
SW.OnSniff += new HTTPSessionWatcher.SniffHandler(SniffSink);
CS.OnReceive += new HTTPSession.ReceiveHandler(ReceiveSink);
if (CS.StateObject.GetType() == typeof(HTTPMessage))
{
CS.Send((HTTPMessage)CS.StateObject);
}
else
{
Queue Q = (Queue)CS.StateObject;
HTTPMessage M;
M = (HTTPMessage)Q.Dequeue();
while (M != null && Q.Count > 0)
{
CS.Send(M);
M = (HTTPMessage)Q.Dequeue();
}
}
}
private void SniffSink(byte[] raw, int offset, int length)
{
UTF8Encoding U = new UTF8Encoding();
SniffText.Text = SniffText.Text + U.GetString(raw, offset, length);
}
private void ReceiveSink(HTTPSession sender, HTTPMessage msg)
{
GetText.Text = msg.StringPacket;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private void RequestButton_Click(object sender, System.EventArgs e)
{
if (RequestButton.Text == "Request")
{
if (RequestQ.Count == 0)
{
Request(Request(), GetIPEndPoint());
}
else
{
Request(RequestQ, GetIPEndPoint());
RequestQ = new Queue();
}
}
else
{
RequestQ.Enqueue(Request());
}
}
public void Request(string address)
{
addressTextBox.Text = address;
try
{
directiveObjTextBox.Text = new Uri(address).PathAndQuery;
}
catch { }
Request();
}
private IPEndPoint GetIPEndPoint()
{
IPAddress Addr;
Uri uri;
try
{
uri = new Uri(addressTextBox.Text);
if (uri.HostNameType == UriHostNameType.Dns)
{
Addr = Dns.GetHostEntry(uri.Host).AddressList[0];
}
else
{
Addr = IPAddress.Parse(uri.Host);
}
}
catch
{
SniffText.Text = "Invalid Request URI";
GetText.Text = "Invalid Request URI";
return null;
}
return new IPEndPoint(Addr, uri.Port);
}
private HTTPMessage Request()
{
HTTPMessage RetVal = null;
if (this.Visible == false)
{
Show();
}
else
{
Activate();
}
Uri uri;
try
{
uri = new Uri(addressTextBox.Text);
}
catch
{
SniffText.Text = "Invalid Request URI";
GetText.Text = "Invalid Request URI";
return (null);
}
SniffText.Text = "";
GetText.Text = "";
if (MethodBox.SelectedIndex == 0)
{
// GET 1.0
RetVal = Request(uri, true, false);
}
else if (MethodBox.SelectedIndex == 1)
{
// GET 1.1
RetVal = Request(uri, true, true);
}
else if (MethodBox.SelectedIndex == 2)
{
// HEAD 1.0
RetVal = Request(uri, false, false);
}
else if (MethodBox.SelectedIndex == 3)
{
// HEAD 1.1
RetVal = Request(uri, false, true);
}
else if (MethodBox.SelectedIndex == 4)
{
HTTPMessage msg = new HTTPMessage();
msg.Directive = directiveTextBox.Text;
msg.DirectiveObj = directiveObjTextBox.Text;
if (versionComboBox.SelectedIndex == 0)
{
msg.Version = "0.9";
}
if (versionComboBox.SelectedIndex == 1)
{
msg.Version = "1.0";
}
if (versionComboBox.SelectedIndex == 2)
{
msg.Version = "1.1";
}
try
{
bool addreturn = false;
if (fieldsTextBox.Text.EndsWith("\r\n") == false)
{
fieldsTextBox.Text += "\r\n";
addreturn = true;
}
int pos = 0;
while (pos != -1)
{
int s1 = fieldsTextBox.Text.IndexOf(":", pos);
int s2 = fieldsTextBox.Text.IndexOf("\r\n", pos);
if (s1 == -1 || s2 == -1) break;
msg.AppendTag(fieldsTextBox.Text.Substring(pos, s1 - pos), fieldsTextBox.Text.Substring(s1 + 1, s2 - s1 - 1));
pos = s2 + 2;
}
if (addreturn == true)
{
fieldsTextBox.Text = fieldsTextBox.Text.Substring(0, fieldsTextBox.Text.Length - 2);
}
}
catch { }
msg.StringBuffer = bodyTextBox.Text;
RetVal = msg;
}
if (RetVal == null)
{
SniffText.Text = "Invalid Request URI";
GetText.Text = "Invalid Request URI";
}
return (RetVal);
}
#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.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(HttpRequestor));
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.SniffText = new System.Windows.Forms.TextBox();
this.networkContextMenu = new System.Windows.Forms.ContextMenu();
this.networkCopyMenuItem = new System.Windows.Forms.MenuItem();
this.networkSeparatorMenuItem = new System.Windows.Forms.MenuItem();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.GetText = new System.Windows.Forms.TextBox();
this.panel1 = new System.Windows.Forms.Panel();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.RequestButton = new System.Windows.Forms.Button();
this.requestContextMenu = new System.Windows.Forms.ContextMenu();
this.RequestQueueMenuItem = new System.Windows.Forms.MenuItem();
this.addressTextBox = new System.Windows.Forms.TextBox();
this.MethodBox = new System.Windows.Forms.ComboBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.customRequestPanel = new System.Windows.Forms.Panel();
this.label6 = new System.Windows.Forms.Label();
this.bodyTextBox = new System.Windows.Forms.TextBox();
this.versionComboBox = new System.Windows.Forms.ComboBox();
this.fieldsTextBox = new System.Windows.Forms.TextBox();
this.label8 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.directiveObjTextBox = new System.Windows.Forms.TextBox();
this.directiveTextBox = new System.Windows.Forms.TextBox();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.panel1.SuspendLayout();
this.customRequestPanel.SuspendLayout();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Alignment = System.Windows.Forms.TabAlignment.Bottom;
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl1.Location = new System.Drawing.Point(0, 248);
this.tabControl1.Multiline = true;
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(488, 166);
this.tabControl1.TabIndex = 2;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.SniffText);
this.tabPage1.Location = new System.Drawing.Point(4, 4);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Size = new System.Drawing.Size(480, 140);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Network Data";
//
// SniffText
//
this.SniffText.ContextMenu = this.networkContextMenu;
this.SniffText.Dock = System.Windows.Forms.DockStyle.Fill;
this.SniffText.Location = new System.Drawing.Point(0, 0);
this.SniffText.Multiline = true;
this.SniffText.Name = "SniffText";
this.SniffText.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.SniffText.Size = new System.Drawing.Size(480, 140);
this.SniffText.TabIndex = 1;
this.SniffText.Text = "";
//
// networkContextMenu
//
this.networkContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.networkCopyMenuItem,
this.networkSeparatorMenuItem});
this.networkContextMenu.Popup += new System.EventHandler(this.networkContextMenu_Popup);
//
// networkCopyMenuItem
//
this.networkCopyMenuItem.Index = 0;
this.networkCopyMenuItem.Text = "&Copy to Clipboard";
this.networkCopyMenuItem.Click += new System.EventHandler(this.networkCopyMenuItem_Click);
//
// networkSeparatorMenuItem
//
this.networkSeparatorMenuItem.Index = 1;
this.networkSeparatorMenuItem.Text = "-";
//
// tabPage2
//
this.tabPage2.Controls.Add(this.GetText);
this.tabPage2.Location = new System.Drawing.Point(4, 4);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Size = new System.Drawing.Size(480, 140);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Parsed Data";
//
// GetText
//
this.GetText.Dock = System.Windows.Forms.DockStyle.Fill;
this.GetText.Location = new System.Drawing.Point(0, 0);
this.GetText.Multiline = true;
this.GetText.Name = "GetText";
this.GetText.ReadOnly = true;
this.GetText.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.GetText.Size = new System.Drawing.Size(480, 140);
this.GetText.TabIndex = 2;
this.GetText.Text = "";
//
// panel1
//
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.label1);
this.panel1.Controls.Add(this.RequestButton);
this.panel1.Controls.Add(this.addressTextBox);
this.panel1.Controls.Add(this.MethodBox);
this.panel1.Controls.Add(this.pictureBox1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(488, 53);
this.panel1.TabIndex = 4;
//
// label2
//
this.label2.Location = new System.Drawing.Point(48, 30);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(64, 16);
this.label2.TabIndex = 26;
this.label2.Text = "Address";
//
// label1
//
this.label1.Location = new System.Drawing.Point(48, 7);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 16);
this.label1.TabIndex = 25;
this.label1.Text = "Request Type";
//
// RequestButton
//
this.RequestButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.RequestButton.ContextMenu = this.requestContextMenu;
this.RequestButton.Location = new System.Drawing.Point(412, 2);
this.RequestButton.Name = "RequestButton";
this.RequestButton.Size = new System.Drawing.Size(64, 20);
this.RequestButton.TabIndex = 24;
this.RequestButton.Text = "Request";
this.RequestButton.Click += new System.EventHandler(this.RequestButton_Click);
//
// requestContextMenu
//
this.requestContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.RequestQueueMenuItem});
//
// RequestQueueMenuItem
//
this.RequestQueueMenuItem.Index = 0;
this.RequestQueueMenuItem.Text = "Toggle Mode";
this.RequestQueueMenuItem.Click += new System.EventHandler(this.RequestQueueMenuItem_Click);
//
// addressTextBox
//
this.addressTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.addressTextBox.Location = new System.Drawing.Point(128, 26);
this.addressTextBox.Name = "addressTextBox";
this.addressTextBox.Size = new System.Drawing.Size(348, 20);
this.addressTextBox.TabIndex = 23;
this.addressTextBox.Text = "http://";
this.addressTextBox.TextChanged += new System.EventHandler(this.addressTextBox_TextChanged);
//
// MethodBox
//
this.MethodBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.MethodBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.MethodBox.Items.AddRange(new object[] {
"HTTP/1.0 GET",
"HTTP/1.1 GET",
"HTTP/1.0 HEAD",
"HTTP/1.1 HEAD",
"CUSTOM HTTP"});
this.MethodBox.Location = new System.Drawing.Point(128, 2);
this.MethodBox.Name = "MethodBox";
this.MethodBox.Size = new System.Drawing.Size(276, 21);
this.MethodBox.TabIndex = 22;
this.MethodBox.SelectedIndexChanged += new System.EventHandler(this.MethodBox_SelectedIndexChanged);
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(9, 13);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(32, 32);
this.pictureBox1.TabIndex = 21;
this.pictureBox1.TabStop = false;
//
// customRequestPanel
//
this.customRequestPanel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.customRequestPanel.Controls.Add(this.label6);
this.customRequestPanel.Controls.Add(this.bodyTextBox);
this.customRequestPanel.Controls.Add(this.versionComboBox);
this.customRequestPanel.Controls.Add(this.fieldsTextBox);
this.customRequestPanel.Controls.Add(this.label8);
this.customRequestPanel.Controls.Add(this.label5);
this.customRequestPanel.Controls.Add(this.label4);
this.customRequestPanel.Controls.Add(this.label3);
this.customRequestPanel.Controls.Add(this.directiveObjTextBox);
this.customRequestPanel.Controls.Add(this.directiveTextBox);
this.customRequestPanel.Dock = System.Windows.Forms.DockStyle.Top;
this.customRequestPanel.Location = new System.Drawing.Point(0, 53);
this.customRequestPanel.Name = "customRequestPanel";
this.customRequestPanel.Size = new System.Drawing.Size(488, 195);
this.customRequestPanel.TabIndex = 5;
this.customRequestPanel.Visible = false;
//
// label6
//
this.label6.Location = new System.Drawing.Point(8, 114);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(100, 14);
this.label6.TabIndex = 21;
this.label6.Text = "Body";
//
// bodyTextBox
//
this.bodyTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.bodyTextBox.Location = new System.Drawing.Point(8, 128);
this.bodyTextBox.Multiline = true;
this.bodyTextBox.Name = "bodyTextBox";
this.bodyTextBox.Size = new System.Drawing.Size(468, 56);
this.bodyTextBox.TabIndex = 20;
this.bodyTextBox.Text = "";
//
// versionComboBox
//
this.versionComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.versionComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.versionComboBox.Items.AddRange(new object[] {
"HTTP/0.9",
"HTTP/1.0",
"HTTP/1.1"});
this.versionComboBox.Location = new System.Drawing.Point(384, 24);
this.versionComboBox.Name = "versionComboBox";
this.versionComboBox.Size = new System.Drawing.Size(96, 21);
this.versionComboBox.TabIndex = 19;
//
// fieldsTextBox
//
this.fieldsTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.fieldsTextBox.Location = new System.Drawing.Point(8, 64);
this.fieldsTextBox.Multiline = true;
this.fieldsTextBox.Name = "fieldsTextBox";
this.fieldsTextBox.Size = new System.Drawing.Size(468, 48);
this.fieldsTextBox.TabIndex = 18;
this.fieldsTextBox.Text = "";
//
// label8
//
this.label8.Location = new System.Drawing.Point(8, 48);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(96, 16);
this.label8.TabIndex = 17;
this.label8.Text = "Fields";
//
// label5
//
this.label5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label5.Location = new System.Drawing.Point(380, 8);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(88, 16);
this.label5.TabIndex = 11;
this.label5.Text = "Version";
//
// label4
//
this.label4.Location = new System.Drawing.Point(80, 8);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(88, 16);
this.label4.TabIndex = 10;
this.label4.Text = "Directive Object";
//
// label3
//
this.label3.Location = new System.Drawing.Point(8, 8);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(56, 16);
this.label3.TabIndex = 9;
this.label3.Text = "Directive";
//
// directiveObjTextBox
//
this.directiveObjTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.directiveObjTextBox.Location = new System.Drawing.Point(80, 24);
this.directiveObjTextBox.Name = "directiveObjTextBox";
this.directiveObjTextBox.ReadOnly = true;
this.directiveObjTextBox.Size = new System.Drawing.Size(292, 20);
this.directiveObjTextBox.TabIndex = 7;
this.directiveObjTextBox.Text = "/";
this.directiveObjTextBox.DoubleClick += new System.EventHandler(this.OnDblClick_DirectiveObject);
//
// directiveTextBox
//
this.directiveTextBox.Location = new System.Drawing.Point(8, 24);
this.directiveTextBox.Name = "directiveTextBox";
this.directiveTextBox.Size = new System.Drawing.Size(64, 20);
this.directiveTextBox.TabIndex = 6;
this.directiveTextBox.Text = "GET";
//
// HttpRequestor
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(488, 414);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.customRequestPanel);
this.Controls.Add(this.panel1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu1;
this.Name = "HttpRequestor";
this.Text = "Device Sniffer - HTTP Requestor";
this.Closing += new System.ComponentModel.CancelEventHandler(this.HttpRequestor_Closing);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.customRequestPanel.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void HttpRequestor_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
this.Hide();
}
private void WebPageOpenMenuSink(object sender, System.EventArgs arg)
{
MenuItem mi = (MenuItem)sender;
Request(mi.Text.Substring(5));
}
private void networkContextMenu_Popup(object sender, System.EventArgs e)
{
while (networkContextMenu.MenuItems.Count > 2)
{
networkContextMenu.MenuItems.RemoveAt(2);
}
networkSeparatorMenuItem.Visible = false;
int pos = 0;
pos = SniffText.Text.IndexOf("http://", pos);
while (pos != -1)
{
int posfin1 = SniffText.Text.IndexOf("\r\n", pos);
int posfin2 = SniffText.Text.IndexOf("<", pos);
int posfin = -1;
if (posfin1 == -1) posfin = posfin2; else if (posfin2 == -1) posfin = posfin1; else posfin = Math.Min(posfin1, posfin2);
MenuItem mi = new MenuItem("Open " + SniffText.Text.Substring(pos, posfin - pos), new EventHandler(WebPageOpenMenuSink));
networkContextMenu.MenuItems.Add(mi);
networkSeparatorMenuItem.Visible = true;
pos = SniffText.Text.IndexOf("http://", posfin);
}
}
private void networkCopyMenuItem_Click(object sender, System.EventArgs e)
{
Clipboard.SetDataObject(SniffText.Text);
}
private void MethodBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
customRequestPanel.Visible = (MethodBox.SelectedIndex == 4);
}
private void addressTextBox_TextChanged(object sender, System.EventArgs e)
{
try
{
directiveObjTextBox.Text = new Uri(addressTextBox.Text).PathAndQuery;
}
catch
{
directiveObjTextBox.Text = "/";
}
}
private void RequestQueueMenuItem_Click(object sender, System.EventArgs e)
{
RequestButton.Text = RequestButton.Text == "Request" ? "Queue" : "Request";
}
private void OnDblClick_DirectiveObject(object sender, System.EventArgs e)
{
this.directiveObjTextBox.ReadOnly = !this.directiveObjTextBox.ReadOnly;
}
}
}
| |
//
// Copyright 2012, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Xamarin.Forms;
namespace EmployeeDirectory.Data
{
/// <summary>
/// Person.
/// </summary>
/// <remarks>
/// Derived from <a href="http://fsuid.fsu.edu/admin/lib/WinADLDAPAttributes.html#RANGE!B19">Windows AD LDAP Schema</a>
/// and <a href="http://www.zytrax.com/books/ldap/ape/core-schema.html">core.schema</a> from OpenLDAP.
/// </remarks>
public class Person
{
string id;
public string Id {
get {
if (!string.IsNullOrEmpty (id)) {
return id;
} else if (!string.IsNullOrEmpty (Email)) {
return Email;
} else {
return Name;
}
}
set {
id = value;
}
}
[Property (Group = "General", Ldap = "cn")]
public string Name { get; set; }
[Property (Group = "General", Ldap = "givenName")]
public string FirstName { get; set; }
[Property (Group = "General", Ldap = "initials")]
public string Initials { get; set; }
[Property (Group = "General", Ldap = "sn")]
public string LastName { get; set; }
[Property (Group = "General", Ldap = "displayName")]
public string DisplayName { get; set; }
[Property (Group = "General", Ldap = "description")]
public string Description { get; set; }
[Property (Group = "Contact", Ldap = "physicalDeliveryOfficeName,roomNumber")]
public string Office { get; set; }
[Property (Group = "Contact", Ldap = "telephoneNumber,otherTelephone")]
public List<string> TelephoneNumbers { get; set; }
[Property (Group = "Contact", Ldap = "homePhone,otherHomePhone")]
public List<string> HomeNumbers { get; set; }
[Property (Group = "Contact", Ldap = "mobile,otherMobile")]
public List<string> MobileNumbers { get; set; }
string email;
[Property (Group = "Contact", Ldap = "mail")]
public string Email {
get {
return email;
}
set {
email = value;
PrecacheImage ();
}
}
[Property (Group = "Contact", Ldap = "wWWHomePage")]
public string WebPage { get; set; }
[Property (Group = "Contact", Ldap = "notes")]
public string Info { get; set; }
[Property (Group = "Contact", Ldap = "twitter")]
public string Twitter { get; set; }
[Property (Group = "Address", Ldap = "street,streetAddress")]
public string Street { get; set; }
[Property (Group = "Address", Ldap = "postOfficeBox")]
public string POBox { get; set; }
[Property (Group = "Address", Ldap = "l,localityName")]
public string City { get; set; }
[Property (Group = "Address", Ldap = "st,stateOrProvinceName")]
public string State { get; set; }
[Property (Group = "Address", Ldap = "postalCode")]
public string PostalCode { get; set; }
[Property (Group = "Address", Ldap = "c,co,countryCode")]
public string Country { get; set; }
[Property (Group = "Organization", Ldap = "title")]
public string Title { get; set; }
[Property (Group = "Organization", Ldap = "department,ou,organizationalUnitName")]
public string Department { get; set; }
[Property (Group = "Organization", Ldap = "company,o,organizationName")]
public string Company { get; set; }
[Property (Group = "Organization", Ldap = "manager")]
public string Manager { get; set; }
#region Derived Properties
public Uri GravatarUrl {
get {
return HasEmail ? EmployeeDirectory.Utilities.Gravatar.GetImageUrl (Email, 80) :
new Uri("http://www.fao.org/fileadmin/templates/aiq2013/images/user-placeholder.jpg");
}
}
public bool HasEmail {
get {
return !string.IsNullOrWhiteSpace (Email);
}
}
private async void PrecacheImage ()
{
if (!HasEmail)
return;
try {
System.Diagnostics.Debug.WriteLine (GravatarUrl.AbsoluteUri);
LocalImagePath = await FileCache.Download (GravatarUrl, Email);
} catch (Exception ex) {
System.Diagnostics.Debug.WriteLine (ex);
}
}
string localImagePath = "Placeholder.jpg";
public string LocalImagePath {
get {
return localImagePath;
}
set {
if (string.IsNullOrEmpty (value)) {
value = "Placeholder.jpg";
} else {
localImagePath = value;
}
}
}
public ImageSource Photo {
get {
return Device.OnPlatform (
FileImageSource.FromUri (GravatarUrl),
FileImageSource.FromFile (LocalImagePath),
FileImageSource.FromUri (GravatarUrl)
);
}
}
public string TitleAndDepartment {
get {
var hasTitle = !string.IsNullOrEmpty (Title);
var hasDepartment = !string.IsNullOrEmpty (Department);
if (hasTitle && hasDepartment) {
return (Title + " - " + Department).Trim ();
} else if (hasTitle && !hasDepartment) {
return Title.Trim ();
} else if (!hasTitle && hasDepartment) {
return Department.Trim ();
} else {
return "";
}
}
}
public string FirstNameAndInitials {
get {
if (!string.IsNullOrWhiteSpace (FirstName)) {
if (!string.IsNullOrWhiteSpace (Initials)) {
return FirstName + " " + Initials;
} else {
return FirstName;
}
} else {
return SplitFirstAndLastName () [0];
}
}
}
public string SafeFirstName {
get {
if (!string.IsNullOrWhiteSpace (FirstName)) {
return FirstName;
} else {
return SplitFirstAndLastName () [0];
}
}
}
public string SafeLastName {
get {
if (!string.IsNullOrWhiteSpace (LastName)) {
return LastName;
} else {
return SplitFirstAndLastName () [1];
}
}
}
public string SafeDisplayName {
get {
if (!string.IsNullOrWhiteSpace (DisplayName)) {
return DisplayName;
} else if (!string.IsNullOrWhiteSpace (Name)) {
return Name;
} else if (!string.IsNullOrEmpty (Initials)) {
return FirstName + " " + Initials + " " + LastName;
} else {
return FirstName + " " + LastName;
}
}
}
#endregion
public Person ()
{
TelephoneNumbers = new List<string> ();
HomeNumbers = new List<string> ();
MobileNumbers = new List<string> ();
}
public override string ToString ()
{
return SafeDisplayName;
}
static readonly char[] WS = new [] { ' ', '\t', '\r', '\n' };
string[] SplitFirstAndLastName ()
{
var r = new [] { "", "" };
var parts = SafeDisplayName.Split (WS, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 1) {
r [0] = parts [0];
} else if (parts.Length == 2) {
r [0] = parts [0];
r [1] = parts [1];
} else {
var li = parts.Length - 1;
while (li - 1 > 0 && char.IsLower (parts [li - 1] [0])) {
li--;
}
r [0] = string.Join (" ", parts.Take (li));
r [1] = string.Join (" ", parts.Skip (li));
}
return r;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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 Import
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.CRM.Core;
using ASC.CRM.Core.Dao;
using ASC.CRM.Core.Entities;
using ASC.MessagingSystem;
using ASC.Web.CRM.Classes;
using ASC.Web.CRM.Controls.Common;
using ASC.Web.CRM.Core;
using ASC.Web.CRM.Resources;
using ASC.Web.CRM.Services.NotifyService;
using ASC.Web.Studio.Core.Users;
using Autofac;
#endregion
namespace ASC.Web.CRM.Controls.Deals
{
public partial class DealActionView : BaseUserControl
{
#region Members
public static string Location
{
get { return PathProvider.GetFileStaticRelativePath("Deals/DealActionView.ascx"); }
}
public Deal TargetDeal { get; set; }
protected bool HavePermission { get; set; }
private const string ErrorCookieKey = "save_opportunity_error";
#endregion
#region Events
public bool IsSelectedBidCurrency(String abbreviation)
{
return TargetDeal != null ?
String.Compare(abbreviation, TargetDeal.BidCurrency) == 0 :
String.Compare(abbreviation, Global.TenantSettings.DefaultCurrency.Abbreviation, true) == 0;
}
protected void Page_Load(object sender, EventArgs e)
{
if (TargetDeal != null)
{
HavePermission = CRMSecurity.IsAdmin || TargetDeal.CreateBy == SecurityContext.CurrentAccount.ID;
}
else
{
HavePermission = true;
}
if (TargetDeal == null)
{
saveDealButton.Text = CRMDealResource.AddThisDealButton;
saveAndCreateDealButton.Text = CRMDealResource.AddThisAndCreateDealButton;
cancelButton.Attributes.Add("href",
Request.UrlReferrer != null && Request.Url != null && String.Compare(Request.UrlReferrer.PathAndQuery, Request.Url.PathAndQuery) != 0
? Request.UrlReferrer.OriginalString
: "Deals.aspx");
}
else
{
saveDealButton.Text = CRMCommonResource.SaveChanges;
cancelButton.Attributes.Add("href", String.Format("Deals.aspx?id={0}", TargetDeal.ID));
RegisterClientScriptHelper.DataListContactTab(Page, TargetDeal.ID, EntityType.Opportunity);
}
RegisterClientScriptHelper.DataDealActionView(Page, TargetDeal);
if (HavePermission)
{
InitPrivatePanel();
}
RegisterScript();
}
protected void InitPrivatePanel()
{
var cntrlPrivatePanel = (PrivatePanel)LoadControl(PrivatePanel.Location);
cntrlPrivatePanel.CheckBoxLabel = CRMDealResource.PrivatePanelCheckBoxLabel;
if (TargetDeal != null)
{
cntrlPrivatePanel.IsPrivateItem = CRMSecurity.IsPrivate(TargetDeal);
if (cntrlPrivatePanel.IsPrivateItem)
cntrlPrivatePanel.SelectedUsers = CRMSecurity.GetAccessSubjectTo(TargetDeal);
}
var usersWhoHasAccess = new List<string> { CustomNamingPeople.Substitute<CRMCommonResource>("CurrentUser"), CRMDealResource.ResponsibleDeal };
cntrlPrivatePanel.UsersWhoHasAccess = usersWhoHasAccess;
cntrlPrivatePanel.DisabledUsers = new List<Guid> { SecurityContext.CurrentAccount.ID };
phPrivatePanel.Controls.Add(cntrlPrivatePanel);
}
#endregion
#region Save Or Update Deal
protected void SaveOrUpdateDeal(Object sender, CommandEventArgs e)
{
try
{
using (var scope = DIHelper.Resolve())
{
var dao = scope.Resolve<DaoFactory>();
int dealID;
var _isPrivate = false;
var _selectedUsersWithoutCurUsr = new List<Guid>();
#region BaseInfo
var deal = new Deal
{
Title = Request["nameDeal"],
Description = Request["descriptionDeal"],
DealMilestoneID = Convert.ToInt32(Request["dealMilestone"])
};
int contactID;
if (int.TryParse(Request["selectedContactID"], out contactID))
deal.ContactID = contactID;
int probability;
if (int.TryParse(Request["probability"], out probability))
deal.DealMilestoneProbability = probability;
if (deal.DealMilestoneProbability < 0) deal.DealMilestoneProbability = 0;
if (deal.DealMilestoneProbability > 100) deal.DealMilestoneProbability = 100;
deal.BidCurrency = Request["bidCurrency"];
if (String.IsNullOrEmpty(deal.BidCurrency))
deal.BidCurrency = Global.TenantSettings.DefaultCurrency.Abbreviation;
else
deal.BidCurrency = deal.BidCurrency.ToUpper();
if (!String.IsNullOrEmpty(Request["bidValue"]))
{
decimal bidValue;
if (!decimal.TryParse(Request["bidValue"], out bidValue))
bidValue = 0;
deal.BidValue = bidValue;
deal.BidType = (BidType)Enum.Parse(typeof(BidType), Request["bidType"]);
if (deal.BidType != BidType.FixedBid)
{
int perPeriodValue;
if (int.TryParse(Request["perPeriodValue"], out perPeriodValue))
deal.PerPeriodValue = perPeriodValue;
}
}
else
{
deal.BidValue = 0;
deal.BidType = BidType.FixedBid;
}
DateTime expectedCloseDate;
if (!DateTime.TryParse(Request["expectedCloseDate"], out expectedCloseDate))
expectedCloseDate = DateTime.MinValue;
deal.ExpectedCloseDate = expectedCloseDate;
deal.ResponsibleID = new Guid(Request["responsibleID"]);
#endregion
#region Validation
CRMSecurity.DemandCreateOrUpdate(deal);
if (HavePermission)
{
var CurrentAccountID = SecurityContext.CurrentAccount.ID;
bool value;
if (bool.TryParse(Request.Form["isPrivateDeal"], out value))
{
_isPrivate = value;
}
if (_isPrivate)
{
_selectedUsersWithoutCurUsr = Request.Form["selectedPrivateUsers"]
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(item => new Guid(item)).Where(i => i != CurrentAccountID).Distinct().ToList();
foreach (var uID in _selectedUsersWithoutCurUsr)
{
var usr = CoreContext.UserManager.GetUsers(uID);
if (usr.IsVisitor()) throw new ArgumentException();
}
if (deal.ResponsibleID != CurrentAccountID)
{
_selectedUsersWithoutCurUsr.Add(deal.ResponsibleID);
var responsible = CoreContext.UserManager.GetUsers(deal.ResponsibleID);
if (responsible.IsVisitor())
throw new ArgumentException(CRMErrorsResource.ResponsibleCannotBeVisitor);
}
}
}
#endregion
var dealMilestone = dao.DealMilestoneDao.GetByID(deal.DealMilestoneID);
if (TargetDeal == null)
{
if (dealMilestone.Status != DealMilestoneStatus.Open)
deal.ActualCloseDate = TenantUtil.DateTimeNow();
dealID = dao.DealDao.CreateNewDeal(deal);
deal.ID = dealID;
deal.CreateBy = SecurityContext.CurrentAccount.ID;
deal.CreateOn = TenantUtil.DateTimeNow();
deal = dao.DealDao.GetByID(dealID);
SetPermission(deal, _isPrivate, _selectedUsersWithoutCurUsr);
if (deal.ResponsibleID != Guid.Empty && deal.ResponsibleID != SecurityContext.CurrentAccount.ID)
{
NotifyClient.Instance.SendAboutResponsibleForOpportunity(deal);
}
MessageService.Send(HttpContext.Current.Request, MessageAction.OpportunityCreated,
MessageTarget.Create(deal.ID), deal.Title);
}
else
{
dealID = TargetDeal.ID;
deal.ID = TargetDeal.ID;
deal.ActualCloseDate = TargetDeal.ActualCloseDate;
if (TargetDeal.ResponsibleID != Guid.Empty && TargetDeal.ResponsibleID != deal.ResponsibleID)
NotifyClient.Instance.SendAboutResponsibleForOpportunity(deal);
if (TargetDeal.DealMilestoneID != deal.DealMilestoneID)
deal.ActualCloseDate = dealMilestone.Status != DealMilestoneStatus.Open
? TenantUtil.DateTimeNow()
: DateTime.MinValue;
dao.DealDao.EditDeal(deal);
deal = dao.DealDao.GetByID(dealID);
SetPermission(deal, _isPrivate, _selectedUsersWithoutCurUsr);
MessageService.Send(HttpContext.Current.Request, MessageAction.OpportunityUpdated,
MessageTarget.Create(deal.ID), deal.Title);
}
#region Members
var dealMembers = !String.IsNullOrEmpty(Request["selectedMembersID"])
? Request["selectedMembersID"].Split(new[] { ',' }).Select(
id => Convert.ToInt32(id)).Where(id => id != deal.ContactID).ToList()
: new List<int>();
var dealMembersContacts =
dao.ContactDao.GetContacts(dealMembers.ToArray()).Where(CRMSecurity.CanAccessTo).ToList();
dealMembers = dealMembersContacts.Select(m => m.ID).ToList();
if (deal.ContactID > 0)
dealMembers.Add(deal.ContactID);
dao.DealDao.SetMembers(dealID, dealMembers.ToArray());
#endregion
#region CustomFields
foreach (var customField in Request.Form.AllKeys)
{
if (!customField.StartsWith("customField_")) continue;
var fieldID = Convert.ToInt32(customField.Split('_')[1]);
var fieldValue = Request.Form[customField];
if (String.IsNullOrEmpty(fieldValue) && TargetDeal == null)
continue;
dao.CustomFieldDao.SetFieldValue(EntityType.Opportunity, dealID, fieldID, fieldValue);
}
#endregion
string redirectUrl;
if (TargetDeal == null && UrlParameters.ContactID != 0)
{
redirectUrl =
string.Format(
e.CommandArgument.ToString() == "1"
? "Deals.aspx?action=manage&contactID={0}"
: "Default.aspx?id={0}#deals", UrlParameters.ContactID);
}
else
{
redirectUrl = e.CommandArgument.ToString() == "1"
? "Deals.aspx?action=manage"
: string.Format("Deals.aspx?id={0}", dealID);
}
Response.Redirect(redirectUrl, false);
Context.ApplicationInstance.CompleteRequest();
}
}
catch (Exception ex)
{
LogManager.GetLogger("ASC.CRM").Error(ex);
var cookie = HttpContext.Current.Request.Cookies.Get(ErrorCookieKey);
if (cookie == null)
{
cookie = new HttpCookie(ErrorCookieKey)
{
Value = ex.Message
};
HttpContext.Current.Response.Cookies.Add(cookie);
}
}
}
#endregion
#region Methods
protected void SetPermission(Deal deal, bool isPrivate, List<Guid> selectedUsersWithoutCurUsr)
{
if (HavePermission)
{
var notifyPrivateUsers = false;
bool value;
if (bool.TryParse(Request.Form["notifyPrivateUsers"], out value))
{
notifyPrivateUsers = value;
}
if (isPrivate)
{
if (notifyPrivateUsers)
Services.NotifyService.NotifyClient.Instance.SendAboutSetAccess(EntityType.Opportunity, deal.ID, DaoFactory, selectedUsersWithoutCurUsr.ToArray());
selectedUsersWithoutCurUsr.Add(SecurityContext.CurrentAccount.ID);
CRMSecurity.SetAccessTo(deal, selectedUsersWithoutCurUsr);
}
else
{
CRMSecurity.MakePublic(deal);
}
}
}
private void RegisterScript()
{
var sb = new StringBuilder();
sb.AppendFormat(@"ASC.CRM.DealActionView.init(""{0}"", ""{1}"");",
TenantUtil.DateTimeNow().ToString(DateTimeExtension.DateFormatPattern),
ErrorCookieKey);
Page.RegisterInlineScript(sb.ToString());
}
#endregion
}
}
| |
//
// MenuItem.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.ComponentModel;
using Xwt.Drawing;
using Xwt.Accessibility;
namespace Xwt
{
[BackendType (typeof(IMenuItemBackend))]
public class MenuItem: XwtComponent, ICellContainer
{
CellViewCollection cells;
Menu subMenu;
EventHandler clicked;
Image image;
protected class MenuItemBackendHost: BackendHost<MenuItem,IMenuItemBackend>, IMenuItemEventSink
{
protected override void OnBackendCreated ()
{
base.OnBackendCreated ();
Backend.Initialize (this);
}
public void OnClicked ()
{
Parent.DoClick ();
}
}
Accessible accessible;
public Accessible Accessible {
get {
if (accessible == null) {
accessible = new Accessible (this);
}
return accessible;
}
}
protected override Xwt.Backends.BackendHost CreateBackendHost ()
{
return new MenuItemBackendHost ();
}
static MenuItem ()
{
MapEvent (MenuItemEvent.Clicked, typeof(MenuItem), "OnClicked");
}
public MenuItem ()
{
if (!IsSeparator)
UseMnemonic = true;
}
public MenuItem (Command command)
{
VerifyConstructorCall (this);
LoadCommandProperties (command);
}
public MenuItem (string label)
{
VerifyConstructorCall (this);
Label = label;
}
protected void LoadCommandProperties (Command command)
{
Label = command.Label;
Image = command.Icon;
}
IMenuItemBackend Backend {
get { return (IMenuItemBackend) base.BackendHost.Backend; }
}
bool IsSeparator {
get { return this is SeparatorMenuItem; }
}
[DefaultValue ("")]
public string Label {
get { return Backend.Label; }
set {
if (IsSeparator)
throw new NotSupportedException ();
Backend.Label = value;
}
}
string markup;
/// <summary>
/// Gets or sets the text with markup to display.
/// </summary>
/// <remarks>
/// <see cref="Xwt.FormattedText"/> for supported formatting options.</remarks>
[DefaultValue ("")]
public string Markup {
get { return markup; }
set {
markup = value;
var t = FormattedText.FromMarkup (markup);
Backend.SetFormattedText (t);
}
}
/// <summary>
/// Gets or sets the tooltip text.
/// </summary>
/// <value>The tooltip text.</value>
[DefaultValue("")]
public string TooltipText
{
get { return Backend.TooltipText ?? ""; }
set
{
if (IsSeparator)
throw new NotSupportedException();
Backend.TooltipText = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Xwt.Button"/> uses a mnemonic.
/// </summary>
/// <value><c>true</c> if it uses a mnemonic; otherwise, <c>false</c>.</value>
/// <remarks>
/// When set to true, the character after the first underscore character in the Label property value is
/// interpreted as the mnemonic for that Label.
/// </remarks>
[DefaultValue(true)]
public bool UseMnemonic {
get { return Backend.UseMnemonic; }
set {
if (IsSeparator)
throw new NotSupportedException ();
Backend.UseMnemonic = value;
}
}
[DefaultValue (true)]
public bool Sensitive {
get { return Backend.Sensitive; }
set { Backend.Sensitive = value; }
}
[DefaultValue (true)]
public bool Visible {
get { return Backend.Visible; }
set { Backend.Visible = value; }
}
public Image Image {
get { return image; }
set {
if (IsSeparator)
throw new NotSupportedException ();
image = value;
if (!IsSeparator)
Backend.SetImage (image != null ? image.GetImageDescription (BackendHost.ToolkitEngine) : ImageDescription.Null);
}
}
public void Show ()
{
Visible = true;
}
public void Hide ()
{
Visible = false;
}
public CellViewCollection Cells {
get {
if (cells == null)
cells = new CellViewCollection (this);
return cells;
}
}
public Menu SubMenu {
get { return subMenu; }
set {
if (IsSeparator)
throw new NotSupportedException ();
Backend.SetSubmenu ((IMenuBackend)BackendHost.ToolkitEngine.GetSafeBackend (value));
subMenu = value;
}
}
public void NotifyCellChanged ()
{
throw new NotImplementedException ();
}
internal virtual void DoClick ()
{
OnClicked (EventArgs.Empty);
}
protected virtual void OnClicked (EventArgs e)
{
if (clicked != null)
clicked (this, e);
}
public event EventHandler Clicked {
add {
base.BackendHost.OnBeforeEventAdd (MenuItemEvent.Clicked, clicked);
clicked += value;
}
remove {
clicked -= value;
base.BackendHost.OnAfterEventRemove (MenuItemEvent.Clicked, clicked);
}
}
protected override void Dispose (bool release_all)
{
if (release_all) {
Backend.Dispose ();
}
base.Dispose (release_all);
}
}
public enum MenuItemType
{
Normal,
CheckBox,
RadioButton
}
}
| |
#region Using directives
using Google.GData.Client;
#endregion
//////////////////////////////////////////////////////////////////////
// <summary>GDataParserNameTable</summary>
//////////////////////////////////////////////////////////////////////
namespace Google.GData.Extensions
{
/// <summary>
/// Subclass of the nametable, has the extensions for the GNamespace
/// </summary>
public class GDataParserNameTable : BaseNameTable
{
/// <summary>the google calendar namespace</summary>
public const string NSGCal = "http://schemas.google.com/gCal/2005";
/// <summary>the google calendar prefix</summary>
public const string gCalPrefix = "gCal";
/// <summary>
/// the starting string to define contacts relationship values
/// </summary>
public const string gContactsRel = "http://schemas.google.com/contacts/2008/rel";
/// <summary>
/// a relationship to a photo
/// </summary>
public const string ServicePhoto = gContactsRel + "#photo";
/// <summary>the event prefix </summary>
public const string Event = gNamespacePrefix + "event";
#region element strings
/// <summary> timezone indicator on the feedlevel</summary>
public const string XmlTimeZoneElement = "timezone";
/// <summary>static string for parsing</summary>
public const string XmlWhenElement = "when";
/// <summary>static string for parsing</summary>
public const string XmlWhereElement = "where";
/// <summary>static string for parsing</summary>
public const string XmlWhoElement = "who";
/// <summary>static string for parsing</summary>
public const string XmlEntryLinkElement = "entryLink";
/// <summary>static string for parsing</summary>
public const string XmlFeedLinkElement = "feedLink";
/// <summary>static string for parsing</summary>
public const string XmlEventStatusElement = "eventStatus";
/// <summary>static string for parsing</summary>
public const string XmlVisibilityElement = "visibility";
/// <summary>static string for parsing</summary>
public const string XmlTransparencyElement = "transparency";
/// <summary>static string for parsing</summary>
public const string XmlAttendeeTypeElement = "attendeeType";
/// <summary>static string for parsing</summary>
public const string XmlAttendeeStatusElement = "attendeeStatus";
/// <summary>static string for parsing</summary>
public const string XmlRecurrenceElement = "recurrence";
/// <summary>static string for parsing</summary>
public const string XmlRecurrenceExceptionElement = "recurrenceException";
/// <summary>static string for parsing</summary>
public const string XmlOriginalEventElement = "originalEvent";
/// <summary>static string for parsing</summary>
public const string XmlReminderElement = "reminder";
/// <summary>static string for parsing</summary>
public const string XmlCommentsElement = "comments";
/// <summary>static string for parsing the color element in a calendar</summary>
public const string XmlColorElement = "color";
/// <summary>static string for parsing the selected element in a calendar</summary>
public const string XmlSelectedElement = "selected";
/// <summary>static string for parsing the ACL element in a calendar</summary>
public const string XmlAccessLevelElement = "accesslevel";
/// <summary>static string for parsing the hidden element in a calendar</summary>
public const string XmlHiddenElement = "hidden";
/// <summary>static string for parsing the email element in a contact</summary>
public const string XmlEmailElement = "email";
/// <summary>static string for parsing the IM element in a contact</summary>
public const string XmlIMElement = "im";
/// <summary>static string for parsing the phonenumber element in a contact</summary>
public const string XmlPhoneNumberElement = "phoneNumber";
/// <summary>static string for parsing the postalAddress element in a contact</summary>
public const string XmlPostalAddressElement = "postalAddress";
/// <summary>static string for parsing the Organization element in a contact</summary>
public const string XmlOrganizationElement = "organization";
/// <summary>static string for parsing the deleted element in a contacts</summary>
public const string XmlDeletedElement = "deleted";
/// <summary>static string for parsing the organization name element in a contacts</summary>
public const string XmlOrgNameElement = "orgName";
/// <summary>static string for parsing the organization symbol element in a contacts</summary>
public const string XmlOrgSymbolElement = "orgSymbol";
/// <summary>static string for parsing the organization job description element in a contacts</summary>
public const string XmlOrgJobDescriptionElement = "orgJobDescription";
/// <summary>static string for parsing the organization department element in a contacts</summary>
public const string XmlOrgDepartmentElement = "orgDepartment";
/// <summary>static string for parsing the organization title element in a contacts</summary>
public const string XmlOrgTitleElement = "orgTitle";
/// <summary>static string for parsing the quotaBytesUsed element </summary>
public const string XmlQuotaBytesUsedElement = "quotaBytesUsed";
/// <summary>xmlelement for gd:rating</summary>
public const string XmlRatingElement = "rating";
/// <summary>xml attribute min for gd:rating</summary>
public const string XmlAttributeMin = "min";
/// <summary>xml attribute max for gd:rating</summary>
public const string XmlAttributeMax = "max";
/// <summary>xml attribute numRaters for gd:rating</summary>
public const string XmlAttributeNumRaters = "numRaters";
/// <summary>xml attribute average for gd:rating</summary>
public const string XmlAttributeAverage = "average";
#endregion
#region attribute strings
/// <summary>static string for parsing</summary>
public const string XmlAttributeStartTime = "startTime";
/// <summary>static string for parsing</summary>
public const string XmlAttributeEndTime = "endTime";
/// <summary>static string for parsing</summary>
public const string XmlAttributeValueString = "valueString";
/// <summary>static string for parsing the email in gd:who</summary>
public const string XmlAttributeEmail = "email";
/// <summary>static string for parsing</summary>
public const string XmlAttributeRel = "rel";
/// <summary>static string for parsing</summary>
public const string XmlAttributeLabel = "label";
/// <summary>static string for parsing</summary>
public const string XmlAttributeHref = "href";
/// <summary>static string for parsing</summary>
public const string XmlAttributeCountHint = "countHint";
/// <summary>static string for parsing</summary>
public const string XmlAttributeReadOnly = "readOnly";
/// <summary>static string for parsing</summary>
public const string XmlAttributeId = "id";
/// <summary>static string for parsing</summary>
public const string XmlAttributeDays = "days";
/// <summary>static string for parsing</summary>
public const string XmlAttributeHours = "hours";
/// <summary>static string for parsing</summary>
public const string XmlAttributeMinutes = "minutes";
/// <summary>static string for parsing</summary>
public const string XmlAttributeAbsoluteTime = "absoluteTime";
/// <summary>static string for parsing the specialized attribute on a RecurringException</summary>
public const string XmlAttributeSpecialized = "specialized";
/// <summary>static string for parsing</summary>
public const string XmlAttributeMethod = "method";
/// <summary>static string for parsing the address attribute</summary>
public const string XmlAttributeAddress = "address";
/// <summary>static string for parsing the primary attribute</summary>
public const string XmlAttributePrimary = "primary";
/// <summary>static string for parsing the protocol attribute</summary>
public const string XmlAttributeProtocol = "protocol";
/// <summary>static string for parsing the uri attribute</summary>
public const string XmlAttributeUri = "uri";
/// <summary>static string for parsing the displayname attribute</summary>
public const string XmlAttributeDisplayName = "displayName";
/// <summary>
/// a resource id
/// </summary>
public const string XmlResourceIdElement = "resourceId";
/// <summary>
/// lastviewed constant
/// </summary>
/// <returns></returns>
public const string XmlLastViewedElement = "lastViewed";
/// <summary>
/// lastviewed constant
/// </summary>
/// <returns></returns>
public const string XmlLastModifiedByElement = "lastModifiedBy";
#endregion
#region Calendar specific (consider moving to seperate table)
/// <summary>static string for parsing a webcontent element</summary>
public const string XmlWebContentElement = "webContent";
/// <summary>static string for parsing a webcontent element</summary>
public const string XmlWebContentGadgetElement = "webContentGadgetPref";
/// <summary>static string for parsing the extendedProperty element</summary>
public const string XmlExtendedPropertyElement = "extendedProperty";
/// <summary>static string for the url attribute</summary>
public const string XmlAttributeUrl = "url";
/// <summary>static string for the display attribute</summary>
public const string XmlAttributeDisplay = "display";
/// <summary>static string for the width attribute</summary>
public const string XmlAttributeWidth = "width";
/// <summary>static string for the height attribute</summary>
public const string XmlAttributeHeight = "height";
/// <summary>static string for the sendEventNotifications element</summary>
public const string XmlSendNotificationsElement = "sendEventNotifications";
/// <summary>static string for the quickAdd element</summary>
public const string XmlQuickAddElement = "quickadd";
#endregion
#region Contacts specific
/// <summary>
/// Allows storing person's name in a structured way. Consists of given name, additional name, family name, prefix, suffix and full name.
/// </summary>
public const string NameElement = "name";
/// <summary>
/// Person's given name
/// </summary>
public const string GivenNameElement = "givenName";
/// <summary>
/// Additional name of the person, e.g. middle name
/// </summary>
public const string AdditionalNameElement = "additionalName";
/// <summary>
/// Person's family Name
/// </summary>
public const string FamilyNameElement = "familyName";
/// <summary>
/// honorific prefix, eg. Mr or Mrs
/// </summary>
public const string NamePrefixElement = "namePrefix";
/// <summary>
/// Honorific suffix, eg. san
/// </summary>
public const string NameSuffixElement = "nameSuffix";
/// <summary>
/// Unstructured representation of the name
/// </summary>
public const string FullNameElement = "fullName";
/// <summary>
/// Postal address split into components. It allows to store the address in locale independent format.
/// The fields can be interpreted and used to generate formatted, locale dependent address.
/// </summary>
public const string StructuredPostalAddressElement = "structuredPostalAddress";
/// <summary>
/// The agent who actually receives the mail.
/// </summary>
public const string AgentElement = "agent";
/// <summary>
/// Used in places where houses have names
/// </summary>
public const string HousenameElement = "housename";
/// <summary>
/// Can be stree, avenue, road, etc
/// </summary>
public const string StreetElement = "street";
/// <summary>
/// Covers actual P.O. Boxes, drawers, locked bags etc
/// </summary>
public const string PoboxElement = "pobox";
/// <summary>
/// This is used to disambiguate a street address when a city contains
/// more than one street with the same name, or to specify a small place whose
/// mail is routed through a larger postal town.
/// In China it could be a county or a minor city.
/// </summary>
public const string NeighborhoodElement = "neighborhood";
/// <summary>
/// Can be City, village etc
/// </summary>
public const string CityElement = "city";
/// <summary>
/// Administrative districts
/// </summary>
public const string SubregionElement = "subregion";
/// <summary>
/// A state, province etc
/// </summary>
public const string RegionElement = "region";
/// <summary>
/// Postal code
/// </summary>
public const string PostcodeElement = "postcode";
/// <summary>
/// The name or code of the country
/// </summary>
public const string CountryElement = "country";
/// <summary>
/// The full, unstructured postal address
/// </summary>
public const string FormattedAddressElement = "formattedAddress";
/// <summary>
/// The full, unstructured postal address
/// </summary>
public const string XmlAttributeMailClass = "mailClass";
/// <summary>
/// The full, unstructured postal address
/// </summary>
public const string XmlAttributeUsage = "usage";
#endregion
}
/////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////
| |
#nullable enable
using System;
using System.Linq;
using System.Threading;
using System.Collections;
using System.ComponentModel;
using LanguageExt.TypeClasses;
using static LanguageExt.Prelude;
using LanguageExt.ClassInstances;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace LanguageExt
{
/// <summary>
/// <para>
/// Versioned hash-map. Each value has a vector-clock attached to it which understands the causality of updates
/// from multiple actors. Actors are just unique keys that represent individual contributors. They could be client
/// connections, nodes in a network, users, or whatever is appropriate to discriminate between commits.
/// </para>
/// <para>
/// Deleted items are not removed from the hash-map, they are merely marked as deleted. This allows conflicts between
/// writes and deletes to be resolved.
/// </para>
/// <para>
/// Run `RemoveDeletedItemsOlderThan` to clean up items that have been deleted and are now just hanging around. Use
/// a big enough delay that it won't conflict with other commits (this could be seconds, minutes, or longer:
/// depending on the expected latency of writes to the hash-map).
/// </para>
/// </summary>
public class VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V> :
IEnumerable<(K Key, V Value)>,
IEquatable<VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V>>
where OrdActor : struct, Ord<Actor>
where EqK : struct, Eq<K>
where ConflictV : struct, Conflict<V>
{
internal volatile TrieMap<EqK, K, VersionVector<ConflictV, OrdActor, TLong, Actor, long, V>> Items;
/// <summary>
/// Empty version map
/// </summary>
public static VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V> Empty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V>(TrieMap<EqK, K, VersionVector<ConflictV, OrdActor, TLong, Actor, long, V>>.Empty);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="items">Trie map</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
VersionHashMap(TrieMap<EqK, K, VersionVector<ConflictV, OrdActor, TLong, Actor, long, V>> items) =>
this.Items = items;
/// <summary>
/// 'this' accessor
/// </summary>
/// <param name="key">Key</param>
/// <returns>Version - this may be in a state of never existing, but won't ever fail</returns>
[Pure]
public Version<Actor, K, V> this[K key]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => FindVersion(key);
}
/// <summary>
/// Is the map empty
/// </summary>
[Pure]
public bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Items.IsEmpty;
}
/// <summary>
/// Number of items in the map
/// </summary>
[Pure]
public int Count
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Items.Count;
}
/// <summary>
/// Alias of Count
/// </summary>
[Pure]
public int Length
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Items.Count;
}
/// <summary>
/// Atomically swap a key in the map. Allows for multiple operations on the hash-map in an entirely
/// transactional and atomic way.
/// </summary>
/// <param name="swap">Swap function, maps the current state of the value associated with the key to a new state</param>
/// <remarks>Any functions passed as arguments may be run multiple times if there are multiple threads competing
/// to update this data structure. Therefore the functions must spend as little time performing the injected
/// behaviours as possible to avoid repeated attempts</remarks>
public Unit SwapKey(K key, Func<Version<Actor, K, V>, Version<Actor, K, V>> swap)
{
SpinWait sw = default;
while (true)
{
var oitems = Items;
var okey = oitems.Find(key)
.Map(v => v.ToVersion(key))
.IfNone(() => VersionNeverExistedVector<ConflictV, OrdActor, Actor, K, V>.New(key));
var nversion = swap(okey);
var nitems = oitems.AddOrMaybeUpdate(key,
exists => exists.Put(nversion.ToVector<ConflictV, OrdActor, Actor, K, V>()),
#nullable disable
() => Optional(nversion.ToVector<ConflictV, OrdActor, Actor, K, V>()));
#nullable enable
if(ReferenceEquals(oitems, nitems))
{
// no change
return default;
}
if (ReferenceEquals(Interlocked.CompareExchange(ref Items, nitems, oitems), oitems))
{
return default;
}
else
{
sw.SpinOnce();
}
}
}
/// <summary>
/// Atomically updates a new item in the map. If the key already exists, then the vector clocks, within the version
/// vector, are compared to ascertain if the proposed version was caused-by, causes, or conflicts with the current
/// version:
///
/// * If the proposed version was caused-by the current version, then it is ignored.
/// * If the proposed version causes the current version, then it is accepted and updated as the latest version
/// * If the proposed version is in conflict with the current version, then values from both versions are
/// passed to ConflictV.Append(v1, v2) for value resolution, and the pairwise-maximum of the two vector-clocks
/// is taken to be the new 'time.
///
/// </summary>
/// <param name="version">Version to update</param>
public Unit Update(Version<Actor, K, V> nversion)
{
SpinWait sw = default;
while (true)
{
var oitems = Items;
var nitems = oitems.AddOrMaybeUpdate(nversion.Key,
exists => exists.Put(nversion.ToVector<ConflictV, OrdActor, Actor, K, V>()),
#nullable disable
() => Optional(nversion.ToVector<ConflictV, OrdActor, Actor, K, V>()));
#nullable enable
if(ReferenceEquals(oitems, nitems))
{
// no change
return default;
}
if (ReferenceEquals(Interlocked.CompareExchange(ref Items, nitems, oitems), oitems))
{
return default;
}
else
{
sw.SpinOnce();
}
}
}
/// <summary>
/// Remove items that are older than the specified time-stamp
/// </summary>
/// <param name="cutoff">Cut off time-stamp</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Unit RemoveOlderThan(DateTime cutoff) =>
RemoveOlderThan(cutoff.ToUniversalTime().Ticks);
/// <summary>
/// Remove items that are older than the specified time-stamp
/// </summary>
/// <param name="timeStamp">Cut off time-stamp</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Unit RemoveOlderThan(long timeStamp) =>
FilterInPlace((ts, _) => ts > timeStamp);
/// <summary>
/// Remove deleted items that are older than the specified time-stamp
/// </summary>
/// <param name="cutoff">Cut off time-stamp</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Unit RemoveDeletedItemsOlderThan(DateTime cutoff) =>
RemoveDeletedItemsOlderThan(cutoff.ToUniversalTime().Ticks);
/// <summary>
/// Remove deleted items that are older than the specified time-stamp
/// </summary>
/// <param name="timeStamp">Cut off time-stamp</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Unit RemoveDeletedItemsOlderThan(long timeStamp) =>
FilterInPlace((ts, v) => v.IsSome || ts > timeStamp);
/// <summary>
/// Retrieve a value from the map by key
/// </summary>
/// <param name="key">Key to find</param>
/// <returns>Found value</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Option<V> Find(K value) =>
Items.Find(value).Bind(static v => v.Value);
/// <summary>
/// Retrieve a value from the map by key
/// </summary>
/// <param name="key">Key to find</param>
/// <returns>Found value</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Version<Actor, K, V> FindVersion(K key) =>
Items.Find(key).Match(
Some: v => v.ToVersion(key),
None: () => VersionNeverExistedVector<ConflictV, OrdActor, Actor, K, V>.New(key));
/// <summary>
/// Enumerable of keys
/// </summary>
[Pure]
public IEnumerable<K> Keys
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => AsEnumerable().Map(static x => x.Key);
}
/// <summary>
/// Enumerable of value
/// </summary>
[Pure]
public IEnumerable<V> Values
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => AsEnumerable().Map(static x => x.Value);
}
/// <summary>
/// Convert to a HashMap
/// </summary>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HashMap<K, V> ToHashMap() =>
Items.AsEnumerable().Choose(static x => x.Value.Value.Map(v => (x.Key, v))).ToHashMap();
/// <summary>
/// GetEnumerator - IEnumerable interface
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public IEnumerator<(K Key, V Value)> GetEnumerator() =>
Items.AsEnumerable().Choose(static x => x.Value.Value.Map(v => (x.Key, v))).GetEnumerator();
/// <summary>
/// GetEnumerator - IEnumerable interface
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
IEnumerator IEnumerable.GetEnumerator() =>
Items.GetEnumerator();
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Seq<(K Key, V Value)> ToSeq() =>
toSeq(AsEnumerable());
/// <summary>
/// Format the collection as `[(key: value), (key: value), (key: value), ...]`
/// The ellipsis is used for collections over 50 items
/// To get a formatted string with all the items, use `ToFullString`
/// or `ToFullArrayString`.
/// </summary>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string ToString() =>
CollectionFormat.ToShortArrayString(AsEnumerable().Map(kv => $"({kv.Key}: {kv.Value})"), Count);
/// <summary>
/// Format the collection as `(key: value), (key: value), (key: value), ...`
/// </summary>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string ToFullString(string separator = ", ") =>
CollectionFormat.ToFullString(AsEnumerable().Map(kv => $"({kv.Key}: {kv.Value})"), separator);
/// <summary>
/// Format the collection as `[(key: value), (key: value), (key: value), ...]`
/// </summary>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string ToFullArrayString(string separator = ", ") =>
CollectionFormat.ToFullArrayString(AsEnumerable().Map(kv => $"({kv.Key}: {kv.Value})"), separator);
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public IEnumerable<(K Key, V Value)> AsEnumerable() =>
Items.AsEnumerable().Choose(static x => x.Value.Value.Map(v => (x.Key, v)));
/// <summary>
/// Returns True if 'other' is a proper subset of this set
/// </summary>
/// <returns>True if 'other' is a proper subset of this set</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsProperSubsetOf(IEnumerable<(K Key, V Value)> other) =>
ToHashMap().IsProperSubsetOf(other);
/// <summary>
/// Returns True if 'other' is a proper subset of this set
/// </summary>
/// <returns>True if 'other' is a proper subset of this set</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsProperSubsetOf(IEnumerable<K> other) =>
Items.IsProperSubsetOf(other);
/// <summary>
/// Returns True if 'other' is a proper superset of this set
/// </summary>
/// <returns>True if 'other' is a proper superset of this set</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsProperSupersetOf(IEnumerable<(K Key, V Value)> other) =>
ToHashMap().IsProperSupersetOf(other);
/// <summary>
/// Returns True if 'other' is a proper superset of this set
/// </summary>
/// <returns>True if 'other' is a proper superset of this set</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsProperSupersetOf(IEnumerable<K> other) =>
Items.IsProperSupersetOf(other);
/// <summary>
/// Returns True if 'other' is a superset of this set
/// </summary>
/// <returns>True if 'other' is a superset of this set</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsSubsetOf(IEnumerable<(K Key, V Value)> other) =>
ToHashMap().IsSubsetOf(other);
/// <summary>
/// Returns True if 'other' is a superset of this set
/// </summary>
/// <returns>True if 'other' is a superset of this set</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsSubsetOf(IEnumerable<K> other) =>
Items.IsSubsetOf(other);
/// <summary>
/// Returns True if 'other' is a superset of this set
/// </summary>
/// <returns>True if 'other' is a superset of this set</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsSubsetOf(HashMap<K, V> other) =>
ToHashMap().IsSubsetOf(other.Value);
/// <summary>
/// Returns True if 'other' is a superset of this set
/// </summary>
/// <returns>True if 'other' is a superset of this set</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsSupersetOf(IEnumerable<(K Key, V Value)> other) =>
ToHashMap().IsSupersetOf(other);
/// <summary>
/// Returns True if 'other' is a superset of this set
/// </summary>
/// <returns>True if 'other' is a superset of this set</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsSupersetOf(IEnumerable<K> rhs) =>
Items.IsSupersetOf(rhs);
/// <summary>
/// Returns the elements that are in both this and other
/// </summary>
public Unit Intersect(IEnumerable<K> rhs)
{
SpinWait sw = default;
var srhs = toSeq(rhs);
while (true)
{
var oitems = this.Items;
var nitems = this.Items.Intersect(srhs);
if (ReferenceEquals(Interlocked.CompareExchange(ref this.Items, nitems, oitems), oitems))
{
return default;
}
else
{
sw.SpinOnce();
}
}
}
/// <summary>
/// Returns True if other overlaps this set
/// </summary>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Overlaps(IEnumerable<(K Key, V Value)> other) =>
ToHashMap().Overlaps(other);
/// <summary>
/// Returns True if other overlaps this set
/// </summary>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Overlaps(IEnumerable<K> other) =>
ToHashMap().Overlaps(other);
/// <summary>
/// Returns this - rhs. Only the items in this that are not in
/// rhs will be returned.
/// </summary>
public Unit Except(IEnumerable<K> rhs)
{
SpinWait sw = default;
var srhs = toSeq(rhs);
while (true)
{
var oitems = this.Items;
var nitems = this.Items.Except(srhs);
if (ReferenceEquals(Interlocked.CompareExchange(ref this.Items, nitems, oitems), oitems))
{
return default;
}
else
{
sw.SpinOnce();
}
}
}
/// <summary>
/// Equality of keys and values with `EqDefault<V>` used for values
/// </summary>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Equals(object obj) =>
obj is VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V> hm && Equals(hm);
/// <summary>
/// Equality of keys and values with `EqDefault<V>` used for values
/// </summary>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V> other) =>
Items.Equals(other.Items);
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode() =>
Items.GetHashCode();
/// <summary>
/// Atomically filter out items that return false when a predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>New map with items filtered</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V> Where(Func<long, Option<V>, bool> pred) =>
new VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V>(Items.Filter(v => pred(v.TimeStamp, v.Value)));
/// <summary>
/// Atomically filter out items that return false when a predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>New map with items filtered</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V> Where(Func<K, long, Option<V>, bool> pred) =>
new VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V>(Items.Filter((k, v) => pred(k, v.TimeStamp, v.Value)));
/// <summary>
/// Atomically filter out items that return false when a predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>New map with items filtered</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V> Filter(Func<long, Option<V>, bool> pred) =>
new VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V>(Items.Filter(v => pred(v.TimeStamp, v.Value)));
/// <summary>
/// Atomically filter out items that return false when a predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>New map with items filtered</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V> Filter(Func<K, long, Option<V>, bool> pred) =>
new VersionHashMap<ConflictV, OrdActor, EqK, Actor, K, V>(Items.Filter((k, v) => pred(k, v.TimeStamp, v.Value)));
/// <summary>
/// Atomically filter out items that return false when a predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>New map with items filtered</returns>
public Unit FilterInPlace(Func<long, Option<V>, bool> pred)
{
SpinWait sw = default;
while (true)
{
var oitems = Items;
var nitems = oitems.Filter(v => pred(v.TimeStamp, v.Value));
if (ReferenceEquals(oitems, nitems))
{
// no change
return default;
}
if (ReferenceEquals(Interlocked.CompareExchange(ref Items, nitems, oitems), oitems))
{
return default;
}
else
{
sw.SpinOnce();
}
}
}
/// <summary>
/// Atomically filter out items that return false when a predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>New map with items filtered</returns>
public Unit FilterInPlace(Func<K, long, Option<V>, bool> pred)
{
SpinWait sw = default;
while (true)
{
var oitems = Items;
var nitems = oitems.Filter((k, v) => pred(k, v.TimeStamp, v.Value));
if (ReferenceEquals(oitems, nitems))
{
// no change
return default;
}
if (ReferenceEquals(Interlocked.CompareExchange(ref Items, nitems, oitems), oitems))
{
return default;
}
else
{
sw.SpinOnce();
}
}
}
/// <summary>
/// Return true if all items in the map return true when the predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>True if all items in the map return true when the predicate is applied</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ForAll(Func<K, V, bool> pred)
{
foreach (var (key, value) in AsEnumerable())
{
if (!pred(key, value)) return false;
}
return true;
}
/// <summary>
/// Return true if all items in the map return true when the predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>True if all items in the map return true when the predicate is applied</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ForAll(Func<(K Key, V Value), bool> pred) =>
AsEnumerable().Map(kv => (Key: kv.Key, Value: kv.Value)).ForAll(pred);
/// <summary>
/// Return true if *all* items in the map return true when the predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>True if all items in the map return true when the predicate is applied</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ForAll(Func<KeyValuePair<K, V>, bool> pred) =>
AsEnumerable().Map(kv => new KeyValuePair<K, V>(kv.Key, kv.Value)).ForAll(pred);
/// <summary>
/// Return true if all items in the map return true when the predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>True if all items in the map return true when the predicate is applied</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ForAll(Func<V, bool> pred) =>
AsEnumerable().Map(static x => x.Value).ForAll(pred);
/// <summary>
/// Return true if *any* items in the map return true when the predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>True if all items in the map return true when the predicate is applied</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Exists(Func<K, V, bool> pred)
{
foreach (var (key, value) in AsEnumerable())
{
if (pred(key, value)) return true;
}
return false;
}
/// <summary>
/// Return true if *any* items in the map return true when the predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>True if all items in the map return true when the predicate is applied</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Exists(Func<(K Key, V Value), bool> pred) =>
AsEnumerable().Map(kv => (Key: kv.Key, Value: kv.Value)).Exists(pred);
/// <summary>
/// Return true if *any* items in the map return true when the predicate is applied
/// </summary>
/// <param name="pred">Predicate</param>
/// <returns>True if all items in the map return true when the predicate is applied</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Exists(Func<V, bool> pred) =>
AsEnumerable().Map(static x => x.Value).Exists(pred);
/// <summary>
/// Atomically iterate through all key/value pairs in the map (in order) and execute an
/// action on each
/// </summary>
/// <param name="action">Action to execute</param>
/// <returns>Unit</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Unit Iter(Action<K, V> action)
{
foreach (var (key, value) in this)
{
action(key, value);
}
return unit;
}
/// <summary>
/// Atomically iterate through all values in the map (in order) and execute an
/// action on each
/// </summary>
/// <param name="action">Action to execute</param>
/// <returns>Unit</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Unit Iter(Action<V> action)
{
foreach (var item in this)
{
action(item.Value);
}
return unit;
}
/// <summary>
/// Atomically iterate through all key/value pairs (as tuples) in the map (in order)
/// and execute an action on each
/// </summary>
/// <param name="action">Action to execute</param>
/// <returns>Unit</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Unit Iter(Action<(K Key, V Value)> action)
{
foreach (var item in this)
{
action(item);
}
return unit;
}
/// <summary>
/// Atomically iterate through all key/value pairs in the map (in order) and execute an
/// action on each
/// </summary>
/// <param name="action">Action to execute</param>
/// <returns>Unit</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Unit Iter(Action<KeyValuePair<K, V>> action)
{
foreach (var item in this)
{
action(new KeyValuePair<K, V>(item.Key, item.Value));
}
return unit;
}
/// <summary>
/// Atomically folds all items in the map (in order) using the folder function provided.
/// </summary>
/// <typeparam name="S">State type</typeparam>
/// <param name="state">Initial state</param>
/// <param name="folder">Fold function</param>
/// <returns>Folded state</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public S Fold<S>(S state, Func<S, K, V, S> folder) =>
AsEnumerable().Fold(state, (s, x) => folder(s, x.Key, x.Value));
/// <summary>
/// Atomically folds all items in the map (in order) using the folder function provided.
/// </summary>
/// <typeparam name="S">State type</typeparam>
/// <param name="state">Initial state</param>
/// <param name="folder">Fold function</param>
/// <returns>Folded state</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public S Fold<S>(S state, Func<S, V, S> folder) =>
AsEnumerable().Map(static x => x.Value).Fold(state, folder);
}
}
#nullable disable
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
#if CORECLR
// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
// - for missing APIs, System.Management.Automation.Environment has extension implementation.
// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
using Environment = System.Management.Automation.Environment;
#endif
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The formats that export-alias supports
/// </summary>
public enum ExportAliasFormat
{
/// <summary>
/// Aliases will be exported to a CSV file
/// </summary>
Csv,
/// <summary>
/// Aliases will be exported as an MSH script
/// </summary>
Script
}
/// <summary>
/// The implementation of the "export-alias" cmdlet
/// </summary>
///
[Cmdlet(VerbsData.Export, "Alias", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113296")]
[OutputType(typeof(AliasInfo))]
public class ExportAliasCommand : PSCmdlet
{
#region Parameters
/// <summary>
/// The Path of the file to export the aliases to.
/// </summary>
///
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")]
public string Path
{
get { return _path; }
set { _path = value ?? "."; }
}
private string _path = ".";
/// <summary>
/// The literal path of the file to export the aliases to.
/// </summary>
///
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")]
[Alias("PSPath")]
public string LiteralPath
{
get { return _path; }
set
{
if (value == null)
{
_path = ".";
}
else
{
_path = value;
_isLiteralPath = true;
}
}
}
private bool _isLiteralPath = false;
/// <summary>
/// The Name parameter for the command
/// </summary>
///
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true)]
public string[] Name
{
get { return _names; }
set { _names = value ?? new string[] { "*" }; }
}
private string[] _names = new string[] { "*" };
/// <summary>
/// If set to true, the alias that is set is passed to the
/// pipeline.
/// </summary>
///
[Parameter]
public SwitchParameter PassThru
{
get
{
return _passThru;
}
set
{
_passThru = value;
}
}
private bool _passThru;
/// <summary>
/// Parameter that determines the format of the file created.
/// </summary>
///
[Parameter]
public ExportAliasFormat As { get; set; } = ExportAliasFormat.Csv;
/// <summary>
/// Property that sets append parameter.
/// </summary>
[Parameter()]
public SwitchParameter Append
{
get
{
return _append;
}
set
{
_append = value;
}
}
private bool _append;
/// <summary>
/// Property that sets force parameter.
/// </summary>
[Parameter()]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
private bool _force;
/// <summary>
/// Property that prevents file overwrite.
/// </summary>
[Parameter()]
[Alias("NoOverwrite")]
public SwitchParameter NoClobber
{
get
{
return _noclobber;
}
set
{
_noclobber = value;
}
}
private bool _noclobber;
/// <summary>
/// The description that gets added to the file as a comment
/// </summary>
/// <value></value>
[Parameter]
public string Description { get; set; }
/// <summary>
/// The scope parameter for the command determines
/// which scope the aliases are retrieved from.
/// </summary>
///
[Parameter]
public string Scope { get; set; }
#endregion Parameters
#region Command code
/// <summary>
/// The main processing loop of the command.
/// </summary>
///
protected override void ProcessRecord()
{
// First get the alias table (from the proper scope if necessary)
IDictionary<string, AliasInfo> aliasTable = null;
if (!String.IsNullOrEmpty(Scope))
{
// This can throw PSArgumentException and PSArgumentOutOfRangeException
// but just let them go as this is terminal for the pipeline and the
// exceptions are already properly adorned with an ErrorRecord.
aliasTable = SessionState.Internal.GetAliasTableAtScope(Scope);
}
else
{
aliasTable = SessionState.Internal.GetAliasTable();
}
foreach (string aliasName in _names)
{
bool resultFound = false;
// Create the name pattern
WildcardPattern namePattern =
WildcardPattern.Get(
aliasName,
WildcardOptions.IgnoreCase);
// Now loop through the table and write out any aliases that
// match the name and don't match the exclude filters and are
// visible to the caller...
CommandOrigin origin = MyInvocation.CommandOrigin;
foreach (KeyValuePair<string, AliasInfo> tableEntry in aliasTable)
{
if (!namePattern.IsMatch(tableEntry.Key))
{
continue;
}
if (SessionState.IsVisible(origin, tableEntry.Value))
{
resultFound = true;
_matchingAliases.Add(tableEntry.Value);
}
}
if (!resultFound &&
!WildcardPattern.ContainsWildcardCharacters(aliasName))
{
// Need to write an error if the user tries to get an alias
// that doesn't exist and they are not globbing.
ItemNotFoundException itemNotFound =
new ItemNotFoundException(
aliasName,
"AliasNotFound",
SessionStateStrings.AliasNotFound);
WriteError(
new ErrorRecord(
itemNotFound.ErrorRecord,
itemNotFound));
}
}
} // ProcessRecord
/// <summary>
/// Writes the aliases to the file
/// </summary>
protected override void EndProcessing()
{
StreamWriter writer = null;
FileInfo readOnlyFileInfo = null;
try
{
if (ShouldProcess(Path))
{
writer = OpenFile(out readOnlyFileInfo);
}
if (null != writer)
WriteHeader(writer);
// Now write out the aliases
foreach (AliasInfo alias in _matchingAliases)
{
string line = null;
if (this.As == ExportAliasFormat.Csv)
{
line = GetAliasLine(alias, "\"{0}\",\"{1}\",\"{2}\",\"{3}\"");
}
else
{
line = GetAliasLine(alias, "set-alias -Name:\"{0}\" -Value:\"{1}\" -Description:\"{2}\" -Option:\"{3}\"");
}
if (null != writer)
writer.WriteLine(line);
if (PassThru)
{
WriteObject(alias);
}
}
}
finally
{
if (null != writer)
writer.Dispose();
// reset the read-only attribute
if (null != readOnlyFileInfo)
readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly;
}
}
/// <summary>
/// Holds all the matching aliases for writing to the file
/// </summary>
private Collection<AliasInfo> _matchingAliases = new Collection<AliasInfo>();
private static string GetAliasLine(AliasInfo alias, string formatString)
{
// Using the invariant culture here because we don't want the
// file to vary based on locale.
string result =
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
formatString,
alias.Name,
alias.Definition,
alias.Description,
alias.Options);
return result;
}
private void WriteHeader(StreamWriter writer)
{
WriteFormattedResourceString(writer, AliasCommandStrings.ExportAliasHeaderTitle);
string user = Environment.UserName;
WriteFormattedResourceString(writer, AliasCommandStrings.ExportAliasHeaderUser, user);
DateTime now = DateTime.Now;
WriteFormattedResourceString(writer, AliasCommandStrings.ExportAliasHeaderDate, now);
string machine = Environment.MachineName;
WriteFormattedResourceString(writer, AliasCommandStrings.ExportAliasHeaderMachine, machine);
// Now write the description if there is one
if (Description != null)
{
// First we need to break up the description on newlines and add a
// # for each line.
Description = Description.Replace("\n", "\n# ");
// Now write out the description
writer.WriteLine("#");
writer.Write("# ");
writer.WriteLine(Description);
}
}
private static void WriteFormattedResourceString(
StreamWriter writer,
string resourceId,
params object[] args)
{
string line = StringUtil.Format(resourceId, args);
writer.Write("# ");
writer.WriteLine(line);
}
/// <summary>
/// Open the file to which aliases should be exported
/// </summary>
/// <param name="readOnlyFileInfo">
/// If not null, this is the file whose read-only attribute
/// was cleared (due to the -Force parameter). The attribute
/// should be reset.
/// </param>
/// <returns></returns>
private StreamWriter OpenFile(out FileInfo readOnlyFileInfo)
{
StreamWriter result = null;
FileStream file = null;
readOnlyFileInfo = null;
PathUtils.MasterStreamOpen(
this,
this.Path,
EncodingConversion.Unicode,
false, // defaultEncoding
Append,
Force,
NoClobber,
out file,
out result,
out readOnlyFileInfo,
_isLiteralPath
);
return result;
}
private void ThrowFileOpenError(Exception e, string pathWithError)
{
string message = StringUtil.Format(AliasCommandStrings.ExportAliasFileOpenFailed, pathWithError, e.Message);
ErrorRecord errorRecord = new ErrorRecord(
e,
"FileOpenFailure",
ErrorCategory.OpenError,
pathWithError);
errorRecord.ErrorDetails = new ErrorDetails(message);
this.ThrowTerminatingError(errorRecord);
}
#endregion Command code
} // class ExportAliasCommand
}//Microsoft.PowerShell.Commands
| |
// 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: The contract class allows for expressing preconditions,
** postconditions, and object invariants about methods in source
** code for runtime checking & static analysis.
**
** Two classes (Contract and ContractHelper) are split into partial classes
** in order to share the public front for multiple platforms (this file)
** while providing separate implementation details for each platform.
**
===========================================================*/
#define DEBUG // The behavior of this contract library should be consistent regardless of build type.
#if SILVERLIGHT
#define FEATURE_UNTRUSTED_CALLERS
#elif REDHAWK_RUNTIME
#elif BARTOK_RUNTIME
#else // CLR
#define FEATURE_UNTRUSTED_CALLERS
#define FEATURE_RELIABILITY_CONTRACTS
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
#if FEATURE_RELIABILITY_CONTRACTS
using System.Runtime.ConstrainedExecution;
#endif
#if FEATURE_UNTRUSTED_CALLERS
using System.Security;
#endif
namespace System.Diagnostics.Contracts
{
#region Attributes
/// <summary>
/// Methods and classes marked with this attribute can be used within calls to Contract methods. Such methods not make any visible state changes.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class PureAttribute : Attribute
{
}
/// <summary>
/// Types marked with this attribute specify that a separate type contains the contracts for this type.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[Conditional("DEBUG")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
public sealed class ContractClassAttribute : Attribute
{
private Type _typeWithContracts;
public ContractClassAttribute(Type typeContainingContracts)
{
_typeWithContracts = typeContainingContracts;
}
public Type TypeContainingContracts
{
get { return _typeWithContracts; }
}
}
/// <summary>
/// Types marked with this attribute specify that they are a contract for the type that is the argument of the constructor.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class ContractClassForAttribute : Attribute
{
private Type _typeIAmAContractFor;
public ContractClassForAttribute(Type typeContractsAreFor)
{
_typeIAmAContractFor = typeContractsAreFor;
}
public Type TypeContractsAreFor
{
get { return _typeIAmAContractFor; }
}
}
/// <summary>
/// This attribute is used to mark a method as being the invariant
/// method for a class. The method can have any name, but it must
/// return "void" and take no parameters. The body of the method
/// must consist solely of one or more calls to the method
/// Contract.Invariant. A suggested name for the method is
/// "ObjectInvariant".
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class ContractInvariantMethodAttribute : Attribute
{
}
/// <summary>
/// Attribute that specifies that an assembly is a reference assembly with contracts.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
public sealed class ContractReferenceAssemblyAttribute : Attribute
{
}
/// <summary>
/// Methods (and properties) marked with this attribute can be used within calls to Contract methods, but have no runtime behavior associated with them.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ContractRuntimeIgnoredAttribute : Attribute
{
}
/*
[Serializable]
internal enum Mutability
{
Immutable, // read-only after construction, except for lazy initialization & caches
// Do we need a "deeply immutable" value?
Mutable,
HasInitializationPhase, // read-only after some point.
// Do we need a value for mutable types with read-only wrapper subclasses?
}
// Note: This hasn't been thought through in any depth yet. Consider it experimental.
// We should replace this with Joe's concepts.
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
[SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")]
internal sealed class MutabilityAttribute : Attribute
{
private Mutability _mutabilityMarker;
public MutabilityAttribute(Mutability mutabilityMarker)
{
_mutabilityMarker = mutabilityMarker;
}
public Mutability Mutability {
get { return _mutabilityMarker; }
}
}
*/
/// <summary>
/// Instructs downstream tools whether to assume the correctness of this assembly, type or member without performing any verification or not.
/// Can use [ContractVerification(false)] to explicitly mark assembly, type or member as one to *not* have verification performed on it.
/// Most specific element found (member, type, then assembly) takes precedence.
/// (That is useful if downstream tools allow a user to decide which polarity is the default, unmarked case.)
/// </summary>
/// <remarks>
/// Apply this attribute to a type to apply to all members of the type, including nested types.
/// Apply this attribute to an assembly to apply to all types and members of the assembly.
/// Apply this attribute to a property to apply to both the getter and setter.
/// </remarks>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)]
public sealed class ContractVerificationAttribute : Attribute
{
private bool _value;
public ContractVerificationAttribute(bool value) { _value = value; }
public bool Value
{
get { return _value; }
}
}
/// <summary>
/// Allows a field f to be used in the method contracts for a method m when f has less visibility than m.
/// For instance, if the method is public, but the field is private.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Field)]
[SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")]
public sealed class ContractPublicPropertyNameAttribute : Attribute
{
private String _publicName;
public ContractPublicPropertyNameAttribute(String name)
{
_publicName = name;
}
public String Name
{
get { return _publicName; }
}
}
/// <summary>
/// Enables factoring legacy if-then-throw into separate methods for reuse and full control over
/// thrown exception and arguments
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
[Conditional("CONTRACTS_FULL")]
public sealed class ContractArgumentValidatorAttribute : Attribute
{
}
/// <summary>
/// Enables writing abbreviations for contracts that get copied to other methods
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
[Conditional("CONTRACTS_FULL")]
public sealed class ContractAbbreviatorAttribute : Attribute
{
}
/// <summary>
/// Allows setting contract and tool options at assembly, type, or method granularity.
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
[Conditional("CONTRACTS_FULL")]
public sealed class ContractOptionAttribute : Attribute
{
private String _category;
private String _setting;
private bool _enabled;
private String _value;
public ContractOptionAttribute(String category, String setting, bool enabled)
{
_category = category;
_setting = setting;
_enabled = enabled;
}
public ContractOptionAttribute(String category, String setting, String value)
{
_category = category;
_setting = setting;
_value = value;
}
public String Category
{
get { return _category; }
}
public String Setting
{
get { return _setting; }
}
public bool Enabled
{
get { return _enabled; }
}
public String Value
{
get { return _value; }
}
}
#endregion Attributes
/// <summary>
/// Contains static methods for representing program contracts such as preconditions, postconditions, and invariants.
/// </summary>
/// <remarks>
/// WARNING: A binary rewriter must be used to insert runtime enforcement of these contracts.
/// Otherwise some contracts like Ensures can only be checked statically and will not throw exceptions during runtime when contracts are violated.
/// Please note this class uses conditional compilation to help avoid easy mistakes. Defining the preprocessor
/// symbol CONTRACTS_PRECONDITIONS will include all preconditions expressed using Contract.Requires in your
/// build. The symbol CONTRACTS_FULL will include postconditions and object invariants, and requires the binary rewriter.
/// </remarks>
public static partial class Contract
{
#region User Methods
#region Assume
/// <summary>
/// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true.
/// </summary>
/// <param name="condition">Expression to assume will always be true.</param>
/// <remarks>
/// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Debug.Assert(bool)"/>.
/// </remarks>
[Pure]
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void Assume(bool condition)
{
if (!condition)
{
ReportFailure(ContractFailureKind.Assume, null, null, null);
}
}
/// <summary>
/// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true.
/// </summary>
/// <param name="condition">Expression to assume will always be true.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Debug.Assert(bool)"/>.
/// </remarks>
[Pure]
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void Assume(bool condition, String userMessage)
{
if (!condition)
{
ReportFailure(ContractFailureKind.Assume, userMessage, null, null);
}
}
#endregion Assume
#region Assert
/// <summary>
/// In debug builds, perform a runtime check that <paramref name="condition"/> is true.
/// </summary>
/// <param name="condition">Expression to check to always be true.</param>
[Pure]
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void Assert(bool condition)
{
if (!condition)
ReportFailure(ContractFailureKind.Assert, null, null, null);
}
/// <summary>
/// In debug builds, perform a runtime check that <paramref name="condition"/> is true.
/// </summary>
/// <param name="condition">Expression to check to always be true.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
[Pure]
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void Assert(bool condition, String userMessage)
{
if (!condition)
ReportFailure(ContractFailureKind.Assert, userMessage, null, null);
}
#endregion Assert
#region Requires
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// Use this form when backward compatibility does not force you to throw a particular exception.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void Requires(bool condition)
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires");
}
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// Use this form when backward compatibility does not force you to throw a particular exception.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void Requires(bool condition, String userMessage)
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires");
}
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// Use this form when you want to throw a particular exception.
/// </remarks>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "condition")]
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void Requires<TException>(bool condition) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>");
}
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// Use this form when you want to throw a particular exception.
/// </remarks>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "condition")]
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void Requires<TException>(bool condition, String userMessage) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>");
}
#endregion Requires
#region Ensures
/// <summary>
/// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally.
/// </summary>
/// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this postcondition.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void Ensures(bool condition)
{
AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures");
}
/// <summary>
/// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally.
/// </summary>
/// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this postcondition.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void Ensures(bool condition, String userMessage)
{
AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures");
}
/// <summary>
/// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally.
/// </summary>
/// <typeparam name="TException">Type of exception related to this postcondition.</typeparam>
/// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this postcondition.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void EnsuresOnThrow<TException>(bool condition) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow");
}
/// <summary>
/// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally.
/// </summary>
/// <typeparam name="TException">Type of exception related to this postcondition.</typeparam>
/// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this postcondition.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void EnsuresOnThrow<TException>(bool condition, String userMessage) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow");
}
#region Old, Result, and Out Parameters
/// <summary>
/// Represents the result (a.k.a. return value) of a method or property.
/// </summary>
/// <typeparam name="T">Type of return value of the enclosing method or property.</typeparam>
/// <returns>Return value of the enclosing method or property.</returns>
/// <remarks>
/// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Not intended to be called at runtime.")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static T Result<T>() { return default(T); }
/// <summary>
/// Represents the final (output) value of an out parameter when returning from a method.
/// </summary>
/// <typeparam name="T">Type of the out parameter.</typeparam>
/// <param name="value">The out parameter.</param>
/// <returns>The output value of the out parameter.</returns>
/// <remarks>
/// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Not intended to be called at runtime.")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static T ValueAtReturn<T>(out T value) { value = default(T); return value; }
/// <summary>
/// Represents the value of <paramref name="value"/> as it was at the start of the method or property.
/// </summary>
/// <typeparam name="T">Type of <paramref name="value"/>. This can be inferred.</typeparam>
/// <param name="value">Value to represent. This must be a field or parameter.</param>
/// <returns>Value of <paramref name="value"/> at the start of the method or property.</returns>
/// <remarks>
/// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract.
/// </remarks>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static T OldValue<T>(T value) { return default(T); }
#endregion Old, Result, and Out Parameters
#endregion Ensures
#region Invariant
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <remarks>
/// This contact can only be specified in a dedicated invariant method declared on a class.
/// This contract is not exposed to clients so may reference members less visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this invariant.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void Invariant(bool condition)
{
AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant");
}
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This contact can only be specified in a dedicated invariant method declared on a class.
/// This contract is not exposed to clients so may reference members less visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this invariant.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void Invariant(bool condition, String userMessage)
{
AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant");
}
#endregion Invariant
#region Quantifiers
#region ForAll
/// <summary>
/// Returns whether the <paramref name="predicate"/> returns <c>true</c>
/// for all integers starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.
/// </summary>
/// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param>
/// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param>
/// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param>
/// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for all integers
/// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns>
/// <seealso cref="System.Collections.Generic.List<T>.TrueForAll"/>
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static bool ForAll(int fromInclusive, int toExclusive, Predicate<int> predicate)
{
if (fromInclusive > toExclusive)
#if CORECLR
throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive);
#else
throw new ArgumentException("fromInclusive must be less than or equal to toExclusive.");
#endif
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
for (int i = fromInclusive; i < toExclusive; i++)
if (!predicate(i)) return false;
return true;
}
/// <summary>
/// Returns whether the <paramref name="predicate"/> returns <c>true</c>
/// for all elements in the <paramref name="collection"/>.
/// </summary>
/// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param>
/// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param>
/// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for all elements in
/// <paramref name="collection"/>.</returns>
/// <seealso cref="System.Collections.Generic.List<T>.TrueForAll"/>
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static bool ForAll<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
foreach (T t in collection)
if (!predicate(t)) return false;
return true;
}
#endregion ForAll
#region Exists
/// <summary>
/// Returns whether the <paramref name="predicate"/> returns <c>true</c>
/// for any integer starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.
/// </summary>
/// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param>
/// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param>
/// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param>
/// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for any integer
/// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns>
/// <seealso cref="System.Collections.Generic.List<T>.Exists"/>
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static bool Exists(int fromInclusive, int toExclusive, Predicate<int> predicate)
{
if (fromInclusive > toExclusive)
#if CORECLR
throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive);
#else
throw new ArgumentException("fromInclusive must be less than or equal to toExclusive.");
#endif
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
for (int i = fromInclusive; i < toExclusive; i++)
if (predicate(i)) return true;
return false;
}
/// <summary>
/// Returns whether the <paramref name="predicate"/> returns <c>true</c>
/// for any element in the <paramref name="collection"/>.
/// </summary>
/// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param>
/// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param>
/// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for an element in
/// <paramref name="collection"/>.</returns>
/// <seealso cref="System.Collections.Generic.List<T>.Exists"/>
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static bool Exists<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
foreach (T t in collection)
if (predicate(t)) return true;
return false;
}
#endregion Exists
#endregion Quantifiers
#region Pointers
#endregion
#region Misc.
/// <summary>
/// Marker to indicate the end of the contract section of a method.
/// </summary>
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void EndContractBlock() { }
#endregion
#endregion User Methods
#region Failure Behavior
/// <summary>
/// Without contract rewriting, failing Assert/Assumes end up calling this method.
/// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call
/// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by
/// System.Runtime.CompilerServices.ContractHelper.TriggerFailure.
/// </summary>
static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException);
/// <summary>
/// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly.
/// It is NEVER used to indicate failure of actual contracts at runtime.
/// </summary>
static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind);
#endregion
}
public enum ContractFailureKind
{
Precondition,
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")]
Postcondition,
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")]
PostconditionOnException,
Invariant,
Assert,
Assume,
}
}
// Note: In .NET FX 4.5, we duplicated the ContractHelper class in the System.Runtime.CompilerServices
// namespace to remove an ugly wart of a namespace from the Windows 8 profile. But we still need the
// old locations left around, so we can support rewritten .NET FX 4.0 libraries. Consider removing
// these from our reference assembly in a future version.
namespace System.Diagnostics.Contracts.Internal
{
[Obsolete("Use the ContractHelper class in the System.Runtime.CompilerServices namespace instead.")]
public static class ContractHelper
{
#region Rewriter Failure Hooks
/// <summary>
/// Rewriter will call this method on a contract failure to allow listeners to be notified.
/// The method should not perform any failure (assert/throw) itself.
/// </summary>
/// <returns>null if the event was handled and should not trigger a failure.
/// Otherwise, returns the localized failure message</returns>
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException)
{
return System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException);
}
/// <summary>
/// Rewriter calls this method to get the default failure behavior.
/// </summary>
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException)
{
System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, displayMessage, userMessage, conditionText, innerException);
}
#endregion Rewriter Failure Hooks
}
} // namespace System.Diagnostics.Contracts.Internal
namespace System.Runtime.CompilerServices
{
public static partial class ContractHelper
{
#region Rewriter Failure Hooks
/// <summary>
/// Rewriter will call this method on a contract failure to allow listeners to be notified.
/// The method should not perform any failure (assert/throw) itself.
/// </summary>
/// <returns>null if the event was handled and should not trigger a failure.
/// Otherwise, returns the localized failure message</returns>
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException)
{
var resultFailureMessage = "Contract failed"; // default in case implementation does not assign anything.
RaiseContractFailedEventImplementation(failureKind, userMessage, conditionText, innerException, ref resultFailureMessage);
return resultFailureMessage;
}
/// <summary>
/// Rewriter calls this method to get the default failure behavior.
/// </summary>
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException)
{
TriggerFailureImplementation(kind, displayMessage, userMessage, conditionText, innerException);
}
#endregion Rewriter Failure Hooks
#region Implementation Stubs
/// <summary>
/// Rewriter will call this method on a contract failure to allow listeners to be notified.
/// The method should not perform any failure (assert/throw) itself.
/// This method has 3 functions:
/// 1. Call any contract hooks (such as listeners to Contract failed events)
/// 2. Determine if the listeners deem the failure as handled (then resultFailureMessage should be set to null)
/// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently.
/// </summary>
/// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough.
/// On exit: null if the event was handled and should not trigger a failure.
/// Otherwise, returns the localized failure message</param>
static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage);
/// <summary>
/// Implements the default failure behavior of the platform. Under the BCL, it triggers an Assert box.
/// </summary>
static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException);
#endregion Implementation Stubs
}
} // namespace System.Runtime.CompilerServices
| |
#region Namespaces
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Collections.Generic;
using Epi.Fields;
using Epi.Windows;
#endregion
namespace Epi.Windows.Controls
{
/// <summary>
/// A dragable group box to be used in MakeView's questionnaire designer
/// </summary>
public class DragableGroupBox : FieldGroupBox, IDragable, IFieldControl
{
#region Private Members
private bool isMouseDown = false;
private int x;
private int y;
private bool hasMoved = false;
private Epi.Fields.Field field;
private ControlTracker controlTracker;
private Enums.TrackerStatus trackerStatus;
private List<Control> childControls = new List<Control>();
private Dictionary<Control, int> verticalDistances;
private Dictionary<Control, int> horizontalDistances;
#endregion
#region Constructors
/// <summary>
/// Constructor for the class
/// </summary>
public DragableGroupBox()
{
InitializeComponent();
}
#endregion
#region Override Methods
/// <summary>
/// Overrides the button's OnPaint event
/// </summary>
/// <param name="e">Parameters for the paint event</param>
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
base.OnPaint(e);
}
#endregion
#region Private Methods
/// <summary>
/// Initializes the Dragable button
/// </summary>
private void InitializeComponent()
{
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.DragableGroupBox_MouseDown);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.DragableGroupBox_MouseMove);
this.MouseLeave += new System.EventHandler(this.DragableGroupBox_MouseLeave);
base.DragOver += new DragEventHandler(DragableGroupBox_DragOver);
}
#endregion
#region Event Handlers
/// <summary>
/// Handles the mouse-move event over the group box
/// </summary>
/// <param name="sender">.NET supplied object</param>
/// <param name="e">.NET supplied event parameters</param>
private void DragableGroupBox_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (isMouseDown)
{
DataObject data = new DataObject("DragControl", this);
this.DoDragDrop(data, DragDropEffects.Move);
isMouseDown = false;
this.hasMoved = true;
}
}
/// <summary>
/// Handles the mouse-down event of the group box
/// </summary>
/// <param name="sender">.NET supplied object</param>
/// <param name="e">.NET supplied event parameters</param>
private void DragableGroupBox_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && (this.ChildControls != null))
{
isMouseDown = true;
x = e.X;
y = e.Y;
}
}
/// <summary>
///
/// </summary>
/// <param name="currentPanel"></param>
public void CaptureDistances(Panel currentPanel)
{
verticalDistances = new Dictionary<Control, int>();
horizontalDistances = new Dictionary<Control, int>();
foreach (Control control in GetChildControls(currentPanel))
{
if (!verticalDistances.ContainsKey(control))
{
verticalDistances.Add(control, control.Top - this.Top);
}
if (!horizontalDistances.ContainsKey(control))
{
horizontalDistances.Add(control, control.Left - this.Left);
}
}
}
/// <summary>
/// Gets the vertical distance to a hosted control
/// </summary>
/// <param name="control">The hosted control</param>
/// <returns>Distance</returns>
public int GetVerticalDistanceTo(Control control)
{
return verticalDistances[control];
}
/// <summary>
/// Gets the horizontal distance to a hosted control
/// </summary>
/// <param name="control">The hosted control</param>
/// <returns>Distance</returns>
public int GetHorizontalDistanceTo(Control control)
{
return horizontalDistances[control];
}
/// <summary>
/// Handles the mouse-leave event of the group box
/// </summary>
/// <param name="sender">.NET supplied object</param>
/// <param name="e">.NET supplied event parameters</param>
private void DragableGroupBox_MouseLeave(object sender, System.EventArgs e)
{
isMouseDown = false;
}
/// <summary>
/// Handles the drag-over event of the group box
/// </summary>
/// <param name="sender">.NET supplied object</param>
/// <param name="e">.NET supplied event parameters</param>
private void DragableGroupBox_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
#endregion
#region Public Properties
/// <summary>
/// Gets all the controls being hosted by the group box
/// </summary>
public List<Control> ChildControls
{
get { return childControls; }
}
/// <summary>
/// Gets all the controls being hosted by the group box
/// </summary>
private List<Control> GetChildControls(Panel currentPanel)
{
List<Control> controls = new List<Control>();
if (this.field != null && this.field is OptionField)
{
return controls;
}
else if (this.field != null)
{
String[] names = ((GroupField)this.Field).ChildFieldNames.Split(new char[] { ',' });
foreach (Control pageControl in currentPanel.Controls)
{
IFieldControl fieldControl = pageControl as IFieldControl;
if (fieldControl != null )
{
foreach (String name in names)
{
if (fieldControl.Field.Name == name)
{
controls.Add(pageControl);
}
}
}
}
}
childControls = controls;
return controls;
}
/// <summary>
/// Gets or sets the horizontal distance of the mouse from the edge of the group box
/// </summary>
public int XOffset
{
get
{
return this.x;
}
set
{
this.x = value;
}
}
/// <summary>
/// Gets or sets the vertical distance of the mouse from the edge of the group box
/// </summary>
public int YOffset
{
get
{
return this.y;
}
set
{
this.y = value;
}
}
/// <summary>
/// Gets or sets whether or not the dynamic control has moved
/// </summary>
public bool HasMoved
{
get
{
return hasMoved;
}
set
{
hasMoved = value;
}
}
#endregion
#region Public Methods
private void CheckLabelPosition(List<Control> controls, Control control, int bottom, int right)
{
//if label is in the group box, then add it
DragableLabel label = control as DragableLabel;
if (label.Top >= this.Top && (label.Top + label.Height) <= bottom
&& label.Left >= this.Left && (label.Left + label.Width) <= right)
{
label.BringToFront();
if (label.LabelFor != null)
{
label.LabelFor.BringToFront();
}
}
//if the label is not in the group box, then remove it's linked control
else
{
control.SendToBack();
controls.Remove(control);
if (label.LabelFor != null && controls.Contains(label.LabelFor))
{
label.LabelFor.SendToBack();
controls.Remove(label.LabelFor);
controls.Remove(label);
}
}
}
#endregion
#region IFieldControl Members
/// <summary>
/// IFieldControl implementation
/// </summary>
public int FieldId
{
get
{
return 0;
}
set
{
// do nothing
}
}
/// <summary>
/// IFieldControl implementation
/// </summary>
public Epi.Fields.Field Field
{
get
{
return this.field;
}
set
{
this.field = value;
}
}
/// <summary>
/// Gets and sets the ControlTracker this control is associated with.
/// </summary>
public ControlTracker ControlTracker
{
get
{
return controlTracker;
}
set
{
controlTracker = value;
}
}
/// <summary>
/// IFieldControl implementation
/// </summary>
public bool IsFieldGroup
{
get
{
return (this.Field == null);
}
set
{
// do nothing
}
}
public ControlTracker Tracker
{
get { return controlTracker; }
set { controlTracker = value; }
}
public Enums.TrackerStatus TrackerStatus
{
get { return trackerStatus; }
set
{
controlTracker.TrackerStatus = value;
this.trackerStatus = value;
}
}
#endregion
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
#if !SILVERLIGHT // ComObject
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using ComTypes = System.Runtime.InteropServices.ComTypes;
//using Microsoft.Scripting.Utils;
namespace System.Management.Automation.ComInterop
{
/// <summary>
/// This class implements an event sink for a particular RCW.
/// Unlike the implementation of events in TlbImp'd assemblies,
/// we will create only one event sink per RCW (theoretically RCW might have
/// several ComEventSink evenk sinks - but all these implement different source interfaces).
/// Each ComEventSink contains a list of ComEventSinkMethod objects - which represent
/// a single method on the source interface an a multicast delegate to redirect
/// the calls. Notice that we are chaining multicast delegates so that same
/// ComEventSinkMethod can invoke multiple event handlers).
///
/// ComEventSink implements an IDisposable pattern to Unadvise from the connection point.
/// Typically, when RCW is finalized the corresponding Dispose will be triggered by
/// ComEventSinksContainer finalizer. Notice that lifetime of ComEventSinksContainer
/// is bound to the lifetime of the RCW.
/// </summary>
internal sealed class ComEventSink : MarshalByRefObject, IReflect, IDisposable
{
#region private fields
private Guid _sourceIid;
private ComTypes.IConnectionPoint _connectionPoint;
private int _adviseCookie;
private List<ComEventSinkMethod> _comEventSinkMethods;
private object _lockObject = new object(); // We cannot lock on ComEventSink since it causes a DoNotLockOnObjectsWithWeakIdentity warning
#endregion
#region private classes
/// <summary>
/// Contains a methods DISPID (in a string formatted of "[DISPID=N]"
/// and a chained list of delegates to invoke
/// </summary>
private class ComEventSinkMethod
{
public string _name;
public Func<object[], object> _handlers;
}
#endregion
#region ctor
private ComEventSink(object rcw, Guid sourceIid)
{
Initialize(rcw, sourceIid);
}
#endregion
private void Initialize(object rcw, Guid sourceIid)
{
_sourceIid = sourceIid;
_adviseCookie = -1;
Debug.Assert(_connectionPoint == null, "re-initializing event sink w/o unadvising from connection point");
ComTypes.IConnectionPointContainer cpc = rcw as ComTypes.IConnectionPointContainer;
if (cpc == null)
throw Error.COMObjectDoesNotSupportEvents();
cpc.FindConnectionPoint(ref _sourceIid, out _connectionPoint);
if (_connectionPoint == null)
throw Error.COMObjectDoesNotSupportSourceInterface();
// Read the comments for ComEventSinkProxy about why we need it
ComEventSinkProxy proxy = new ComEventSinkProxy(this, _sourceIid);
_connectionPoint.Advise(proxy.GetTransparentProxy(), out _adviseCookie);
}
#region static methods
public static ComEventSink FromRuntimeCallableWrapper(object rcw, Guid sourceIid, bool createIfNotFound)
{
List<ComEventSink> comEventSinks = ComEventSinksContainer.FromRuntimeCallableWrapper(rcw, createIfNotFound);
if (comEventSinks == null)
{
return null;
}
ComEventSink comEventSink = null;
lock (comEventSinks)
{
foreach (ComEventSink sink in comEventSinks)
{
if (sink._sourceIid == sourceIid)
{
comEventSink = sink;
break;
}
else if (sink._sourceIid == Guid.Empty)
{
// we found a ComEventSink object that
// was previously disposed. Now we will reuse it.
sink.Initialize(rcw, sourceIid);
comEventSink = sink;
}
}
if (comEventSink == null && createIfNotFound == true)
{
comEventSink = new ComEventSink(rcw, sourceIid);
comEventSinks.Add(comEventSink);
}
}
return comEventSink;
}
#endregion
public void AddHandler(int dispid, object func)
{
string name = String.Format(CultureInfo.InvariantCulture, "[DISPID={0}]", dispid);
lock (_lockObject)
{
ComEventSinkMethod sinkMethod;
sinkMethod = FindSinkMethod(name);
if (sinkMethod == null)
{
if (_comEventSinkMethods == null)
{
_comEventSinkMethods = new List<ComEventSinkMethod>();
}
sinkMethod = new ComEventSinkMethod();
sinkMethod._name = name;
_comEventSinkMethods.Add(sinkMethod);
}
sinkMethod._handlers += new SplatCallSite(func).Invoke;
}
}
public void RemoveHandler(int dispid, object func)
{
string name = String.Format(CultureInfo.InvariantCulture, "[DISPID={0}]", dispid);
lock (_lockObject)
{
ComEventSinkMethod sinkEntry = FindSinkMethod(name);
if (sinkEntry == null)
{
return;
}
// Remove the delegate from multicast delegate chain.
// We will need to find the delegate that corresponds
// to the func handler we want to remove. This will be
// easy since we Target property of the delegate object
// is a ComEventCallContext object.
Delegate[] delegates = sinkEntry._handlers.GetInvocationList();
foreach (Delegate d in delegates)
{
SplatCallSite callContext = d.Target as SplatCallSite;
if (callContext != null && callContext._callable.Equals(func))
{
sinkEntry._handlers -= d as Func<object[], object>;
break;
}
}
// If the delegates chain is empty - we can remove
// corresponding ComEvenSinkEntry
if (sinkEntry._handlers == null)
_comEventSinkMethods.Remove(sinkEntry);
// We can Unadvise from the ConnectionPoint if no more sink entries
// are registered for this interface
//(calling Dispose will call IConnectionPoint.Unadvise).
if (_comEventSinkMethods.Count == 0)
{
// notice that we do not remove
// ComEventSinkEntry from the list, we will re-use this data structure
// if a new handler needs to be attached.
Dispose();
}
}
}
public object ExecuteHandler(string name, object[] args)
{
ComEventSinkMethod site;
site = FindSinkMethod(name);
if (site != null && site._handlers != null)
{
return site._handlers(args);
}
return null;
}
#region IReflect
#region Unimplemented members
public FieldInfo GetField(string name, BindingFlags bindingAttr)
{
return null;
}
public FieldInfo[] GetFields(BindingFlags bindingAttr)
{
return Utils.EmptyArray<FieldInfo>();
}
public MemberInfo[] GetMember(string name, BindingFlags bindingAttr)
{
return Utils.EmptyArray<MemberInfo>();
}
public MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
return Utils.EmptyArray<MemberInfo>();
}
public MethodInfo GetMethod(string name, BindingFlags bindingAttr)
{
return null;
}
public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
{
return null;
}
public MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
return Utils.EmptyArray<MethodInfo>();
}
public PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
{
return null;
}
public PropertyInfo GetProperty(string name, BindingFlags bindingAttr)
{
return null;
}
public PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
return Utils.EmptyArray<PropertyInfo>();
}
#endregion
public Type UnderlyingSystemType
{
get
{
return typeof(object);
}
}
public object InvokeMember(
string name,
BindingFlags invokeAttr,
Binder binder,
object target,
object[] args,
ParameterModifier[] modifiers,
CultureInfo culture,
string[] namedParameters)
{
return ExecuteHandler(name, args);
}
#endregion
#region IDisposable
public void Dispose()
{
DisposeAll();
GC.SuppressFinalize(this);
}
#endregion
~ComEventSink()
{
DisposeAll();
}
private void DisposeAll()
{
if (_connectionPoint == null)
{
return;
}
if (_adviseCookie == -1)
{
return;
}
try
{
_connectionPoint.Unadvise(_adviseCookie);
// _connectionPoint has entered the CLR in the constructor
// for this object and hence its ref counter has been increased
// by us. We have not exposed it to other components and
// hence it is safe to call RCO on it w/o worrying about
// killing the RCW for other objects that link to it.
Marshal.ReleaseComObject(_connectionPoint);
}
catch (Exception ex)
{
// if something has gone wrong, and the object is no longer attached to the CLR,
// the Unadvise is going to throw. In this case, since we're going away anyway,
// we'll ignore the failure and quietly go on our merry way.
COMException exCOM = ex as COMException;
if (exCOM != null && exCOM.ErrorCode == ComHresults.CONNECT_E_NOCONNECTION)
{
Debug.Assert(false, "IConnectionPoint::Unadvise returned CONNECT_E_NOCONNECTION.");
throw;
}
}
finally
{
_connectionPoint = null;
_adviseCookie = -1;
_sourceIid = Guid.Empty;
}
}
private ComEventSinkMethod FindSinkMethod(string name)
{
if (_comEventSinkMethods == null)
return null;
ComEventSinkMethod site;
site = _comEventSinkMethods.Find(element => element._name == name);
return site;
}
}
}
#endif
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Replication Links. Contains operations to: Delete and Retrieve
/// replication links.
/// </summary>
internal partial class ReplicationLinkOperations : IServiceOperations<SqlManagementClient>, IReplicationLinkOperations
{
/// <summary>
/// Initializes a new instance of the ReplicationLinkOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ReplicationLinkOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Deletes the Azure SQL Database Replication Link with the given id.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be dropped.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serverName, string databaseName, string linkId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (linkId == null)
{
throw new ArgumentNullException("linkId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("linkId", linkId);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/replicationLinks/";
url = url + Uri.EscapeDataString(linkId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about an Azure SQL Database Replication Link.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to get the link for.
/// </param>
/// <param name='linkId'>
/// Required. The replication link id to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database Replication
/// Link request.
/// </returns>
public async Task<ReplicationLinkGetResponse> GetAsync(string resourceGroupName, string serverName, string databaseName, string linkId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (linkId == null)
{
throw new ArgumentNullException("linkId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("linkId", linkId);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/replicationLinks/";
url = url + Uri.EscapeDataString(linkId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ReplicationLinkGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ReplicationLinkGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ReplicationLink replicationLinkInstance = new ReplicationLink();
result.ReplicationLink = replicationLinkInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ReplicationLinkProperties propertiesInstance = new ReplicationLinkProperties();
replicationLinkInstance.Properties = propertiesInstance;
JToken partnerServerValue = propertiesValue["partnerServer"];
if (partnerServerValue != null && partnerServerValue.Type != JTokenType.Null)
{
string partnerServerInstance = ((string)partnerServerValue);
propertiesInstance.PartnerServer = partnerServerInstance;
}
JToken partnerDatabaseValue = propertiesValue["partnerDatabase"];
if (partnerDatabaseValue != null && partnerDatabaseValue.Type != JTokenType.Null)
{
string partnerDatabaseInstance = ((string)partnerDatabaseValue);
propertiesInstance.PartnerDatabase = partnerDatabaseInstance;
}
JToken partnerLocationValue = propertiesValue["partnerLocation"];
if (partnerLocationValue != null && partnerLocationValue.Type != JTokenType.Null)
{
string partnerLocationInstance = ((string)partnerLocationValue);
propertiesInstance.PartnerLocation = partnerLocationInstance;
}
JToken roleValue = propertiesValue["role"];
if (roleValue != null && roleValue.Type != JTokenType.Null)
{
string roleInstance = ((string)roleValue);
propertiesInstance.Role = roleInstance;
}
JToken partnerRoleValue = propertiesValue["partnerRole"];
if (partnerRoleValue != null && partnerRoleValue.Type != JTokenType.Null)
{
string partnerRoleInstance = ((string)partnerRoleValue);
propertiesInstance.PartnerRole = partnerRoleInstance;
}
JToken startTimeValue = propertiesValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTime startTimeInstance = ((DateTime)startTimeValue);
propertiesInstance.StartTime = startTimeInstance;
}
JToken percentCompleteValue = propertiesValue["percentComplete"];
if (percentCompleteValue != null && percentCompleteValue.Type != JTokenType.Null)
{
string percentCompleteInstance = ((string)percentCompleteValue);
propertiesInstance.PercentComplete = percentCompleteInstance;
}
JToken replicationStateValue = propertiesValue["replicationState"];
if (replicationStateValue != null && replicationStateValue.Type != JTokenType.Null)
{
string replicationStateInstance = ((string)replicationStateValue);
propertiesInstance.ReplicationState = replicationStateInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
replicationLinkInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
replicationLinkInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
replicationLinkInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
replicationLinkInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
replicationLinkInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about Azure SQL Database Replication Links.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server in which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to retrieve links for.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database Replication
/// Link request.
/// </returns>
public async Task<ReplicationLinkListResponse> ListAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/replicationLinks";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ReplicationLinkListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ReplicationLinkListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ReplicationLink replicationLinkInstance = new ReplicationLink();
result.ReplicationLinks.Add(replicationLinkInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ReplicationLinkProperties propertiesInstance = new ReplicationLinkProperties();
replicationLinkInstance.Properties = propertiesInstance;
JToken partnerServerValue = propertiesValue["partnerServer"];
if (partnerServerValue != null && partnerServerValue.Type != JTokenType.Null)
{
string partnerServerInstance = ((string)partnerServerValue);
propertiesInstance.PartnerServer = partnerServerInstance;
}
JToken partnerDatabaseValue = propertiesValue["partnerDatabase"];
if (partnerDatabaseValue != null && partnerDatabaseValue.Type != JTokenType.Null)
{
string partnerDatabaseInstance = ((string)partnerDatabaseValue);
propertiesInstance.PartnerDatabase = partnerDatabaseInstance;
}
JToken partnerLocationValue = propertiesValue["partnerLocation"];
if (partnerLocationValue != null && partnerLocationValue.Type != JTokenType.Null)
{
string partnerLocationInstance = ((string)partnerLocationValue);
propertiesInstance.PartnerLocation = partnerLocationInstance;
}
JToken roleValue = propertiesValue["role"];
if (roleValue != null && roleValue.Type != JTokenType.Null)
{
string roleInstance = ((string)roleValue);
propertiesInstance.Role = roleInstance;
}
JToken partnerRoleValue = propertiesValue["partnerRole"];
if (partnerRoleValue != null && partnerRoleValue.Type != JTokenType.Null)
{
string partnerRoleInstance = ((string)partnerRoleValue);
propertiesInstance.PartnerRole = partnerRoleInstance;
}
JToken startTimeValue = propertiesValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTime startTimeInstance = ((DateTime)startTimeValue);
propertiesInstance.StartTime = startTimeInstance;
}
JToken percentCompleteValue = propertiesValue["percentComplete"];
if (percentCompleteValue != null && percentCompleteValue.Type != JTokenType.Null)
{
string percentCompleteInstance = ((string)percentCompleteValue);
propertiesInstance.PercentComplete = percentCompleteInstance;
}
JToken replicationStateValue = propertiesValue["replicationState"];
if (replicationStateValue != null && replicationStateValue.Type != JTokenType.Null)
{
string replicationStateInstance = ((string)replicationStateValue);
propertiesInstance.ReplicationState = replicationStateInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
replicationLinkInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
replicationLinkInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
replicationLinkInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
replicationLinkInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
replicationLinkInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .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;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Text.Unicode.Tests
{
public class Utf8UtilityTests
{
private unsafe delegate byte* GetPointerToFirstInvalidByteDel(byte* pInputBuffer, int inputLength, out int utf16CodeUnitCountAdjustment, out int scalarCountAdjustment);
private static readonly Lazy<GetPointerToFirstInvalidByteDel> _getPointerToFirstInvalidByteFn = CreateGetPointerToFirstInvalidByteFn();
private const string X = "58"; // U+0058 LATIN CAPITAL LETTER X, 1 byte
private const string Y = "59"; // U+0058 LATIN CAPITAL LETTER Y, 1 byte
private const string Z = "5A"; // U+0058 LATIN CAPITAL LETTER Z, 1 byte
private const string E_ACUTE = "C3A9"; // U+00E9 LATIN SMALL LETTER E WITH ACUTE, 2 bytes
private const string EURO_SYMBOL = "E282AC"; // U+20AC EURO SIGN, 3 bytes
private const string GRINNING_FACE = "F09F9880"; // U+1F600 GRINNING FACE, 4 bytes
[Theory]
[InlineData("", 0, 0)] // empty string is OK
[InlineData(X, 1, 0)]
[InlineData(X + Y, 2, 0)]
[InlineData(X + Y + Z, 3, 0)]
[InlineData(E_ACUTE, 1, 0)]
[InlineData(X + E_ACUTE, 2, 0)]
[InlineData(E_ACUTE + X, 2, 0)]
[InlineData(EURO_SYMBOL, 1, 0)]
public void GetIndexOfFirstInvalidUtf8Sequence_WithSmallValidBuffers(string input, int expectedRuneCount, int expectedSurrogatePairCount)
{
// These test cases are for the "slow processing" code path at the end of GetIndexOfFirstInvalidUtf8Sequence,
// so inputs should be less than 4 bytes.
Assert.InRange(input.Length, 0, 6);
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(input, -1 /* expectedRetVal */, expectedRuneCount, expectedSurrogatePairCount);
}
[Theory]
[InlineData("80", 0, 0, 0)] // sequence cannot begin with continuation character
[InlineData("8182", 0, 0, 0)] // sequence cannot begin with continuation character
[InlineData("838485", 0, 0, 0)] // sequence cannot begin with continuation character
[InlineData(X + "80", 1, 1, 0)] // sequence cannot begin with continuation character
[InlineData(X + "8182", 1, 1, 0)] // sequence cannot begin with continuation character
[InlineData("C0", 0, 0, 0)] // [ C0 ] is always invalid
[InlineData("C080", 0, 0, 0)] // [ C0 ] is always invalid
[InlineData("C08081", 0, 0, 0)] // [ C0 ] is always invalid
[InlineData(X + "C1", 1, 1, 0)] // [ C1 ] is always invalid
[InlineData(X + "C180", 1, 1, 0)] // [ C1 ] is always invalid
[InlineData("C2", 0, 0, 0)] // [ C2 ] is improperly terminated
[InlineData(X + "C27F", 1, 1, 0)] // [ C2 ] is improperly terminated
[InlineData(X + "E282", 1, 1, 0)] // [ E2 82 ] is improperly terminated
[InlineData("E2827F", 0, 0, 0)] // [ E2 82 ] is improperly terminated
[InlineData("E09F80", 0, 0, 0)] // [ E0 9F ... ] is overlong
[InlineData("E0C080", 0, 0, 0)] // [ E0 ] is improperly terminated
[InlineData("ED7F80", 0, 0, 0)] // [ ED ] is improperly terminated
[InlineData("EDA080", 0, 0, 0)] // [ ED A0 ... ] is surrogate
public void GetIndexOfFirstInvalidUtf8Sequence_WithSmallInvalidBuffers(string input, int expectedRetVal, int expectedRuneCount, int expectedSurrogatePairCount)
{
// These test cases are for the "slow processing" code path at the end of GetIndexOfFirstInvalidUtf8Sequence,
// so inputs should be less than 4 bytes.
Assert.InRange(input.Length, 0, 6);
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(input, expectedRetVal, expectedRuneCount, expectedSurrogatePairCount);
}
[Theory]
[InlineData(E_ACUTE + "21222324" + "303132333435363738393A3B3C3D3E3F", 21, 0)] // Loop unrolling at end of buffer
[InlineData(E_ACUTE + "21222324" + "303132333435363738393A3B3C3D3E3F" + "3031323334353637" + E_ACUTE + "38393A3B3C3D3E3F", 38, 0)] // Loop unrolling interrupted by non-ASCII
[InlineData("212223" + E_ACUTE + "30313233", 8, 0)] // 3 ASCII bytes followed by non-ASCII
[InlineData("2122" + E_ACUTE + "30313233", 7, 0)] // 2 ASCII bytes followed by non-ASCII
[InlineData("21" + E_ACUTE + "30313233", 6, 0)] // 1 ASCII byte followed by non-ASCII
[InlineData(E_ACUTE + E_ACUTE + E_ACUTE + E_ACUTE, 4, 0)] // 4x 2-byte sequences, exercises optimization code path in 2-byte sequence processing
[InlineData(E_ACUTE + E_ACUTE + E_ACUTE + "5051", 5, 0)] // 3x 2-byte sequences + 2 ASCII bytes, exercises optimization code path in 2-byte sequence processing
[InlineData(E_ACUTE + "5051", 3, 0)] // single 2-byte sequence + 2 trailing ASCII bytes, exercises draining logic in 2-byte sequence processing
[InlineData(E_ACUTE + "50" + E_ACUTE + "304050", 6, 0)] // single 2-byte sequences + 1 trailing ASCII byte + 2-byte sequence, exercises draining logic in 2-byte sequence processing
[InlineData(EURO_SYMBOL + "20", 2, 0)] // single 3-byte sequence + 1 trailing ASCII byte, exercises draining logic in 3-byte sequence processing
[InlineData(EURO_SYMBOL + "203040", 4, 0)] // single 3-byte sequence + 3 trailing ASCII byte, exercises draining logic and "running out of data" logic in 3-byte sequence processing
[InlineData(EURO_SYMBOL + EURO_SYMBOL + EURO_SYMBOL, 3, 0)] // 3x 3-byte sequences, exercises "stay within 3-byte loop" logic in 3-byte sequence processing
[InlineData(EURO_SYMBOL + EURO_SYMBOL + EURO_SYMBOL + EURO_SYMBOL, 4, 0)] // 4x 3-byte sequences, exercises "consume multiple bytes at a time" logic in 3-byte sequence processing
[InlineData(EURO_SYMBOL + EURO_SYMBOL + EURO_SYMBOL + E_ACUTE, 4, 0)] // 3x 3-byte sequences + single 2-byte sequence, exercises "consume multiple bytes at a time" logic in 3-byte sequence processing
[InlineData(EURO_SYMBOL + EURO_SYMBOL + E_ACUTE + E_ACUTE + E_ACUTE + E_ACUTE, 6, 0)] // 2x 3-byte sequences + 4x 2-byte sequences, exercises "consume multiple bytes at a time" logic in 3-byte sequence processing
[InlineData(GRINNING_FACE + GRINNING_FACE, 2, 2)] // 2x 4-byte sequences, exercises 4-byte sequence processing
[InlineData(GRINNING_FACE + "303132", 4, 1)] // single 4-byte sequence + 3 ASCII bytes, exercises 4-byte sequence processing and draining logic
[InlineData("F09FA4B8" + "F09F8FBD" + "E2808D" + "E29980" + "EFB88F", 5, 2)] // U+1F938 U+1F3FD U+200D U+2640 U+FE0F WOMAN CARTWHEELING: MEDIUM SKIN TONE, exercising switching between multiple sequence lengths
public void GetIndexOfFirstInvalidUtf8Sequence_WithLargeValidBuffers(string input, int expectedRuneCount, int expectedSurrogatePairCount)
{
// These test cases are for the "fast processing" code which is the main loop of GetIndexOfFirstInvalidUtf8Sequence,
// so inputs should be less >= 4 bytes.
Assert.True(input.Length >= 8);
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(input, -1 /* expectedRetVal */, expectedRuneCount, expectedSurrogatePairCount);
}
[Theory]
[InlineData("3031" + "80" + "202122232425", 2, 2, 0)] // Continuation character at start of sequence should match no bitmask
[InlineData("3031" + "C080" + "2021222324", 2, 2, 0)] // Overlong 2-byte sequence at start of DWORD
[InlineData("3031" + "C180" + "2021222324", 2, 2, 0)] // Overlong 2-byte sequence at start of DWORD
[InlineData("C280" + "C180", 2, 1, 0)] // Overlong 2-byte sequence at end of DWORD
[InlineData("C27F" + "C280", 0, 0, 0)] // Improperly terminated 2-byte sequence at start of DWORD
[InlineData("C2C0" + "C280", 0, 0, 0)] // Improperly terminated 2-byte sequence at start of DWORD
[InlineData("C280" + "C27F", 2, 1, 0)] // Improperly terminated 2-byte sequence at end of DWORD
[InlineData("C280" + "C2C0", 2, 1, 0)] // Improperly terminated 2-byte sequence at end of DWORD
[InlineData("C280" + "C280" + "80203040", 4, 2, 0)] // Continuation character at start of sequence, within "stay in 2-byte processing" optimization
[InlineData("C280" + "C280" + "C180" + "C280", 4, 2, 0)] // Overlong 2-byte sequence at start of DWORD, within "stay in 2-byte processing" optimization
[InlineData("C280" + "C280" + "C280" + "C180", 6, 3, 0)] // Overlong 2-byte sequence at end of DWORD, within "stay in 2-byte processing" optimization
[InlineData("3031" + "E09F80" + EURO_SYMBOL + EURO_SYMBOL, 2, 2, 0)] // Overlong 3-byte sequence at start of DWORD
[InlineData("3031" + "E07F80" + EURO_SYMBOL + EURO_SYMBOL, 2, 2, 0)] // Improperly terminated 3-byte sequence at start of DWORD
[InlineData("3031" + "E0C080" + EURO_SYMBOL + EURO_SYMBOL, 2, 2, 0)] // Improperly terminated 3-byte sequence at start of DWORD
[InlineData("3031" + "E17F80" + EURO_SYMBOL + EURO_SYMBOL, 2, 2, 0)] // Improperly terminated 3-byte sequence at start of DWORD
[InlineData("3031" + "E1C080" + EURO_SYMBOL + EURO_SYMBOL, 2, 2, 0)] // Improperly terminated 3-byte sequence at start of DWORD
[InlineData("3031" + "EDA080" + EURO_SYMBOL + EURO_SYMBOL, 2, 2, 0)] // Surrogate 3-byte sequence at start of DWORD
[InlineData("3031" + "E69C88" + "E59B" + "E69C88", 5, 3, 0)] // Incomplete 3-byte sequence surrounded by valid 3-byte sequences
[InlineData("E78B80" + "80", 3, 1, 0)] // Valid 3-byte sequence followed by standalone continuation byte
[InlineData("3031" + "F5808080", 2, 2, 0)] // [ F5 ] is always invalid
[InlineData("3031" + "F6808080", 2, 2, 0)] // [ F6 ] is always invalid
[InlineData("3031" + "F7808080", 2, 2, 0)] // [ F7 ] is always invalid
[InlineData("3031" + "F8808080", 2, 2, 0)] // [ F8 ] is always invalid
[InlineData("3031" + "F9808080", 2, 2, 0)] // [ F9 ] is always invalid
[InlineData("3031" + "FA808080", 2, 2, 0)] // [ FA ] is always invalid
[InlineData("3031" + "FB808080", 2, 2, 0)] // [ FB ] is always invalid
[InlineData("3031" + "FC808080", 2, 2, 0)] // [ FC ] is always invalid
[InlineData("3031" + "FD808080", 2, 2, 0)] // [ FD ] is always invalid
[InlineData("3031" + "FE808080", 2, 2, 0)] // [ FE ] is always invalid
[InlineData("3031" + "FF808080", 2, 2, 0)] // [ FF ] is always invalid
public void GetIndexOfFirstInvalidUtf8Sequence_WithLargeInvalidBuffers(string input, int expectedRetVal, int expectedRuneCount, int expectedSurrogatePairCount)
{
// These test cases are for the "fast processing" code which is the main loop of GetIndexOfFirstInvalidUtf8Sequence,
// so inputs should be less >= 4 bytes.
Assert.True(input.Length >= 8);
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(input, expectedRetVal, expectedRuneCount, expectedSurrogatePairCount);
}
[Fact]
public void GetIndexOfFirstInvalidUtf8Sequence_WithOverlongTwoByteSequences_ReturnsInvalid()
{
// [ C0 ] is never a valid byte, indicates overlong 2-byte sequence
// We'll test that [ C0 ] [ 00..FF ] is treated as invalid
for (int i = 0; i < 256; i++)
{
AssertIsInvalidTwoByteSequence(new byte[] { 0xC0, (byte)i });
}
// [ C1 ] is never a valid byte, indicates overlong 2-byte sequence
// We'll test that [ C1 ] [ 00..FF ] is treated as invalid
for (int i = 0; i < 256; i++)
{
AssertIsInvalidTwoByteSequence(new byte[] { 0xC1, (byte)i });
}
}
[Fact]
public void GetIndexOfFirstInvalidUtf8Sequence_WithImproperlyTerminatedTwoByteSequences_ReturnsInvalid()
{
// Test [ C2..DF ] [ 00..7F ] and [ C2..DF ] [ C0..FF ]
for (int i = 0xC2; i < 0xDF; i++)
{
for (int j = 0; j < 0x80; j++)
{
AssertIsInvalidTwoByteSequence(new byte[] { (byte)i, (byte)j });
}
for (int j = 0xC0; j < 0x100; j++)
{
AssertIsInvalidTwoByteSequence(new byte[] { (byte)i, (byte)j });
}
}
}
[Fact]
public void GetIndexOfFirstInvalidUtf8Sequence_WithOverlongThreeByteSequences_ReturnsInvalid()
{
// [ E0 ] [ 80..9F ] [ 80..BF ] is overlong 3-byte sequence
for (int i = 0x00; i < 0xA0; i++)
{
AssertIsInvalidThreeByteSequence(new byte[] { 0xE0, (byte)i, 0x80 });
}
}
[Fact]
public void GetIndexOfFirstInvalidUtf8Sequence_WithSurrogateThreeByteSequences_ReturnsInvalid()
{
// [ ED ] [ A0..BF ] [ 80..BF ] is surrogate 3-byte sequence
for (int i = 0xA0; i < 0x100; i++)
{
AssertIsInvalidThreeByteSequence(new byte[] { 0xED, (byte)i, 0x80 });
}
}
[Fact]
public void GetIndexOfFirstInvalidUtf8Sequence_WithImproperlyTerminatedThreeByteSequence_ReturnsInvalid()
{
// [ E0..EF ] [ 80..BF ] [ !(80..BF) ] is improperly terminated 3-byte sequence
for (int i = 0xE0; i < 0xF0; i++)
{
for (int j = 0x00; j < 0x80; j++)
{
// Use both '9F' and 'A0' to make sure at least one isn't caught by overlong / surrogate checks
AssertIsInvalidThreeByteSequence(new byte[] { (byte)i, 0x9F, (byte)j });
AssertIsInvalidThreeByteSequence(new byte[] { (byte)i, 0xA0, (byte)j });
}
for (int j = 0xC0; j < 0x100; j++)
{
// Use both '9F' and 'A0' to make sure at least one isn't caught by overlong / surrogate checks
AssertIsInvalidThreeByteSequence(new byte[] { (byte)i, 0x9F, (byte)j });
AssertIsInvalidThreeByteSequence(new byte[] { (byte)i, 0xA0, (byte)j });
}
}
}
[Fact]
public void GetIndexOfFirstInvalidUtf8Sequence_WithOverlongFourByteSequences_ReturnsInvalid()
{
// [ F0 ] [ 80..8F ] [ 80..BF ] [ 80..BF ] is overlong 4-byte sequence
for (int i = 0x00; i < 0x90; i++)
{
AssertIsInvalidFourByteSequence(new byte[] { 0xF0, (byte)i, 0x80, 0x80 });
}
}
[Fact]
public void GetIndexOfFirstInvalidUtf8Sequence_WithOutOfRangeFourByteSequences_ReturnsInvalid()
{
// [ F4 ] [ 90..BF ] [ 80..BF ] [ 80..BF ] is out-of-range 4-byte sequence
for (int i = 0x90; i < 0x100; i++)
{
AssertIsInvalidFourByteSequence(new byte[] { 0xF4, (byte)i, 0x80, 0x80 });
}
}
[Fact]
public void GetIndexOfFirstInvalidUtf8Sequence_WithInvalidFourByteSequence_ReturnsInvalid()
{
// [ F0..F4 ] [ !(80..BF) ] [ !(80..BF) ] [ !(80..BF) ] is improperly terminated 4-byte sequence
for (int i = 0xF0; i < 0xF5; i++)
{
for (int j = 0x00; j < 0x80; j++)
{
AssertIsInvalidFourByteSequence(new byte[] { (byte)i, (byte)j, 0x80, 0x80 });
// Use both '8F' and '90' to make sure at least one isn't caught by overlong / out-of-range checks
AssertIsInvalidFourByteSequence(new byte[] { (byte)i, 0x9F, (byte)j, 0x80 });
AssertIsInvalidFourByteSequence(new byte[] { (byte)i, 0xA0, (byte)j, 0x80 });
AssertIsInvalidFourByteSequence(new byte[] { (byte)i, 0x9F, 0x80, (byte)j });
AssertIsInvalidFourByteSequence(new byte[] { (byte)i, 0xA0, 0x80, (byte)j });
}
for (int j = 0xC0; j < 0x100; j++)
{
AssertIsInvalidFourByteSequence(new byte[] { (byte)i, (byte)j, 0x80, 0x80 });
// Use both '8F' and '90' to make sure at least one isn't caught by overlong / out-of-range checks
AssertIsInvalidFourByteSequence(new byte[] { (byte)i, 0x9F, (byte)j, 0x80 });
AssertIsInvalidFourByteSequence(new byte[] { (byte)i, 0xA0, (byte)j, 0x80 });
AssertIsInvalidFourByteSequence(new byte[] { (byte)i, 0x9F, 0x80, (byte)j });
AssertIsInvalidFourByteSequence(new byte[] { (byte)i, 0xA0, 0x80, (byte)j });
}
}
}
private static void AssertIsInvalidTwoByteSequence(byte[] invalidSequence)
{
Assert.Equal(2, invalidSequence.Length);
byte[] knownGoodBytes = Utf8Tests.DecodeHex(E_ACUTE);
byte[] toTest = invalidSequence.Concat(invalidSequence).Concat(knownGoodBytes).ToArray(); // at start of first DWORD
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(toTest, 0, 0, 0);
toTest = knownGoodBytes.Concat(invalidSequence).Concat(knownGoodBytes).ToArray(); // at end of first DWORD
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(toTest, 2, 1, 0);
// Run the same tests but with extra data at the beginning so that we're inside one of
// the 2-byte processing "hot loop" code paths.
toTest = knownGoodBytes.Concat(knownGoodBytes).Concat(invalidSequence).Concat(knownGoodBytes).ToArray(); // at start of next DWORD
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(toTest, 4, 2, 0);
toTest = knownGoodBytes.Concat(knownGoodBytes).Concat(knownGoodBytes).Concat(invalidSequence).Concat(knownGoodBytes).ToArray(); // at end of next DWORD
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(toTest, 6, 3, 0);
}
private static void AssertIsInvalidThreeByteSequence(byte[] invalidSequence)
{
Assert.Equal(3, invalidSequence.Length);
byte[] knownGoodBytes = Utf8Tests.DecodeHex(EURO_SYMBOL);
byte[] toTest = invalidSequence.Concat(invalidSequence).Concat(knownGoodBytes).ToArray(); // at start of first DWORD
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(toTest, 0, 0, 0);
// Run the same tests but with extra data at the beginning so that we're inside one of
// the 3-byte processing "hot loop" code paths.
toTest = knownGoodBytes.Concat(invalidSequence).Concat(knownGoodBytes).ToArray(); // straddling first and second DWORDs
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(toTest, 3, 1, 0);
toTest = knownGoodBytes.Concat(knownGoodBytes).Concat(invalidSequence).Concat(knownGoodBytes).ToArray(); // straddling second and third DWORDs
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(toTest, 6, 2, 0);
toTest = knownGoodBytes.Concat(knownGoodBytes).Concat(knownGoodBytes).Concat(invalidSequence).Concat(knownGoodBytes).ToArray(); // at end of third DWORD
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(toTest, 9, 3, 0);
}
private static void AssertIsInvalidFourByteSequence(byte[] invalidSequence)
{
Assert.Equal(4, invalidSequence.Length);
byte[] knownGoodBytes = Utf8Tests.DecodeHex(GRINNING_FACE);
byte[] toTest = invalidSequence.Concat(invalidSequence).Concat(knownGoodBytes).ToArray();
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(toTest, 0, 0, 0);
toTest = knownGoodBytes.Concat(invalidSequence).Concat(knownGoodBytes).ToArray();
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(toTest, 4, 1, 1);
}
private static void GetIndexOfFirstInvalidUtf8Sequence_Test_Core(string inputHex, int expectedRetVal, int expectedRuneCount, int expectedSurrogatePairCount)
{
byte[] inputBytes = Utf8Tests.DecodeHex(inputHex);
// Run the test normally
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(inputBytes, expectedRetVal, expectedRuneCount, expectedSurrogatePairCount);
// Then run the test with a bunch of ASCII data at the beginning (to exercise the vectorized code paths)
inputBytes = Enumerable.Repeat((byte)'x', 128).Concat(inputBytes).ToArray();
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(inputBytes, (expectedRetVal < 0) ? expectedRetVal : (expectedRetVal + 128), expectedRuneCount + 128, expectedSurrogatePairCount);
// Then put a few more ASCII bytes at the beginning (to test that offsets are properly handled)
inputBytes = Enumerable.Repeat((byte)'x', 7).Concat(inputBytes).ToArray();
GetIndexOfFirstInvalidUtf8Sequence_Test_Core(inputBytes, (expectedRetVal < 0) ? expectedRetVal : (expectedRetVal + 135), expectedRuneCount + 135, expectedSurrogatePairCount);
}
private static unsafe void GetIndexOfFirstInvalidUtf8Sequence_Test_Core(byte[] input, int expectedRetVal, int expectedRuneCount, int expectedSurrogatePairCount)
{
// Arrange
using BoundedMemory<byte> boundedMemory = BoundedMemory.AllocateFromExistingData(input);
boundedMemory.MakeReadonly();
// Act
int actualRetVal;
int actualSurrogatePairCount;
int actualRuneCount;
fixed (byte* pInputBuffer = &MemoryMarshal.GetReference(boundedMemory.Span))
{
byte* pFirstInvalidByte = _getPointerToFirstInvalidByteFn.Value(pInputBuffer, input.Length, out int utf16CodeUnitCountAdjustment, out int scalarCountAdjustment);
long ptrDiff = pFirstInvalidByte - pInputBuffer;
Assert.True((ulong)ptrDiff <= (uint)input.Length, "ptrDiff was outside expected range.");
Assert.True(utf16CodeUnitCountAdjustment <= 0, "UTF-16 code unit count adjustment must be 0 or negative.");
Assert.True(scalarCountAdjustment <= 0, "Scalar count adjustment must be 0 or negative.");
actualRetVal = (ptrDiff == input.Length) ? -1 : (int)ptrDiff;
// The last two 'out' parameters are:
// a) The number to be added to the "bytes processed" return value to come up with the total UTF-16 code unit count, and
// b) The number to be added to the "total UTF-16 code unit count" value to come up with the total scalar count.
int totalUtf16CodeUnitCount = (int)ptrDiff + utf16CodeUnitCountAdjustment;
actualRuneCount = totalUtf16CodeUnitCount + scalarCountAdjustment;
// Surrogate pair count is number of UTF-16 code units less the number of scalars.
actualSurrogatePairCount = totalUtf16CodeUnitCount - actualRuneCount;
}
// Assert
Assert.Equal(expectedRetVal, actualRetVal);
Assert.Equal(expectedRuneCount, actualRuneCount);
Assert.Equal(expectedSurrogatePairCount, actualSurrogatePairCount);
}
private static Lazy<GetPointerToFirstInvalidByteDel> CreateGetPointerToFirstInvalidByteFn()
{
return new Lazy<GetPointerToFirstInvalidByteDel>(() =>
{
Type utf8UtilityType = typeof(Utf8).Assembly.GetType("System.Text.Unicode.Utf8Utility");
if (utf8UtilityType is null)
{
throw new Exception("Couldn't find Utf8Utility type in System.Private.CoreLib.");
}
MethodInfo methodInfo = utf8UtilityType.GetMethod("GetPointerToFirstInvalidByte", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (methodInfo is null)
{
throw new Exception("Couldn't find GetPointerToFirstInvalidByte method on Utf8Utility.");
}
return (GetPointerToFirstInvalidByteDel)methodInfo.CreateDelegate(typeof(GetPointerToFirstInvalidByteDel));
});
}
}
}
| |
namespace ZetaResourceEditor.RuntimeBusinessLogic.FileGroups;
using BL;
using DL;
using DynamicSettings;
using FileInformations;
using Helpers;
using Language;
using ProjectFolders;
using Projects;
using Properties;
using Runtime.FileAccess;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using Translation;
using Zeta.VoyagerLibrary.Common;
using Zeta.VoyagerLibrary.Common.Collections;
using Zeta.VoyagerLibrary.Logging;
using ZetaAsync;
using ZetaLongPaths;
/// <summary>
/// Groups multiple single files.
/// </summary>
[DebuggerDisplay(@"Name = {Name}, files = {_fileInfos.Count}")]
public class FileGroup :
ITranslationStateInformation,
IComparable,
IComparable<FileGroup>,
IUniqueID,
IOrderPosition,
IGridEditableData
{
public FileGroup(Project project)
{
Project = project;
}
private string _name;
private Guid _projectFolderUniqueID;
private int _orderPosition;
private bool _ignoreDuringExportAndImport;
public FileInformation[] GetFileInfos()
{
lock (_fileInfos)
{
return _fileInfos.ToArray();
}
}
FileInformation[] IGridEditableData.GetFileInformationsSorted()
{
lock (_fileInfos)
{
_fileInfos.Sort();
return _fileInfos.ToArray();
}
}
public IInheritedSettings ParentSettings
{
get
{
var projectFolder = ProjectFolder;
var project = Project;
if (projectFolder == null)
{
// When opening without a project,
// use a dummy project.
return project ?? Project.Empty;
}
else
{
return projectFolder;
}
}
}
public bool IgnoreDuringExportAndImport
{
get => _ignoreDuringExportAndImport;
set => _ignoreDuringExportAndImport = value;
}
public static FileGroupStateColor TranslateStateToColorKey(
FileGroupStates state)
{
switch (state)
{
case FileGroupStates.Empty:
return FileGroupStateColor.Grey;
case FileGroupStates.CompletelyTranslated:
return FileGroupStateColor.Green;
default:
if ((state & FileGroupStates.FormatParameterMismatches) != 0)
{
return FileGroupStateColor.Red;
}
else if ((state & FileGroupStates.TranslationsMissing) != 0)
{
return FileGroupStateColor.Yellow;
}
else if ((state & FileGroupStates.AutomaticTranslationsExist) != 0)
{
return FileGroupStateColor.Blue;
}
else
{
return FileGroupStateColor.Green;
}
}
}
public static FileGroupStateColor CombineColorKeys(
FileGroupStateColor c1,
FileGroupStateColor c2)
{
if (c1 == FileGroupStateColor.None) return c2;
switch (c2)
{
case FileGroupStateColor.None:
return c1;
case FileGroupStateColor.Grey:
return c1;
case FileGroupStateColor.Green:
switch (c1)
{
case FileGroupStateColor.Grey:
case FileGroupStateColor.Yellow:
return FileGroupStateColor.Yellow;
case FileGroupStateColor.Green:
return FileGroupStateColor.Green;
case FileGroupStateColor.Blue:
return FileGroupStateColor.Blue;
case FileGroupStateColor.Red:
return FileGroupStateColor.Red;
default:
throw new ArgumentException();
}
case FileGroupStateColor.Yellow:
switch (c1)
{
case FileGroupStateColor.Grey:
case FileGroupStateColor.Green:
case FileGroupStateColor.Yellow:
case FileGroupStateColor.Blue:
return FileGroupStateColor.Yellow;
case FileGroupStateColor.Red:
return FileGroupStateColor.Red;
default:
throw new ArgumentException();
}
case FileGroupStateColor.Red:
return FileGroupStateColor.Red;
case FileGroupStateColor.Blue:
switch (c1)
{
case FileGroupStateColor.Green:
case FileGroupStateColor.Blue:
return FileGroupStateColor.Blue;
case FileGroupStateColor.Grey:
case FileGroupStateColor.Yellow:
return FileGroupStateColor.Yellow;
case FileGroupStateColor.Red:
return FileGroupStateColor.Red;
default:
throw new ArgumentException();
}
default:
throw new ArgumentException();
}
}
public ProjectFolder ProjectFolder
{
get => Project?.GetProjectFolderByUniqueID(_projectFolderUniqueID);
set => _projectFolderUniqueID = value?.UniqueID ?? Guid.Empty;
}
/*
public static FileGroup CheckCreate(
Project project,
string joinedFilePaths)
{
return string.IsNullOrEmpty(joinedFilePaths) ? new FileGroup(project) : CheckCreate(project, SplitFilePaths(joinedFilePaths));
}
*/
public static FileGroup CheckCreate(
Project project,
string[] filePaths)
{
return CheckCreate(project, filePaths.Select(filePath => new ZlpFileInfo(filePath)).ToArray());
}
public static FileGroup CheckCreate(
Project project,
ZlpFileInfo[] filePaths)
{
var result = new FileGroup(project);
if (filePaths.Length > 0)
{
foreach (var filePath in filePaths)
{
result.Add(
new FileInformation(result)
{
File = filePath
});
}
}
var same = project?.GetFileGroupByCheckSum(result.GetChecksum(project));
return same ?? result;
}
private FileGroupStates TranslationState => _inMemoryState ?? calculateEditingState();
public FileGroupStateColor TranslationStateColor => TranslateStateToColorKey(TranslationState);
private FileGroupStates calculateEditingState()
{
var data = new DataProcessing(this);
var table = data.GetDataTableFromResxFiles(Project);
return DoCalculateEditingState(Project, table, CommentVisibilityScope.InMemory);
}
public static FileGroupStates DoCalculateEditingState(
Project project,
DataTable table,
CommentVisibilityScope commentVisibilityScope)
{
if (table == null)
{
return FileGroupStates.Empty;
}
else
{
var result = FileGroupStates.CompletelyTranslated;
foreach (DataRow row in table.Rows)
{
if (IsCompleteRowEmpty(row))
{
result |= FileGroupStates.EmptyRows;
}
if (areTranslationsMissing(project, row, commentVisibilityScope))
{
result |= FileGroupStates.TranslationsMissing;
}
if (hasPlaceholderMismatch(project, row, commentVisibilityScope))
{
result |= FileGroupStates.FormatParameterMismatches;
}
if (doesAutomaticTranslationsExist(project, row, commentVisibilityScope))
{
result |= FileGroupStates.AutomaticTranslationsExist;
}
}
return result;
}
}
// AJ CHANGE
private static bool doesAutomaticTranslationsExist(
Project project,
DataRow row,
CommentVisibilityScope commentVisibilityScope)
{
// Column 0=FileGroup checksum, column 1=Tag name.
for (var i = 2;
i < row.Table.Columns.Count -
(DataProcessing.CommentsAreVisible(project, row, commentVisibilityScope) ? 1 : 0);
++i)
{
var s = ConvertHelper.ToString(row[i], string.Empty);
if (s.StartsWith(DefaultTranslatedPrefix)) return true;
}
return false;
}
private static bool areTranslationsMissing(
Project project,
DataRow row,
CommentVisibilityScope commentVisibilityScope)
{
var hasEmpty = false;
var hasNonEmpty = false;
// AJ CHANGE
// Don't check the comments column
// Column 0=FileGroup checksum, column 1=Tag name.
for (var i = 2;
i < row.Table.Columns.Count -
(DataProcessing.CommentsAreVisible(project, row, commentVisibilityScope) ? 1 : 0);
++i)
{
var s = ConvertHelper.ToString(row[i], string.Empty);
if (string.IsNullOrEmpty(s))
{
hasEmpty = true;
}
else
{
hasNonEmpty = true;
}
}
return hasEmpty && hasNonEmpty;
}
private static int findColumnIndex(
DataTable table,
string columnName,
int fallbackIndex)
{
if (string.IsNullOrEmpty(columnName))
{
return fallbackIndex;
}
else
{
foreach (DataColumn column in table.Columns)
{
if (column.ColumnName.EqualsNoCase(columnName))
{
return column.Ordinal;
}
}
return fallbackIndex;
}
}
private static bool hasPlaceholderMismatch(
Project project,
DataRow row,
CommentVisibilityScope commentVisibilityScope)
{
// 2011-11-17, Uwe Keim.
var neutralCode = project == null ? @"en-US" : project.NeutralLanguageCode;
var neutralColumnIndex = findColumnIndex(row.Table, neutralCode, 2);
var columnCount = row.Table.Columns.Count;
var s0 =
columnCount > 0
// Column 0=FileGroup checksum, column 1=Tag name.
? ConvertHelper.ToString(row[neutralColumnIndex], string.Empty)
: string.Empty;
var firstPlaceholderCount = ExtractPlaceholders(s0);
// AJ CHANGE, skip the comments column
// Column 0=FileGroup checksum, column 1=Tag name.
for (var i = 2;
i < columnCount -
(DataProcessing.CommentsAreVisible(project, row, commentVisibilityScope) ? 1 : 0);
++i)
{
if (i != neutralColumnIndex)
{
var s = ConvertHelper.ToString(row[i], string.Empty);
// 2011-11-16, Uwe Keim: Only check if non-empty, non-default-language.
if (!string.IsNullOrEmpty(s))
{
var other = ExtractPlaceholders(s);
if (other != firstPlaceholderCount)
{
return true;
}
}
}
}
return false;
}
public static bool IsCompleteRowEmpty(
DataRow row)
{
// Column 0=FileGroup checksum, column 1=Tag name.
for (var i = 2; i < row.Table.Columns.Count; ++i)
{
if (ConvertHelper.ToString(row[i], string.Empty).Trim().Length > 0)
{
return false;
}
}
return true;
}
// http://www.codeproject.com/KB/aspnet/ZetaResourceEditor.aspx?msg=3367544#xx3367544xx
public static bool IsInternalRow(DataRow row)
{
var name = row[@"Name"] as string;
return string.IsNullOrEmpty(name) ||
name.StartsWith(@">>") ||
!name.Equals(@"$this.Text") && name.StartsWith(@"$this.");
}
public static string ExtractPlaceholders(
string text)
{
if (string.IsNullOrEmpty(text) || text.IndexOf('{') < 0 ||
text.IndexOf('}') < 0)
{
return string.Empty;
}
else
{
const string pattern = @"\{(\d+(:\w+)?)\}";
var matches = Regex.Matches(
text,
pattern,
RegexOptions.IgnoreCase);
if (matches.Count <= 0)
{
return string.Empty;
}
else
{
var indexes = new HashSet<int>();
foreach (Match match in matches)
{
var i = match.Groups[1].Value;
indexes.Add(ConvertHelper.ToInt32(i));
}
var l = indexes.ToList();
l.Sort();
var result = new StringBuilder();
foreach (var i in l)
{
result.Append('-');
result.Append(i);
}
// Do not return the count but the hash to allow
// for comparing the exact placeholders equality.
return result.ToString();
}
}
}
public bool Contains(
FileInformation item)
{
lock (_fileInfos)
{
return _fileInfos.Any(fileInfo => item.File.FullName.EqualsNoCase(fileInfo.File.FullName));
}
}
public void Add(
FileInformation item)
{
lock (_fileInfos)
{
if (!Contains(item))
{
_fileInfos.Add(item);
}
}
}
internal void StoreToXml(
Project project,
XmlElement parentNode)
{
lock (_fileInfos)
{
foreach (var fileInfo in _fileInfos)
{
if (parentNode.OwnerDocument != null)
{
var fileNode =
parentNode.OwnerDocument.CreateElement(@"file");
parentNode.AppendChild(fileNode);
fileInfo.StoreToXml(project, fileNode);
}
}
}
if (parentNode.OwnerDocument != null)
{
var a = parentNode.OwnerDocument.CreateAttribute(@"name");
a.Value = _name;
parentNode.Attributes.Append(a);
a = parentNode.OwnerDocument.CreateAttribute(@"projectFolderUniqueID");
a.Value = _projectFolderUniqueID.ToString();
parentNode.Attributes.Append(a);
a = parentNode.OwnerDocument.CreateAttribute(@"orderPosition");
a.Value = OrderPosition.ToString(CultureInfo.InvariantCulture);
parentNode.Attributes.Append(a);
a = parentNode.OwnerDocument.CreateAttribute(@"ignoreDuringExportAndImport");
a.Value = _ignoreDuringExportAndImport.ToString(CultureInfo.InvariantCulture);
parentNode.Attributes.Append(a);
var remarksNode =
parentNode.OwnerDocument.CreateElement(@"remarks");
parentNode.AppendChild(remarksNode);
remarksNode.InnerText = Remarks;
if (parentNode.OwnerDocument != null)
{
a = parentNode.OwnerDocument.CreateAttribute(@"uniqueID");
a.Value = _uniqueID.ToString();
parentNode.Attributes.Append(a);
}
}
}
internal void LoadFromXml(
Project project,
XmlNode parentNode)
{
lock (_fileInfos)
{
_fileInfos.Clear();
var fileNodes = parentNode.SelectNodes(@"file");
if (fileNodes != null)
{
foreach (XmlNode fileNode in fileNodes)
{
var ffi = new FileInformation(this);
if (ffi.LoadFromXml(project, fileNode))
{
Add(ffi);
}
}
}
// --
if (parentNode.Attributes != null)
{
XmlHelper.ReadAttribute(
out _uniqueID,
parentNode.Attributes[@"uniqueID"]);
}
if (_uniqueID == Guid.Empty)
{
_uniqueID = Guid.NewGuid();
}
// --
if (parentNode.Attributes != null)
{
XmlHelper.ReadAttribute(
out _projectFolderUniqueID,
parentNode.Attributes[@"projectFolderUniqueID"]);
XmlHelper.ReadAttribute(
out _name,
parentNode.Attributes[@"name"]);
XmlHelper.ReadAttribute(
out _orderPosition,
parentNode.Attributes[@"orderPosition"]);
XmlHelper.ReadAttribute(
out _ignoreDuringExportAndImport,
parentNode.Attributes[@"ignoreDuringExportAndImport"]);
}
var remarksNode = parentNode.SelectSingleNode(@"remarks");
Remarks = remarksNode?.InnerText;
// --
_fileInfos.Sort();
}
}
public string GetNameIntelligent(
Project project)
{
lock (_fileInfos)
{
if (string.IsNullOrEmpty(_name) && _fileInfos.Count > 0)
{
// Try guessing several names.
var filePath = _fileInfos[0].File;
var folderPath = filePath.Directory;
//CHANGED: use base name instead
var baseName = LanguageCodeDetection.GetBaseName(project, filePath.Name);
filePath = new ZlpFileInfo(ZlpPathHelper.Combine(folderPath.FullName, baseName));
if ((@"Properties".EqualsNoCase(folderPath.Name) ||
@"App_GlobalResources".EqualsNoCase(folderPath.Name)) &&
filePath.Name.StartsWithNoCase(@"Resources."))
{
var parentFolderPath = folderPath.Parent;
if (parentFolderPath == null)
{
return project is not { DisplayFileGroupWithoutFolder: true }
? _name
: ZlpPathHelper.GetFileNameFromFilePath(_name);
}
else
{
//CHANGED: append fileName, otherwise name is not complete.
var pathToMakeRelative = ZlpPathHelper.Combine(parentFolderPath.FullName, filePath.Name);
return
project is not { DisplayFileGroupWithoutFolder: true }
? shortenFilePath(
ZlpPathHelper.GetRelativePath(
project == null
? string.Empty
: project.ProjectConfigurationFilePath.DirectoryName,
pathToMakeRelative))
: filePath.Name;
}
}
else if (@"App_LocalResources".EqualsNoCase(folderPath.Name))
{
var name =
ZlpPathHelper.GetRelativePath(
project == null
? string.Empty
: project.ProjectConfigurationFilePath.DirectoryName,
filePath.FullName);
var ext = ZlpPathHelper.GetExtension(name);
var result = name.Substring(0, name.Length - ext.Length);
return
project is not { DisplayFileGroupWithoutFolder: true }
? shortenFilePath(result)
: filePath.Name;
}
else
{
return
project is not { DisplayFileGroupWithoutFolder: true }
? shortenFilePath(
ZlpPathHelper.GetRelativePath(
project == null
? string.Empty
: project.ProjectConfigurationFilePath.DirectoryName,
filePath.FullName))
: filePath.Name;
}
}
else
{
return project is not { DisplayFileGroupWithoutFolder: true }
? _name
: ZlpPathHelper.GetFileNameFromFilePath(_name);
}
}
}
public string Name
{
get
{
lock (_fileInfos)
{
if (string.IsNullOrEmpty(_name) && _fileInfos.Count > 0)
{
// Try guessing several names.
var filePath = _fileInfos[0].File;
var folderPath = filePath.Directory;
if (@"Properties".EqualsNoCase(folderPath.Name) ||
@"App_GlobalResources".EqualsNoCase(folderPath.Name))
{
var parentFolderPath = folderPath.Parent;
if (parentFolderPath == null)
{
return _name;
}
else
{
return
ZlpPathHelper.Combine(
parentFolderPath.Name,
folderPath.Name);
}
}
else if (@"App_LocalResources".EqualsNoCase(folderPath.Name))
{
return
ZlpPathHelper.Combine(
@"App_LocalResources",
ZlpPathHelper.GetFileNameWithoutExtension(filePath.Name));
}
else
{
return filePath.Name;
}
}
else
{
return _name;
}
}
}
set => _name = value;
}
public string GetFullNameIntelligent(
Project project)
{
lock (_fileInfos)
{
return _fileInfos.Count <= 0 ? GetNameIntelligent(project) : _fileInfos[0].File.DirectoryName;
}
}
public ZlpDirectoryInfo FolderPath
{
get
{
lock (_fileInfos)
{
return _fileInfos.Count <= 0 ? null : _fileInfos[0].File.Directory;
}
}
}
public long GetChecksum(
Project project)
{
lock (_fileInfos)
{
return BuildChecksum(project, _fileInfos);
}
}
public string JoinedFilePaths => JoinFilePaths(FilePaths);
public static string JoinFilePaths(
params string[] paths)
{
return paths is not { Length: > 0 } ? string.Empty : string.Join(@";", paths);
}
public static string[] SplitFilePaths(string paths)
{
return string.IsNullOrEmpty(paths) ? new string[] { } : paths.Split(';');
}
public string[] FilePaths
{
get
{
lock (_fileInfos)
{
var xs = sortFiles(_fileInfos.ToArray());
return xs.Select(x => x.File.FullName).ToArray();
}
}
}
public string[] GetLanguageCodes(
Project project)
{
var result = new HashSet<string>();
foreach (var filePath in FilePaths)
{
var lc =
new LanguageCodeDetection(project).DetectLanguageCodeFromFileName(
ParentSettings,
filePath);
if (!string.IsNullOrEmpty(lc))
{
result.Add(lc.ToLowerInvariant());
}
}
return result.ToArray();
}
public MyTuple<string, string>[] GetLanguageCodesExtended(
Project project)
{
var result = new HashSet<MyTuple<string, string>>();
foreach (var filePath in FilePaths)
{
var lc =
new LanguageCodeDetection(project).DetectLanguageCodeFromFileName(
ParentSettings,
filePath);
if (!string.IsNullOrEmpty(lc))
{
result.Add(
new MyTuple<string, string>(
lc.ToLowerInvariant(),
filePath));
}
}
return result.ToArray();
}
public FileInformation GetFileByLanguageCode(
Project project,
CultureInfo culture)
{
return GetFileByLanguageCode(project, culture.Name);
}
public FileInformation GetFileByLanguageCode(
Project project,
string languageCode)
{
lock (_fileInfos)
{
foreach (var ffi in _fileInfos)
{
var lc = new LanguageCodeDetection(project).DetectLanguageCodeFromFileName(
ParentSettings,
ffi.File.FullName);
if (languageCode.EqualsNoCase(lc))
{
return ffi;
}
}
// Not found.
return null;
}
}
public static string DefaultTranslatedPrefix => @"####";
public static string DefaultTranslationErrorPrefix => @"****";
/// <summary>
/// Gets the base name.
/// </summary>
/// <remarks>
/// E.g. for:
/// - Main.master.resx
/// - Main.master.de.resx
/// - Main.master.en-us.resx
/// it would be "Main.master"
///
/// E.g. for:
/// - Properties.resx
/// - Properties.de.resx
/// it would be "Properties".
/// </remarks>
/// <value>The base name.</value>
public string BaseName => new LanguageCodeDetection(Project).GetBaseName(this);
public string BaseExtension => new LanguageCodeDetection(Project).GetBaseExtension(this);
public string BaseOptionalDefaultType => new LanguageCodeDetection(Project).GetBaseOptionalDefaultType(this);
private string Remarks { get; set; }
public Guid ProjectFolderUniqueID => _projectFolderUniqueID;
public void StoreOrderPosition(
object threadPoolManager,
object postExecuteCallback,
AsynchronousMode asynchronousMode,
object userState)
{
Project.MarkAsModified();
}
public int OrderPosition
{
get => _orderPosition;
set => _orderPosition = value;
}
private FileGroupStates? _inMemoryState;
private Guid _uniqueID;
private readonly List<FileInformation> _fileInfos = new();
public FileGroupStates InMemoryState
{
get => _inMemoryState.GetValueOrDefault(FileGroupStates.Empty);
set => _inMemoryState = value;
}
private static IEnumerable<FileInformation> sortFiles(
ICollection<FileInformation> filePaths)
{
if (filePaths == null || filePaths.Count < 2)
{
return filePaths;
}
else
{
var sortableP = new List<FileInformation>(filePaths);
sortableP.Sort();
return sortableP.ToArray();
}
}
private static long BuildChecksum(
Project project,
IEnumerable<FileInformation> filePaths)
{
long result = 0;
if (filePaths != null)
{
// Clone.
var fp = new List<FileInformation>(filePaths);
foreach (var filePath in fp)
{
// Changed 2009-07-11, Uwe Keim:
// Use relative path if available.
var realPath =
project == null
? filePath.File.FullName
: project.MakeRelativeFilePath(filePath.File.FullName);
result += Math.Abs(realPath.ToLowerInvariant().GetHashCode());
}
}
return result;
}
private static string shortenFilePath(
string filePath)
{
return ShortenFilePath(filePath, 150);
}
public static string ShortenFilePath(
string filePath,
int maxLength)
{
if (string.IsNullOrEmpty(filePath) || filePath.Length <= maxLength)
{
return filePath;
}
else
{
return ZrePathHelper.ShortenPathName(filePath, maxLength);
}
}
public int CompareTo(FileGroup other)
{
var a = _orderPosition.CompareTo(other._orderPosition);
return a == 0 ? string.CompareOrdinal(Name, other.Name) : a;
}
public int CompareTo(object obj)
{
return CompareTo((FileGroup)obj);
}
public override bool Equals(object obj)
{
if (obj is FileGroup to)
{
var compareTo = to;
return compareTo.GetChecksum(null) == GetChecksum(null);
}
else
{
return false;
}
}
public override int GetHashCode()
{
return GetChecksum(null).GetHashCode();
}
public Guid UniqueID
{
get
{
if (_uniqueID == Guid.Empty) _uniqueID = Guid.NewGuid();
return _uniqueID;
}
}
public GridSourceType SourceType => GridSourceType.FileGroup;
FileGroup IGridEditableData.FileGroup => this;
public Project Project { get; set; }
public int FileInfoCount
{
get
{
lock (_fileInfos)
{
return _fileInfos.Count;
}
}
}
public FileInformation CreateAndAddNewFile(
string baseFolderPath,
string newFileName)
{
if (newFileName.StartsWithNoCase(BaseName) && newFileName.EndsWithNoCase(BaseExtension))
{
var newFilePath = ZlpPathHelper.Combine(baseFolderPath, newFileName);
// Add to myself.
var ffi =
new FileInformation(this)
{
File = new ZlpFileInfo(newFilePath)
};
Add(ffi);
return ffi;
}
else
{
throw new Exception(
string.Format(
Resources.SR_FileGroup_CreateAndAddNewFile_New_file_name_does_not_match,
BaseName,
BaseExtension));
}
}
public bool CreateAndAddNewFile(
string sourceFilePath,
string newFileName,
string sourceLanguageCode,
string newLanguageCode,
bool copyTextsFromSource,
bool automaticallyTranslateTexts,
string prefix,
bool includeFileInCsProj,
bool includeFileAsDependantUpon)
{
if (newFileName.StartsWithNoCase(BaseName) && newFileName.EndsWithNoCase(BaseExtension))
{
var newFilePath =
ZlpPathHelper.Combine(
ZlpPathHelper.GetDirectoryPathNameFromFilePath(sourceFilePath),
newFileName);
bool didCopy;
if (ZlpIOHelper.FileExists(newFilePath))
{
// Simply ignore and add.
didCopy = false;
// File may already exist but was not yet added
// to the file group.
/*
throw new Exception(
string.Format(
"New file '{0}' already exists.",
newFileName));
*/
}
else
{
// Copy only if not exists.
ZlpIOHelper.CopyFile(sourceFilePath, newFilePath, false);
didCopy = true;
}
// Add to myself.
var ffi =
new FileInformation(this)
{
File = new ZlpFileInfo(newFilePath)
};
Add(ffi);
// --
// Further process.
if (includeFileInCsProj)
{
try
{
addFileToCsProj(new ZlpFileInfo(sourceFilePath), new ZlpFileInfo(newFilePath),
includeFileAsDependantUpon);
}
catch
{
//Including new resource file to csproj should not break process of creating new files.
//To consider showing this information in any form
}
}
if (!copyTextsFromSource /*&& !automaticallyTranslateTexts*/)
{
if (didCopy)
{
clearAllTexts(ffi);
}
}
if (automaticallyTranslateTexts)
{
if (didCopy)
{
translateTexts(
Project,
ffi,
sourceLanguageCode,
newLanguageCode,
prefix);
}
}
return didCopy;
}
else
{
throw new Exception(
string.Format(
Resources.SR_FileGroup_CreateAndAddNewFile_New_file_name_does_not_match,
BaseName,
BaseExtension));
}
}
//private FileInformation getFfiForFilePath( string filePath )
//{
// var fileName = Path.GetFileName( filePath );
// foreach ( var ffi in this )
// {
// if ( string.Compare( ffi.File.Name, fileName, true ) == 0 )
// {
// return ffi;
// }
// }
// return null;
//}
private void addFileToCsProj(ZlpFileInfo sourceFile, ZlpFileInfo newFile, bool addDependantUpon)
{
var newFilePath = newFile.FullName;
var csProjWithFileResult = CsProjHelper.GetProjectContainingFile(sourceFile);
if (csProjWithFileResult?.Project?.Items == null)
{
//If we are unable to find correlated csProj, we do nothing
return;
}
var project = csProjWithFileResult.Project;
if (project.Items.FirstOrDefault(i => i.EvaluatedInclude == newFilePath) == null)
{
var metaData = new List<KeyValuePair<string, string>>();
if (addDependantUpon && !string.IsNullOrEmpty(csProjWithFileResult.DependantUponRootFileName))
{
metaData.Add(new KeyValuePair<string, string>(CsProjHelper.DependentUponLiteral,
csProjWithFileResult.DependantUponRootFileName));
}
var relativeFilePath = newFilePath.Replace(project.DirectoryPath + "\\", string.Empty);
project.AddItem(CsProjHelper.EmbeddedResourceLiteral, relativeFilePath, metaData);
}
project.Save();
}
private void clearAllTexts(FileInformation ffi)
{
var tmpFileGroup = new FileGroup(Project);
tmpFileGroup.AddFileInfo(ffi);
var data = new DataProcessing(tmpFileGroup);
var table = data.GetDataTableFromResxFiles(Project);
foreach (DataRow row in table.Rows)
{
// Clear.
// Column 0=FileGroup checksum, column 1=Tag name.
row[2] = null;
}
// Write back.
data.SaveDataTableToResxFiles(Project, table, false, false);
}
private void AddFileInfo(FileInformation ffi)
{
lock (_fileInfos)
{
_fileInfos.Add(ffi);
}
}
private void translateTexts(
Project project,
FileInformation destinationFfi,
string sourceLanguageCode,
string destinationLanguageCode,
string prefix)
{
project ??= Project.Empty;
var continueOnErrors = project.TranslationContinueOnErrors;
var delayMilliseconds = project.TranslationDelayMilliseconds;
var translationCount = 0;
var translationSuccessCount = 0;
var translationErrorCount = 0;
// --
var tmpFileGroup = new FileGroup(Project);
tmpFileGroup.AddFileInfo(destinationFfi);
var data = new DataProcessing(tmpFileGroup);
var table = data.GetDataTableFromResxFiles(Project);
// --
TranslationHelper.GetTranslationAppID(project, out var appID);
var ti = TranslationHelper.GetTranslationEngine(project);
// 2017-03-11, Uwe Keim: Only translate if supported.
if (ti.IsSourceLanguageSupported(appID, sourceLanguageCode) &&
ti.IsDestinationLanguageSupported(appID, destinationLanguageCode))
{
var slc =
ti.MapCultureToSourceLanguageCode(
appID,
CultureHelper.CreateCultureErrorTolerant(sourceLanguageCode));
var dlc =
ti.MapCultureToDestinationLanguageCode(
appID,
CultureHelper.CreateCultureErrorTolerant(destinationLanguageCode));
// --
foreach (DataRow row in table.Rows)
{
var sourceText = ConvertHelper.ToString(row[2]);
if (!string.IsNullOrEmpty(sourceText))
{
if (delayMilliseconds > 0)
{
Thread.Sleep(delayMilliseconds);
}
try
{
var destinationText =
prefix +
ti.Translate(
appID,
sourceText,
slc,
dlc,
project.TranslationWordsToProtect,
project.TranslationWordsToRemove);
row[2] = destinationText;
translationSuccessCount++;
}
catch (Exception x)
{
translationErrorCount++;
if (continueOnErrors)
{
var prefixError = DefaultTranslationErrorPrefix.Trim() + @" ";
var destinationText = prefixError + x.Message;
if (row[2] != null)
{
row[2] = destinationText;
}
}
else
{
throw;
}
}
translationCount++;
}
}
// Write back.
data.SaveDataTableToResxFiles(project, table, false, false);
}
LogCentral.Current.Info(
$@"Finished translating: {nameof(translationCount)} = '{translationCount}', {
nameof(translationSuccessCount)
} = '{translationSuccessCount}', {nameof(translationErrorCount)} = '{translationErrorCount}'.");
}
public bool IsDeepChildOf(ProjectFolder folder)
{
var pf = ProjectFolder;
while (pf != null)
{
if (pf.UniqueID == folder.UniqueID)
{
return true;
}
pf = pf.Parent;
}
return false;
}
public bool HasLanguageCode(CultureInfo cultureInfo)
{
var lcd = new LanguageCodeDetection(Project);
return FilePaths
.Select(filePath => lcd.DetectCultureFromFileName(ParentSettings, filePath))
.Any(ci => ci.Name.EqualsNoCase(cultureInfo.Name));
}
public bool DeleteFile(FileInformation fileInformation)
{
RemoveFileInfo(fileInformation);
fileInformation.File.SafeDelete();
return !fileInformation.File.SafeExists();
}
public void RemoveFileInfo(FileInformation fileInformation)
{
lock (_fileInfos)
{
_fileInfos.Remove(fileInformation);
}
}
public CsProjectWithFileResult GetConnectedCsProject()
{
CsProjectWithFileResult csProjResult = null;
if (FilePaths is { Length: >= 2 })
{
var notDefaultLanguageVersion = FilePaths
.Select(t => new
{
Replaced = CsProjHelper.RegexFindMainResourceFile.Replace(t,
CsProjHelper.RegexFindMainResourceFileReplacePattern),
Original = t
}).FirstOrDefault(t => t.Original != t.Replaced)?.Original;
csProjResult = CsProjHelper.GetProjectContainingFile(new ZlpFileInfo(notDefaultLanguageVersion));
}
return csProjResult;
}
}
| |
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing.Drawing2D;
namespace CloudBox.Controller
{
/// <summary>
/// A replacement for the Windows Button Control.
/// </summary>
public class VistaPanel : System.Windows.Forms.Panel
{
#region - Designer -
private System.ComponentModel.Container components = null;
/// <summary>
/// Initialize the component with it's
/// default settings.
/// </summary>
public VistaPanel()
{
InitializeComponent();
this.mFadeIn.Tick += new EventHandler(mFadeIn_Tick);
this.mFadeOut.Tick += new EventHandler(mFadeOut_Tick);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.Selectable, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.BackColor = Color.Transparent;
mFadeIn.Interval = 30;
mFadeOut.Interval = 30;
}
/// <summary>
/// Release resources used by the control.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region - Component Designer generated code -
private void InitializeComponent()
{
//
// VistaPanel
//
this.Name = "VistaPanel";
this.Size = new System.Drawing.Size(100, 32);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.VistaPanel_Paint);
//this.MouseEnter += new System.EventHandler(this.VistaPanel_MouseEnter);
//this.MouseLeave += new System.EventHandler(this.VistaPanel_MouseLeave);
//this.GotFocus += new EventHandler(VistaPanel_MouseEnter);
//this.LostFocus += new EventHandler(VistaPanel_MouseLeave);
this.Resize += new EventHandler(VistaPanel_Resize);
}
#endregion
#endregion
#region - Enums -
/// <summary>
/// A private enumeration that determines
/// the mouse state in relation to the
/// current instance of the control.
/// </summary>
enum State {None, Hover, Pressed};
/// <summary>
/// A public enumeration that determines whether
/// the button background is painted when the
/// mouse is not inside the ClientArea.
/// </summary>
public enum Style
{
/// <summary>
/// Draw the button as normal
/// </summary>
Default,
/// <summary>
/// Only draw the background on mouse over.
/// </summary>
Flat
};
#endregion
#region - Properties -
#region - Private Variables -
private State mButtonState = State.None;
private Timer mFadeIn = new Timer();
private Timer mFadeOut = new Timer();
private int mGlowAlpha = 0;
#endregion
//#region - Text -
// private string mText;
// /// <summary>
// /// The text that is displayed on the button.
// /// </summary>
// [Category("Text"),
// Description("The text that is displayed on the button.")]
// public string ButtonText
// {
// get { return mText; }
// set { mText = value; this.Invalidate(); }
// }
// private Color mForeColor = Color.White;
// /// <summary>
// /// The color with which the text is drawn.
// /// </summary>
// [Category("Text"),
// Browsable(true),
// DefaultValue(typeof(Color),"White"),
// Description("The color with which the text is drawn.")]
// public override Color ForeColor
// {
// get { return mForeColor; }
// set { mForeColor = value; this.Invalidate(); }
// }
// private ContentAlignment mTextAlign = ContentAlignment.MiddleCenter;
// /// <summary>
// /// The alignment of the button text
// /// that is displayed on the control.
// /// </summary>
// [Category("Text"),
// DefaultValue(typeof(ContentAlignment),"MiddleCenter"),
// Description("The alignment of the button text " +
// "that is displayed on the control.")]
// public ContentAlignment TextAlign
// {
// get { return mTextAlign; }
// set { mTextAlign = value; this.Invalidate(); }
// }
//#endregion
#region - Image -
private Image mImage;
/// <summary>
/// The image displayed on the button that
/// is used to help the user identify
/// it's function if the text is ambiguous.
/// </summary>
[Category("Image"),
DefaultValue(null),
Description("The image displayed on the button that " +
"is used to help the user identify" +
"it's function if the text is ambiguous.")]
public Image Image
{
get { return mImage; }
set { mImage = value; this.Invalidate(); }
}
private ContentAlignment mImageAlign = ContentAlignment.MiddleLeft;
/// <summary>
/// The alignment of the image
/// in relation to the button.
/// </summary>
[Category("Image"),
DefaultValue(typeof(ContentAlignment),"MiddleLeft"),
Description("The alignment of the image " +
"in relation to the button.")]
public ContentAlignment ImageAlign
{
get { return mImageAlign; }
set { mImageAlign = value; this.Invalidate(); }
}
private Size mImageSize = new Size(24,24);
/// <summary>
/// The size of the image to be displayed on the
/// button. This property defaults to 24x24.
/// </summary>
[Category("Image"),
DefaultValue(typeof(Size),"24, 24"),
Description("The size of the image to be displayed on the" +
"button. This property defaults to 24x24.")]
public Size ImageSize
{
get { return mImageSize; }
set { mImageSize = value; this.Invalidate(); }
}
#endregion
#region - Appearance -
private Style mButtonStyle = Style.Default;
/// <summary>
/// Sets whether the button background is drawn
/// while the mouse is outside of the client area.
/// </summary>
[Category("Appearance"),
DefaultValue(typeof(Style),"Default"),
Description("Sets whether the button background is drawn " +
"while the mouse is outside of the client area.")]
public Style ButtonStyle
{
get { return mButtonStyle; }
set { mButtonStyle = value; this.Invalidate(); }
}
private int mCornerRadius = 8;
/// <summary>
/// The radius for the button corners. The
/// greater this value is, the more 'smooth'
/// the corners are. This property should
/// not be greater than half of the
/// controls height.
/// </summary>
[Category("Appearance"),
DefaultValue(8),
Description("The radius for the button corners. The " +
"greater this value is, the more 'smooth' " +
"the corners are. This property should " +
"not be greater than half of the " +
"controls height.")]
public int CornerRadius
{
get { return mCornerRadius; }
set { mCornerRadius = value; this.Invalidate(); }
}
private Color mHighlightColor = Color.White;
/// <summary>
/// The colour of the highlight on the top of the button.
/// </summary>
[Category("Appearance"),
DefaultValue(typeof(Color), "White"),
Description("The colour of the highlight on the top of the button.")]
public Color HighlightColor
{
get { return mHighlightColor; }
set { mHighlightColor = value; this.Invalidate(); }
}
private Color mButtonColor = Color.Black;
/// <summary>
/// The bottom color of the button that
/// will be drawn over the base color.
/// </summary>
[Category("Appearance"),
DefaultValue(typeof(Color), "Black"),
Description("The bottom color of the button that " +
"will be drawn over the base color.")]
public Color ButtonColor
{
get { return mButtonColor; }
set { mButtonColor = value; this.Invalidate(); }
}
private Color mGlowColor = Color.FromArgb(141,189,255);
/// <summary>
/// The colour that the button glows when
/// the mouse is inside the client area.
/// </summary>
[Category("Appearance"),
DefaultValue(typeof(Color), "141,189,255"),
Description("The colour that the button glows when " +
"the mouse is inside the client area.")]
public Color GlowColor
{
get { return mGlowColor; }
set { mGlowColor = value; this.Invalidate(); }
}
private Image mBackImage;
/// <summary>
/// The background image for the button,
/// this image is drawn over the base
/// color of the button.
/// </summary>
[Category("Appearance"),
DefaultValue(null),
Description("The background image for the button, " +
"this image is drawn over the base " +
"color of the button.")]
public Image BackImage
{
get { return mBackImage; }
set { mBackImage = value; this.Invalidate(); }
}
private Color mBaseColor = Color.Black;
/// <summary>
/// The backing color that the rest of
/// the button is drawn. For a glassier
/// effect set this property to Transparent.
/// </summary>
[Category("Appearance"),
DefaultValue(typeof(Color), "Black"),
Description("The backing color that the rest of" +
"the button is drawn. For a glassier " +
"effect set this property to Transparent.")]
public Color BaseColor
{
get { return mBaseColor; }
set { mBaseColor = value; this.Invalidate(); }
}
#endregion
#endregion
#region - Functions -
private GraphicsPath RoundRect(RectangleF r, float r1, float r2, float r3, float r4)
{
float x = r.X, y = r.Y, w = r.Width, h = r.Height;
GraphicsPath rr = new GraphicsPath();
rr.AddBezier(x, y + r1, x, y, x + r1, y, x + r1, y);
rr.AddLine(x + r1, y, x + w - r2, y);
rr.AddBezier(x + w - r2, y, x + w, y, x + w, y + r2, x + w, y + r2);
rr.AddLine(x + w, y + r2, x + w, y + h - r3);
rr.AddBezier(x + w, y + h - r3, x + w, y + h, x + w - r3, y + h, x + w - r3, y + h);
rr.AddLine(x + w - r3, y + h, x + r4, y + h);
rr.AddBezier(x + r4, y + h, x, y + h, x, y + h - r4, x, y + h - r4);
rr.AddLine(x, y + h - r4, x, y + r1);
return rr;
}
private StringFormat StringFormatAlignment(ContentAlignment textalign)
{
StringFormat sf = new StringFormat();
switch (textalign)
{
case ContentAlignment.TopLeft:
case ContentAlignment.TopCenter:
case ContentAlignment.TopRight:
sf.LineAlignment = StringAlignment.Near;
break;
case ContentAlignment.MiddleLeft:
case ContentAlignment.MiddleCenter:
case ContentAlignment.MiddleRight:
sf.LineAlignment = StringAlignment.Center;
break;
case ContentAlignment.BottomLeft:
case ContentAlignment.BottomCenter:
case ContentAlignment.BottomRight:
sf.LineAlignment = StringAlignment.Far;
break;
}
switch (textalign)
{
case ContentAlignment.TopLeft:
case ContentAlignment.MiddleLeft:
case ContentAlignment.BottomLeft:
sf.Alignment = StringAlignment.Near;
break;
case ContentAlignment.TopCenter:
case ContentAlignment.MiddleCenter:
case ContentAlignment.BottomCenter:
sf.Alignment = StringAlignment.Center;
break;
case ContentAlignment.TopRight:
case ContentAlignment.MiddleRight:
case ContentAlignment.BottomRight:
sf.Alignment = StringAlignment.Far;
break;
}
return sf;
}
#endregion
#region - Drawing -
/// <summary>
/// Draws the outer border for the control
/// using the ButtonColor property.
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawOuterStroke(Graphics g)
{
if (this.ButtonStyle == Style.Flat && this.mButtonState == State.None){return;}
Rectangle r = this.ClientRectangle;
r.Width -= 1; r.Height -= 1;
using (GraphicsPath rr = RoundRect(r, CornerRadius, CornerRadius, CornerRadius, CornerRadius))
{
using (Pen p = new Pen(this.ButtonColor))
{
g.DrawPath(p, rr);
}
}
}
/// <summary>
/// Draws the inner border for the control
/// using the HighlightColor property.
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawInnerStroke(Graphics g)
{
if (this.ButtonStyle == Style.Flat && this.mButtonState == State.None){return;}
Rectangle r = this.ClientRectangle;
r.X++; r.Y++;
r.Width -= 3; r.Height -= 3;
using (GraphicsPath rr = RoundRect(r, CornerRadius, CornerRadius, CornerRadius, CornerRadius))
{
using (Pen p = new Pen(this.HighlightColor))
{
g.DrawPath(p, rr);
}
}
}
/// <summary>
/// Draws the background for the control
/// using the background image and the
/// BaseColor.
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawBackground(Graphics g)
{
if (this.ButtonStyle == Style.Flat && this.mButtonState == State.None){return;}
int alpha = (mButtonState == State.Pressed) ? 204 : 127;
Rectangle r = this.ClientRectangle;
r.Width--; r.Height--;
using (GraphicsPath rr = RoundRect(r, CornerRadius, CornerRadius, CornerRadius, CornerRadius))
{
using (SolidBrush sb = new SolidBrush(this.BaseColor))
{
g.FillPath(sb, rr);
}
SetClip(g);
if (this.BackImage != null){g.DrawImage(this.BackImage, this.ClientRectangle);}
g.ResetClip();
using (SolidBrush sb = new SolidBrush(Color.FromArgb(alpha, this.ButtonColor)))
{
g.FillPath(sb, rr);
}
}
}
/// <summary>
/// Draws the Highlight over the top of the
/// control using the HightlightColor.
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawHighlight(Graphics g)
{
if (this.ButtonStyle == Style.Flat && this.mButtonState == State.None){return;}
int alpha = (mButtonState == State.Pressed) ? 60 : 150;
Rectangle rect = new Rectangle(0, 0, this.Width, this.Height / 2);
using (GraphicsPath r = RoundRect(rect, CornerRadius, CornerRadius, 0, 0))
{
using (LinearGradientBrush lg = new LinearGradientBrush(r.GetBounds(),
Color.FromArgb(alpha, this.HighlightColor),
Color.FromArgb(alpha / 3, this.HighlightColor),
LinearGradientMode.Vertical))
{
g.FillPath(lg, r);
}
}
}
/// <summary>
/// Draws the glow for the button when the
/// mouse is inside the client area using
/// the GlowColor property.
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawGlow(Graphics g)
{
if (this.mButtonState == State.Pressed){return;}
SetClip(g);
using (GraphicsPath glow = new GraphicsPath())
{
glow.AddEllipse(-5,this.Height / 2 - 10, this.Width + 11, this.Height + 11);
using (PathGradientBrush gl = new PathGradientBrush(glow))
{
gl.CenterColor = Color.FromArgb(mGlowAlpha, this.GlowColor);
gl.SurroundColors = new Color[] {Color.FromArgb(0, this.GlowColor)};
g.FillPath(gl, glow);
}
}
g.ResetClip();
}
///// <summary>
///// Draws the text for the button.
///// </summary>
///// <param name="g">The graphics object used in the paint event.</param>
//private void DrawText(Graphics g)
//{
// StringFormat sf = StringFormatAlignment(this.TextAlign);
// Rectangle r = new Rectangle(8,8,this.Width - 17,this.Height - 17);
// g.DrawString(this.ButtonText,this.Font,new SolidBrush(this.ForeColor),r,sf);
//}
/// <summary>
/// Draws the image for the button
/// </summary>
/// <param name="g">The graphics object used in the paint event.</param>
private void DrawImage(Graphics g)
{
if (this.Image == null) {return;}
Rectangle r = new Rectangle(8,8,this.ImageSize.Width,this.ImageSize.Height);
switch (this.ImageAlign)
{
case ContentAlignment.TopCenter:
r = new Rectangle(this.Width / 2 - this.ImageSize.Width / 2,8,this.ImageSize.Width,this.ImageSize.Height);
break;
case ContentAlignment.TopRight:
r = new Rectangle(this.Width - 8 - this.ImageSize.Width,8,this.ImageSize.Width,this.ImageSize.Height);
break;
case ContentAlignment.MiddleLeft:
r = new Rectangle(8,this.Height / 2 - this.ImageSize.Height / 2,this.ImageSize.Width,this.ImageSize.Height);
break;
case ContentAlignment.MiddleCenter:
r = new Rectangle(this.Width / 2 - this.ImageSize.Width / 2,this.Height / 2 - this.ImageSize.Height / 2,this.ImageSize.Width,this.ImageSize.Height);
break;
case ContentAlignment.MiddleRight:
r = new Rectangle(this.Width - 8 - this.ImageSize.Width,this.Height / 2 - this.ImageSize.Height / 2,this.ImageSize.Width,this.ImageSize.Height);
break;
case ContentAlignment.BottomLeft:
r = new Rectangle(8,this.Height - 8 - this.ImageSize.Height,this.ImageSize.Width,this.ImageSize.Height);
break;
case ContentAlignment.BottomCenter:
r = new Rectangle(this.Width / 2 - this.ImageSize.Width / 2,this.Height - 8 - this.ImageSize.Height,this.ImageSize.Width,this.ImageSize.Height);
break;
case ContentAlignment.BottomRight:
r = new Rectangle(this.Width - 8 - this.ImageSize.Width,this.Height - 8 - this.ImageSize.Height,this.ImageSize.Width,this.ImageSize.Height);
break;
}
g.DrawImage(this.Image,r);
}
private void SetClip(Graphics g)
{
Rectangle r = this.ClientRectangle;
r.X++; r.Y++; r.Width-=3; r.Height-=3;
using (GraphicsPath rr = RoundRect(r, CornerRadius, CornerRadius, CornerRadius, CornerRadius))
{
g.SetClip(rr);
}
}
#endregion
#region - Private Subs -
private void VistaPanel_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
DrawBackground(e.Graphics);
DrawHighlight(e.Graphics);
DrawImage(e.Graphics);
//DrawText(e.Graphics);
DrawGlow(e.Graphics);
DrawOuterStroke(e.Graphics);
DrawInnerStroke(e.Graphics);
}
private void VistaPanel_Resize(object sender, EventArgs e)
{
Rectangle r = this.ClientRectangle;
r.X -= 1; r.Y -= 1;
r.Width += 2; r.Height += 2;
using (GraphicsPath rr = RoundRect(r, CornerRadius, CornerRadius, CornerRadius, CornerRadius))
{
this.Region = new Region(rr);
}
}
#region - Mouse and Keyboard Events -
//private void VistaPanel_MouseEnter(object sender, EventArgs e)
//{
// mButtonState = State.Hover;
// mFadeOut.Stop();
// mFadeIn.Start();
//}
//private void VistaPanel_MouseLeave(object sender, EventArgs e)
//{
// mButtonState = State.None;
// if (this.mButtonStyle == Style.Flat) { mGlowAlpha = 0; }
// mFadeIn.Stop();
// mFadeOut.Start();
//}
//private void VistaPanel_MouseDown(object sender, MouseEventArgs e)
//{
// if (e.Button == MouseButtons.Left)
// {
// mButtonState = State.Pressed;
// if (this.mButtonStyle != Style.Flat) { mGlowAlpha = 255; }
// mFadeIn.Stop();
// mFadeOut.Stop();
// this.Invalidate();
// }
//}
private void mFadeIn_Tick(object sender, EventArgs e)
{
if (this.ButtonStyle == Style.Flat) {mGlowAlpha = 0;}
if (mGlowAlpha + 30 >= 255)
{
mGlowAlpha = 255;
mFadeIn.Stop();
}
else
{
mGlowAlpha += 30;
}
this.Invalidate();
}
private void mFadeOut_Tick(object sender, EventArgs e)
{
if (this.ButtonStyle == Style.Flat) {mGlowAlpha = 0;}
if (mGlowAlpha - 30 <= 0)
{
mGlowAlpha = 0;
mFadeOut.Stop();
}
else
{
mGlowAlpha -= 30;
}
this.Invalidate();
}
//private void VistaPanel_KeyDown(object sender, KeyEventArgs e)
//{
// if (e.KeyCode == Keys.Space)
// {
// MouseEventArgs m = new MouseEventArgs(MouseButtons.Left,0,0,0,0);
// VistaPanel_MouseDown(sender, m);
// }
//}
//private void VistaPanel_KeyUp(object sender, KeyEventArgs e)
//{
// if (e.KeyCode == Keys.Space)
// {
// MouseEventArgs m = new MouseEventArgs(MouseButtons.Left,0,0,0,0);
// calledbykey = true;
// VistaPanel_MouseUp(sender, m);
// }
//}
//private void VistaPanel_MouseUp(object sender, MouseEventArgs e)
//{
// if (e.Button == MouseButtons.Left)
// {
// mButtonState = State.Hover;
// mFadeIn.Stop();
// mFadeOut.Stop();
// this.Invalidate();
// if (calledbykey == true) {this.OnClick(EventArgs.Empty); calledbykey = false;}
// }
//}
#endregion
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace JWPush.Server.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// FolderItemsResponse
/// </summary>
[DataContract]
public partial class FolderItemsResponse : IEquatable<FolderItemsResponse>, IValidatableObject
{
public FolderItemsResponse()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="FolderItemsResponse" /> class.
/// </summary>
/// <param name="EndPosition">The last position in the result set. .</param>
/// <param name="Envelopes">Envelopes.</param>
/// <param name="Folders">Folders.</param>
/// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param>
/// <param name="PreviousUri">The postal code for the billing address..</param>
/// <param name="ResultSetSize">The number of results returned in this response. .</param>
/// <param name="StartPosition">Starting position of the current result set..</param>
/// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param>
public FolderItemsResponse(string EndPosition = default(string), List<EnvelopeSummary> Envelopes = default(List<EnvelopeSummary>), List<Folder> Folders = default(List<Folder>), string NextUri = default(string), string PreviousUri = default(string), string ResultSetSize = default(string), string StartPosition = default(string), string TotalSetSize = default(string))
{
this.EndPosition = EndPosition;
this.Envelopes = Envelopes;
this.Folders = Folders;
this.NextUri = NextUri;
this.PreviousUri = PreviousUri;
this.ResultSetSize = ResultSetSize;
this.StartPosition = StartPosition;
this.TotalSetSize = TotalSetSize;
}
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set. </value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public string EndPosition { get; set; }
/// <summary>
/// Gets or Sets Envelopes
/// </summary>
[DataMember(Name="envelopes", EmitDefaultValue=false)]
public List<EnvelopeSummary> Envelopes { get; set; }
/// <summary>
/// Gets or Sets Folders
/// </summary>
[DataMember(Name="folders", EmitDefaultValue=false)]
public List<Folder> Folders { get; set; }
/// <summary>
/// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
/// </summary>
/// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// The postal code for the billing address.
/// </summary>
/// <value>The postal code for the billing address.</value>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response. </value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public string ResultSetSize { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public string StartPosition { get; set; }
/// <summary>
/// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.
/// </summary>
/// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value>
[DataMember(Name="totalSetSize", EmitDefaultValue=false)]
public string TotalSetSize { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class FolderItemsResponse {\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" Envelopes: ").Append(Envelopes).Append("\n");
sb.Append(" Folders: ").Append(Folders).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as FolderItemsResponse);
}
/// <summary>
/// Returns true if FolderItemsResponse instances are equal
/// </summary>
/// <param name="other">Instance of FolderItemsResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FolderItemsResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.Envelopes == other.Envelopes ||
this.Envelopes != null &&
this.Envelopes.SequenceEqual(other.Envelopes)
) &&
(
this.Folders == other.Folders ||
this.Folders != null &&
this.Folders.SequenceEqual(other.Folders)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.TotalSetSize == other.TotalSetSize ||
this.TotalSetSize != null &&
this.TotalSetSize.Equals(other.TotalSetSize)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.EndPosition != null)
hash = hash * 59 + this.EndPosition.GetHashCode();
if (this.Envelopes != null)
hash = hash * 59 + this.Envelopes.GetHashCode();
if (this.Folders != null)
hash = hash * 59 + this.Folders.GetHashCode();
if (this.NextUri != null)
hash = hash * 59 + this.NextUri.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 59 + this.PreviousUri.GetHashCode();
if (this.ResultSetSize != null)
hash = hash * 59 + this.ResultSetSize.GetHashCode();
if (this.StartPosition != null)
hash = hash * 59 + this.StartPosition.GetHashCode();
if (this.TotalSetSize != null)
hash = hash * 59 + this.TotalSetSize.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield 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.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.NetworkInformation
{
public partial class Ping
{
private const int IcmpHeaderLengthInBytes = 8;
private const int IpHeaderLengthInBytes = 20;
private async Task<PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
try
{
Task<PingReply> t = RawSocketPermissions.CanUseRawSockets(address.AddressFamily) ?
SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options) :
SendWithPingUtility(address, buffer, timeout, options);
PingReply reply = await t.ConfigureAwait(false);
if (_canceled)
{
throw new OperationCanceledException();
}
return reply;
}
finally
{
Finish();
}
}
private async Task<PingReply> SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
EndPoint endPoint = new IPEndPoint(address, 0);
bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork;
ProtocolType protocolType = isIpv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6;
// Use the current thread's ID as the identifier.
ushort identifier = (ushort)Environment.CurrentManagedThreadId;
IcmpHeader header = new IcmpHeader()
{
Type = isIpv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest,
Code = 0,
HeaderChecksum = 0,
Identifier = identifier,
SequenceNumber = 0,
};
byte[] sendBuffer = CreateSendMessageBuffer(header, buffer);
using (Socket socket = new Socket(address.AddressFamily, SocketType.Raw, protocolType))
{
socket.ReceiveTimeout = timeout;
socket.SendTimeout = timeout;
// Setting Socket.DontFragment and .Ttl is not supported on Unix, so ignore the PingOptions parameter.
int ipHeaderLength = isIpv4 ? IpHeaderLengthInBytes : 0;
await socket.SendToAsync(new ArraySegment<byte>(sendBuffer), SocketFlags.None, endPoint).ConfigureAwait(false);
byte[] receiveBuffer = new byte[ipHeaderLength + IcmpHeaderLengthInBytes + buffer.Length];
long elapsed;
Stopwatch sw = Stopwatch.StartNew();
// Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response
// to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout.
// For example, when pinging the local host, we need to filter out our own echo requests that the socket reads.
while ((elapsed = sw.ElapsedMilliseconds) < timeout)
{
Task<SocketReceiveFromResult> receiveTask = socket.ReceiveFromAsync(
new ArraySegment<byte>(receiveBuffer),
SocketFlags.None,
endPoint);
var cts = new CancellationTokenSource();
Task finished = await Task.WhenAny(receiveTask, Task.Delay(timeout - (int)elapsed, cts.Token)).ConfigureAwait(false);
cts.Cancel();
if (finished != receiveTask)
{
sw.Stop();
return CreateTimedOutPingReply();
}
SocketReceiveFromResult receiveResult = receiveTask.GetAwaiter().GetResult();
int bytesReceived = receiveResult.ReceivedBytes;
if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes)
{
continue; // Not enough bytes to reconstruct IP header + ICMP header.
}
byte type, code;
unsafe
{
fixed (byte* bytesPtr = receiveBuffer)
{
int icmpHeaderOffset = ipHeaderLength;
IcmpHeader receivedHeader = *((IcmpHeader*)(bytesPtr + icmpHeaderOffset)); // Skip IP header.
type = receivedHeader.Type;
code = receivedHeader.Code;
if (identifier != receivedHeader.Identifier
|| type == (byte)IcmpV4MessageType.EchoRequest
|| type == (byte)IcmpV6MessageType.EchoRequest) // Echo Request, ignore
{
continue;
}
}
}
sw.Stop();
long roundTripTime = sw.ElapsedMilliseconds;
int dataOffset = ipHeaderLength + IcmpHeaderLengthInBytes;
// We want to return a buffer with the actual data we sent out, not including the header data.
byte[] dataBuffer = new byte[bytesReceived - dataOffset];
Buffer.BlockCopy(receiveBuffer, dataOffset, dataBuffer, 0, dataBuffer.Length);
IPStatus status = isIpv4
? IcmpV4MessageConstants.MapV4TypeToIPStatus(type, code)
: IcmpV6MessageConstants.MapV6TypeToIPStatus(type, code);
return new PingReply(address, options, status, roundTripTime, dataBuffer);
}
// We have exceeded our timeout duration, and no reply has been received.
sw.Stop();
return CreateTimedOutPingReply();
}
}
private async Task<PingReply> SendWithPingUtility(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork;
string pingExecutable = isIpv4 ? UnixCommandLinePing.Ping4UtilityPath : UnixCommandLinePing.Ping6UtilityPath;
if (pingExecutable == null)
{
throw new PlatformNotSupportedException(SR.net_ping_utility_not_found);
}
string processArgs = UnixCommandLinePing.ConstructCommandLine(buffer.Length, address.ToString(), isIpv4);
ProcessStartInfo psi = new ProcessStartInfo(pingExecutable, processArgs);
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
Process p = new Process() { StartInfo = psi };
var processCompletion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
p.EnableRaisingEvents = true;
p.Exited += (s, e) => processCompletion.SetResult(true);
p.Start();
var cts = new CancellationTokenSource();
Task timeoutTask = Task.Delay(timeout, cts.Token);
Task finished = await Task.WhenAny(processCompletion.Task, timeoutTask).ConfigureAwait(false);
if (finished == timeoutTask && !p.HasExited)
{
// Try to kill the ping process if it didn't return. If it is already in the process of exiting, a Win32Exception will be thrown.
try
{
p.Kill();
}
catch (Win32Exception) { }
return CreateTimedOutPingReply();
}
else
{
cts.Cancel();
if (p.ExitCode != 0)
{
// This means no reply was received, although transmission may have been successful.
return CreateTimedOutPingReply();
}
try
{
string output = await p.StandardOutput.ReadToEndAsync().ConfigureAwait(false);
long rtt = UnixCommandLinePing.ParseRoundTripTime(output);
return new PingReply(
address,
null, // Ping utility cannot accommodate these, return null to indicate they were ignored.
IPStatus.Success,
rtt,
Array.Empty<byte>()); // Ping utility doesn't deliver this info.
}
catch (Exception)
{
// If the standard output cannot be successfully parsed, throw a generic PingException.
throw new PingException(SR.net_ping);
}
}
}
private PingReply CreateTimedOutPingReply()
{
// Documentation indicates that you should only pay attention to the IPStatus value when
// its value is not "Success", but the rest of these values match that of the Windows implementation.
return new PingReply(new IPAddress(0), null, IPStatus.TimedOut, 0, Array.Empty<byte>());
}
#if DEBUG
static Ping()
{
Debug.Assert(Marshal.SizeOf<IcmpHeader>() == 8, "The size of an ICMP Header must be 8 bytes.");
}
#endif
// Must be 8 bytes total.
[StructLayout(LayoutKind.Sequential)]
internal struct IcmpHeader
{
public byte Type;
public byte Code;
public ushort HeaderChecksum;
public ushort Identifier;
public ushort SequenceNumber;
}
private static unsafe byte[] CreateSendMessageBuffer(IcmpHeader header, byte[] payload)
{
int headerSize = sizeof(IcmpHeader);
byte[] result = new byte[headerSize + payload.Length];
Marshal.Copy(new IntPtr(&header), result, 0, headerSize);
payload.CopyTo(result, headerSize);
ushort checksum = ComputeBufferChecksum(result);
// Jam the checksum into the buffer.
result[2] = (byte)(checksum >> 8);
result[3] = (byte)(checksum & (0xFF));
return result;
}
private static ushort ComputeBufferChecksum(byte[] buffer)
{
// This is using the "deferred carries" approach outlined in RFC 1071.
uint sum = 0;
for (int i = 0; i < buffer.Length; i += 2)
{
// Combine each pair of bytes into a 16-bit number and add it to the sum
ushort element0 = (ushort)((buffer[i] << 8) & 0xFF00);
ushort element1 = (i + 1 < buffer.Length)
? (ushort)(buffer[i + 1] & 0x00FF)
: (ushort)0; // If there's an odd number of bytes, pad by one octet of zeros.
ushort combined = (ushort)(element0 | element1);
sum += (uint)combined;
}
// Add back the "carry bits" which have risen to the upper 16 bits of the sum.
while ((sum >> 16) != 0)
{
var partialSum = sum & 0xFFFF;
var carries = sum >> 16;
sum = partialSum + carries;
}
return (ushort)~sum;
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Diagnostics;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Architecture;
using PFRF = Autodesk.Revit.DB.ParameterFilterRuleFactory;
namespace Revit.SDK.Samples.ViewFilters.CS
{
/// <summary>
/// Sample custom immutable class used to represents Revit internal FilterRule.
/// This class and its variables will help display the contents of UI controls.
/// This class can build its data caches to Revit FilterRule object.
/// </summary>
public sealed class FilterRuleBuilder
{
#region Class Member Variables
/// <summary>
/// Parameter of filter rule
/// </summary>
public BuiltInParameter Parameter { get; private set; }
/// <summary>
/// Filter rule criteria(in String type)
/// </summary>
public String RuleCriteria { get; private set; }
/// <summary>
/// Rule values in string
/// </summary>
public String RuleValue { get; private set; }
/// <summary>
/// Parameter storage type of current FilterRule.
/// </summary>
public StorageType ParamType { get; private set; }
/// <summary>
/// Tolerance of double comparison, valid only when ParamType is double
/// </summary>
public double Epsilon { get; private set; }
/// <summary>
/// Indicates if string comparison is case sensitive, valid only when ParamType is String
/// </summary>
public bool CaseSensitive { get; private set; }
#endregion
#region Class Public Properties
/// <summary>
/// Get ElementId of current parameter
/// </summary>
public ElementId ParamId
{
get { return new ElementId(Parameter); }
}
#endregion
#region Class Public Methods
/// <summary>
/// Create FilterRuleBuilder for String FilterRule
/// </summary>
/// <param name="param">Parameter of FilterRule.</param>
/// <param name="ruleCriteria">Rule criteria.</param>
/// <param name="ruleValue">Rule value.</param>
/// <param name="caseSensitive">Indicates if rule value is case sensitive.</param>
public FilterRuleBuilder(BuiltInParameter param, String ruleCriteria, String ruleValue, bool caseSensitive)
{
InitializeMemebers();
//
// set data with specified values
ParamType = StorageType.String;
Parameter = param;
RuleCriteria = ruleCriteria;
RuleValue = ruleValue;
CaseSensitive = caseSensitive;
}
/// <summary>
/// Create FilterRuleBuilder for double FilterRule
/// </summary>
/// <param name="param">Parameter of FilterRule.</param>
/// <param name="ruleCriteria">Rule criteria.</param>
/// <param name="ruleValue">Rule value.</param>
/// <param name="tolerance">Epsilon for double values comparison.</param>
public FilterRuleBuilder(BuiltInParameter param, String ruleCriteria, double ruleValue, double tolearance)
{
InitializeMemebers();
//
// set data with specified values
ParamType = StorageType.Double;
Parameter = param;
RuleCriteria = ruleCriteria;
RuleValue = ruleValue.ToString();
Epsilon = tolearance;
}
/// <summary>
/// Create FilterRuleBuilder for int FilterRule
/// </summary>
/// <param name="param">Parameter of FilterRule.</param>
/// <param name="ruleCriteria">Rule criteria.</param>
/// <param name="ruleValue">Rule value.</param>
public FilterRuleBuilder(BuiltInParameter param, String ruleCriteria, int ruleValue)
{
InitializeMemebers();
//
// set data with specified values
ParamType = StorageType.Integer;
Parameter = param;
RuleCriteria = ruleCriteria;
RuleValue = ruleValue.ToString();
}
/// <summary>
/// Create FilterRuleBuilder for ElementId FilterRule
/// </summary>
/// <param name="param">Parameter of FilterRule.</param>
/// <param name="ruleCriteria">Rule criteria.</param>
/// <param name="ruleValue">Rule value.</param>
public FilterRuleBuilder(BuiltInParameter param, String ruleCriteria, ElementId ruleValue)
{
InitializeMemebers();
//
// set data with specified values
ParamType = StorageType.ElementId;
Parameter = param;
RuleCriteria = ruleCriteria;
RuleValue = ruleValue.ToString();
}
/// <summary>
/// Create API FilterRule according to sample's FilterRuleBuilder
/// </summary>
/// <returns>API FilterRule converted from current FilterRuleBuilder.</returns>
public FilterRule AsFilterRule()
{
ElementId paramId = new ElementId(Parameter);
if (ParamType == StorageType.String)
{
switch(RuleCriteria)
{
case RuleCriteraNames.BeginWith:
return PFRF.CreateBeginsWithRule(paramId, RuleValue, CaseSensitive);
case RuleCriteraNames.Contains:
return PFRF.CreateContainsRule(paramId, RuleValue, CaseSensitive);
case RuleCriteraNames.EndsWith:
return PFRF.CreateEndsWithRule(paramId, RuleValue, CaseSensitive);
case RuleCriteraNames.Equals_:
return PFRF.CreateEqualsRule(paramId, RuleValue, CaseSensitive);
case RuleCriteraNames.Greater:
return PFRF.CreateGreaterRule(paramId, RuleValue, CaseSensitive);
case RuleCriteraNames.GreaterOrEqual:
return PFRF.CreateGreaterOrEqualRule(paramId, RuleValue, CaseSensitive);
case RuleCriteraNames.Less:
return PFRF.CreateLessRule(paramId, RuleValue, CaseSensitive);
case RuleCriteraNames.LessOrEqual:
return PFRF.CreateLessOrEqualRule(paramId, RuleValue, CaseSensitive);
case RuleCriteraNames.NotBeginWith:
return PFRF.CreateNotBeginsWithRule(paramId, RuleValue, CaseSensitive);
case RuleCriteraNames.NotContains:
return PFRF.CreateNotContainsRule(paramId, RuleValue, CaseSensitive);
case RuleCriteraNames.NotEndsWith:
return PFRF.CreateNotEndsWithRule(paramId, RuleValue, CaseSensitive);
case RuleCriteraNames.NotEquals:
return PFRF.CreateNotEqualsRule(paramId, RuleValue, CaseSensitive);
}
}
else if (ParamType == StorageType.Double)
{
switch(RuleCriteria)
{
case RuleCriteraNames.Equals_:
return PFRF.CreateEqualsRule(paramId, double.Parse(RuleValue), Epsilon);
case RuleCriteraNames.Greater:
return PFRF.CreateGreaterRule(paramId, double.Parse(RuleValue), Epsilon);
case RuleCriteraNames.GreaterOrEqual:
return PFRF.CreateGreaterOrEqualRule(paramId, double.Parse(RuleValue), Epsilon);
case RuleCriteraNames.Less:
return PFRF.CreateLessRule(paramId, double.Parse(RuleValue), Epsilon);
case RuleCriteraNames.LessOrEqual:
return PFRF.CreateLessOrEqualRule(paramId, double.Parse(RuleValue), Epsilon);
case RuleCriteraNames.NotEquals:
return PFRF.CreateNotEqualsRule(paramId, double.Parse(RuleValue), Epsilon);
}
}
else if (ParamType == StorageType.Integer)
{
switch(RuleCriteria)
{
case RuleCriteraNames.Equals_:
return PFRF.CreateEqualsRule(paramId, int.Parse(RuleValue));
case RuleCriteraNames.Greater:
return PFRF.CreateGreaterRule(paramId, int.Parse(RuleValue));
case RuleCriteraNames.GreaterOrEqual:
return PFRF.CreateGreaterOrEqualRule(paramId, int.Parse(RuleValue));
case RuleCriteraNames.Less:
return PFRF.CreateLessRule(paramId, int.Parse(RuleValue));
case RuleCriteraNames.LessOrEqual:
return PFRF.CreateLessOrEqualRule(paramId, int.Parse(RuleValue));
case RuleCriteraNames.NotEquals:
return PFRF.CreateNotEqualsRule(paramId, int.Parse(RuleValue));
}
}
else if (ParamType == StorageType.ElementId)
{
switch(RuleCriteria)
{
case RuleCriteraNames.Equals_:
return PFRF.CreateEqualsRule(paramId, new ElementId(int.Parse(RuleValue)));
case RuleCriteraNames.Greater:
return PFRF.CreateGreaterRule(paramId, new ElementId(int.Parse(RuleValue)));
case RuleCriteraNames.GreaterOrEqual:
return PFRF.CreateGreaterOrEqualRule(paramId, new ElementId(int.Parse(RuleValue)));
case RuleCriteraNames.Less:
return PFRF.CreateLessRule(paramId, new ElementId(int.Parse(RuleValue)));
case RuleCriteraNames.LessOrEqual:
return PFRF.CreateLessOrEqualRule(paramId, new ElementId(int.Parse(RuleValue)));
case RuleCriteraNames.NotEquals:
return PFRF.CreateNotEqualsRule(paramId, new ElementId(int.Parse(RuleValue)));
}
}
//
// Throw exception for others
throw new System.NotImplementedException("This filter rule or criteria is not implemented yet.");
}
#endregion
#region Class Implementations
/// <summary>
/// Make sure all members are initialized with expected values.
/// </summary>
private void InitializeMemebers()
{
Parameter = (BuiltInParameter)(ElementId.InvalidElementId.IntegerValue);
RuleCriteria = String.Empty;
RuleValue = String.Empty;
ParamType = StorageType.None;
Epsilon = 0.0f;
CaseSensitive = false;
}
#endregion
}
/// <summary>
/// This class used to represents data for one API filter.
/// It consists of BuiltInCategory and filter rules
/// </summary>
public sealed class FilterData
{
#region Class Members
/// <summary>
/// Reserves current active document
/// </summary>
Autodesk.Revit.DB.Document m_doc;
/// <summary>
/// BuiltInCategories of filter
/// </summary>
List<BuiltInCategory> m_filterCategories;
/// <summary>
/// Filer rules of filter
/// </summary>
List<FilterRuleBuilder> m_filterRules;
#endregion
#region Public Class Methods
/// <summary>
/// Get BuiltInCategories of filter
/// </summary>
public List<BuiltInCategory> FilterCategories
{
get { return m_filterCategories; }
}
/// <summary>
/// Get BuiltInCategory Ids of filter
/// </summary>
public IList<ElementId> GetCategoryIds()
{
List<ElementId> catIds = new List<ElementId>();
foreach (BuiltInCategory cat in m_filterCategories)
catIds.Add(new ElementId(cat));
return catIds;
}
/// <summary>
/// Set new categories, this method will possibly update existing criteria
/// </summary>
/// <param name="newCatIds">New categories for current filter.</param>
/// <returns>true if categories or criteria are changed; otherwise false.</returns>
/// <remarks>
/// If someone parameter of criteria cannot be supported by new categories,
/// the old criteria will be cleaned and set to empty
/// </remarks>
public bool SetNewCategories(ICollection<ElementId> newCatIds)
{
// do nothing if new categories are equals to old categories
List<BuiltInCategory> newCats = new List<BuiltInCategory>();
foreach (ElementId catId in newCatIds)
newCats.Add((BuiltInCategory)catId.IntegerValue);
if (ListCompareUtility<BuiltInCategory>.Equals(newCats, m_filterCategories))
return false;
m_filterCategories = newCats; // update categories
//
// Check if need to update file rules:
// . if filer rule is empty, do nothing
// . if some parameters of rules cannot be supported by new categories, clean all old rules
ICollection<ElementId> supportParams =
ParameterFilterUtilities.GetFilterableParametersInCommon(m_doc, newCatIds);
foreach (FilterRuleBuilder rule in m_filterRules)
{
if (!supportParams.Contains(new ElementId(rule.Parameter)))
{
m_filterRules.Clear();
break;
}
}
return true;
}
/// <summary>
/// Get FilterRuleBuilder of API filter's rules
/// </summary>
public List<FilterRuleBuilder> RuleData
{
get { return m_filterRules; }
}
/// <summary>
/// Create sample custom FilterData with specified categories and FilterRuleBuilder
/// </summary>
/// <param name="doc">Revit active document.</param>
/// <param name="categories">BuilInCategories of filter.</param>
/// <param name="filterRules">FilterRuleBuilder set of filter.</param>
public FilterData(Autodesk.Revit.DB.Document doc,
ICollection<BuiltInCategory> categories, ICollection<FilterRuleBuilder> filterRules)
{
m_doc = doc;
m_filterCategories = new List<BuiltInCategory>();
m_filterCategories.AddRange(categories);
m_filterRules = new List<FilterRuleBuilder>();
m_filterRules.AddRange(filterRules);
}
/// <summary>
/// Create sample custom FilterData with specified category id and FilterRuleBuilder
/// </summary>
/// <param name="doc">Revit active document.</param>
/// <param name="categories">BuilInCategory ids of filter.</param>
/// <param name="filterRules">FilterRuleBuilder set of filter.</param>
public FilterData(Autodesk.Revit.DB.Document doc,
ICollection<ElementId> categories, ICollection<FilterRuleBuilder> filterRules)
{
m_doc = doc;
m_filterCategories = new List<BuiltInCategory>();
foreach (ElementId catId in categories)
m_filterCategories.Add((BuiltInCategory)catId.IntegerValue);
m_filterRules = new List<FilterRuleBuilder>();
m_filterRules.AddRange(filterRules);
}
#endregion
}
/// <summary>
/// This class define constant strings to map rule criteria
/// </summary>
public sealed class RuleCriteraNames
{
#region Public Class Members
/// <summary>
/// String represents BeginWith criteria
/// </summary>
public const String BeginWith = "begins with";
/// <summary>
/// String represents Contains criteria
/// </summary>
public const String Contains = "contains";
/// <summary>
/// String represents EndWith criteria
/// </summary>
public const String EndsWith = "ends with";
/// <summary>
/// String represents Equals criteria
/// </summary>
public const String Equals_ = "equals";
/// <summary>
/// String represents GreaterThan criteria
/// </summary>
public const String Greater = "is greater than";
/// <summary>
/// String represents GreaterOrEqual criteria
/// </summary>
public const String GreaterOrEqual = "is greater than or equal to";
/// <summary>
/// String represents LessOrEqual criteria
/// </summary>
public const String LessOrEqual = "is less than or equal to";
/// <summary>
/// String represents Less criteria
/// </summary>
public const String Less = "is less than";
/// <summary>
/// String represents NotBeginWith criteria
/// </summary>
public const String NotBeginWith = "does not begin with";
/// <summary>
/// String represents NotContains criteria
/// </summary>
public const String NotContains = "does not contain";
/// <summary>
/// String represents NotEndsWith criteria
/// </summary>
public const String NotEndsWith = "does not end with";
/// <summary>
/// String represents NotEquals criteria
/// </summary>
public const String NotEquals = "does not equal";
/// <summary>
/// Invalid criteria
/// </summary>
public const String Invalid = "n/a";
#endregion
/// <summary>
/// Hide ctor, this class defines only static members, no need to be created
/// </summary>
private RuleCriteraNames() { }
/// <summary>
/// Get all supported criteria(in string) according to StorageType of parameter
/// </summary>
/// <param name="paramType">Parameter type.</param>
/// <returns>String list of criteria supported for specified parameter type.</returns>
public static ICollection<String> Criterions(StorageType paramType)
{
ICollection<String> returns = new List<String>();
//
// all parameter supports following criteria
returns.Add(Equals_);
returns.Add(Greater);
returns.Add(GreaterOrEqual);
returns.Add(LessOrEqual);
returns.Add(Less);
returns.Add(NotEquals);
//
// Only string parameter support criteria below
if (paramType == StorageType.String)
{
returns.Add(BeginWith);
returns.Add(Contains);
returns.Add(EndsWith);
returns.Add(NotBeginWith);
returns.Add(NotContains);
returns.Add(NotEndsWith);
}
return returns;
}
}
}
| |
// 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 Xunit;
namespace System.PrivateUri.Tests
{
/// <summary>
/// Summary description for UriIsWellFormedUriStringTest
/// </summary>
public class UriIsWellFormedUriStringTest
{
[Fact]
public void UriIsWellFormed_AbsoluteWellFormed_Success()
{
Assert.True(Uri.IsWellFormedUriString("http://foo.com/bad:url", UriKind.Absolute));
}
[Fact]
public void UriIsWellFormed_RelativeWellFormed_Success()
{
Assert.True(Uri.IsWellFormedUriString("/path/file?Query", UriKind.Relative));
}
[Fact]
public void UriIsWellFormed_RelativeWithColon_Failure()
{
Assert.False(Uri.IsWellFormedUriString("http://foo", UriKind.Relative));
}
[Fact]
public void UriIsWellFormed_RelativeWithPercentAndColon_Failure()
{
Assert.False(Uri.IsWellFormedUriString("bad%20http://foo", UriKind.Relative));
}
[Fact]
public void UriIsWellFormed_NewRelativeRegisteredAbsolute_Throws()
{
Assert.ThrowsAny<FormatException>(() =>
{
Uri test = new Uri("http://foo", UriKind.Relative);
});
}
[Fact]
public void UriIsWellFormed_NewAbsoluteUnregisteredAsRelative_Throws()
{
Assert.ThrowsAny<FormatException>(() =>
{
Uri test = new Uri("any://foo", UriKind.Relative);
});
}
[Fact]
public void UriIsWellFormed_NewRelativeWithKnownSchemeAndQuery_SuccessButNotWellFormed()
{
Uri test = new Uri("http:?foo", UriKind.Relative);
Assert.False(Uri.IsWellFormedUriString(test.ToString(), UriKind.Relative), "Not well formed");
Assert.False(Uri.IsWellFormedUriString(test.ToString(), UriKind.Absolute), "Should not be well formed");
Assert.True(Uri.TryCreate(test.ToString(), UriKind.Relative, out test), "TryCreate Mismatch");
Uri result = new Uri(new Uri("http://host.com"), test);
Assert.True(Uri.IsWellFormedUriString(result.ToString(), UriKind.Absolute), "Not well formed");
}
[Fact]
public void UriIsWellFormed_NewRelativeWithUnknownSchemeAndQuery_Throws()
{
Assert.ThrowsAny<FormatException>(() =>
{
// The generic parser allows this kind of absolute Uri, where the http parser does not
Uri test;
Assert.False(Uri.TryCreate("any:?foo", UriKind.Relative, out test), "TryCreate should have Failed");
test = new Uri("any:?foo", UriKind.Relative);
});
}
[Fact]
public void UriIsWellFormed_TryCreateNewRelativeWithColon_Failure()
{
Uri test;
Assert.False(Uri.TryCreate("http://foo", UriKind.Relative, out test));
}
// App-compat - A colon in the first segment of a relative Uri is invalid, but we cannot reject it.
[Fact]
public void UriIsWellFormed_TryCreateNewRelativeWithPercentAndColon_Success()
{
string input = "bad%20http://foo";
Uri test;
Assert.True(Uri.TryCreate(input, UriKind.Relative, out test));
Assert.False(test.IsWellFormedOriginalString());
Assert.False(Uri.IsWellFormedUriString(input, UriKind.Relative));
Assert.False(Uri.IsWellFormedUriString(input, UriKind.RelativeOrAbsolute));
Assert.False(Uri.IsWellFormedUriString(input, UriKind.Absolute));
}
[Fact]
public void UriIsWellFormed_AbsoluteWithColonToRelative_AppendsDotSlash()
{
Uri baseUri = new Uri("https://base.com/path/stuff");
Uri test = new Uri("https://base.com/path/hi:there/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Assert.True(Uri.IsWellFormedUriString(rel.ToString(), UriKind.Relative), "Not well formed: " + rel);
Uri result = new Uri(baseUri, rel);
Assert.Equal<Uri>(test, result); //"Transitivity failure"
Assert.True(string.CompareOrdinal(rel.ToString(), 0, "./", 0, 2) == 0, "Cannot have colon in first segment, must append ./");
}
[Fact]
public void UriIsWellFormed_AbsoluteWithPercentAndColonToRelative_AppendsDotSlash()
{
Uri baseUri = new Uri("https://base.com/path/stuff");
Uri test = new Uri("https://base.com/path/h%20i:there/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Assert.True(Uri.IsWellFormedUriString(rel.ToString(), UriKind.Relative), "Not well formed: " + rel);
Uri result = new Uri(baseUri, rel);
Assert.Equal<Uri>(test, result); //"Transitivity failure"
Assert.True(string.CompareOrdinal(rel.ToString(), 0, "./", 0, 2) == 0, "Cannot have colon in first segment, must append ./");
}
[Fact]
public void UriMakeRelative_ImplicitFileCommonBaseWithColon_AppendsDotSlash()
{
Uri baseUri = new Uri(@"c:/base/path/stuff");
Uri test = new Uri(@"c:/base/path/hi:there/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Assert.True(Uri.IsWellFormedUriString(rel.ToString(), UriKind.Relative), "Not well formed: " + rel);
Uri result = new Uri(baseUri, rel);
Assert.Equal<String>(test.LocalPath, result.LocalPath); // "Transitivity failure"
Assert.True(string.CompareOrdinal(rel.ToString(), 0, "./", 0, 2) == 0, "Cannot have colon in first segment, must append ./");
}
[Fact]
public void UriMakeRelative_ImplicitFileDifferentBaseWithColon_ReturnsSecondUri()
{
Uri baseUri = new Uri(@"c:/base/path/stuff");
Uri test = new Uri(@"d:/base/path/hi:there/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Uri result = new Uri(baseUri, rel);
Assert.Equal<String>(test.LocalPath, result.LocalPath); //"Transitivity failure"
}
[Fact]
public void UriMakeRelative_ExplicitFileDifferentBaseWithColon_ReturnsSecondUri()
{
Uri baseUri = new Uri(@"file://c:/stuff");
Uri test = new Uri(@"file://d:/hi:there/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Assert.False(rel.IsAbsoluteUri, "Result should be relative");
Assert.Equal<String>("d:/hi:there/", rel.ToString());
Uri result = new Uri(baseUri, rel);
Assert.Equal<String>(test.LocalPath, result.LocalPath); // "Transitivity failure"
Assert.Equal<String>(test.ToString(), result.ToString()); // "Transitivity failure"
}
[Fact]
public void UriMakeRelative_ExplicitUncFileVsDosFile_ReturnsSecondPath()
{
Uri baseUri = new Uri(@"file:///u:/stuff");
Uri test = new Uri(@"file:///unc/hi:there/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Uri result = new Uri(baseUri, rel);
// This is a known oddity when mix and matching Unc & dos paths in this order.
// The other way works as expected.
Assert.Equal<string>("file:///u:/unc/hi:there/", result.ToString());
}
[Fact]
public void UriMakeRelative_ExplicitDosFileWithHost_ReturnsSecondPath()
{
Uri baseUri = new Uri(@"file://host/u:/stuff");
Uri test = new Uri(@"file://host/unc/hi:there/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Uri result = new Uri(baseUri, rel);
Assert.Equal<String>(test.LocalPath, result.LocalPath); // "Transitivity failure"
}
[Fact]
public void UriMakeRelative_ExplicitDosFileSecondWithHost_ReturnsSecondPath()
{
Uri baseUri = new Uri(@"file://host/unc/stuff");
Uri test = new Uri(@"file://host/u:/hi:there/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Uri result = new Uri(baseUri, rel);
Assert.Equal<String>(test.LocalPath, result.LocalPath); //"Transitivity failure"
}
[Fact]
public void UriMakeRelative_ExplicitDosFileVsUncFile_ReturnsSecondUri()
{
Uri baseUri = new Uri(@"file:///unc/stuff");
Uri test = new Uri(@"file:///u:/hi:there/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Uri result = new Uri(baseUri, rel);
Assert.Equal<String>(test.LocalPath, result.LocalPath); //"Transitivity failure"
}
[Fact]
public void UriMakeRelative_ExplicitDosFileContainingImplicitDosPath_AddsDotSlash()
{
Uri baseUri = new Uri(@"file:///u:/stuff/file");
Uri test = new Uri(@"file:///u:/stuff/h:there/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Uri result = new Uri(baseUri, rel);
Assert.Equal<String>(test.LocalPath, result.LocalPath); //"Transitivity failure"
}
[Fact]
public void UriMakeRelative_DifferentSchemes_ReturnsSecondUri()
{
Uri baseUri = new Uri(@"http://base/path/stuff");
Uri test = new Uri(@"https://base/path/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Assert.Equal<Uri>(test, rel);
Assert.True(Uri.IsWellFormedUriString(rel.ToString(), UriKind.Absolute), "Not well formed: " + rel);
Uri result = new Uri(baseUri, rel);
Assert.Equal<Uri>(result, test);
}
[Fact]
public void UriMakeRelative_DifferentHost_ReturnsSecondUri()
{
Uri baseUri = new Uri(@"http://host1/path/stuff");
Uri test = new Uri(@"http://host2/path/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Assert.Equal<Uri>(test, rel);
Assert.True(Uri.IsWellFormedUriString(rel.ToString(), UriKind.Absolute), "Not well formed: " + rel);
Uri result = new Uri(baseUri, rel);
Assert.Equal<Uri>(result, test);
}
[Fact]
public void UriMakeRelative_DifferentPort_ReturnsSecondUri()
{
Uri baseUri = new Uri(@"http://host:1/path/stuff");
Uri test = new Uri(@"http://host:2/path/", UriKind.Absolute);
Uri rel = baseUri.MakeRelativeUri(test);
Assert.Equal<Uri>(test, rel);
Assert.True(Uri.IsWellFormedUriString(rel.ToString(), UriKind.Absolute), "Not well formed: " + rel);
Uri result = new Uri(baseUri, rel);
Assert.Equal<Uri>(result, test);
}
[Fact]
public void UriIsWellFormed_IPv6HostIriOn_True()
{
Assert.True(Uri.IsWellFormedUriString("http://[::1]/", UriKind.Absolute));
}
public static IEnumerable<object[]> TestIsWellFormedUriStringData =>
new List<object[]>
{
// Test ImplicitFile/UNC
new object[] { "c:\\directory\filename", false },
new object[] { "file://c:/directory/filename", false },
new object[] { "\\\\?\\UNC\\Server01\\user\\docs\\Letter.txt", false },
// Test Host
new object[] { "http://www.contoso.com", true },
new object[] { "http://\u00E4.contos.com", true },
new object[] { "http://www.contos\u00E4.com", true },
new object[] { "http://www.contoso.com ", true },
new object[] { "http://\u00E4.contos.com ", true },
new object[] { "http:// www.contoso.com", false },
new object[] { "http:// \u00E4.contos.com", false },
new object[] { "http:// www.contos\u00E4.com", false },
new object[] { "http://www.contos o.com", false },
new object[] { "http://www.contos \u00E4.com", false },
// Test Path
new object[] { "http://www.contoso.com/path???/file name", false },
new object[] { "http://www.contoso.com/\u00E4???/file name", false },
new object[] { "http:\\host/path/file", false },
new object[] { "http://www.contoso.com/a/sek http://test.com", false },
new object[] { "http://www.contoso.com/\u00E4/sek http://test.com", false },
new object[] { "http://www.contoso.com/ seka http://test.com", false },
new object[] { "http://www.contoso.com/ sek\u00E4 http://test.com", false },
new object[] { "http://www.contoso.com/ a sek http://test.com", false },
new object[] { "http://www.contoso.com/ \u00E4 sek http://test.com", false },
new object[] { "http://www.contoso.com/ \u00E4/", false },
new object[] { "http://www.contoso.com/ path/", false },
new object[] { "http://www.contoso.com/path", true },
new object[] { "http://www.contoso.com/\u00E4/", true },
new object[] { "http://www.contoso.com/path/#", true },
new object[] { "http://www.contoso.com/\u00E4/#", true },
new object[] { "http://www.contoso.com/path/# ", true },
new object[] { "http://www.contoso.com/\u00E4/# ", true },
new object[] { "http://www.contoso.com/path/ # ", false },
new object[] { "http://www.contoso.com/\u00E4/ # ", false },
new object[] { "http://www.contoso.com/path/ #", false },
new object[] { "http://www.contoso.com/\u00E4/ #", false },
new object[] { "http://www.contoso.com/path ", true },
new object[] { "http://www.contoso.com/\u00E4/ ", true },
new object[] { "http://www.contoso.com/path/\u00E4/path /", false },
new object[] { "http://www.contoso.com/path/\u00E4/path / ", false },
new object[] { "http://www.contoso.com/path/\u00E4/path/", true },
new object[] { "http://www.contoso.com/path/\u00E4 /path/", false },
new object[] { "http://www.contoso.com/path/\u00E4 /path/ ", false },
new object[] { "http://www.contoso.com/path/\u00E4/path/ \u00E4/", false },
// Test Query
new object[] { "http://www.contoso.com/path?name", true },
new object[] { "http://www.contoso.com/path?\u00E4", true },
new object[] { "http://www.contoso.com/path?name ", true },
new object[] { "http://www.contoso.com/path?\u00E4 ", true },
new object[] { "http://www.contoso.com/path ?name ", false },
new object[] { "http://www.contoso.com/path ?\u00E4 ", false },
new object[] { "http://www.contoso.com/path?par=val?", true },
new object[] { "http://www.contoso.com/path?\u00E4=\u00E4?", true },
new object[] { "http://www.contoso.com/path? name ", false },
new object[] { "http://www.contoso.com/path? \u00E4 ", false },
new object[] { "http://www.contoso.com/path?p=", true },
new object[] { "http://www.contoso.com/path?\u00E4=", true },
new object[] { "http://www.contoso.com/path?p= ", true },
new object[] { "http://www.contoso.com/path?\u00E4= ", true },
new object[] { "http://www.contoso.com/path?p= val", false },
new object[] { "http://www.contoso.com/path?\u00E4= \u00E4", false },
new object[] { "http://www.contoso.com/path?par=value& par=value", false },
new object[] { "http://www.contoso.com/path?\u00E4=\u00E4& \u00E4=\u00E4", false },
// Test Fragment
new object[] { "http://www.contoso.com/path?name#", true },
new object[] { "http://www.contoso.com/path?\u00E4#", true },
new object[] { "http://www.contoso.com/path?name# ", true },
new object[] { "http://www.contoso.com/path?\u00E4# ", true },
new object[] { "http://www.contoso.com/path?name#a", true },
new object[] { "http://www.contoso.com/path?\u00E4#\u00E4", true },
new object[] { "http://www.contoso.com/path?name#a ", true },
new object[] { "http://www.contoso.com/path?\u00E4#\u00E4 ", true },
new object[] { "http://www.contoso.com/path?name# a", false },
new object[] { "http://www.contoso.com/path?\u00E4# \u00E4", false },
// Test Path+Query
new object[] { "http://www.contoso.com/path? a ", false },
new object[] { "http://www.contoso.com/\u00E4? \u00E4 ", false },
new object[] { "http://www.contoso.com/a?val", true },
new object[] { "http://www.contoso.com/\u00E4?\u00E4", true },
new object[] { "http://www.contoso.com/path /path?par=val", false },
new object[] { "http://www.contoso.com/\u00E4 /\u00E4?\u00E4=\u00E4", false },
// Test Path+Query+Fragment
new object[] { "http://www.contoso.com/path?a#a", true },
new object[] { "http://www.contoso.com/\u00E4?\u00E4#\u00E4", true },
new object[] { "http://www.contoso.com/path?par=val#a ", true },
new object[] { "http://www.contoso.com/\u00E4?\u00E4=\u00E4#\u00E4 ", true },
new object[] { "http://www.contoso.com/path?val#", true },
new object[] { "http://www.contoso.com/\u00E4?\u00E4#", true },
new object[] { "http://www.contoso.com/path?val#?val", true },
new object[] { "http://www.contoso.com/\u00E4?\u00E4#?\u00E4", true },
new object[] { "http://www.contoso.com/path?val #", false },
new object[] { "http://www.contoso.com/\u00E4?\u00E4 #", false },
new object[] { "http://www.contoso.com/path?val# val", false },
new object[] { "http://www.contoso.com/\u00E4?\u00E4# \u00E4", false },
new object[] { "http://www.contoso.com/path?val# val ", false },
new object[] { "http://www.contoso.com/\u00E4?\u00E4# \u00E4 ", false },
new object[] { "http://www.contoso.com/path?val#val ", true },
new object[] { "http://www.contoso.com/\u00E4?\u00E4#\u00E4 ", true },
new object[] { "http://www.contoso.com/ path?a#a", false },
new object[] { "http://www.contoso.com/ \u00E4?\u00E4#\u00E4", false },
new object[] { "http://www.contoso.com/ path?a #a", false },
new object[] { "http://www.contoso.com/ \u00E4?\u00E4 #\u00E4", false },
new object[] { "http://www.contoso.com/ path?a #a ", false },
new object[] { "http://www.contoso.com/ \u00E4?\u00E4 #\u00E4 ", false },
new object[] { "http://www.contoso.com/path?a# a ", false },
new object[] { "http://www.contoso.com/path?\u00E4# \u00E4 ", false },
new object[] { "http://www.contoso.com/path?a#a?a", true },
new object[] { "http://www.contoso.com/\u00E4?\u00E4#u00E4?\u00E4", true },
// Sample in "private unsafe Check CheckCanonical(char* str, ref ushort idx, ushort end, char delim)" code comments
new object[] { "http://www.contoso.com/\u00E4/ path2/ param=val", false },
new object[] { "http://www.contoso.com/\u00E4? param=val", false },
new object[] { "http://www.contoso.com/\u00E4?param=val# fragment", false },
};
[Theory]
[MemberData(nameof(TestIsWellFormedUriStringData))]
public static void TestIsWellFormedUriString(string uriString, bool expected)
{
Assert.Equal(expected, Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute));
}
public static IEnumerable<object[]> UriIsWellFormedUnwiseStringData =>
new List<object[]>
{
// escaped
new object[] { "https://www.contoso.com/?a=%7B%7C%7D&b=%E2%80%99", true },
new object[] { "https://www.contoso.com/?a=%7B%7C%7D%E2%80%99", true },
// unescaped
new object[] { "https://www.contoso.com/?a=}", false },
new object[] { "https://www.contoso.com/?a=|", false },
new object[] { "https://www.contoso.com/?a={", false },
// not query
new object[] { "https://www.%7Bcontoso.com/", false },
new object[] { "http%7Bs://www.contoso.com/", false },
new object[] { "https://www.contoso.com%7B/", false },
new object[] { "htt%7Cps://www.contoso.com/", false },
new object[] { "https://www.con%7Ctoso.com/", false },
new object[] { "https://www.contoso.com%7C/", false },
new object[] { "htt%7Dps://www.contoso.com/", false },
new object[] { "https://www.con%7Dtoso.com/", false },
new object[] { "https://www.contoso.com%7D/", false },
new object[] { "htt{ps://www.contoso.com/", false },
new object[] { "https://www.con{toso.com/", false },
new object[] { "https://www.contoso.com{/", false },
new object[] { "htt|ps://www.contoso.com/", false },
new object[] { "https://www.con|toso.com/", false },
new object[] { "https://www.contoso.com|/", false },
new object[] { "htt}ps://www.contoso.com/", false },
new object[] { "https://www.con}toso.com/", false },
new object[] { "https://www.contoso.com}/", false },
};
[Theory]
[MemberData(nameof(UriIsWellFormedUnwiseStringData))]
public void UriIsWellFormed_AbsoluteUnicodeWithUnwise_Success(string uriString, bool expected)
{
Assert.Equal(expected, Uri.IsWellFormedUriString(uriString, UriKind.Absolute));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using UnityEngine;
namespace UniRx
{
public static partial class Scheduler
{
static IScheduler mainThread;
/// <summary>
/// Unity native MainThread Queue Scheduler. Run on mainthread and delayed on coroutine update loop, elapsed time is calculated based on Time.time.
/// </summary>
public static IScheduler MainThread
{
get
{
return mainThread ?? (mainThread = new MainThreadScheduler());
}
}
static IScheduler mainThreadIgnoreTimeScale;
/// <summary>
/// Another MainThread scheduler, delay elapsed time is calculated based on Time.realtimeSinceStartup.
/// </summary>
public static IScheduler MainThreadIgnoreTimeScale
{
get
{
return mainThreadIgnoreTimeScale ?? (mainThreadIgnoreTimeScale = new IgnoreTimeScaleMainThreadScheduler());
}
}
class MainThreadScheduler : IScheduler
{
public MainThreadScheduler()
{
MainThreadDispatcher.Initialize();
}
// delay action is run in StartCoroutine
// Okay to action run synchronous and guaranteed run on MainThread
IEnumerator DelayAction(TimeSpan dueTime, Action action, ICancelable cancellation)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying)
{
var startTime = DateTimeOffset.UtcNow;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
var elapsed = DateTimeOffset.UtcNow - startTime;
if (elapsed >= dueTime)
{
MainThreadDispatcher.UnsafeSend(action);
break;
}
};
yield break;
}
#endif
if (dueTime == TimeSpan.Zero)
{
yield return null; // not immediately, run next frame
MainThreadDispatcher.UnsafeSend(action);
}
else if (dueTime.TotalMilliseconds % 1000 == 0)
{
yield return new WaitForSeconds((float)dueTime.TotalSeconds);
MainThreadDispatcher.UnsafeSend(action);
}
else
{
var startTime = Time.time;
var dt = (float)dueTime.TotalSeconds;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
var elapsed = Time.time - startTime;
if (elapsed >= dt)
{
MainThreadDispatcher.UnsafeSend(action);
break;
}
}
}
}
public DateTimeOffset Now
{
get { return Scheduler.Now; }
}
public IDisposable Schedule(Action action)
{
var d = new BooleanDisposable();
MainThreadDispatcher.Post(() =>
{
if (!d.IsDisposed)
{
action();
}
});
return d;
}
public IDisposable Schedule(DateTimeOffset dueTime, Action action)
{
return Schedule(dueTime - Now, action);
}
public IDisposable Schedule(TimeSpan dueTime, Action action)
{
var d = new BooleanDisposable();
var time = Normalize(dueTime);
MainThreadDispatcher.SendStartCoroutine(DelayAction(time, () =>
{
if (!d.IsDisposed)
{
action();
}
}, d));
return d;
}
}
class IgnoreTimeScaleMainThreadScheduler : IScheduler
{
public IgnoreTimeScaleMainThreadScheduler()
{
MainThreadDispatcher.Initialize();
}
IEnumerator DelayAction(TimeSpan dueTime, Action action, ICancelable cancellation)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying)
{
var startTime = DateTimeOffset.UtcNow;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
var elapsed = DateTimeOffset.UtcNow - startTime;
if (elapsed >= dueTime)
{
MainThreadDispatcher.UnsafeSend(action);
break;
}
};
yield break;
}
#endif
if (dueTime == TimeSpan.Zero)
{
yield return null;
MainThreadDispatcher.UnsafeSend(action);
}
else
{
var startTime = Time.realtimeSinceStartup; // this is difference
var dt = (float)dueTime.TotalSeconds;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
var elapsed = Time.realtimeSinceStartup - startTime;
if (elapsed >= dt)
{
MainThreadDispatcher.UnsafeSend(action);
break;
}
}
}
}
public DateTimeOffset Now
{
get { return Scheduler.Now; }
}
public IDisposable Schedule(Action action)
{
var d = new BooleanDisposable();
MainThreadDispatcher.Post(() =>
{
if (!d.IsDisposed)
{
action();
}
});
return d;
}
public IDisposable Schedule(DateTimeOffset dueTime, Action action)
{
return Schedule(dueTime - Now, action);
}
public IDisposable Schedule(TimeSpan dueTime, Action action)
{
var d = new BooleanDisposable();
var time = Normalize(dueTime);
MainThreadDispatcher.SendStartCoroutine(DelayAction(time, () =>
{
if (!d.IsDisposed)
{
action();
}
}, d));
return d;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.ComponentModel.EventBasedAsync.Tests
{
public class AsyncOperationTests
{
private const int SpinTimeoutSeconds = 30;
[Fact]
public static void Noop()
{
// Test that a simple AsyncOperation can be dispatched and completed via AsyncOperationManager
Task.Run(() =>
{
var operation = new TestAsyncOperation(op => { });
operation.Wait();
Assert.True(operation.Completed);
Assert.False(operation.Cancelled);
Assert.Null(operation.Exception);
}).GetAwaiter().GetResult();
}
[Fact]
public static void ThrowAfterAsyncComplete()
{
Task.Run(() =>
{
var operation = new TestAsyncOperation(op => { });
operation.Wait();
SendOrPostCallback noopCallback = state => { };
Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.Post(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.PostOperationCompleted(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.OperationCompleted());
}).GetAwaiter().GetResult();
}
[Fact]
public static void ThrowAfterSynchronousComplete()
{
Task.Run(() =>
{
var operation = AsyncOperationManager.CreateOperation(null);
operation.OperationCompleted();
SendOrPostCallback noopCallback = state => { };
Assert.Throws<InvalidOperationException>(() => operation.Post(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.PostOperationCompleted(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.OperationCompleted());
}).GetAwaiter().GetResult();
}
[Fact]
public static void Cancel()
{
// Test that cancellation gets passed all the way through PostOperationCompleted(callback, AsyncCompletedEventArgs)
Task.Run(() =>
{
var cancelEvent = new ManualResetEventSlim();
var operation = new TestAsyncOperation(op =>
{
Assert.True(cancelEvent.Wait(TimeSpan.FromSeconds(SpinTimeoutSeconds)));
}, cancelEvent: cancelEvent);
operation.Cancel();
operation.Wait();
Assert.True(operation.Completed);
Assert.True(operation.Cancelled);
Assert.Null(operation.Exception);
}).GetAwaiter().GetResult();
}
[Fact]
public static void Throw()
{
// Test that exceptions get passed all the way through PostOperationCompleted(callback, AsyncCompletedEventArgs)
Task.Run(() =>
{
var operation = new TestAsyncOperation(op =>
{
throw new TestException("Test throw");
});
Assert.Throws<TestException>(() => operation.Wait());
}).GetAwaiter().GetResult();
}
[Fact]
public static void PostNullDelegate()
{
// the xUnit SynchronizationContext - AysncTestSyncContext interferes with the current SynchronizationContext
// used by AsyncOperation when there is exception thrown -> the SC.OperationCompleted() is not called.
// use new SC here to avoid this issue
var orignal = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null);
// Pass a non-null state just to emphasize we're only testing passing a null delegate
var state = new object();
var operation = AsyncOperationManager.CreateOperation(state);
Assert.Throws<ArgumentNullException>("d", () => operation.Post(null, state));
Assert.Throws<ArgumentNullException>("d", () => operation.PostOperationCompleted(null, state));
}
finally
{
SynchronizationContext.SetSynchronizationContext(orignal);
}
}
// A simple wrapper for AsyncOperation which executes the specified delegate and a completion handler asynchronously.
public class TestAsyncOperation
{
private readonly object _operationId;
private readonly Action<TestAsyncOperation> _executeDelegate;
private readonly ManualResetEventSlim _cancelEvent;
private readonly ManualResetEventSlim _completeEvent;
public AsyncOperation AsyncOperation { get; private set; }
public bool Completed { get { return _completeEvent.IsSet; } }
public bool Cancelled { get { return _cancelEvent.IsSet; } }
public Exception Exception { get; private set; }
public TestAsyncOperation(Action<TestAsyncOperation> executeDelegate, ManualResetEventSlim cancelEvent = null)
{
// Create an async operation passing an object as the state so we can
// verify that state is passed properly.
_operationId = new object();
AsyncOperation = AsyncOperationManager.CreateOperation(_operationId);
Assert.Same(_operationId, AsyncOperation.UserSuppliedState);
Assert.Same(AsyncOperationManager.SynchronizationContext, AsyncOperation.SynchronizationContext);
_completeEvent = new ManualResetEventSlim(false);
_cancelEvent = cancelEvent ?? new ManualResetEventSlim(false);
// Post work to the wrapped synchronization context
_executeDelegate = executeDelegate;
AsyncOperation.Post((SendOrPostCallback)ExecuteWorker, _operationId);
}
public void Wait()
{
Assert.True(_completeEvent.Wait(TimeSpan.FromSeconds(SpinTimeoutSeconds)));
if (Exception != null)
{
throw Exception;
}
}
public void Cancel()
{
CompleteOperationAsync(cancelled: true);
}
private void ExecuteWorker(object operationId)
{
Assert.Same(_operationId, operationId);
Exception exception = null;
try
{
_executeDelegate(this);
}
catch (Exception e)
{
exception = e;
}
finally
{
CompleteOperationAsync(exception: exception);
}
}
private void CompleteOperationAsync(Exception exception = null, bool cancelled = false)
{
if (!(Completed || Cancelled))
{
AsyncOperation.PostOperationCompleted(
(SendOrPostCallback)OnOperationCompleted,
new AsyncCompletedEventArgs(
exception,
cancelled,
_operationId));
}
}
private void OnOperationCompleted(object state)
{
AsyncCompletedEventArgs e = Assert.IsType<AsyncCompletedEventArgs>(state);
Assert.Equal(_operationId, e.UserState);
Exception = e.Error;
// Make sure to set _cancelEvent before _completeEvent so that anyone waiting on
// _completeEvent will not be at risk of reading Cancelled before it is set.
if (e.Cancelled)
_cancelEvent.Set();
_completeEvent.Set();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
namespace ClosedXML.Excel
{
internal class XLColumn : XLRangeBase, IXLColumn
{
#region Private fields
private bool _collapsed;
private bool _isHidden;
private int _outlineLevel;
private Double _width;
#endregion
#region Constructor
public XLColumn(Int32 column, XLColumnParameters xlColumnParameters)
: base(
new XLRangeAddress(new XLAddress(xlColumnParameters.Worksheet, 1, column, false, false),
new XLAddress(xlColumnParameters.Worksheet, XLHelper.MaxRowNumber, column, false,
false)))
{
SetColumnNumber(column);
IsReference = xlColumnParameters.IsReference;
if (IsReference)
SubscribeToShiftedColumns((range, columnsShifted) => this.WorksheetRangeShiftedColumns(range, columnsShifted));
else
{
SetStyle(xlColumnParameters.DefaultStyleId);
_width = xlColumnParameters.Worksheet.ColumnWidth;
}
}
public XLColumn(XLColumn column)
: base(
new XLRangeAddress(new XLAddress(column.Worksheet, 1, column.ColumnNumber(), false, false),
new XLAddress(column.Worksheet, XLHelper.MaxRowNumber, column.ColumnNumber(),
false, false)))
{
_width = column._width;
IsReference = column.IsReference;
if (IsReference)
SubscribeToShiftedColumns((range, columnsShifted) => this.WorksheetRangeShiftedColumns(range, columnsShifted));
_collapsed = column._collapsed;
_isHidden = column._isHidden;
_outlineLevel = column._outlineLevel;
SetStyle(column.GetStyleId());
}
#endregion
public Boolean IsReference { get; private set; }
public override IEnumerable<IXLStyle> Styles
{
get
{
UpdatingStyle = true;
yield return Style;
int column = ColumnNumber();
foreach (XLCell cell in Worksheet.Internals.CellsCollection.GetCellsInColumn(column))
yield return cell.Style;
UpdatingStyle = false;
}
}
public override Boolean UpdatingStyle { get; set; }
public override IXLStyle InnerStyle
{
get
{
return IsReference
? Worksheet.Internals.ColumnsCollection[ColumnNumber()].InnerStyle
: GetStyle();
}
set
{
if (IsReference)
Worksheet.Internals.ColumnsCollection[ColumnNumber()].InnerStyle = value;
else
SetStyle(value);
}
}
public Boolean Collapsed
{
get { return IsReference ? Worksheet.Internals.ColumnsCollection[ColumnNumber()].Collapsed : _collapsed; }
set
{
if (IsReference)
Worksheet.Internals.ColumnsCollection[ColumnNumber()].Collapsed = value;
else
_collapsed = value;
}
}
#region IXLColumn Members
public Double Width
{
get { return IsReference ? Worksheet.Internals.ColumnsCollection[ColumnNumber()].Width : _width; }
set
{
if (IsReference)
Worksheet.Internals.ColumnsCollection[ColumnNumber()].Width = value;
else
_width = value;
}
}
public void Delete()
{
int columnNumber = ColumnNumber();
using (var asRange = AsRange())
{
asRange.Delete(XLShiftDeletedCells.ShiftCellsLeft);
}
Worksheet.Internals.ColumnsCollection.Remove(columnNumber);
var columnsToMove = new List<Int32>();
columnsToMove.AddRange(
Worksheet.Internals.ColumnsCollection.Where(c => c.Key > columnNumber).Select(c => c.Key));
foreach (int column in columnsToMove.OrderBy(c => c))
{
Worksheet.Internals.ColumnsCollection.Add(column - 1, Worksheet.Internals.ColumnsCollection[column]);
Worksheet.Internals.ColumnsCollection.Remove(column);
}
}
public new IXLColumn Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats)
{
base.Clear(clearOptions);
return this;
}
public IXLCell Cell(Int32 rowNumber)
{
return Cell(rowNumber, 1);
}
public new IXLCells Cells(String cellsInColumn)
{
var retVal = new XLCells(false, false);
var rangePairs = cellsInColumn.Split(',');
foreach (string pair in rangePairs)
retVal.Add(Range(pair.Trim()).RangeAddress);
return retVal;
}
public new IXLCells Cells()
{
return Cells(true, true);
}
public new IXLCells Cells(Boolean usedCellsOnly)
{
if (usedCellsOnly)
return Cells(true, true);
else
return Cells(FirstCellUsed().Address.RowNumber, LastCellUsed().Address.RowNumber);
}
public IXLCells Cells(Int32 firstRow, Int32 lastRow)
{
return Cells(firstRow + ":" + lastRow);
}
public override IXLStyle Style
{
get { return IsReference ? Worksheet.Internals.ColumnsCollection[ColumnNumber()].Style : GetStyle(); }
set
{
if (IsReference)
Worksheet.Internals.ColumnsCollection[ColumnNumber()].Style = value;
else
{
SetStyle(value);
Int32 minRow = 1;
Int32 maxRow = 0;
int column = ColumnNumber();
if (Worksheet.Internals.CellsCollection.ColumnsUsed.ContainsKey(column))
{
minRow = Worksheet.Internals.CellsCollection.MinRowInColumn(column);
maxRow = Worksheet.Internals.CellsCollection.MaxRowInColumn(column);
}
if (Worksheet.Internals.RowsCollection.Count > 0)
{
Int32 minInCollection = Worksheet.Internals.RowsCollection.Keys.Min();
Int32 maxInCollection = Worksheet.Internals.RowsCollection.Keys.Max();
if (minInCollection < minRow)
minRow = minInCollection;
if (maxInCollection > maxRow)
maxRow = maxInCollection;
}
if (minRow > 0 && maxRow > 0)
{
for (Int32 ro = minRow; ro <= maxRow; ro++)
Worksheet.Cell(ro, column).Style = value;
}
}
}
}
public new IXLColumns InsertColumnsAfter(Int32 numberOfColumns)
{
int columnNum = ColumnNumber();
Worksheet.Internals.ColumnsCollection.ShiftColumnsRight(columnNum + 1, numberOfColumns);
using (var column = Worksheet.Column(columnNum))
{
using (var asRange = column.AsRange())
{
asRange.InsertColumnsAfterVoid(true, numberOfColumns);
}
}
var newColumns = Worksheet.Columns(columnNum + 1, columnNum + numberOfColumns);
CopyColumns(newColumns);
return newColumns;
}
public new IXLColumns InsertColumnsBefore(Int32 numberOfColumns)
{
int columnNum = ColumnNumber();
if (columnNum > 1)
{
using (var column = Worksheet.Column(columnNum - 1))
{
return column.InsertColumnsAfter(numberOfColumns);
}
}
Worksheet.Internals.ColumnsCollection.ShiftColumnsRight(columnNum, numberOfColumns);
using (var column = Worksheet.Column(columnNum))
{
using (var asRange = column.AsRange())
{
asRange.InsertColumnsBeforeVoid(true, numberOfColumns);
}
}
return Worksheet.Columns(columnNum, columnNum + numberOfColumns - 1);
}
private void CopyColumns(IXLColumns newColumns)
{
foreach (var newColumn in newColumns)
{
var internalColumn = Worksheet.Internals.ColumnsCollection[newColumn.ColumnNumber()];
internalColumn._width = Width;
internalColumn.SetStyle(Style);
internalColumn._collapsed = Collapsed;
internalColumn._isHidden = IsHidden;
internalColumn._outlineLevel = OutlineLevel;
}
}
public IXLColumn AdjustToContents()
{
return AdjustToContents(1);
}
public IXLColumn AdjustToContents(Int32 startRow)
{
return AdjustToContents(startRow, XLHelper.MaxRowNumber);
}
public IXLColumn AdjustToContents(Int32 startRow, Int32 endRow)
{
return AdjustToContents(startRow, endRow, 0, Double.MaxValue);
}
public IXLColumn AdjustToContents(Double minWidth, Double maxWidth)
{
return AdjustToContents(1, XLHelper.MaxRowNumber, minWidth, maxWidth);
}
public IXLColumn AdjustToContents(Int32 startRow, Double minWidth, Double maxWidth)
{
return AdjustToContents(startRow, XLHelper.MaxRowNumber, minWidth, maxWidth);
}
public IXLColumn AdjustToContents(Int32 startRow, Int32 endRow, Double minWidth, Double maxWidth)
{
var fontCache = new Dictionary<IXLFontBase, Font>();
Double colMaxWidth = minWidth;
List<Int32> autoFilterRows = new List<Int32>();
if (this.Worksheet.AutoFilter != null && this.Worksheet.AutoFilter.Range != null)
autoFilterRows.Add(this.Worksheet.AutoFilter.Range.FirstRow().RowNumber());
autoFilterRows.AddRange(Worksheet.Tables.Where(t =>
t.AutoFilter != null
&& t.AutoFilter.Range != null
&& !autoFilterRows.Contains(t.AutoFilter.Range.FirstRow().RowNumber()))
.Select(t => t.AutoFilter.Range.FirstRow().RowNumber()));
foreach (XLCell c in Column(startRow, endRow).CellsUsed())
{
if (c.IsMerged()) continue;
Double thisWidthMax = 0;
Int32 textRotation = c.Style.Alignment.TextRotation;
if (c.HasRichText || textRotation != 0 || c.InnerText.Contains(Environment.NewLine))
{
var kpList = new List<KeyValuePair<IXLFontBase, string>>();
#region if (c.HasRichText)
if (c.HasRichText)
{
foreach (IXLRichString rt in c.RichText)
{
String formattedString = rt.Text;
var arr = formattedString.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
Int32 arrCount = arr.Count();
for (Int32 i = 0; i < arrCount; i++)
{
String s = arr[i];
if (i < arrCount - 1)
s += Environment.NewLine;
kpList.Add(new KeyValuePair<IXLFontBase, String>(rt, s));
}
}
}
else
{
String formattedString = c.GetFormattedString();
var arr = formattedString.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
Int32 arrCount = arr.Count();
for (Int32 i = 0; i < arrCount; i++)
{
String s = arr[i];
if (i < arrCount - 1)
s += Environment.NewLine;
kpList.Add(new KeyValuePair<IXLFontBase, String>(c.Style.Font, s));
}
}
#endregion
#region foreach (var kp in kpList)
Double runningWidth = 0;
Boolean rotated = false;
Double maxLineWidth = 0;
Int32 lineCount = 1;
foreach (KeyValuePair<IXLFontBase, string> kp in kpList)
{
var f = kp.Key;
String formattedString = kp.Value;
Int32 newLinePosition = formattedString.IndexOf(Environment.NewLine);
if (textRotation == 0)
{
#region if (newLinePosition >= 0)
if (newLinePosition >= 0)
{
if (newLinePosition > 0)
runningWidth += f.GetWidth(formattedString.Substring(0, newLinePosition), fontCache);
if (runningWidth > thisWidthMax)
thisWidthMax = runningWidth;
runningWidth = newLinePosition < formattedString.Length - 2
? f.GetWidth(formattedString.Substring(newLinePosition + 2), fontCache)
: 0;
}
else
runningWidth += f.GetWidth(formattedString, fontCache);
#endregion
}
else
{
#region if (textRotation == 255)
if (textRotation == 255)
{
if (runningWidth <= 0)
runningWidth = f.GetWidth("X", fontCache);
if (newLinePosition >= 0)
runningWidth += f.GetWidth("X", fontCache);
}
else
{
rotated = true;
Double vWidth = f.GetWidth("X", fontCache);
if (vWidth > maxLineWidth)
maxLineWidth = vWidth;
if (newLinePosition >= 0)
{
lineCount++;
if (newLinePosition > 0)
runningWidth += f.GetWidth(formattedString.Substring(0, newLinePosition), fontCache);
if (runningWidth > thisWidthMax)
thisWidthMax = runningWidth;
runningWidth = newLinePosition < formattedString.Length - 2
? f.GetWidth(formattedString.Substring(newLinePosition + 2), fontCache)
: 0;
}
else
runningWidth += f.GetWidth(formattedString, fontCache);
}
#endregion
}
}
#endregion
if (runningWidth > thisWidthMax)
thisWidthMax = runningWidth;
#region if (rotated)
if (rotated)
{
Int32 rotation;
if (textRotation == 90 || textRotation == 180 || textRotation == 255)
rotation = 90;
else
rotation = textRotation % 90;
Double r = DegreeToRadian(rotation);
thisWidthMax = (thisWidthMax * Math.Cos(r)) + (maxLineWidth * lineCount);
}
#endregion
}
else
thisWidthMax = c.Style.Font.GetWidth(c.GetFormattedString(), fontCache);
if (autoFilterRows.Contains(c.Address.RowNumber))
thisWidthMax += 2.7148; // Allow room for arrow icon in autofilter
if (thisWidthMax >= maxWidth)
{
colMaxWidth = maxWidth;
break;
}
if (thisWidthMax > colMaxWidth)
colMaxWidth = thisWidthMax + 1;
}
if (colMaxWidth <= 0)
colMaxWidth = Worksheet.ColumnWidth;
Width = colMaxWidth;
foreach (IDisposable font in fontCache.Values)
{
font.Dispose();
}
return this;
}
public IXLColumn Hide()
{
IsHidden = true;
return this;
}
public IXLColumn Unhide()
{
IsHidden = false;
return this;
}
public Boolean IsHidden
{
get { return IsReference ? Worksheet.Internals.ColumnsCollection[ColumnNumber()].IsHidden : _isHidden; }
set
{
if (IsReference)
Worksheet.Internals.ColumnsCollection[ColumnNumber()].IsHidden = value;
else
_isHidden = value;
}
}
public Int32 OutlineLevel
{
get { return IsReference ? Worksheet.Internals.ColumnsCollection[ColumnNumber()].OutlineLevel : _outlineLevel; }
set
{
if (value < 0 || value > 8)
throw new ArgumentOutOfRangeException("value", "Outline level must be between 0 and 8.");
if (IsReference)
Worksheet.Internals.ColumnsCollection[ColumnNumber()].OutlineLevel = value;
else
{
Worksheet.IncrementColumnOutline(value);
Worksheet.DecrementColumnOutline(_outlineLevel);
_outlineLevel = value;
}
}
}
public IXLColumn Group()
{
return Group(false);
}
public IXLColumn Group(Boolean collapse)
{
if (OutlineLevel < 8)
OutlineLevel += 1;
Collapsed = collapse;
return this;
}
public IXLColumn Group(Int32 outlineLevel)
{
return Group(outlineLevel, false);
}
public IXLColumn Group(Int32 outlineLevel, Boolean collapse)
{
OutlineLevel = outlineLevel;
Collapsed = collapse;
return this;
}
public IXLColumn Ungroup()
{
return Ungroup(false);
}
public IXLColumn Ungroup(Boolean ungroupFromAll)
{
if (ungroupFromAll)
OutlineLevel = 0;
else
{
if (OutlineLevel > 0)
OutlineLevel -= 1;
}
return this;
}
public IXLColumn Collapse()
{
Collapsed = true;
return Hide();
}
public IXLColumn Expand()
{
Collapsed = false;
return Unhide();
}
public Int32 CellCount()
{
return RangeAddress.LastAddress.ColumnNumber - RangeAddress.FirstAddress.ColumnNumber + 1;
}
public IXLColumn Sort(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false,
Boolean ignoreBlanks = true)
{
Sort(1, sortOrder, matchCase, ignoreBlanks);
return this;
}
IXLRangeColumn IXLColumn.CopyTo(IXLCell target)
{
using (var asRange = AsRange())
using (var copy = asRange.CopyTo(target))
return copy.Column(1);
}
IXLRangeColumn IXLColumn.CopyTo(IXLRangeBase target)
{
using (var asRange = AsRange())
using (var copy = asRange.CopyTo(target))
return copy.Column(1);
}
public IXLColumn CopyTo(IXLColumn column)
{
column.Clear();
var newColumn = (XLColumn)column;
newColumn._width = _width;
newColumn.Style = GetStyle();
using (var asRange = AsRange())
asRange.CopyTo(column).Dispose();
return newColumn;
}
public IXLRangeColumn Column(Int32 start, Int32 end)
{
return Range(start, 1, end, 1).Column(1);
}
public IXLRangeColumn Column(IXLCell start, IXLCell end)
{
return Column(start.Address.RowNumber, end.Address.RowNumber);
}
public IXLRangeColumns Columns(String columns)
{
var retVal = new XLRangeColumns();
var columnPairs = columns.Split(',');
foreach (string pair in columnPairs)
using (var asRange = AsRange())
asRange.Columns(pair.Trim()).ForEach(retVal.Add);
return retVal;
}
/// <summary>
/// Adds a vertical page break after this column.
/// </summary>
public IXLColumn AddVerticalPageBreak()
{
Worksheet.PageSetup.AddVerticalPageBreak(ColumnNumber());
return this;
}
public IXLColumn SetDataType(XLDataType dataType)
{
DataType = dataType;
return this;
}
public IXLRangeColumn ColumnUsed(Boolean includeFormats = false)
{
return Column(FirstCellUsed(includeFormats), LastCellUsed(includeFormats));
}
#endregion
public override XLRange AsRange()
{
return Range(1, 1, XLHelper.MaxRowNumber, 1);
}
private void WorksheetRangeShiftedColumns(XLRange range, int columnsShifted)
{
if (range.RangeAddress.FirstAddress.ColumnNumber <= ColumnNumber())
SetColumnNumber(ColumnNumber() + columnsShifted);
}
private void SetColumnNumber(int column)
{
if (column <= 0)
RangeAddress.IsInvalid = false;
else
{
RangeAddress.FirstAddress = new XLAddress(Worksheet,
1,
column,
RangeAddress.FirstAddress.FixedRow,
RangeAddress.FirstAddress.FixedColumn);
RangeAddress.LastAddress = new XLAddress(Worksheet,
XLHelper.MaxRowNumber,
column,
RangeAddress.LastAddress.FixedRow,
RangeAddress.LastAddress.FixedColumn);
}
}
public override XLRange Range(String rangeAddressStr)
{
String rangeAddressToUse;
if (rangeAddressStr.Contains(':') || rangeAddressStr.Contains('-'))
{
if (rangeAddressStr.Contains('-'))
rangeAddressStr = rangeAddressStr.Replace('-', ':');
var arrRange = rangeAddressStr.Split(':');
string firstPart = arrRange[0];
string secondPart = arrRange[1];
rangeAddressToUse = FixColumnAddress(firstPart) + ":" + FixColumnAddress(secondPart);
}
else
rangeAddressToUse = FixColumnAddress(rangeAddressStr);
var rangeAddress = new XLRangeAddress(Worksheet, rangeAddressToUse);
return Range(rangeAddress);
}
public IXLRangeColumn Range(int firstRow, int lastRow)
{
return Range(firstRow, 1, lastRow, 1).Column(1);
}
private static double DegreeToRadian(double angle)
{
return Math.PI * angle / 180.0;
}
private XLColumn ColumnShift(Int32 columnsToShift)
{
return Worksheet.Column(ColumnNumber() + columnsToShift);
}
#region XLColumn Left
IXLColumn IXLColumn.ColumnLeft()
{
return ColumnLeft();
}
IXLColumn IXLColumn.ColumnLeft(Int32 step)
{
return ColumnLeft(step);
}
public XLColumn ColumnLeft()
{
return ColumnLeft(1);
}
public XLColumn ColumnLeft(Int32 step)
{
return ColumnShift(step * -1);
}
#endregion
#region XLColumn Right
IXLColumn IXLColumn.ColumnRight()
{
return ColumnRight();
}
IXLColumn IXLColumn.ColumnRight(Int32 step)
{
return ColumnRight(step);
}
public XLColumn ColumnRight()
{
return ColumnRight(1);
}
public XLColumn ColumnRight(Int32 step)
{
return ColumnShift(step);
}
#endregion
public override Boolean IsEmpty()
{
return IsEmpty(false);
}
public override Boolean IsEmpty(Boolean includeFormats)
{
if (includeFormats && !Style.Equals(Worksheet.Style))
return false;
return base.IsEmpty(includeFormats);
}
public override Boolean IsEntireRow()
{
return false;
}
public override Boolean IsEntireColumn()
{
return true;
}
}
}
| |
using System;
using System.Linq;
using Xunit;
using Signum.Engine;
using Signum.Entities;
using Signum.Utilities;
using Signum.Test.Environment;
using Signum.Engine.Maps;
namespace Signum.Test.LinqProviderUpdateDelete
{
/// <summary>
/// Summary description for LinqProvider
/// </summary>
public class UpdateUpdateTest
{
public UpdateUpdateTest()
{
MusicStarter.StartAndLoad();
Connector.CurrentLogger = new DebugTextWriter();
Schema.Current.EntityEvents<LabelEntity>().PreUnsafeUpdate += (update, query) => null;
Schema.Current.EntityEvents<AlbumEntity>().PreUnsafeUpdate += (update, query) => null;
Schema.Current.EntityEvents<BandEntity>().PreUnsafeUpdate += (update, query) => null;
Schema.Current.EntityEvents<ArtistEntity>().PreUnsafeUpdate += (update, query) => null;
}
[Fact]
public void UpdateValue()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<AlbumEntity>().UnsafeUpdate().Set(a => a.Year, a => a.Year * 2).Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateValueSqlFunction()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<AlbumEntity>().UnsafeUpdate().Set(a => a.Name, a => a.Name.ToUpper()).Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateValueNull()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<NoteWithDateEntity>().UnsafeUpdate().Set(a => a.Text, a => null!).Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateValueConstant()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<AlbumEntity>().Where(a => a.Year < 1990)
.UnsafeUpdate().Set(a => a.Year, a => 1990).Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateEnumConstant()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<ArtistEntity>().UnsafeUpdate()
.Set(a => a.Sex, a => Sex.Male)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateEnum()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<ArtistEntity>().UnsafeUpdate()
.Set(a => a.Sex, a => a.Sex == Sex.Female ? Sex.Male : Sex.Female)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateEfie()
{
using (Transaction tr = new Transaction())
{
SongEmbedded song = new SongEmbedded
{
Name = "Mana Mana",
Duration = TimeSpan.FromSeconds(184),
};
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.BonusTrack, a => song)
.Execute();
Assert.False(Database.Query<AlbumEntity>().Any(a => a.BonusTrack == null));
Assert.Equal("Mana Mana", Database.Query<AlbumEntity>().Select(a => a.BonusTrack.Try(b => b.Name)).Distinct().SingleEx());
//tr.Commit();
}
}
[Fact]
public void UpdateEfieNull()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.BonusTrack, a => null)
.Execute();
Assert.True(Database.Query<AlbumEntity>().All(a => a.BonusTrack == null));
Assert.True(Database.Query<AlbumEntity>().All(a => a.BonusTrack.Try(bt => bt.Name) == null));
//tr.Commit();
}
}
[Fact]
public void UpdateEfieConditional()
{
using (Transaction tr = new Transaction())
{
SongEmbedded song = new SongEmbedded
{
Name = "Mana Mana",
Duration = TimeSpan.FromSeconds(184),
};
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.BonusTrack, a => (int)a.Id % 2 == 0 ? song : null)
.Execute();
Assert.True(Database.Query<AlbumEntity>().All(a => (int)a.Id % 2 == 0 ? a.BonusTrack.Try(b => b.Name) == "Mana Mana" : a.BonusTrack.Try(b => b.Name) == null));
//tr.Commit();
}
}
[Fact]
public void UpdateFie()
{
using (Transaction tr = new Transaction())
{
LabelEntity label = Database.Query<LabelEntity>().FirstEx();
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.Label, a => label)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateFieConditional()
{
using (Transaction tr = new Transaction())
{
LabelEntity label = Database.Query<LabelEntity>().FirstEx();
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.Label, a => (int)a.Id % 2 == 0 ? label : null)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateFieSetReadonly()
{
using (Transaction tr = new Transaction())
{
LabelEntity label = Database.Query<LabelEntity>().FirstEx();
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.Label, a => label)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateMixin()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<NoteWithDateEntity>().UnsafeUpdate()
.Set(a => a.Mixin<CorruptMixin>().Corrupt, a => true)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateFieToLite()
{
using (Transaction tr = new Transaction())
{
LabelEntity label = Database.Query<LabelEntity>().FirstEx();
int count = Database.Query<LabelEntity>().UnsafeUpdate()
.Set(a => a.Owner, a => label.ToLite())
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateFieNew()
{
var e = Assert.Throws<InvalidOperationException>(()=> {
using (Transaction tr = new Transaction())
{
LabelEntity label = new LabelEntity();
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.Label, a => label)
.Execute();
//tr.Commit();
}
});
Assert.Contains("is new and has no Id", e.Message);
}
[Fact]
public void UpdateFieNull()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.Label, a => null!)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateIbFie()
{
using (Transaction tr = new Transaction())
{
ArtistEntity michael = Database.Query<ArtistEntity>().SingleEx(a => a.Dead);
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.Author, a => michael)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateIbFieConditional()
{
using (Transaction tr = new Transaction())
{
ArtistEntity michael = Database.Query<ArtistEntity>().SingleEx(a => a.Dead);
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.Author, a => a.Id > 1 ? michael : null!)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateIbNull()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.Author, a => null!)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateIbaFie()
{
using (Transaction tr = new Transaction())
{
ArtistEntity michael = Database.Query<ArtistEntity>().SingleEx(a => a.Dead);
int count = Database.Query<NoteWithDateEntity>().UnsafeUpdate()
.Set(a => a.Target, a => michael)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateIbaLiteFie()
{
using (Transaction tr = new Transaction())
{
ArtistEntity michael = Database.Query<ArtistEntity>().SingleEx(a => a.Dead);
int count = Database.Query<NoteWithDateEntity>().UnsafeUpdate()
.Set(a => a.OtherTarget, a => michael.ToLite())
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateIbaNull()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<NoteWithDateEntity>().UnsafeUpdate()
.Set(a => a.Target, a => null!)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateIbaLiteNull()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<NoteWithDateEntity>().UnsafeUpdate()
.Set(a => a.OtherTarget, a => null)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateIbaConditional()
{
using (Transaction tr = new Transaction())
{
ArtistEntity michael = Database.Query<ArtistEntity>().SingleEx(a => a.Dead);
int count = Database.Query<NoteWithDateEntity>().UnsafeUpdate()
.Set(a => a.Target, a => a.CreationTime > DateTime.Now ? michael : null!)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateIbaLiteConditional()
{
using (Transaction tr = new Transaction())
{
ArtistEntity michael = Database.Query<ArtistEntity>().SingleEx(a => a.Dead);
int count = Database.Query<NoteWithDateEntity>().UnsafeUpdate()
.Set(a => a.OtherTarget, a => a.CreationTime > DateTime.Today ? michael.ToLite() : null)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateIbaCoalesce()
{
using (Transaction tr = new Transaction())
{
ArtistEntity michael = Database.Query<ArtistEntity>().SingleEx(a => a.Dead);
int count = Database.Query<NoteWithDateEntity>().UnsafeUpdate()
.Set(a => a.Target, a=>a.Target ?? michael)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateIbaLiteCoalesce()
{
using (Transaction tr = new Transaction())
{
ArtistEntity michael = Database.Query<ArtistEntity>().SingleEx(a => a.Dead);
int count = Database.Query<NoteWithDateEntity>().UnsafeUpdate()
.Set(a => a.OtherTarget, a => a.OtherTarget ?? michael.ToLite())
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateEmbeddedField()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.BonusTrack!.Name, a => a.BonusTrack!.Name + " - ")
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateEmbeddedNull()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<AlbumEntity>().UnsafeUpdate()
.Set(a => a.BonusTrack, a => null)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UnsafeUpdatePart()
{
using (Transaction tr = new Transaction())
{
int count = Database.Query<AlbumEntity>()
.Select(a => new { a.Label, Album = a })
.UnsafeUpdatePart(p => p.Label!)
.Set(a => a.Name, p => p.Label!.Name + "/" + p.Album!.Id)
.Execute();
var list = Database.Query<LabelEntity>().Select(a => a.Name);
//tr.Commit();
}
}
[Fact]
public void UpdateMListLite()
{
using (Transaction tr = new Transaction())
{
ArtistEntity artist = Database.Query<ArtistEntity>().FirstEx();
int count = Database.MListQuery((ArtistEntity a) => a.Friends).UnsafeUpdateMList()
.Set(mle => mle.Element, mle => artist.ToLite())
.Set(mle => mle.Parent, mle => artist)
.Execute();
var list = Database.MListQuery((ArtistEntity a) => a.Friends);
//tr.Commit();
}
}
[Fact]
public void UpdateMListEntity()
{
using (Transaction tr = new Transaction())
{
ArtistEntity artist = Database.Query<ArtistEntity>().FirstEx();
int count = Database.MListQuery((BandEntity a) => a.Members).UnsafeUpdateMList()
.Set(mle => mle.Element, mle => artist)
.Execute();
//tr.Commit();
}
}
[Fact]
public void UpdateMListEmbedded()
{
using (Transaction tr = new Transaction())
{
int count = Database.MListQuery((AlbumEntity a) => a.Songs).UnsafeUpdateMList()
.Set(mle => mle.Element.Seconds, mle => 3)
.Execute();
var list = Database.MListQuery((AlbumEntity a) => a.Songs);
//tr.Commit();
}
}
[Fact]
public void UpdateMListEmbeddedPart()
{
using (Transaction tr = new Transaction())
{
int count = (from a in Database.Query<AlbumEntity>()
from mle in a.MListElements(_ => _.Songs)
select new
{
LabelId = a.Label.Id,
mle
}).UnsafeUpdateMListPart(p => p.mle!) /*CSBUG*/
.Set(mle => mle.Element.Seconds, p => (int)p.LabelId)
.Execute();
var list = Database.MListQuery((AlbumEntity a) => a.Songs);
//tr.Commit();
}
}
[Fact]
public void UpdateExplicitInterfaceImplementedField()
{
using (Transaction tr = new Transaction())
{
Database.Query<AlbumEntity>()
.UnsafeUpdate()
.Set(a=>((ISecretContainer)a).Secret, a=>"Hi")
.Execute();
}
}
[Fact]
public void UnsafeUpdatePartExpand()
{
using (Transaction tr = new Transaction())
{
Database.Query<LabelEntity>()
.UnsafeUpdatePart(lb => lb.Owner!.Entity.Country)
.Set(ctr => ctr.Name, lb => lb.Name)
.Execute();
}
}
[Fact]
public void UnsafeUpdateNullableEmbeddedValue()
{
using (Transaction tr = new Transaction())
{
Database.Query<AlbumEntity>()
.UnsafeUpdate()
.Set(ctr => ctr.BonusTrack!.Index, lb => 2)
.Execute();
}
}
[TableName("#MyView")]
class MyTempView : IView
{
[ViewPrimaryKey]
public int MyId { get; set; }
public bool Used { get; set; }
}
[Fact]
public void UnsafeUpdateMyView()
{
using (Transaction tr = new Transaction())
{
Administrator.CreateTemporaryTable<MyTempView>();
Database.Query<ArtistEntity>().UnsafeInsertView(a => new MyTempView { MyId = (int)a.Id, Used = false, });
Database.View<MyTempView>().Where(a => a.MyId > 1).UnsafeUpdateView().Set(a => a.Used, a => true).Execute();
tr.Commit();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Metaheuristics
{
public static class SPPUtils
{
public static double Fitness(SPPInstance instance, int[] assignment)
{
double deviation = 0;
for (int subset = 0; subset < instance.NumberSubsets; subset++) {
double subsetWeight = 0;
for (int item = 0; item < instance.NumberItems; item++) {
if (subset == assignment[item]) {
subsetWeight += instance.ItemsWeight[item];
}
}
deviation += Math.Abs(subsetWeight - instance.SubsetsWeight[subset]);
}
return deviation;
}
// Implementation of the 2-opt (first improvement) local search algorithm.
public static void LocalSearch2OptFirst(SPPInstance instance, int[] assignment)
{
int tmp;
double currentFitness, bestFitness;
bestFitness = Fitness(instance, assignment);
for (int j = 1; j < assignment.Length; j++) {
for (int i = 0; i < j; i++) {
if (assignment[i] != assignment[j]) {
// Swap the items.
tmp = assignment[j];
assignment[j] = assignment[i];
assignment[i] = tmp;
// Evaluate the fitness of this new solution.
currentFitness = Fitness(instance, assignment);
if (currentFitness < bestFitness) {
return;
}
// Undo the swap.
tmp = assignment[j];
assignment[j] = assignment[i];
assignment[i] = tmp;
}
}
}
}
// Implementation of the 2-opt (best improvement) local search algorithm.
public static void LocalSearch2OptBest(SPPInstance instance, int[] assignment)
{
int tmp;
int firstSwapItem = 0, secondSwapItem = 0;
double currentFitness, bestFitness;
bestFitness = Fitness(instance, assignment);
for (int j = 1; j < assignment.Length; j++) {
for (int i = 0; i < j; i++) {
if (assignment[i] != assignment[j]) {
// Swap the items.
tmp = assignment[j];
assignment[j] = assignment[i];
assignment[i] = tmp;
// Evaluate the fitness of this new solution.
currentFitness = Fitness(instance, assignment);
if (currentFitness < bestFitness) {
firstSwapItem = j;
secondSwapItem = i;
bestFitness = currentFitness;
}
// Undo the swap.
tmp = assignment[j];
assignment[j] = assignment[i];
assignment[i] = tmp;
}
}
}
// Use the best assignment.
if (firstSwapItem != secondSwapItem) {
tmp = assignment[firstSwapItem];
assignment[firstSwapItem] = assignment[secondSwapItem];
assignment[secondSwapItem] = tmp;
}
}
// Implementation of the Tabu Movement of two movements.
public static Tuple<int, int> GetTabu(int[] source, int[] destiny)
{
Tuple<int, int> tabu = new Tuple<int, int>(-1, -1);
for (int i = 0; i < source.Length; i++) {
if (source[i] != destiny[i]) {
tabu.Val1 = i;
tabu.Val2 = destiny[i];
break;
}
}
return tabu;
}
// Implementation of the GRC solution's construction algorithm.
public static int[] GRCSolution(SPPInstance instance, double rclThreshold)
{
int numItems = instance.NumberItems;
int numSets = instance.NumberSubsets;
int[] assigment = new int[numItems];
int index = 0;
double best = 0;
double cost = 0;
int setItem = 0;
double[] setWeigths = new double[instance.NumberSubsets];
instance.SubsetsWeight.CopyTo(setWeigths, 0);
// Restricted Candidate List.
SortedList<double, int> rcl = new SortedList<double, int>();
assigment[0] = Statistics.RandomDiscreteUniform(0, numSets-1);
index++;
numItems --;
while (numItems > 0) {
rcl = new SortedList<double, int>();
for (int i = 0; i < numSets; i++) {
cost = Math.Abs(setWeigths[i] - instance.ItemsWeight[index]);
if(rcl.Count == 0) {
best = cost;
rcl.Add(cost, i);
}
else if(cost < best) {
// The new assignment is the new best;
best = cost;
for (int j = rcl.Count-1; j > 0; j--) {
if (rcl.Keys[j] > rclThreshold * best) {
rcl.RemoveAt(j);
}
else {
break;
}
}
rcl.Add(cost, i);
}
else if (cost < rclThreshold * best) {
// The new assigment is a mostly good candidate.
rcl.Add(cost, i);
}
}
setItem = rcl.Values[Statistics.RandomDiscreteUniform(0, rcl.Count-1)];
assigment[index] = setItem;
setWeigths[setItem] -= instance.ItemsWeight[index];
index++;
numItems--;
}
return assigment;
}
public static int[] RandomSolution(SPPInstance instance)
{
int[] solution = new int[instance.NumberItems];
for (int i = 0; i < instance.NumberItems; i++) {
solution[i] = Statistics.RandomDiscreteUniform(0, instance.NumberSubsets - 1);
}
return solution;
}
public static int[] GetNeighbor(SPPInstance instance, int[] solution)
{
int[] neighbor = new int[instance.NumberItems];
int index = Statistics.RandomDiscreteUniform(0, solution.Length - 1);
int oldSubset = solution[index];
int newSubset = oldSubset;
while (newSubset == oldSubset) {
newSubset = Statistics.RandomDiscreteUniform(0, instance.NumberSubsets - 1);
}
for (int i = 0; i < solution.Length; i++) {
if (i == index) {
neighbor[i] = newSubset;
}
else {
neighbor[i] = solution[i];
}
}
return neighbor;
}
public static double Distance(SPPInstance instance, int[] a, int[] b)
{
double distance = 0;
for (int i = 0; i < a.Length; i++) {
if (a[i] != b[i]) {
distance += 1;
}
}
return distance;
}
public static void PerturbateSolution(SPPInstance instance, int[] solution, int perturbations)
{
int point1 = 0;
for (int i = 0; i < perturbations; i++) {
point1 = Statistics.RandomDiscreteUniform(0, solution.Length -1 );
solution[point1] = Statistics.RandomDiscreteUniform(0, instance.NumberSubsets - 1);
}
}
}
}
| |
namespace Edi.Apps.ViewModels
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Windows;
using System.Windows.Media;
using Documents.ViewModels.EdiDoc;
using Edi.Themes.Interfaces;
using ICSharpCode.AvalonEdit.Edi;
using ICSharpCode.AvalonEdit.Edi.Interfaces;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Highlighting.Themes;
using MsgBox;
public partial class ApplicationViewModel
{
/// <summary>
/// Change WPF theme.
///
/// This method can be called when the theme is to be reseted by all means
/// (eg.: when powering application up).
///
/// !!! Use the CurrentTheme property to change !!!
/// !!! the theme when App is running !!!
/// </summary>
public void ResetTheme()
{
// Reset customized resources (if there are any from last change) and
// enforce reload of original values from resource dictionary
if (HighlightingManager.Instance.BackupDynResources != null)
{
try
{
foreach (string t in HighlightingManager.Instance.BackupDynResources)
{
Application.Current.Resources[t] = null;
}
}
catch
{
// ignored
}
finally
{
HighlightingManager.Instance.BackupDynResources = null;
}
}
// Get WPF Theme definition from Themes Assembly
IThemeBase nextThemeToSwitchTo = ApplicationThemes.SelectedTheme;
SwitchToSelectedTheme(nextThemeToSwitchTo);
// Backup highlighting names (if any) and restore highlighting associations after reloading highlighting definitions
var hlNames = new List<string>();
foreach (EdiViewModel f in Documents)
{
if (f != null)
{
hlNames.Add(f.HighlightingDefinition?.Name);
}
}
// Is the current theme configured with a highlighting theme???
////this.Config.FindHighlightingTheme(
IHighlightingThemes hlThemes = nextThemeToSwitchTo.HighlightingStyles;
// Re-load all highlighting patterns and re-apply highlightings
HighlightingExtension.RegisterCustomHighlightingPatterns(hlThemes);
//Re-apply highlightings after resetting highlighting manager
List<EdiViewModel> l = Documents;
for (int i = 0; i < l.Count; i++)
{
if (l[i] != null)
{
if (hlNames[i] == null) // The highlighting is null if highlighting is switched off for this file(!)
continue;
IHighlightingDefinition hdef = HighlightingManager.Instance.GetDefinition(hlNames[i]);
if (hdef != null)
l[i].HighlightingDefinition = hdef;
}
}
var backupDynResources = new List<string>();
// Apply global styles to theming elements (dynamic resources in resource dictionary) of editor control
if (HighlightingManager.Instance.HlThemes != null)
{
foreach (WidgetStyle w in HighlightingManager.Instance.HlThemes.GlobalStyles)
ApplyWidgetStyle(w, backupDynResources);
}
if (backupDynResources.Count > 0)
HighlightingManager.Instance.BackupDynResources = backupDynResources;
}
/// <summary>
/// Applies a widget style to a dynamic resource in the WPF Resource Dictionary.
/// The intention is to be more flexible and allow users to configure other editor
/// theme colors than thoses that are pre-defined.
/// </summary>
/// <param name="w"></param>
/// <param name="backupDynResources"></param>
private void ApplyWidgetStyle(WidgetStyle w,
List<string> backupDynResources)
{
if (w == null)
return;
switch (w.Name)
{
case "DefaultStyle":
ApplyToDynamicResource("EditorBackground", w.bgColor, backupDynResources);
ApplyToDynamicResource("EditorForeground", w.fgColor, backupDynResources);
break;
case "CurrentLineBackground":
ApplyToDynamicResource("EditorCurrentLineBackgroundColor", w.bgColor, backupDynResources);
break;
case "LineNumbersForeground":
ApplyToDynamicResource("EditorLineNumbersForeground", w.fgColor, backupDynResources);
break;
case "Selection":
ApplyToDynamicResource("EditorSelectionBrush", w.bgColor, backupDynResources);
ApplyToDynamicResource("EditorSelectionBorder", w.borderColor, backupDynResources);
ApplyToDynamicResource("EditorSelectionForeground", w.fgColor, backupDynResources);
break;
case "Hyperlink":
ApplyToDynamicResource("LinkTextBackgroundBrush", w.bgColor, backupDynResources);
ApplyToDynamicResource("LinkTextForegroundBrush", w.fgColor, backupDynResources);
break;
case "NonPrintableCharacter":
ApplyToDynamicResource("NonPrintableCharacterBrush", w.fgColor, backupDynResources);
break;
default:
Logger.WarnFormat("WidgetStyle named '{0}' is not supported.", w.Name);
break;
}
}
/// <summary>
/// Re-define an existing <seealso cref="SolidColorBrush"/> and backup the originial color
/// as it was before the application of the custom coloring.
/// </summary>
/// <param name="resourceName"></param>
/// <param name="newColor"></param>
/// <param name="backupDynResources"></param>
private void ApplyToDynamicResource(string resourceName,
SolidColorBrush newColor,
List<string> backupDynResources)
{
if (Application.Current.Resources[resourceName] != null && newColor != null)
{
// Re-coloring works with SolidColorBrushs linked as DynamicResource
if (Application.Current.Resources[resourceName] is SolidColorBrush)
{
backupDynResources.Add(resourceName);
Application.Current.Resources[resourceName] = newColor.Clone();
}
}
}
/// <summary>
/// Attempt to switch to the theme stated in <paramref name="nextThemeToSwitchTo"/>.
/// The given name must map into the <seealso cref="Edi.Themes.ThemesVM.EnTheme"/> enumeration.
/// </summary>
/// <param name="nextThemeToSwitchTo"></param>
private void SwitchToSelectedTheme(IThemeBase nextThemeToSwitchTo)
{
const string themesModul = "Edi.Themes.dll";
try
{
// set the style of the message box display in back-end system.
_MsgBox.Style = MsgBoxStyle.System;
// Get WPF Theme definition from Themes Assembly
IThemeBase theme = ApplicationThemes.SelectedTheme;
if (theme != null)
{
Application.Current.Resources.MergedDictionaries.Clear();
string themesPathFileName = Assembly.GetEntryAssembly().Location;
themesPathFileName = System.IO.Path.GetDirectoryName(themesPathFileName);
themesPathFileName = System.IO.Path.Combine(themesPathFileName, themesModul);
Assembly.LoadFrom(themesPathFileName);
if (System.IO.File.Exists(themesPathFileName) == false)
{
_MsgBox.Show(string.Format(CultureInfo.CurrentCulture,
Util.Local.Strings.STR_THEMING_MSG_CANNOT_FIND_PATH, themesModul),
Util.Local.Strings.STR_THEMING_CAPTION,
MsgBoxButtons.OK, MsgBoxImage.Error);
return;
}
foreach (var item in theme.Resources)
{
try
{
var res = new Uri(item, UriKind.Relative);
if (Application.LoadComponent(res) is ResourceDictionary)
{
ResourceDictionary dictionary = Application.LoadComponent(res) as ResourceDictionary;
Application.Current.Resources.MergedDictionaries.Add(dictionary);
}
}
catch (Exception exp)
{
_MsgBox.Show(exp, string.Format(CultureInfo.CurrentCulture, "'{0}'", item), MsgBoxButtons.OK, MsgBoxImage.Error);
}
}
}
}
catch (Exception exp)
{
_MsgBox.Show(exp, Util.Local.Strings.STR_THEMING_CAPTION,
MsgBoxButtons.OK, MsgBoxImage.Error);
}
finally
{
// set the style of the message box display in back-end system.
if (nextThemeToSwitchTo.WPFThemeName != "Generic")
_MsgBox.Style = MsgBoxStyle.WPFThemed;
}
}
}
}
| |
// 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.Text;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.Runtime.Augments;
using Internal.Reflection.Core.Execution;
using Internal.Reflection.Execution.PayForPlayExperience;
using Internal.Reflection.Extensions.NonPortable;
using System.Reflection.Runtime.General;
using Debug = System.Diagnostics.Debug;
namespace Internal.Reflection.Execution
{
//==========================================================================================================================
// This class provides various services down to System.Private.CoreLib. (Though we forward most or all of them directly up to Reflection.Core.)
//==========================================================================================================================
internal sealed class ReflectionExecutionDomainCallbacksImplementation : ReflectionExecutionDomainCallbacks
{
public ReflectionExecutionDomainCallbacksImplementation(ExecutionDomain executionDomain, ExecutionEnvironmentImplementation executionEnvironment)
{
_executionDomain = executionDomain;
_executionEnvironment = executionEnvironment;
}
public sealed override Type GetType(string typeName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase, string defaultAssemblyName)
{
if (defaultAssemblyName == null)
{
return _executionDomain.GetType(typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, ReflectionExecution.DefaultAssemblyNamesForGetType);
}
else
{
LowLevelListWithIList<String> defaultAssemblies = new LowLevelListWithIList<String>();
defaultAssemblies.Add(defaultAssemblyName);
defaultAssemblies.AddRange(ReflectionExecution.DefaultAssemblyNamesForGetType);
return _executionDomain.GetType(typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, defaultAssemblies);
}
}
public sealed override bool IsReflectionBlocked(RuntimeTypeHandle typeHandle)
{
return _executionEnvironment.IsReflectionBlocked(typeHandle);
}
//=======================================================================================
// This group of methods jointly service the Type.GetTypeFromHandle() path. The caller
// is responsible for analyzing the RuntimeTypeHandle to figure out which flavor to call.
//=======================================================================================
public sealed override Type GetNamedTypeForHandle(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition)
{
return _executionDomain.GetNamedTypeForHandle(typeHandle, isGenericTypeDefinition);
}
public sealed override Type GetArrayTypeForHandle(RuntimeTypeHandle typeHandle)
{
return _executionDomain.GetArrayTypeForHandle(typeHandle);
}
public sealed override Type GetMdArrayTypeForHandle(RuntimeTypeHandle typeHandle, int rank)
{
return _executionDomain.GetMdArrayTypeForHandle(typeHandle, rank);
}
public sealed override Type GetPointerTypeForHandle(RuntimeTypeHandle typeHandle)
{
return _executionDomain.GetPointerTypeForHandle(typeHandle);
}
public sealed override Type GetByRefTypeForHandle(RuntimeTypeHandle typeHandle)
{
return _executionDomain.GetByRefTypeForHandle(typeHandle);
}
public sealed override Type GetConstructedGenericTypeForHandle(RuntimeTypeHandle typeHandle)
{
return _executionDomain.GetConstructedGenericTypeForHandle(typeHandle);
}
//=======================================================================================
// MissingMetadataException support.
//=======================================================================================
public sealed override Exception CreateMissingMetadataException(Type pertainant)
{
return _executionDomain.CreateMissingMetadataException(pertainant);
}
// This is called from the ToString() helper of a RuntimeType that does not have full metadata.
// This helper makes a "best effort" to give the caller something better than "EETypePtr nnnnnnnnn".
public sealed override String GetBetterDiagnosticInfoIfAvailable(RuntimeTypeHandle runtimeTypeHandle)
{
return Type.GetTypeFromHandle(runtimeTypeHandle).ToDisplayStringIfAvailable(null);
}
public sealed override MethodBase GetMethodBaseFromStartAddressIfAvailable(IntPtr methodStartAddress)
{
RuntimeTypeHandle declaringTypeHandle = default(RuntimeTypeHandle);
QMethodDefinition methodHandle;
if (!ReflectionExecution.ExecutionEnvironment.TryGetMethodForStartAddress(methodStartAddress,
ref declaringTypeHandle, out methodHandle))
{
return null;
}
// We don't use the type argument handles as we want the uninstantiated method info
return ReflectionCoreExecution.ExecutionDomain.GetMethod(declaringTypeHandle, methodHandle, genericMethodTypeArgumentHandles: null);
}
public sealed override IntPtr TryGetStaticClassConstructionContext(RuntimeTypeHandle runtimeTypeHandle)
{
return _executionEnvironment.TryGetStaticClassConstructionContext(runtimeTypeHandle);
}
/// <summary>
/// Compares FieldInfos, sorting by name.
/// </summary>
private class FieldInfoNameComparer : IComparer<FieldInfo>
{
private static FieldInfoNameComparer s_instance = new FieldInfoNameComparer();
public static FieldInfoNameComparer Instance
{
get
{
return s_instance;
}
}
public int Compare(FieldInfo x, FieldInfo y)
{
return x.Name.CompareTo(y.Name);
}
}
/// <summary>
/// Reflection-based implementation of ValueType.GetHashCode. Matches the implementation created by the ValueTypeTransform.
/// </summary>
/// <param name="valueType">Boxed value type</param>
/// <returns>Hash code for the value type</returns>
public sealed override int ValueTypeGetHashCodeUsingReflection(object valueType)
{
// The algorithm is to use the hash of the first non-null instance field sorted by name.
List<FieldInfo> sortedFilteredFields = new List<FieldInfo>();
foreach (FieldInfo field in valueType.GetType().GetTypeInfo().DeclaredFields)
{
if (field.IsStatic)
{
continue;
}
sortedFilteredFields.Add(field);
}
sortedFilteredFields.Sort(FieldInfoNameComparer.Instance);
foreach (FieldInfo field in sortedFilteredFields)
{
object fieldValue = field.GetValue(valueType);
if (fieldValue != null)
{
return fieldValue.GetHashCode();
}
}
// Fallback path if no non-null instance field. The desktop hashes the GetType() object, but this seems like a lot of effort
// for a corner case - let's wait and see if we really need that.
return 1;
}
/// <summary>
/// Reflection-based implementation of ValueType.Equals. Matches the implementation created by the ValueTypeTransform.
/// </summary>
/// <param name="left">Boxed 'this' value type</param>
/// <param name="right">Boxed 'that' value type</param>
/// <returns>True if all nonstatic fields of the objects are equal</returns>
public sealed override bool ValueTypeEqualsUsingReflection(object left, object right)
{
if (right == null)
{
return false;
}
if (left.GetType() != right.GetType())
{
return false;
}
foreach (FieldInfo field in left.GetType().GetTypeInfo().DeclaredFields)
{
if (field.IsStatic)
{
continue;
}
object leftField = field.GetValue(left);
object rightField = field.GetValue(right);
if (leftField == null)
{
if (rightField != null)
{
return false;
}
}
else if (!leftField.Equals(rightField))
{
return false;
}
}
return true;
}
/// <summary>
/// Retrieves the default value for a parameter of a method.
/// </summary>
/// <param name="defaultParametersContext">The default parameters context used to invoke the method,
/// this should identify the method in question. This is passed to the RuntimeAugments.CallDynamicInvokeMethod.</param>
/// <param name="thType">The type of the parameter to retrieve.</param>
/// <param name="argIndex">The index of the parameter on the method to retrieve.</param>
/// <param name="defaultValue">The default value of the parameter if available.</param>
/// <returns>true if the default parameter value is available, otherwise false.</returns>
public sealed override bool TryGetDefaultParameterValue(object defaultParametersContext, RuntimeTypeHandle thType, int argIndex, out object defaultValue)
{
defaultValue = null;
if (!(defaultParametersContext is MethodBase methodBase))
{
return false;
}
ParameterInfo parameterInfo = methodBase.GetParametersNoCopy()[argIndex];
if (!parameterInfo.HasDefaultValue)
{
// If the parameter is optional, with no default value and we're asked for its default value,
// it means the caller specified Missing.Value as the value for the parameter. In this case the behavior
// is defined as passing in the Missing.Value, regardless of the parameter type.
// If Missing.Value is convertible to the parameter type, it will just work, otherwise we will fail
// due to type mismatch.
if (parameterInfo.IsOptional)
{
defaultValue = Missing.Value;
return true;
}
return false;
}
defaultValue = parameterInfo.DefaultValue;
return true;
}
public sealed override RuntimeTypeHandle GetTypeHandleIfAvailable(Type type)
{
return _executionDomain.GetTypeHandleIfAvailable(type);
}
public sealed override bool SupportsReflection(Type type)
{
return _executionDomain.SupportsReflection(type);
}
public sealed override MethodInfo GetDelegateMethod(Delegate del)
{
return DelegateMethodInfoRetriever.GetDelegateMethodInfo(del);
}
public sealed override Exception GetExceptionForHR(int hr)
{
return Marshal.GetExceptionForHR(hr);
}
private ExecutionDomain _executionDomain;
private ExecutionEnvironmentImplementation _executionEnvironment;
}
}
| |
// 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.Net.Sockets;
using System.Net.Test.Common;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.NetworkInformation.Tests
{
public class NetworkInterfaceBasicTest
{
private readonly ITestOutputHelper _log;
public NetworkInterfaceBasicTest()
{
_log = TestLogging.GetInstance();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308
public void BasicTest_GetNetworkInterfaces_AtLeastOne()
{
Assert.NotEqual<int>(0, NetworkInterface.GetAllNetworkInterfaces().Length);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX
public void BasicTest_AccessInstanceProperties_NoExceptions()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("- NetworkInterface -");
_log.WriteLine("Name: " + nic.Name);
_log.WriteLine("Description: " + nic.Description);
_log.WriteLine("ID: " + nic.Id);
_log.WriteLine("IsReceiveOnly: " + nic.IsReceiveOnly);
_log.WriteLine("Type: " + nic.NetworkInterfaceType);
_log.WriteLine("Status: " + nic.OperationalStatus);
_log.WriteLine("Speed: " + nic.Speed);
// Validate NIC speed overflow.
// We've found that certain WiFi adapters will return speed of -1 when not connected.
// We've found that Wi-Fi Direct Virtual Adapters return speed of -1 even when up.
Assert.InRange(nic.Speed, -1, long.MaxValue);
_log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast);
_log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress());
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308
[PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux
public void BasicTest_AccessInstanceProperties_NoExceptions_Linux()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("- NetworkInterface -");
_log.WriteLine("Name: " + nic.Name);
string description = nic.Description;
Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty.");
_log.WriteLine("Description: " + description);
string id = nic.Id;
Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty.");
_log.WriteLine("ID: " + id);
Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly);
_log.WriteLine("Type: " + nic.NetworkInterfaceType);
_log.WriteLine("Status: " + nic.OperationalStatus);
try
{
_log.WriteLine("Speed: " + nic.Speed);
Assert.InRange(nic.Speed, -1, long.MaxValue);
}
// We cannot guarantee this works on all devices.
catch (PlatformNotSupportedException pnse)
{
_log.WriteLine(pnse.ToString());
}
_log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast);
_log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress());
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)] // Some APIs are not supported on OSX
public void BasicTest_AccessInstanceProperties_NoExceptions_Osx()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("- NetworkInterface -");
_log.WriteLine("Name: " + nic.Name);
string description = nic.Description;
Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty.");
_log.WriteLine("Description: " + description);
string id = nic.Id;
Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty.");
_log.WriteLine("ID: " + id);
Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly);
_log.WriteLine("Type: " + nic.NetworkInterfaceType);
_log.WriteLine("Status: " + nic.OperationalStatus);
_log.WriteLine("Speed: " + nic.Speed);
Assert.InRange(nic.Speed, 0, long.MaxValue);
_log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast);
_log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress());
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308
[Trait("IPv4", "true")]
public void BasicTest_StaticLoopbackIndex_MatchesLoopbackNetworkInterface()
{
Assert.True(Capability.IPv4Support());
_log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex);
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses)
{
if (unicast.Address.Equals(IPAddress.Loopback))
{
Assert.Equal<int>(nic.GetIPProperties().GetIPv4Properties().Index,
NetworkInterface.LoopbackInterfaceIndex);
return; // Only check IPv4 loopback
}
}
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308
[Trait("IPv4", "true")]
public void BasicTest_StaticLoopbackIndex_ExceptionIfV4NotSupported()
{
Assert.True(Capability.IPv4Support());
_log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308
[Trait("IPv6", "true")]
public void BasicTest_StaticIPv6LoopbackIndex_MatchesLoopbackNetworkInterface()
{
Assert.True(Capability.IPv6Support());
_log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex);
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses)
{
if (unicast.Address.Equals(IPAddress.IPv6Loopback))
{
Assert.Equal<int>(
nic.GetIPProperties().GetIPv6Properties().Index,
NetworkInterface.IPv6LoopbackInterfaceIndex);
return; // Only check IPv6 loopback.
}
}
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308
[Trait("IPv6", "true")]
public void BasicTest_StaticIPv6LoopbackIndex_ExceptionIfV6NotSupported()
{
Assert.True(Capability.IPv6Support());
_log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX
public void BasicTest_GetIPInterfaceStatistics_Success()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceStatistics stats = nic.GetIPStatistics();
_log.WriteLine("- Stats for : " + nic.Name);
_log.WriteLine("BytesReceived: " + stats.BytesReceived);
_log.WriteLine("BytesSent: " + stats.BytesSent);
_log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded);
_log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors);
_log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets);
_log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived);
_log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent);
_log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded);
_log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors);
_log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength);
_log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived);
_log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308
[PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux
public void BasicTest_GetIPInterfaceStatistics_Success_Linux()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceStatistics stats = nic.GetIPStatistics();
_log.WriteLine("- Stats for : " + nic.Name);
_log.WriteLine("BytesReceived: " + stats.BytesReceived);
_log.WriteLine("BytesSent: " + stats.BytesSent);
_log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded);
_log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors);
Assert.Throws<PlatformNotSupportedException>(() => stats.IncomingUnknownProtocolPackets);
_log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived);
Assert.Throws<PlatformNotSupportedException>(() => stats.NonUnicastPacketsSent);
_log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded);
_log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors);
_log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength);
_log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived);
_log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)] // Some APIs are not supported on OSX
public void BasicTest_GetIPInterfaceStatistics_Success_OSX()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceStatistics stats = nic.GetIPStatistics();
_log.WriteLine("- Stats for : " + nic.Name);
_log.WriteLine("BytesReceived: " + stats.BytesReceived);
_log.WriteLine("BytesSent: " + stats.BytesSent);
_log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded);
_log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors);
_log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets);
_log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived);
_log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent);
Assert.Throws<PlatformNotSupportedException>(() => stats.OutgoingPacketsDiscarded);
_log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors);
_log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength);
_log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived);
_log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308
public void BasicTest_GetIsNetworkAvailable_Success()
{
Assert.True(NetworkInterface.GetIsNetworkAvailable());
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308
[PlatformSpecific(~TestPlatforms.OSX)]
[InlineData(false)]
[InlineData(true)]
public async Task NetworkInterface_LoopbackInterfaceIndex_MatchesReceivedPackets(bool ipv6)
{
using (var client = new Socket(SocketType.Dgram, ProtocolType.Udp))
using (var server = new Socket(SocketType.Dgram, ProtocolType.Udp))
{
server.Bind(new IPEndPoint(ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0));
var serverEndPoint = (IPEndPoint)server.LocalEndPoint;
Task<SocketReceiveMessageFromResult> receivedTask =
server.ReceiveMessageFromAsync(new ArraySegment<byte>(new byte[1]), SocketFlags.None, serverEndPoint);
while (!receivedTask.IsCompleted)
{
client.SendTo(new byte[] { 42 }, serverEndPoint);
await Task.Delay(1);
}
Assert.Equal(
(await receivedTask).PacketInformation.Interface,
ipv6 ? NetworkInterface.IPv6LoopbackInterfaceIndex : NetworkInterface.LoopbackInterfaceIndex);
}
}
}
}
| |
//
// 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 Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.SiteRecovery;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;
namespace Microsoft.WindowsAzure.Management.SiteRecovery
{
public partial class SiteRecoveryManagementClient : ServiceClient<SiteRecoveryManagementClient>, ISiteRecoveryManagementClient
{
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 string _cloudServiceName;
public string CloudServiceName
{
get { return this._cloudServiceName; }
set { this._cloudServiceName = value; }
}
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 string _resourceName;
public string ResourceName
{
get { return this._resourceName; }
set { this._resourceName = value; }
}
private IJobOperations _jobs;
/// <summary>
/// Definition for Job Operations.
/// </summary>
public virtual IJobOperations Jobs
{
get { return this._jobs; }
}
private INetworkMappingOperations _networkMappings;
/// <summary>
/// Definition of network mapping operations for the Site Recovery
/// extension.
/// </summary>
public virtual INetworkMappingOperations NetworkMappings
{
get { return this._networkMappings; }
}
private INetworkOperations _networks;
/// <summary>
/// Definition of network operations for the Site Recovery extension.
/// </summary>
public virtual INetworkOperations Networks
{
get { return this._networks; }
}
private IProtectionContainerOperations _protectionContainer;
/// <summary>
/// Definition of Protection Container operations for the Site Recovery
/// extension.
/// </summary>
public virtual IProtectionContainerOperations ProtectionContainer
{
get { return this._protectionContainer; }
}
private IProtectionEntityOperations _protectionEntity;
/// <summary>
/// Definition of protection entity operations for the Site Recovery
/// extension.
/// </summary>
public virtual IProtectionEntityOperations ProtectionEntity
{
get { return this._protectionEntity; }
}
private IProtectionProfileOperations _protectionProfile;
/// <summary>
/// Definition of Protection Profile operations for the Site Recovery
/// extension.
/// </summary>
public virtual IProtectionProfileOperations ProtectionProfile
{
get { return this._protectionProfile; }
}
private IRecoveryPlanOperations _recoveryPlan;
/// <summary>
/// Definition of recoveryplan operations for the Site Recovery
/// extension.
/// </summary>
public virtual IRecoveryPlanOperations RecoveryPlan
{
get { return this._recoveryPlan; }
}
private IServerOperations _servers;
/// <summary>
/// Definition of server operations for the Site Recovery extension.
/// </summary>
public virtual IServerOperations Servers
{
get { return this._servers; }
}
private ISiteOperations _sites;
/// <summary>
/// Definition of Site operations for the Site Recovery extension.
/// </summary>
public virtual ISiteOperations Sites
{
get { return this._sites; }
}
private IStorageMappingOperations _storageMappings;
/// <summary>
/// Definition of storage mapping operations for the Site Recovery
/// extension.
/// </summary>
public virtual IStorageMappingOperations StorageMappings
{
get { return this._storageMappings; }
}
private IStorageOperations _storages;
/// <summary>
/// Definition of storage operations for the Site Recovery extension.
/// </summary>
public virtual IStorageOperations Storages
{
get { return this._storages; }
}
private IStoragePoolMappingOperations _storagePoolMappings;
/// <summary>
/// Definition of storage pool mapping operations for the Site Recovery
/// extension.
/// </summary>
public virtual IStoragePoolMappingOperations StoragePoolMappings
{
get { return this._storagePoolMappings; }
}
private IVaultExtendedInfoOperations _vaultExtendedInfo;
/// <summary>
/// Definition of vault extended info operations for the Site Recovery
/// extension.
/// </summary>
public virtual IVaultExtendedInfoOperations VaultExtendedInfo
{
get { return this._vaultExtendedInfo; }
}
private IVirtualMachineGroupOperations _vmGroup;
/// <summary>
/// Definition of virtual machine operations for the Site Recovery
/// extension.
/// </summary>
public virtual IVirtualMachineGroupOperations VmGroup
{
get { return this._vmGroup; }
}
private IVirtualMachineOperations _vm;
/// <summary>
/// Definition of virtual machine operations for the Site Recovery
/// extension.
/// </summary>
public virtual IVirtualMachineOperations Vm
{
get { return this._vm; }
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient
/// class.
/// </summary>
public SiteRecoveryManagementClient()
: base()
{
this._jobs = new JobOperations(this);
this._networkMappings = new NetworkMappingOperations(this);
this._networks = new NetworkOperations(this);
this._protectionContainer = new ProtectionContainerOperations(this);
this._protectionEntity = new ProtectionEntityOperations(this);
this._protectionProfile = new ProtectionProfileOperations(this);
this._recoveryPlan = new RecoveryPlanOperations(this);
this._servers = new ServerOperations(this);
this._sites = new SiteOperations(this);
this._storageMappings = new StorageMappingOperations(this);
this._storages = new StorageOperations(this);
this._storagePoolMappings = new StoragePoolMappingOperations(this);
this._vaultExtendedInfo = new VaultExtendedInfoOperations(this);
this._vmGroup = new VirtualMachineGroupOperations(this);
this._vm = new VirtualMachineOperations(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 SiteRecoveryManagementClient
/// class.
/// </summary>
/// <param name='cloudServiceName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <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'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._cloudServiceName = cloudServiceName;
this._resourceName = resourceName;
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient
/// class.
/// </summary>
/// <param name='cloudServiceName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <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 SiteRecoveryManagementClient(string cloudServiceName, string resourceName, SubscriptionCloudCredentials credentials)
: this()
{
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._cloudServiceName = cloudServiceName;
this._resourceName = resourceName;
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient
/// class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SiteRecoveryManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._jobs = new JobOperations(this);
this._networkMappings = new NetworkMappingOperations(this);
this._networks = new NetworkOperations(this);
this._protectionContainer = new ProtectionContainerOperations(this);
this._protectionEntity = new ProtectionEntityOperations(this);
this._protectionProfile = new ProtectionProfileOperations(this);
this._recoveryPlan = new RecoveryPlanOperations(this);
this._servers = new ServerOperations(this);
this._sites = new SiteOperations(this);
this._storageMappings = new StorageMappingOperations(this);
this._storages = new StorageOperations(this);
this._storagePoolMappings = new StoragePoolMappingOperations(this);
this._vaultExtendedInfo = new VaultExtendedInfoOperations(this);
this._vmGroup = new VirtualMachineGroupOperations(this);
this._vm = new VirtualMachineOperations(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 SiteRecoveryManagementClient
/// class.
/// </summary>
/// <param name='cloudServiceName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <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'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._cloudServiceName = cloudServiceName;
this._resourceName = resourceName;
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient
/// class.
/// </summary>
/// <param name='cloudServiceName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <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 SiteRecoveryManagementClient(string cloudServiceName, string resourceName, SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._cloudServiceName = cloudServiceName;
this._resourceName = resourceName;
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// SiteRecoveryManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of SiteRecoveryManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<SiteRecoveryManagementClient> client)
{
base.Clone(client);
if (client is SiteRecoveryManagementClient)
{
SiteRecoveryManagementClient clonedClient = ((SiteRecoveryManagementClient)client);
clonedClient._cloudServiceName = this._cloudServiceName;
clonedClient._resourceName = this._resourceName;
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// Parse enum values for type LocalNetworkConnectionType.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static LocalNetworkConnectionType ParseLocalNetworkConnectionType(string value)
{
if ("IPsec".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return LocalNetworkConnectionType.IPSecurity;
}
if ("Dedicated".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return LocalNetworkConnectionType.Dedicated;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type LocalNetworkConnectionType to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string LocalNetworkConnectionTypeToString(LocalNetworkConnectionType value)
{
if (value == LocalNetworkConnectionType.IPSecurity)
{
return "IPsec";
}
if (value == LocalNetworkConnectionType.Dedicated)
{
return "Dedicated";
}
throw new ArgumentOutOfRangeException("value");
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
namespace OpenSim.Region.Framework.Scenes.Tests
{
/// <summary>
/// Basic scene object tests (create, read and delete but not update).
/// </summary>
[TestFixture]
public class SceneObjectBasicTests : OpenSimTestCase
{
// [TearDown]
// public void TearDown()
// {
// Console.WriteLine("TearDown");
// GC.Collect();
// Thread.Sleep(3000);
// }
// public class GcNotify
// {
// public static AutoResetEvent gcEvent = new AutoResetEvent(false);
// private static bool _initialized = false;
//
// public static void Initialize()
// {
// if (!_initialized)
// {
// _initialized = true;
// new GcNotify();
// }
// }
//
// private GcNotify(){}
//
// ~GcNotify()
// {
// if (!Environment.HasShutdownStarted &&
// !AppDomain.CurrentDomain.IsFinalizingForUnload())
// {
// Console.WriteLine("GcNotify called");
// gcEvent.Set();
// new GcNotify();
// }
// }
// }
/// <summary>
/// Test adding an object to a scene.
/// </summary>
[Test]
public void TestAddSceneObject()
{
TestHelpers.InMethod();
Scene scene = new SceneHelpers().SetupScene();
int partsToTestCount = 3;
SceneObjectGroup so
= SceneHelpers.CreateSceneObject(partsToTestCount, TestHelpers.ParseTail(0x1), "obj1", 0x10);
SceneObjectPart[] parts = so.Parts;
Assert.That(scene.AddNewSceneObject(so, false), Is.True);
SceneObjectGroup retrievedSo = scene.GetSceneObjectGroup(so.UUID);
SceneObjectPart[] retrievedParts = retrievedSo.Parts;
//m_log.Debug("retrievedPart : {0}", retrievedPart);
// If the parts have the same UUID then we will consider them as one and the same
Assert.That(retrievedSo.PrimCount, Is.EqualTo(partsToTestCount));
for (int i = 0; i < partsToTestCount; i++)
{
Assert.That(retrievedParts[i].Name, Is.EqualTo(parts[i].Name));
Assert.That(retrievedParts[i].UUID, Is.EqualTo(parts[i].UUID));
}
}
[Test]
/// <summary>
/// It shouldn't be possible to add a scene object if one with that uuid already exists in the scene.
/// </summary>
public void TestAddExistingSceneObjectUuid()
{
TestHelpers.InMethod();
Scene scene = new SceneHelpers().SetupScene();
string obj1Name = "Alfred";
string obj2Name = "Betty";
UUID objUuid = new UUID("00000000-0000-0000-0000-000000000001");
SceneObjectPart part1
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = obj1Name, UUID = objUuid };
Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part1), false), Is.True);
SceneObjectPart part2
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = obj2Name, UUID = objUuid };
Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part2), false), Is.False);
SceneObjectPart retrievedPart = scene.GetSceneObjectPart(objUuid);
//m_log.Debug("retrievedPart : {0}", retrievedPart);
// If the parts have the same UUID then we will consider them as one and the same
Assert.That(retrievedPart.Name, Is.EqualTo(obj1Name));
Assert.That(retrievedPart.UUID, Is.EqualTo(objUuid));
}
/// <summary>
/// Test retrieving a scene object via the local id of one of its parts.
/// </summary>
[Test]
public void TestGetSceneObjectByPartLocalId()
{
TestHelpers.InMethod();
Scene scene = new SceneHelpers().SetupScene();
int partsToTestCount = 3;
SceneObjectGroup so
= SceneHelpers.CreateSceneObject(partsToTestCount, TestHelpers.ParseTail(0x1), "obj1", 0x10);
SceneObjectPart[] parts = so.Parts;
scene.AddNewSceneObject(so, false);
// Test getting via the root part's local id
Assert.That(scene.GetGroupByPrim(so.LocalId), Is.Not.Null);
// Test getting via a non root part's local id
Assert.That(scene.GetGroupByPrim(parts[partsToTestCount - 1].LocalId), Is.Not.Null);
// Test that we don't get back an object for a local id that doesn't exist
Assert.That(scene.GetGroupByPrim(999), Is.Null);
// Now delete the scene object and check again
scene.DeleteSceneObject(so, false);
Assert.That(scene.GetGroupByPrim(so.LocalId), Is.Null);
Assert.That(scene.GetGroupByPrim(parts[partsToTestCount - 1].LocalId), Is.Null);
}
/// <summary>
/// Test deleting an object from a scene.
/// </summary>
/// <remarks>
/// This is the most basic form of delete. For all more sophisticated forms of derez (done asynchrnously
/// and where object can be taken to user inventory, etc.), see SceneObjectDeRezTests.
/// </remarks>
[Test]
public void TestDeleteSceneObject()
{
TestHelpers.InMethod();
TestScene scene = new SceneHelpers().SetupScene();
SceneObjectGroup so = SceneHelpers.AddSceneObject(scene);
Assert.That(so.IsDeleted, Is.False);
scene.DeleteSceneObject(so, false);
Assert.That(so.IsDeleted, Is.True);
SceneObjectPart retrievedPart = scene.GetSceneObjectPart(so.LocalId);
Assert.That(retrievedPart, Is.Null);
}
/// <summary>
/// Changing a scene object uuid changes the root part uuid. This is a valid operation if the object is not
/// in a scene and is useful if one wants to supply a UUID directly rather than use the one generated by
/// OpenSim.
/// </summary>
[Test]
public void TestChangeSceneObjectUuid()
{
string rootPartName = "rootpart";
UUID rootPartUuid = new UUID("00000000-0000-0000-0000-000000000001");
string childPartName = "childPart";
UUID childPartUuid = new UUID("00000000-0000-0000-0001-000000000000");
SceneObjectPart rootPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = rootPartName, UUID = rootPartUuid };
SceneObjectPart linkPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = childPartName, UUID = childPartUuid };
SceneObjectGroup sog = new SceneObjectGroup(rootPart);
sog.AddPart(linkPart);
Assert.That(sog.UUID, Is.EqualTo(rootPartUuid));
Assert.That(sog.RootPart.UUID, Is.EqualTo(rootPartUuid));
Assert.That(sog.Parts.Length, Is.EqualTo(2));
UUID newRootPartUuid = new UUID("00000000-0000-0000-0000-000000000002");
sog.UUID = newRootPartUuid;
Assert.That(sog.UUID, Is.EqualTo(newRootPartUuid));
Assert.That(sog.RootPart.UUID, Is.EqualTo(newRootPartUuid));
Assert.That(sog.Parts.Length, Is.EqualTo(2));
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Abstract;
using System.Text;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
namespace Contoso.Web.UI.Integrate
{
using UIClientScript = ClientScript;
/// <summary>
/// ShareThis
/// </summary>
public class ShareThis : HtmlContainerControl
{
private static Type _type = typeof(ShareThis);
private string _scriptBody;
public ShareThis()
: base()
{
DeploymentTarget = DeploymentEnvironment.Production;
Include = new ShareThisInclude();
Inject = true;
}
public DeploymentEnvironment DeploymentTarget { get; set; }
public string AttachToButtonId { get; set; }
public bool UseClientScript { get; set; }
public ShareThisInclude Include { get; set; }
public ShareThisObject Object { get; set; }
public bool Inject { get; set; }
[ServiceDependency]
public IClientScriptManager ClientScriptManager { get; set; }
/// <summary>
/// Gets or sets the button text.
/// </summary>
/// <value>The button text.</value>
public string ButtonText
{
get { return Include.ButtonText; }
set { Include.ButtonText = value; }
}
/// <summary>
/// Gets or sets the color of the header background.
/// </summary>
/// <value>The color of the header background.</value>
public string HeaderBackgroundColor
{
get { return Include.HeaderBackgroundColor; }
set { Include.HeaderBackgroundColor = value; }
}
/// <summary>
/// Gets or sets the color of the header foreground.
/// </summary>
/// <value>The color of the header foreground.</value>
public string HeaderForegroundColor
{
get { return Include.HeaderForegroundColor; }
set { Include.HeaderForegroundColor = value; }
}
/// <summary>
/// Gets or sets the header title.
/// </summary>
/// <value>The header title.</value>
public string HeaderTitle
{
get { return Include.HeaderTitle; }
set { Include.HeaderTitle = value; }
}
/// <summary>
/// Gets or sets the post services.
/// </summary>
/// <value>The post services.</value>
public string PostServices
{
get { return Include.PostServices; }
set { Include.PostServices = value; }
}
/// <summary>
/// Gets or sets the publisher.
/// </summary>
/// <value>The publisher.</value>
public string Publisher
{
get { return Include.Publisher; }
set { Include.Publisher = value; }
}
/// <summary>
/// Gets or sets the send services.
/// </summary>
/// <value>The send services.</value>
public string SendServices
{
get { return Include.SendServices; }
set { Include.SendServices = value; }
}
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>The type.</value>
public string Type
{
get { return Include.Type; }
set { Include.Type = value; }
}
protected override void OnPreRender(EventArgs e)
{
if (Inject)
ServiceLocatorManager.Current.Inject(this);
if (Include == null)
throw new ArgumentNullException("Include");
base.OnPreRender(e);
// include
if (ClientScriptManager != null)
ClientScriptManager.EnsureItem<HtmlHead>(ID, () => new IncludeClientScriptItem(GetIncludeUriString()));
}
protected override void Render(HtmlTextWriter w)
{
if (Object == null)
throw new ArgumentNullException("Object");
// object
_scriptBody = GetObjectString();
if (ClientScriptManager != null)
{
ClientScriptManager.AddRange(_scriptBody);
_scriptBody = null;
}
//if (EnvironmentEx.DeploymentEnvironment == DeploymentTarget)
//{
if (!string.IsNullOrEmpty(_scriptBody))
{
w.Write(@"<script type=""text/javascript"">
// <![CDATA[
");
w.Write(_scriptBody);
w.Write(@"
// ]]>
</script>");
}
//}
//else
// w.WriteLine("<!-- Share This -->");
}
private string GetObjectString()
{
var objectLiteral = (Object as ShareThisObjectLiteral);
if (objectLiteral != null)
return objectLiteral.Literal;
//
var b = new StringBuilder("SHARETHIS.addEntry(");
var obj = Object;
bool hasButton = string.IsNullOrEmpty(AttachToButtonId);
b.Append(SerializeObjectToJsonString(obj));
b.Append(",");
b.Append(SerializeObjectMetaToJsonString((obj.Meta == null ? ShareThisObjectMeta.Default : obj.Meta), hasButton));
b.Append(")");
//
b.Append(!hasButton ? ".attachButton(document.getElementById('" + AttachToButtonId + "'));" : ";");
return b.ToString();
}
private string GetIncludeUriString()
{
var includeLiteral = (Include as ShareThisIncludeLiteral);
if (includeLiteral != null)
{
var value = includeLiteral.Literal;
if (value.IndexOf("&button=", StringComparison.OrdinalIgnoreCase) == -1)
value += "&button=false";
return value;
}
//
var include = Include;
if (string.IsNullOrEmpty(include.Type))
throw new InvalidOperationException("'Type' cannot be null");
return SerializeIncludeToUriString(include);
}
#region Serializers
public static string SerializeIncludeToUriString(ShareThisInclude include)
{
// todo: build urlserialize here
var b = new StringBuilder();
b.Append(string.Format("http://w.sharethis.com/button/sharethis.js#type={0}", Uri.EscapeDataString(include.Type)));
if (!string.IsNullOrEmpty(include.Publisher))
b.Append("&publisher=" + Uri.EscapeDataString(include.Publisher));
if (!string.IsNullOrEmpty(include.ButtonText))
b.Append("&buttonText=" + Uri.EscapeDataString(include.ButtonText));
if (!string.IsNullOrEmpty(include.HeaderBackgroundColor))
b.Append("&headerbg=" + Uri.EscapeDataString(include.HeaderBackgroundColor));
if (!string.IsNullOrEmpty(include.HeaderForegroundColor))
b.Append("&headerfg=" + Uri.EscapeDataString(include.HeaderForegroundColor));
if (!string.IsNullOrEmpty(include.HeaderTitle))
b.Append("&headerTitle=" + Uri.EscapeDataString(include.HeaderTitle));
if (!string.IsNullOrEmpty(include.PostServices))
b.Append("&post_services=" + Uri.EscapeDataString(include.PostServices));
if (!string.IsNullOrEmpty(include.SendServices))
b.Append("&send_services=" + Uri.EscapeDataString(include.SendServices));
//foreach (var keyValue in _javascriptAttribs)
// b.Append("&" + keyValue.Key + "=" + Uri.EscapeDataString(keyValue.Value));
b.Append("&button=false");
return b.ToString();
}
public static string SerializeObjectToJsonString(ShareThisObject obj)
{
var b = new StringBuilder("{");
var objectPropertyList = new List<string>();
if (!string.IsNullOrEmpty(obj.Author))
objectPropertyList.Add("author: " + UIClientScript.EncodeText(obj.Author));
if (!string.IsNullOrEmpty(obj.Category))
objectPropertyList.Add("category: " + UIClientScript.EncodeText(obj.Category));
if (!string.IsNullOrEmpty(obj.Content))
objectPropertyList.Add("content: " + UIClientScript.EncodeText(obj.Content));
if (!string.IsNullOrEmpty(obj.Icon))
objectPropertyList.Add("icon: " + UIClientScript.EncodeText(obj.Icon));
if (!string.IsNullOrEmpty(obj.Published))
objectPropertyList.Add("published: " + UIClientScript.EncodeText(obj.Published));
if (!string.IsNullOrEmpty(obj.Summary))
objectPropertyList.Add("summary: " + UIClientScript.EncodeText(obj.Summary));
if (!string.IsNullOrEmpty(obj.Title))
objectPropertyList.Add("title: " + UIClientScript.EncodeText(obj.Title));
if (!string.IsNullOrEmpty(obj.Updated))
objectPropertyList.Add("updated: " + UIClientScript.EncodeText(obj.Updated));
if (!string.IsNullOrEmpty(obj.Url))
objectPropertyList.Add("url: " + UIClientScript.EncodeText(obj.Url));
//
b.Append(string.Join(",", objectPropertyList.ToArray()));
b.Append("}");
return b.ToString();
}
public static string SerializeObjectMetaToJsonString(ShareThisObjectMeta objMeta, bool hasButton)
{
var b = new StringBuilder("{");
b.Append("button: " + (hasButton ? "true" : "false"));
b.AppendFormat(", embeds: {0}", UIClientScript.EncodeBool(objMeta.Embeds));
if (objMeta.OffsetLeft != 0)
b.AppendFormat(", offsetLeft: {0}", UIClientScript.EncodeInt32(objMeta.OffsetLeft));
if (objMeta.OffsetTop != 0)
b.AppendFormat(", offsetTop: {0}", UIClientScript.EncodeInt32(objMeta.OffsetTop));
if (!string.IsNullOrEmpty(objMeta.OnClientClick))
b.AppendFormat(", onclick: {0}", objMeta.OnClientClick);
b.AppendFormat(", popup: {0}", UIClientScript.EncodeBool(objMeta.Popup));
b.Append("}");
return b.ToString();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using VGAudio.Codecs.CriAdx;
using VGAudio.Codecs.CriHca;
using VGAudio.Containers.Opus;
using VGAudio.Utilities;
namespace VGAudio.Cli
{
internal static class CliArguments
{
public static Options Parse(string[] args)
{
var options = new Options();
for (int i = 0; i < args.Length; i++)
{
if (string.IsNullOrEmpty(args[i])) continue;
if (args[i][0] == '-' || args[i][0] == '/')
{
switch (args[i].Split(':')[0].Substring(1).ToUpper())
{
case "C" when i == 0:
case "-CONVERT" when i == 0:
options.Job = JobType.Convert;
continue;
case "B" when i == 0:
case "-BATCH" when i == 0:
options.Job = JobType.Batch;
continue;
case "M" when i == 0:
case "-METADATA" when i == 0:
options.Job = JobType.Metadata;
continue;
case "H" when i == 0:
case "-HELP" when i == 0:
PrintUsage();
return null;
case "-VERSION" when i == 0:
Console.WriteLine($"VGAudio v{GetProgramVersion()}");
return null;
case "I" when options.Job == JobType.Batch:
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after -i switch.");
return null;
}
options.InDir = args[i + 1];
i++;
continue;
case "I":
List<int> range = null;
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after -i switch.");
return null;
}
if (args[i].Length > 2 && args[i][2] == ':')
{
range = ParseIntRange(args[i].Substring(3));
}
options.InFiles.Add(new AudioFile { Path = args[i + 1], Channels = range });
i++;
continue;
case "O" when options.Job == JobType.Convert:
if (options.OutFiles.Count > 0)
{
PrintWithUsage("Can't set multiple outputs.");
return null;
}
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after -o switch.");
return null;
}
options.OutFiles.Add(new AudioFile { Path = args[i + 1] });
i++;
continue;
case "O" when options.Job == JobType.Batch:
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after -o switch.");
return null;
}
options.OutDir = args[i + 1];
i++;
continue;
case "R":
options.Recurse = true;
continue;
case "L":
if (options.NoLoop)
{
PrintWithUsage("Can't set loop points while using --no-loop.");
return null;
}
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after -l switch.");
return null;
}
string[] loopPoints = args[i + 1].Split('-');
if (loopPoints.Length != 2)
{
PrintWithUsage("-l switch requires two loop points in the format <start>-<end>.");
return null;
}
if (!(int.TryParse(loopPoints[0], out int loopStart) && int.TryParse(loopPoints[1], out int loopEnd)))
{
PrintWithUsage("Error parsing loop points.");
return null;
}
options.Loop = true;
options.LoopStart = loopStart;
options.LoopEnd = loopEnd;
i++;
continue;
case "-NO-LOOP":
if (options.Loop)
{
PrintWithUsage("Can't set loop points while using --no-loop.");
return null;
}
options.NoLoop = true;
continue;
case "-LOOP-ALIGN":
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after --loop-align.");
return null;
}
if (!int.TryParse(args[i + 1], out int align))
{
PrintWithUsage("Error parsing loop alignment.");
return null;
}
options.LoopAlignment = align;
i++;
continue;
case "F":
if (options.OutFormat != AudioFormat.None)
{
PrintWithUsage("Can't set multiple formats.");
return null;
}
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after -f switch.");
return null;
}
AudioFormat format = GetFormat(args[i + 1]);
if (format == AudioFormat.None)
{
PrintWithUsage("Format must be one of pcm16, pcm8, or GcAdpcm");
return null;
}
options.OutFormat = format;
i++;
continue;
case "-VERSION":
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after --version.");
return null;
}
if (!int.TryParse(args[i + 1], out int version))
{
PrintWithUsage("Error parsing version.");
return null;
}
options.Version = version;
i++;
continue;
case "-FRAMESIZE":
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after --FrameSize.");
return null;
}
if (!int.TryParse(args[i + 1], out int framesize))
{
PrintWithUsage("Error parsing frame size.");
return null;
}
options.FrameSize = framesize;
i++;
continue;
case "-FILTER":
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after --filter.");
return null;
}
if (!int.TryParse(args[i + 1], out int filter))
{
PrintWithUsage("Error parsing filter value.");
return null;
}
options.Filter = filter;
i++;
continue;
case "-ADXTYPE":
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after --AdxType.");
return null;
}
string type = args[i + 1];
CriAdxType adxType;
switch (type.ToUpper())
{
case "LINEAR":
adxType = CriAdxType.Linear;
break;
case "FIXED":
adxType = CriAdxType.Fixed;
break;
case "EXP":
case "EXPONENTIAL":
adxType = CriAdxType.Exponential;
break;
default:
Console.WriteLine("Valid ADX types are Linear, Fixed, or Exp(onential)");
return null;
}
options.AdxType = adxType;
i++;
continue;
case "-KEYSTRING":
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after --keystring.");
return null;
}
options.KeyString = args[i + 1];
i++;
continue;
case "-OUT-FORMAT":
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after --out-format.");
return null;
}
options.OutTypeName = args[i + 1];
i++;
continue;
case "-KEYCODE":
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after --keycode.");
return null;
}
if (!ulong.TryParse(args[i + 1], out ulong keycode))
{
PrintWithUsage("Error parsing key code.");
return null;
}
options.KeyCode = keycode;
i++;
continue;
case "-HCAQUALITY":
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after --hcaquality.");
return null;
}
string quality = args[i + 1];
CriHcaQuality hcaQuality;
switch (quality.ToUpper())
{
case "HIGHEST":
hcaQuality = CriHcaQuality.Highest;
break;
case "HIGH":
hcaQuality = CriHcaQuality.High;
break;
case "MIDDLE":
hcaQuality = CriHcaQuality.Middle;
break;
case "LOW":
hcaQuality = CriHcaQuality.Low;
break;
case "LOWEST":
hcaQuality = CriHcaQuality.Lowest;
break;
default:
Console.WriteLine("Valid qualities are Highest, High, Middle, Low, or Lowest.");
return null;
}
options.HcaQuality = hcaQuality;
i++;
continue;
case "-BITRATE":
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after --bitrate.");
return null;
}
if (!int.TryParse(args[i + 1], out int bitrate))
{
PrintWithUsage("Error parsing bitrate.");
return null;
}
options.Bitrate = bitrate;
i++;
continue;
case "-LIMIT-BITRATE":
options.LimitBitrate = true;
continue;
case "-BIG-ENDIAN":
options.Endianness = Endianness.BigEndian;
continue;
case "-LITTLE-ENDIAN":
options.Endianness = Endianness.LittleEndian;
continue;
case "-OPUSHEADER":
if (i + 1 >= args.Length)
{
PrintWithUsage("No argument after --OpusHeader");
return null;
}
string headerType = args[i + 1];
NxOpusHeaderType nxHeaderType;
switch (headerType.ToUpper())
{
case "STANDARD":
nxHeaderType = NxOpusHeaderType.Standard;
break;
case "NAMCO":
nxHeaderType = NxOpusHeaderType.Namco;
break;
case "KTSS":
nxHeaderType = NxOpusHeaderType.Ktss;
break;
default:
Console.WriteLine("Invalid header type");
return null;
}
options.NxOpusHeaderType = nxHeaderType;
i++;
continue;
case "-CBR":
options.EncodeCbr = true;
continue;
}
}
if (options.InFiles.Count == 0)
{
options.InFiles.Add(new AudioFile { Path = args[i] });
continue;
}
if (options.OutFiles.Count == 0)
{
options.OutFiles.Add(new AudioFile { Path = args[i] });
continue;
}
PrintWithUsage($"Unknown parameter: {args[i]}");
return null;
}
if (!ValidateFileNameAndType(options)) return null;
return options;
}
private static bool ValidateFileNameAndType(Options options)
{
if (options.Job == JobType.Batch)
{
if (string.IsNullOrWhiteSpace(options.InDir))
{
PrintWithUsage("Input directory must be specified.");
return false;
}
if (string.IsNullOrWhiteSpace(options.OutDir))
{
PrintWithUsage("Output directory must be specified.");
return false;
}
if (string.IsNullOrWhiteSpace(options.OutTypeName))
{
PrintWithUsage("Output file type must be specified.");
return false;
}
if (!ContainerTypes.Writable.ContainsKey(options.OutTypeName))
{
Console.WriteLine("Output type not available. Available types are:");
Console.WriteLine(string.Join(", ", ContainerTypes.WritableList));
return false;
}
return true;
}
if (options.InFiles.Count == 0)
{
PrintWithUsage("Input file must be specified.");
return false;
}
foreach (AudioFile file in options.InFiles)
{
if (file.Type != FileType.NotSet) continue;
FileType inferredType = GetFileTypeFromName(file.Path);
if (inferredType == FileType.NotSet)
{
PrintWithUsage("Can't infer input file type from extension.");
return false;
}
file.Type = inferredType;
}
if (options.OutFiles.Count == 0)
{
string ext = options.InFiles[0].Type != FileType.Wave ? ".wav" : ".dsp";
options.OutFiles.Add(new AudioFile { Path = Path.GetFileNameWithoutExtension(options.InFiles[0].Path) + ext });
}
foreach (AudioFile file in options.OutFiles)
{
if (file.Type != FileType.NotSet) continue;
FileType inferredType = GetFileTypeFromName(file.Path);
if (inferredType == FileType.NotSet)
{
PrintWithUsage("Can't infer output file type from extension.");
return false;
}
file.Type = inferredType;
}
return true;
}
public static FileType GetFileTypeFromName(string fileName)
{
string extension = Path.GetExtension(fileName)?.TrimStart('.').ToLower() ?? "";
ContainerTypes.Extensions.TryGetValue(extension, out FileType fileType);
return fileType;
}
private static List<int> ParseIntRange(string input)
{
var range = new List<int>();
foreach (string s in input.Split(','))
{
if (int.TryParse(s, out int num))
{
range.Add(num);
continue;
}
string[] subs = s.Split('-');
if (subs.Length > 1 &&
int.TryParse(subs[0], out int start) &&
int.TryParse(subs[1], out int end) &&
end >= start)
{
for (int i = start; i <= end; i++)
{
range.Add(i);
}
}
}
return range;
}
private static AudioFormat GetFormat(string format)
{
switch (format.ToLower())
{
case "pcm16": return AudioFormat.Pcm16;
case "pcm8": return AudioFormat.Pcm8;
case "gcadpcm": return AudioFormat.GcAdpcm;
default: return AudioFormat.None;
}
}
private static void PrintWithUsage(string toPrint)
{
Console.WriteLine(toPrint);
PrintUsage();
}
private static void PrintUsage()
{
string opusHeaderTypes = string.Join(", ", Enum.GetNames(typeof(NxOpusHeaderType)).Select(x => x));
Console.WriteLine($"Usage: {GetProgramName()} [mode] [options] infile [-i infile2...] [outfile]");
Console.WriteLine("\nAvailable Modes:");
Console.WriteLine("If no mode is specified, a single-file conversion is performed");
Console.WriteLine(" -c, --convert Single-file conversion mode");
Console.WriteLine(" -b, --batch Batch conversion mode");
Console.WriteLine(" -m, --metadata Print file metadata");
Console.WriteLine(" -h, --help Display this help and exit");
Console.WriteLine(" --version Display version information and exit");
Console.WriteLine("\nCommon Options:");
Console.WriteLine(" -i <file> Specify an input file");
Console.WriteLine(" -l <start-end> Set the start and end loop points");
Console.WriteLine(" Loop points are given in zero-indexed samples");
Console.WriteLine(" --no-loop Sets the audio to not loop");
Console.WriteLine(" -f Specify the audio format to use in the output file");
Console.WriteLine("\nConvert Options:");
Console.WriteLine(" -i:#,#-# <file> Specify an input file and the channels to use");
Console.WriteLine(" The index for channels is zero-based");
Console.WriteLine(" -o Specify the output file");
Console.WriteLine("\nBatch Options:");
Console.WriteLine(" -i <dir> Specify the input directory");
Console.WriteLine(" -o <dir> Specify the output directory");
Console.WriteLine(" -r Recurse subdirectories");
Console.WriteLine(" --out-format The file type or container to save files as");
Console.WriteLine("\nBCSTM/BFSTM Options:");
Console.WriteLine(" --little-endian Makes the output file little-endian");
Console.WriteLine(" --big-endian Makes the output file big-endian");
Console.WriteLine("\nADX Options:");
Console.WriteLine(" --adxtype The ADX encoding type to use");
Console.WriteLine(" --framesize ADPCM frame size to use for ADX files");
Console.WriteLine(" --keystring String to use for ADX type 8 encryption");
Console.WriteLine(" --keycode Number to use for ADX type 9 encryption");
Console.WriteLine(" Between 1-18446744073709551615");
Console.WriteLine(" --filter Filter to use for fixed-coefficient ADX encoding [0-3]");
Console.WriteLine(" --version # ADX header version to write [3,4]");
Console.WriteLine("\nHCA Options:");
Console.WriteLine(" --hcaquality The quality level to use for the HCA file");
Console.WriteLine(" --bitrate The bitrate in bits per second of the output HCA file");
Console.WriteLine(" --bitrate takes precedence over --hcaquality");
Console.WriteLine(" --limit-bitrate This flag sets a limit on how low the bitrate can go");
Console.WriteLine(" This limit depends on the properties of the input file");
Console.WriteLine("\nSwitch Opus Options:");
Console.WriteLine(" --bitrate The bitrate in bits per second of the output file");
Console.WriteLine(" --cbr Encode the file using a constant bitrate");
Console.WriteLine(" --opusheader The type of header to use for the generated Opus file");
Console.WriteLine(" Available types: " + opusHeaderTypes);
}
private static string GetProgramName() => Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly()?.Location ?? "");
private static string GetProgramVersion()
{
Version version = Assembly.GetEntryAssembly()?.GetName().Version ?? new Version(0, 0, 0);
return $"{version.Major}.{version.Minor}.{version.Build}";
}
}
}
| |
/* ====================================================================
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 TestCases.XWPF.UserModel
{
using System;
using NUnit.Framework;
using NPOI.OpenXmlFormats.Wordprocessing;
using System.Collections.Generic;
using NPOI.XWPF.UserModel;
/**
* Tests for XWPF Run
*/
[TestFixture]
public class TestXWPFTable
{
[SetUp]
public void SetUp()
{
/*
XWPFDocument doc = new XWPFDocument();
p = doc.CreateParagraph();
this.ctRun = CTR.Factory.NewInstance();
*/
}
[Test]
public void TestConstructor()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
XWPFTable xtab = new XWPFTable(ctTable, doc);
Assert.IsNotNull(xtab);
Assert.AreEqual(1, ctTable.SizeOfTrArray());
Assert.AreEqual(1, ctTable.GetTrArray(0).SizeOfTcArray());
Assert.IsNotNull(ctTable.GetTrArray(0).GetTcArray(0).GetPArray(0));
ctTable = new CT_Tbl();
xtab = new XWPFTable(ctTable, doc, 3, 2);
Assert.IsNotNull(xtab);
Assert.AreEqual(3, ctTable.SizeOfTrArray());
Assert.AreEqual(2, ctTable.GetTrArray(0).SizeOfTcArray());
Assert.IsNotNull(ctTable.GetTrArray(0).GetTcArray(0).GetPArray(0));
}
[Test]
public void TestTblGrid()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
CT_TblGrid cttblgrid = ctTable.AddNewTblGrid();
cttblgrid.AddNewGridCol().w = 123;
cttblgrid.AddNewGridCol().w = 321;
XWPFTable xtab = new XWPFTable(ctTable, doc);
Assert.AreEqual(123, xtab.GetCTTbl().tblGrid.gridCol[0].w);
Assert.AreEqual(321, xtab.GetCTTbl().tblGrid.gridCol[1].w);
}
[Test]
public void TestGetText()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl table = new CT_Tbl();
CT_Row row = table.AddNewTr();
CT_Tc cell = row.AddNewTc();
CT_P paragraph = cell.AddNewP();
CT_R run = paragraph.AddNewR();
CT_Text text = run.AddNewT();
text.Value = ("finally I can Write!");
XWPFTable xtab = new XWPFTable(table, doc);
Assert.AreEqual("finally I can Write!\n", xtab.Text);
}
[Test]
public void TestCreateRow()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl table = new CT_Tbl();
CT_Row r1 = table.AddNewTr();
r1.AddNewTc().AddNewP();
r1.AddNewTc().AddNewP();
CT_Row r2 = table.AddNewTr();
r2.AddNewTc().AddNewP();
r2.AddNewTc().AddNewP();
CT_Row r3 = table.AddNewTr();
r3.AddNewTc().AddNewP();
r3.AddNewTc().AddNewP();
XWPFTable xtab = new XWPFTable(table, doc);
Assert.AreEqual(3, xtab.NumberOfRows);
Assert.IsNotNull(xtab.GetRow(2));
//add a new row
xtab.CreateRow();
Assert.AreEqual(4, xtab.NumberOfRows);
//check number of cols
Assert.AreEqual(2, table.GetTrArray(0).SizeOfTcArray());
//check creation of first row
xtab = new XWPFTable(new CT_Tbl(), doc);
Assert.AreEqual(1, xtab.GetCTTbl().GetTrArray(0).SizeOfTcArray());
}
[Test]
public void TestSetGetWidth()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl table = new CT_Tbl();
table.AddNewTblPr().AddNewTblW().w = "1000";
XWPFTable xtab = new XWPFTable(table, doc);
Assert.AreEqual(1000, xtab.Width);
xtab.Width = 100;
Assert.AreEqual(100, int.Parse(table.tblPr.tblW.w));
}
[Test]
public void TestSetGetHeight()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl table = new CT_Tbl();
XWPFTable xtab = new XWPFTable(table, doc);
XWPFTableRow row = xtab.CreateRow();
row.Height = (20);
Assert.AreEqual(20, row.Height);
}
[Test]
public void TestSetGetMargins()
{
// instantiate the following class so it'll Get picked up by
// the XmlBean process and Added to the jar file. it's required
// for the following XWPFTable methods.
CT_TblCellMar ctm = new CT_TblCellMar();
Assert.IsNotNull(ctm);
// create a table
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
XWPFTable table = new XWPFTable(ctTable, doc);
// Set margins
table.SetCellMargins(50, 50, 250, 450);
// Get margin components
int t = table.CellMarginTop;
Assert.AreEqual(50, t);
int l = table.CellMarginLeft;
Assert.AreEqual(50, l);
int b = table.CellMarginBottom;
Assert.AreEqual(250, b);
int r = table.CellMarginRight;
Assert.AreEqual(450, r);
}
[Test]
public void TestSetGetHBorders()
{
// instantiate the following classes so they'll Get picked up by
// the XmlBean process and Added to the jar file. they are required
// for the following XWPFTable methods.
CT_TblBorders cttb = new CT_TblBorders();
Assert.IsNotNull(cttb);
ST_Border stb = new ST_Border();
Assert.IsNotNull(stb);
// create a table
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
XWPFTable table = new XWPFTable(ctTable, doc);
// Set inside horizontal border
table.SetInsideHBorder(NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType.SINGLE, 4, 0, "FF0000");
// Get inside horizontal border components
int s = table.InsideHBorderSize;
Assert.AreEqual(4, s);
int sp = table.InsideHBorderSpace;
Assert.AreEqual(0, sp);
String clr = table.InsideHBorderColor;
Assert.AreEqual("FF0000", clr);
NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType bt = table.InsideHBorderType;
Assert.AreEqual(NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType.SINGLE, bt);
}
[Test]
public void TestSetGetVBorders()
{
// create a table
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
XWPFTable table = new XWPFTable(ctTable, doc);
// Set inside vertical border
table.SetInsideVBorder(NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType.DOUBLE, 4, 0, "00FF00");
// Get inside vertical border components
NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType bt = table.InsideVBorderType;
Assert.AreEqual(NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType.DOUBLE, bt);
int sz = table.InsideVBorderSize;
Assert.AreEqual(4, sz);
int sp = table.InsideVBorderSpace;
Assert.AreEqual(0, sp);
String clr = table.InsideVBorderColor;
Assert.AreEqual("00FF00", clr);
}
[Test]
public void TestSetGetRowBandSize()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
XWPFTable table = new XWPFTable(ctTable, doc);
table.RowBandSize = 12;
int sz = table.RowBandSize;
Assert.AreEqual(12, sz);
}
[Test]
public void TestSetGetColBandSize()
{
XWPFDocument doc = new XWPFDocument();
CT_Tbl ctTable = new CT_Tbl();
XWPFTable table = new XWPFTable(ctTable, doc);
table.ColBandSize = 16;
int sz = table.ColBandSize;
Assert.AreEqual(16, sz);
}
[Test]
public void TestCreateTable()
{
// open an empty document
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
// create a table with 5 rows and 7 coloumns
int noRows = 5;
int noCols = 7;
XWPFTable table = doc.CreateTable(noRows, noCols);
// assert the table is empty
List<XWPFTableRow> rows = table.Rows;
Assert.AreEqual(noRows, rows.Count, "Table has less rows than requested.");
foreach (XWPFTableRow xwpfRow in rows)
{
Assert.IsNotNull(xwpfRow);
for (int i = 0; i < 7; i++)
{
XWPFTableCell xwpfCell = xwpfRow.GetCell(i);
Assert.IsNotNull(xwpfCell);
Assert.AreEqual(1, xwpfCell.Paragraphs.Count, "Empty cells should not have one paragraph.");
xwpfCell = xwpfRow.GetCell(i);
Assert.AreEqual(1, xwpfCell.Paragraphs.Count, "Calling 'getCell' must not modify cells content.");
}
}
doc.Package.Revert();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MobileTemplatedControlDesigner.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.Design.MobileControls
{
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.Design.MobileControls.Adapters;
using System.Web.UI.Design.MobileControls.Converters;
using System.Web.UI.Design.MobileControls.Util;
using System.Web.UI.MobileControls;
using System.Web.UI.MobileControls.Adapters;
using WebCtrlStyle = System.Web.UI.WebControls.Style;
using DialogResult = System.Windows.Forms.DialogResult;
[
System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand,
Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)
]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
internal abstract class MobileTemplatedControlDesigner : TemplatedControlDesigner, IMobileDesigner, IDeviceSpecificDesigner
{
#if TRACE
internal static BooleanSwitch TemplateableControlDesignerSwitch =
new BooleanSwitch("MobileTemplatedControlDesigner", "Enable TemplateableControl designer general purpose traces.");
#endif
private System.Windows.Forms.Control _header;
private MobileControl _mobileControl;
private System.Web.UI.Control _control;
private DesignerVerbCollection _designerVerbs = null;
private DeviceSpecificChoice _currentChoice = null;
private bool _containmentStatusDirty = true;
private ContainmentStatus _containmentStatus;
private IDesignerHost _host;
private IWebFormsDocumentService _iWebFormsDocumentService;
private IMobileWebFormServices _iMobileWebFormServices;
private const String _htmlString = "html";
private TemplateEditingVerb[] _templateVerbs;
private bool _templateVerbsDirty = true;
private const int _templateWidth = 275;
private static readonly String _noChoiceText =
SR.GetString(SR.DeviceFilter_NoChoice);
private static readonly String _defaultChoiceText =
SR.GetString(SR.DeviceFilter_DefaultChoice);
private static readonly String _nonHtmlSchemaErrorMessage =
SR.GetString(SR.MobileControl_NonHtmlSchemaErrorMessage);
private static readonly String _illFormedWarning =
SR.GetString(SR.TemplateFrame_IllFormedWarning);
private const String _illFormedHtml =
"<DIV style=\"font-family:tahoma;font-size:8pt; COLOR: infotext; BACKGROUND-COLOR: infobackground\">{0}</DIV>";
internal const String DefaultTemplateDeviceFilter = "__TemplateDeviceFilter__";
private const String _templateDeviceFilterPropertyName = "TemplateDeviceFilter";
private const String _appliedDeviceFiltersPropertyName = "AppliedDeviceFilters";
private const String _propertyOverridesPropertyName = "PropertyOverrides";
private const String _expressionsPropertyName = "Expressions";
private const String _defaultDeviceSpecificIdentifier = "unique";
// used by DesignerAdapterUtil.GetMaxWidthToFit
// and needs to be exposed in object model because
// custom controls may need to access the value just like
// DesignerAdapterUtil.GetMaxWidthToFit does.
public virtual int TemplateWidth
{
get
{
return _templateWidth;
}
}
public override bool AllowResize
{
get
{
// Non mobilecontrols (ie. DeviceSpecific) does not render templates, no need to resize.
// When templates are not defined, we render a read-only fixed
// size block. Once templates are defined or are being edited
// the control should allow resizing.
return InTemplateMode || (_mobileControl != null && _mobileControl.IsTemplated);
}
}
private bool AllowTemplateEditing
{
get
{
return (CurrentChoice != null && IsHTMLSchema(CurrentChoice) && !ErrorMode);
}
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Editor(typeof(AppliedDeviceFiltersTypeEditor), typeof(UITypeEditor)),
MergableProperty(false),
MobileCategory("Category_DeviceSpecific"),
MobileSysDescription(SR.MobileControl_AppliedDeviceFiltersDescription),
ParenthesizePropertyName(true),
]
protected String AppliedDeviceFilters
{
get
{
return String.Empty;
}
}
protected ContainmentStatus ContainmentStatus
{
get
{
if (!_containmentStatusDirty)
{
return _containmentStatus;
}
_containmentStatus =
DesignerAdapterUtil.GetContainmentStatus(_control);
_containmentStatusDirty = false;
return _containmentStatus;
}
}
public DeviceSpecificChoice CurrentChoice
{
get
{
return _currentChoice;
}
set
{
if (_currentChoice != value)
{
SetTemplateVerbsDirty();
_currentChoice = value;
OnCurrentChoiceChange();
}
}
}
public virtual DeviceSpecific CurrentDeviceSpecific
{
get
{
if (null == _mobileControl)
{
return null;
}
return _mobileControl.DeviceSpecific;
}
}
internal Object DesignTimeElementInternal
{
get
{
return typeof(HtmlControlDesigner).InvokeMember("DesignTimeElement",
BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.NonPublic,
null, this, null, CultureInfo.InvariantCulture);
}
}
public override bool DesignTimeHtmlRequiresLoadComplete
{
get
{
return true;
}
}
//
// Return true only when GetErrorMessage returns non-null string and
// it is not info mode (warning only).
protected virtual bool ErrorMode
{
get
{
bool infoMode;
return (GetErrorMessage(out infoMode) != null && !infoMode);
}
}
protected IDesignerHost Host
{
get
{
if (_host != null)
{
return _host;
}
_host = (IDesignerHost)GetService(typeof(IDesignerHost));
Debug.Assert(_host != null);
return _host;
}
}
protected IMobileWebFormServices IMobileWebFormServices
{
get
{
if (_iMobileWebFormServices == null)
{
_iMobileWebFormServices =
(IMobileWebFormServices)GetService(typeof(IMobileWebFormServices));
}
return _iMobileWebFormServices;
}
}
private IWebFormsDocumentService IWebFormsDocumentService
{
get
{
if (_iWebFormsDocumentService == null)
{
_iWebFormsDocumentService =
(IWebFormsDocumentService)GetService(typeof(IWebFormsDocumentService));
Debug.Assert(_iWebFormsDocumentService != null);
}
return _iWebFormsDocumentService;
}
}
/// <summary>
/// Indicates whether the initial page load is completed
/// </summary>
protected bool LoadComplete
{
get
{
return !IWebFormsDocumentService.IsLoading;
}
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Editor(typeof(PropertyOverridesTypeEditor), typeof(UITypeEditor)),
MergableProperty(false),
MobileCategory("Category_DeviceSpecific"),
MobileSysDescription(SR.MobileControl_DeviceSpecificPropsDescription),
ParenthesizePropertyName(true),
]
protected String PropertyOverrides
{
get
{
return String.Empty;
}
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
MobileSysDescription(SR.TemplateableDesigner_TemplateChoiceDescription),
TypeConverter(typeof(ChoiceConverter)),
]
public String TemplateDeviceFilter
{
get
{
if (null == CurrentChoice)
{
return _noChoiceText;
}
if (CurrentChoice.Filter.Length == 0)
{
return _defaultChoiceText;
}
else
{
return DesignerUtility.ChoiceToUniqueIdentifier(CurrentChoice);
}
}
set
{
if (String.IsNullOrEmpty(value) ||
value.Equals(SR.GetString(SR.DeviceFilter_NoChoice)))
{
CurrentChoice = null;
return;
}
if (null == CurrentDeviceSpecific)
{
return;
}
Debug.Assert(CurrentDeviceSpecific.Choices != null);
foreach (DeviceSpecificChoice choice in CurrentDeviceSpecific.Choices)
{
if (DesignerUtility.ChoiceToUniqueIdentifier(choice).Equals(value) ||
(choice.Filter.Length == 0 &&
value.Equals(SR.GetString(SR.DeviceFilter_DefaultChoice))))
{
CurrentChoice = choice;
return;
}
}
CurrentChoice = null;
}
}
private bool ValidContainment
{
get
{
return (ContainmentStatus == ContainmentStatus.InForm ||
ContainmentStatus == ContainmentStatus.InPanel ||
ContainmentStatus == ContainmentStatus.InTemplateFrame);
}
}
public override DesignerVerbCollection Verbs
{
get
{
if (_designerVerbs == null)
{
_designerVerbs = new DesignerVerbCollection();
_designerVerbs.Add(new DesignerVerb(
SR.GetString(SR.TemplateableDesigner_SetTemplatesFilterVerb),
new EventHandler(this.OnSetTemplatesFilterVerb)));
}
_designerVerbs[0].Enabled = !this.InTemplateMode;
return _designerVerbs;
}
}
protected WebCtrlStyle WebCtrlStyle
{
get
{
WebCtrlStyle style = new WebCtrlStyle();
if (_mobileControl != null)
{
_mobileControl.Style.ApplyTo(style);
}
else
{
Debug.Assert(_control is DeviceSpecific);
if (_control.Parent is Panel)
{
((Panel)_control.Parent).Style.ApplyTo(style);
}
}
return style;
}
}
[
Conditional("DEBUG")
]
private void CheckTemplateName(String templateName)
{
Debug.Assert (
templateName == Constants.HeaderTemplateTag ||
templateName == Constants.FooterTemplateTag ||
templateName == Constants.ItemTemplateTag ||
templateName == Constants.AlternatingItemTemplateTag ||
templateName == Constants.SeparatorTemplateTag ||
templateName == Constants.ItemDetailsTemplateTag ||
templateName == Constants.ContentTemplateTag);
}
protected override ITemplateEditingFrame CreateTemplateEditingFrame(TemplateEditingVerb verb)
{
ITemplateEditingService teService =
(ITemplateEditingService)GetService(typeof(ITemplateEditingService));
Debug.Assert(teService != null,
"How did we get this far without an ITemplateEditingService");
String[] templateNames = GetTemplateFrameNames(verb.Index);
ITemplateEditingFrame editingFrame = teService.CreateFrame(
this,
TemplateDeviceFilter,
templateNames,
WebCtrlStyle,
null /* we don't have template styles */);
editingFrame.InitialWidth = _templateWidth;
return editingFrame;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
DisposeTemplateVerbs();
if (IMobileWebFormServices != null)
{
// If the page is in loading mode, it means the remove is trigged by webformdesigner.
if (IWebFormsDocumentService.IsLoading)
{
IMobileWebFormServices.SetCache(_control.ID, (Object) DefaultTemplateDeviceFilter, (Object) this.TemplateDeviceFilter);
}
else
{
// setting to null will remove the entry.
IMobileWebFormServices.SetCache(_control.ID, (Object) DefaultTemplateDeviceFilter, null);
}
}
}
base.Dispose(disposing);
}
public override void OnComponentChanged(Object sender, ComponentChangedEventArgs ce)
{
base.OnComponentChanged(sender, ce);
MemberDescriptor member = ce.Member;
if (member != null &&
member.GetType().FullName.Equals(Constants.ReflectPropertyDescriptorTypeFullName))
{
PropertyDescriptor propDesc = (PropertyDescriptor)member;
switch (propDesc.Name)
{
case "ID":
{
// Update the dictionary of device filters stored in the page designer
// setting to null will remove the entry.
IMobileWebFormServices.SetCache(ce.OldValue.ToString(), (Object) DefaultTemplateDeviceFilter, null);
break;
}
case "BackColor":
case "ForeColor":
case "Font":
case "StyleReference":
{
SetTemplateVerbsDirty();
break;
}
}
}
}
private void DisposeTemplateVerbs()
{
if (_templateVerbs != null)
{
for (int i = 0; i < _templateVerbs.Length; i++)
{
_templateVerbs[i].Dispose();
}
_templateVerbs = null;
_templateVerbsDirty = true;
}
}
protected override TemplateEditingVerb[] GetCachedTemplateEditingVerbs()
{
if (ErrorMode)
{
return null;
}
// dispose template verbs during template editing would cause exiting from editing mode
// without saving.
if (_templateVerbsDirty == true && !InTemplateMode)
{
DisposeTemplateVerbs();
_templateVerbs = GetTemplateVerbs();
_templateVerbsDirty = false;
}
foreach(TemplateEditingVerb verb in _templateVerbs)
{
verb.Enabled = AllowTemplateEditing;
}
return _templateVerbs;
}
// Gets the HTML to be used for the design time representation of the control runtime.
public sealed override String GetDesignTimeHtml()
{
if (!LoadComplete)
{
return null;
}
bool infoMode;
String errorMessage = GetErrorMessage(out infoMode);
SetStyleAttributes();
if (null != errorMessage)
{
return GetDesignTimeErrorHtml(errorMessage, infoMode);
}
String designTimeHTML = null;
// This is to avoiding cascading error rendering.
try
{
designTimeHTML = GetDesignTimeNormalHtml();
}
catch (Exception ex)
{
Debug.Fail(ex.ToString());
designTimeHTML = GetDesignTimeErrorHtml(ex.Message, false);
}
return designTimeHTML;
}
protected virtual String GetDesignTimeErrorHtml(String errorMessage, bool infoMode)
{
return DesignerAdapterUtil.GetDesignTimeErrorHtml(
errorMessage, infoMode, _control, Behavior, ContainmentStatus);
}
protected virtual String GetDesignTimeNormalHtml()
{
return GetEmptyDesignTimeHtml();
}
// We sealed this method because it will never be called
// by our designers under current structure.
protected override sealed String GetErrorDesignTimeHtml(Exception e)
{
return base.GetErrorDesignTimeHtml(e);
}
protected virtual String GetErrorMessage(out bool infoMode)
{
infoMode = false;
if (!DesignerAdapterUtil.InMobileUserControl(_control))
{
if (DesignerAdapterUtil.InUserControl(_control))
{
infoMode = true;
return MobileControlDesigner._userControlWarningMessage;
}
if (!DesignerAdapterUtil.InMobilePage(_control))
{
return MobileControlDesigner._mobilePageErrorMessage;
}
if (!ValidContainment)
{
return MobileControlDesigner._formPanelContainmentErrorMessage;
}
}
if (CurrentChoice != null && !IsHTMLSchema(CurrentChoice))
{
infoMode = true;
return _nonHtmlSchemaErrorMessage;
}
// Containment is valid, return null;
return null;
}
/// <summary>
/// <para>
/// Gets the HTML to be persisted for the content present within the associated server control runtime.
/// </para>
/// </summary>
/// <returns>
/// <para>
/// Persistable Inner HTML.
/// </para>
/// </returns>
public override String GetPersistInnerHtml()
{
String persist = null;
if (InTemplateMode)
{
SaveActiveTemplateEditingFrame();
}
if (IsDirty)
{
persist = MobileControlPersister.PersistInnerProperties(Component, Host);
}
if (InTemplateMode)
{
IsDirty = true;
}
return persist;
}
public override String GetTemplateContent(
ITemplateEditingFrame editingFrame,
String templateName,
out bool allowEditing)
{
Debug.Assert(AllowTemplateEditing);
#if DEBUG
CheckTemplateName(templateName);
#endif
allowEditing = true;
ITemplate template = null;
String templateContent = String.Empty;
// Here we trust the TemplateVerbs to give valid template names
template = (ITemplate)CurrentChoice.Templates[templateName];
if (template != null)
{
templateContent = GetTextFromTemplate(template);
if (!IsCompleteHtml(templateContent))
{
allowEditing = false;
templateContent = String.Format(CultureInfo.CurrentCulture, _illFormedHtml, _illFormedWarning);
}
}
return templateContent;
}
protected abstract String[] GetTemplateFrameNames(int index);
protected abstract TemplateEditingVerb[] GetTemplateVerbs();
/// <summary>
/// <para>
/// Initializes the designer.
/// </para>
/// </summary>
/// <param name='component'>
/// The control element being designed.
/// </param>
/// <remarks>
/// <para>
/// This is called by the designer host to establish the component being
/// designed.
/// </para>
/// </remarks>
/// <seealso cref='System.ComponentModel.Design.IDesigner'/>
public override void Initialize(IComponent component)
{
Debug.Assert(component is System.Web.UI.MobileControls.MobileControl ||
component is System.Web.UI.MobileControls.DeviceSpecific,
"MobileTemplatedControlDesigner.Initialize - Invalid (Mobile) Control");
base.Initialize(component);
if (component is System.Web.UI.MobileControls.MobileControl)
{
_mobileControl = (System.Web.UI.MobileControls.MobileControl) component;
}
// else the component is a DeviceSpecific control
_control = (System.Web.UI.Control) component;
if (IMobileWebFormServices != null)
{
this.TemplateDeviceFilter = (String) IMobileWebFormServices.GetCache(_control.ID, (Object)DefaultTemplateDeviceFilter);
}
}
private bool IsCompleteHtml(String templateContent)
{
if (!String.IsNullOrEmpty(templateContent))
{
return SimpleParser.IsWellFormed(templateContent);
}
// if template is empty, it's always editable.
return true;
}
protected bool IsHTMLSchema(DeviceSpecificChoice choice)
{
Debug.Assert(choice != null);
return choice.Xmlns != null &&
choice.Xmlns.ToLower(CultureInfo.InvariantCulture).IndexOf(_htmlString, StringComparison.Ordinal) != -1;
}
// Notification that is called when current choice is changed, it is currently
// used to notify StyleSheet that template device filter is changed.
protected virtual void OnCurrentChoiceChange()
{
}
/// <summary>
/// <para>
/// Notification that is called when internal changes have been made.
/// </para>
/// </summary>
protected virtual void OnInternalChange()
{
ISite site = _control.Site;
if (site != null)
{
IComponentChangeService changeService =
(IComponentChangeService)site.GetService(typeof(IComponentChangeService));
if (changeService != null)
{
try
{
changeService.OnComponentChanging(_control, null);
}
catch (CheckoutException ex)
{
if (ex == CheckoutException.Canceled)
{
return;
}
throw;
}
changeService.OnComponentChanged(_control, null, null, null);
}
}
}
/// <summary>
/// <para>
/// Notification that is called when the associated control is parented.
/// </para>
/// </summary>
public override void OnSetParent()
{
base.OnSetParent();
// Template verbs may need to be refreshed
SetTemplateVerbsDirty();
// this needs to be set before OnLoadComplete;
_containmentStatusDirty = true;
if (LoadComplete)
{
UpdateRendering();
}
}
private void OnSetTemplatesFilterVerb(Object sender, EventArgs e)
{
ShowTemplatingOptionsDialog();
}
protected override void OnTemplateModeChanged()
{
base.OnTemplateModeChanged();
if (InTemplateMode)
{
// Set xmlns in view linked document to show HTML intrinsic
// controls in property grid with same schema used by
// Intellisense for current choice tag in HTML view.
// This code won't work in Venus now since there are no viewlinks and
// they don't support this kind of schema.
/*
NativeMethods.IHTMLElement htmlElement = (NativeMethods.IHTMLElement) ((IHtmlControlDesignerBehavior) Behavior).DesignTimeElementView;
Debug.Assert(htmlElement != null,
"Invalid HTML element in MobileTemplateControlDesigner.OnTemplateModeChanged");
NativeMethods.IHTMLDocument2 htmlDocument2 = (NativeMethods.IHTMLDocument2) htmlElement.GetDocument();
Debug.Assert(htmlDocument2 != null,
"Invalid HTML Document2 in MobileTemplateControlDesigner.OnTemplateModeChanged");
NativeMethods.IHTMLElement htmlBody = (NativeMethods.IHTMLElement) htmlDocument2.GetBody();
Debug.Assert(htmlBody != null,
"Invalid HTML Body in MobileTemplateControlDesigner.OnTemplateModeChanged");
htmlBody.SetAttribute("xmlns", (Object) CurrentChoice.Xmlns, 0);
*/
}
}
protected override void PreFilterProperties(IDictionary properties)
{
base.PreFilterProperties(properties);
// DesignTime Property only, we will use this to select choices.
properties[_templateDeviceFilterPropertyName] =
TypeDescriptor.CreateProperty(this.GetType(),
_templateDeviceFilterPropertyName,
typeof(String),
new DefaultValueAttribute(SR.GetString(SR.DeviceFilter_NoChoice)),
MobileCategoryAttribute.Design,
InTemplateMode ? BrowsableAttribute.No : BrowsableAttribute.Yes
);
// design time only entry used to display dialog box used to create choices.
properties[_appliedDeviceFiltersPropertyName] =
TypeDescriptor.CreateProperty(this.GetType(),
_appliedDeviceFiltersPropertyName,
typeof(String),
InTemplateMode? BrowsableAttribute.No : BrowsableAttribute.Yes
);
// design time only entry used to display dialog box to create choices.
properties[_propertyOverridesPropertyName] =
TypeDescriptor.CreateProperty(this.GetType(),
_propertyOverridesPropertyName,
typeof(String),
InTemplateMode? BrowsableAttribute.No : BrowsableAttribute.Yes
);
PropertyDescriptor property = (PropertyDescriptor) properties[_expressionsPropertyName];
if (property != null) {
properties[_expressionsPropertyName] = TypeDescriptor.CreateProperty(this.GetType(), property, BrowsableAttribute.No);
}
}
protected virtual void SetStyleAttributes()
{
Debug.Assert(Behavior != null);
DesignerAdapterUtil.SetStandardStyleAttributes(Behavior, ContainmentStatus);
}
public override void SetTemplateContent(
ITemplateEditingFrame editingFrame,
String templateName,
String templateContent)
{
Debug.Assert(AllowTemplateEditing);
// Debug build only checking
CheckTemplateName(templateName);
ITemplate template = null;
if ((templateContent != null) && (templateContent.Length != 0))
{
template = GetTemplateFromText(templateContent);
}
else
{
CurrentChoice.Templates.Remove(templateName);
return;
}
// Here we trust the TemplateVerbs to give valid template names
CurrentChoice.Templates[templateName] = template;
}
protected internal void SetTemplateVerbsDirty()
{
_templateVerbsDirty = true;
}
protected virtual void ShowTemplatingOptionsDialog()
{
IComponentChangeService changeService =
(IComponentChangeService)GetService(typeof(IComponentChangeService));
if (changeService != null)
{
try
{
changeService.OnComponentChanging(_control, null);
}
catch (CheckoutException ex)
{
if (ex == CheckoutException.Canceled)
{
return;
}
throw;
}
}
try
{
TemplatingOptionsDialog dialog = new TemplatingOptionsDialog(
this,
_control.Site,
MobileControlDesigner.MergingContextTemplates);
dialog.ShowDialog();
}
finally
{
if (changeService != null)
{
changeService.OnComponentChanged(_control, null, null, null);
if (IMobileWebFormServices != null)
{
IMobileWebFormServices.ClearUndoStack();
}
}
}
}
public void UpdateRendering()
{
if (!(null == _mobileControl || _mobileControl is StyleSheet))
{
_mobileControl.RefreshStyle();
}
// template editing frame need to be recreated because the style
// (WebCtrlStyle) to use may have to change
SetTemplateVerbsDirty();
if (!InTemplateMode)
{
UpdateDesignTimeHtml();
}
}
////////////////////////////////////////////////////////////////////////
// Begin IDeviceSpecificDesigner Implementation
////////////////////////////////////////////////////////////////////////
void IDeviceSpecificDesigner.SetDeviceSpecificEditor
(IRefreshableDeviceSpecificEditor editor)
{
}
String IDeviceSpecificDesigner.CurrentDeviceSpecificID
{
get
{
return _defaultDeviceSpecificIdentifier;
}
}
System.Windows.Forms.Control IDeviceSpecificDesigner.Header
{
get
{
return _header;
}
}
System.Web.UI.Control IDeviceSpecificDesigner.UnderlyingControl
{
get
{
return _control;
}
}
Object IDeviceSpecificDesigner.UnderlyingObject
{
get
{
return _control;
}
}
void IDeviceSpecificDesigner.InitHeader(int mergingContext)
{
HeaderPanel panel = new HeaderPanel();
HeaderLabel lblDescription = new HeaderLabel();
lblDescription.TabIndex = 0;
lblDescription.Height = 24;
lblDescription.Width = 204;
panel.Height = 28;
panel.Width = 204;
panel.Controls.Add(lblDescription);
switch (mergingContext)
{
case MobileControlDesigner.MergingContextTemplates:
{
lblDescription.Text = SR.GetString(SR.TemplateableDesigner_SettingTemplatingChoiceDescription);
break;
}
default:
{
lblDescription.Text = SR.GetString(SR.TemplateableDesigner_SettingGenericChoiceDescription);
break;
}
}
_header = panel;
}
void IDeviceSpecificDesigner.RefreshHeader(int mergingContext)
{
}
bool IDeviceSpecificDesigner.GetDeviceSpecific(String deviceSpecificParentID, out DeviceSpecific ds)
{
Debug.Assert(_defaultDeviceSpecificIdentifier == deviceSpecificParentID);
ds = CurrentDeviceSpecific;
return true;
}
void IDeviceSpecificDesigner.SetDeviceSpecific(String deviceSpecificParentID, DeviceSpecific ds)
{
Debug.Assert(_defaultDeviceSpecificIdentifier == deviceSpecificParentID);
if (_mobileControl != null)
{
if (null != ds)
{
ds.SetOwner(_mobileControl);
}
_mobileControl.DeviceSpecific = ds;
}
else if (_control != null && ds == null)
{
Debug.Assert(_control is DeviceSpecific);
// Clear the choices if it is a DeviceSpecific control.
((DeviceSpecific)_control).Choices.Clear();
}
if (null != CurrentChoice)
{
if (null == ds)
{
CurrentChoice = null;
}
else
{
// This makes sure that the CurrentChoice value is set to null if
// it was deleted during the deviceSpecific object editing
if (CurrentChoice.Filter.Length == 0)
{
TemplateDeviceFilter = SR.GetString(SR.DeviceFilter_DefaultChoice);
}
else
{
TemplateDeviceFilter = DesignerUtility.ChoiceToUniqueIdentifier(CurrentChoice);
}
}
}
}
void IDeviceSpecificDesigner.UseCurrentDeviceSpecificID()
{
}
////////////////////////////////////////////////////////////////////////
// End IDeviceSpecificDesigner Implementation
////////////////////////////////////////////////////////////////////////
// Hack : Internal class used to provide TemplateContainerAttribute for Templates.
[
System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand,
Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)
]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
internal class TemplateContainer
{
[
TemplateContainer(typeof(MobileListItem))
]
internal ITemplate HeaderTemplate
{
get {return null;}
}
[
TemplateContainer(typeof(MobileListItem))
]
internal ITemplate FooterTemplate
{
get {return null;}
}
[
TemplateContainer(typeof(MobileListItem))
]
internal ITemplate ItemTemplate
{
get {return null;}
}
[
TemplateContainer(typeof(MobileListItem))
]
internal ITemplate AlternatingItemTemplate
{
get {return null;}
}
[
TemplateContainer(typeof(MobileListItem))
]
internal ITemplate SeparatorTemplate
{
get {return null;}
}
[
TemplateContainer(typeof(MobileListItem))
]
internal ITemplate ContentTemplate
{
get {return null;}
}
[
TemplateContainer(typeof(MobileListItem))
]
internal ITemplate LabelTemplate
{
get {return null;}
}
[
TemplateContainer(typeof(MobileListItem))
]
internal ITemplate ItemDetailsTemplate
{
get {return null;}
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
public class Managed
{
static int failures = 0;
enum StructID
{
INNER2Id,
InnerExplicitId,
InnerArrayExplicitId,
OUTER3Id,
UId,
ByteStructPack2ExplicitId,
ShortStructPack4ExplicitId,
IntStructPack8ExplicitId,
LongStructPack16ExplicitId,
OverlappingLongFloatId,
OverlappingMultipleEightbyteId,
HFAId
}
[SecuritySafeCritical]
public static int Main()
{
RunMarshalStructAsParamAsExpByVal();
RunMarshalStructAsParamAsExpByRef();
RunMarshalStructAsParamAsExpByValIn();
RunMarshalStructAsParamAsExpByRefIn();
RunMarshalStructAsParamAsExpByValOut();
RunMarshalStructAsParamAsExpByRefOut();
RunMarshalStructAsParamAsExpByValInOut();
RunMarshalStructAsParamAsExpByRefInOut();
RunMarshalStructAsReturn();
if (failures > 0)
{
Console.WriteLine("\nTEST FAILED!");
return 100 + failures;
}
else
{
Console.WriteLine("\nTEST PASSED!");
return 100;
}
}
#region Struct with Layout Explicit scenario1
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByValINNER2(INNER2 str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefINNER2(ref INNER2 str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValINNER2")]
static extern bool MarshalStructAsParam_AsExpByValInINNER2([In] INNER2 str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefInINNER2([In] ref INNER2 str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValINNER2")]
static extern bool MarshalStructAsParam_AsExpByValOutINNER2([Out] INNER2 str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefOutINNER2(out INNER2 str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValINNER2")]
static extern bool MarshalStructAsParam_AsExpByValInOutINNER2([In, Out] INNER2 str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByRefINNER2")]
static extern bool MarshalStructAsParam_AsExpByRefInOutINNER2([In, Out] ref INNER2 str1);
#endregion
#region Struct with Layout Explicit scenario2
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValInnerExplicit")]
static extern bool MarshalStructAsParam_AsExpByValInnerExplicit(InnerExplicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByRefInnerExplicit")]
static extern bool MarshalStructAsParam_AsExpByRefInnerExplicit(ref InnerExplicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValInnerExplicit")]
static extern bool MarshalStructAsParam_AsExpByValInInnerExplicit([In] InnerExplicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByRefInInnerExplicit")]
static extern bool MarshalStructAsParam_AsExpByRefInInnerExplicit([In] ref InnerExplicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValInnerExplicit")]
static extern bool MarshalStructAsParam_AsExpByValOutInnerExplicit([Out] InnerExplicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByRefOutInnerExplicit")]
static extern bool MarshalStructAsParam_AsExpByRefOutInnerExplicit(out InnerExplicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValInnerExplicit")]
static extern bool MarshalStructAsParam_AsExpByValInOutInnerExplicit([In, Out] InnerExplicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByRefInnerExplicit")]
static extern bool MarshalStructAsParam_AsExpByRefInOutInnerExplicit([In, Out] ref InnerExplicit str1);
#endregion
#region Struct with Layout Explicit scenario3
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByValInnerArrayExplicit(InnerArrayExplicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefInnerArrayExplicit(ref InnerArrayExplicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValInnerArrayExplicit")]
static extern bool MarshalStructAsParam_AsExpByValInInnerArrayExplicit([In] InnerArrayExplicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefInInnerArrayExplicit([In] ref InnerArrayExplicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValInnerArrayExplicit")]
static extern bool MarshalStructAsParam_AsExpByValOutInnerArrayExplicit([Out] InnerArrayExplicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefOutInnerArrayExplicit(out InnerArrayExplicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValInnerArrayExplicit")]
static extern bool MarshalStructAsParam_AsExpByValInOutInnerArrayExplicit([In, Out] InnerArrayExplicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByRefInnerArrayExplicit")]
static extern bool MarshalStructAsParam_AsExpByRefInOutInnerArrayExplicit([In, Out] ref InnerArrayExplicit str1);
#endregion
#region Struct with Layout Explicit scenario4
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByValOUTER3(OUTER3 str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefOUTER3(ref OUTER3 str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValOUTER3")]
static extern bool MarshalStructAsParam_AsExpByValInOUTER3([In] OUTER3 str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefInOUTER3([In] ref OUTER3 str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValOUTER3")]
static extern bool MarshalStructAsParam_AsExpByValOutOUTER3([Out] OUTER3 str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefOutOUTER3(out OUTER3 str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValOUTER3")]
static extern bool MarshalStructAsParam_AsExpByValInOutOUTER3([In, Out] OUTER3 str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByRefOUTER3")]
static extern bool MarshalStructAsParam_AsExpByRefInOutOUTER3([In, Out] ref OUTER3 str1);
#endregion
#region Struct(U) with Layout Explicit scenario5
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByValU(U str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefU(ref U str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValU")]
static extern bool MarshalStructAsParam_AsExpByValInU([In] U str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefInU([In] ref U str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValU")]
static extern bool MarshalStructAsParam_AsExpByValOutU([Out] U str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefOutU(out U str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValU")]
static extern bool MarshalStructAsParam_AsExpByValInOutU([In, Out] U str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByRefU")]
static extern bool MarshalStructAsParam_AsExpByRefInOutU([In, Out] ref U str1);
#endregion
#region Struct(ByteStructPack2Explicit) with Layout Explicit scenario6
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByValByteStructPack2Explicit(ByteStructPack2Explicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefByteStructPack2Explicit(ref ByteStructPack2Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValByteStructPack2Explicit")]
static extern bool MarshalStructAsParam_AsExpByValInByteStructPack2Explicit([In] ByteStructPack2Explicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefInByteStructPack2Explicit([In] ref ByteStructPack2Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValByteStructPack2Explicit")]
static extern bool MarshalStructAsParam_AsExpByValOutByteStructPack2Explicit([Out] ByteStructPack2Explicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefOutByteStructPack2Explicit(out ByteStructPack2Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValByteStructPack2Explicit")]
static extern bool MarshalStructAsParam_AsExpByValInOutByteStructPack2Explicit([In, Out] ByteStructPack2Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByRefByteStructPack2Explicit")]
static extern bool MarshalStructAsParam_AsExpByRefInOutByteStructPack2Explicit([In, Out] ref ByteStructPack2Explicit str1);
#endregion
#region Struct(ShortStructPack4Explicit) with Layout Explicit scenario7
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByValShortStructPack4Explicit(ShortStructPack4Explicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefShortStructPack4Explicit(ref ShortStructPack4Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValShortStructPack4Explicit")]
static extern bool MarshalStructAsParam_AsExpByValInShortStructPack4Explicit([In] ShortStructPack4Explicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefInShortStructPack4Explicit([In] ref ShortStructPack4Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValShortStructPack4Explicit")]
static extern bool MarshalStructAsParam_AsExpByValOutShortStructPack4Explicit([Out] ShortStructPack4Explicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefOutShortStructPack4Explicit(out ShortStructPack4Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValShortStructPack4Explicit")]
static extern bool MarshalStructAsParam_AsExpByValInOutShortStructPack4Explicit([In, Out] ShortStructPack4Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByRefShortStructPack4Explicit")]
static extern bool MarshalStructAsParam_AsExpByRefInOutShortStructPack4Explicit([In, Out] ref ShortStructPack4Explicit str1);
#endregion
#region Struct(IntStructPack8Explicit) with Layout Explicit scenario8
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByValIntStructPack8Explicit(IntStructPack8Explicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefIntStructPack8Explicit(ref IntStructPack8Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValIntStructPack8Explicit")]
static extern bool MarshalStructAsParam_AsExpByValInIntStructPack8Explicit([In] IntStructPack8Explicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefInIntStructPack8Explicit([In] ref IntStructPack8Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValIntStructPack8Explicit")]
static extern bool MarshalStructAsParam_AsExpByValOutIntStructPack8Explicit([Out] IntStructPack8Explicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefOutIntStructPack8Explicit(out IntStructPack8Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValIntStructPack8Explicit")]
static extern bool MarshalStructAsParam_AsExpByValInOutIntStructPack8Explicit([In, Out] IntStructPack8Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByRefIntStructPack8Explicit")]
static extern bool MarshalStructAsParam_AsExpByRefInOutIntStructPack8Explicit([In, Out] ref IntStructPack8Explicit str1);
#endregion
#region Struct(LongStructPack16Explicit) with Layout Explicit scenario9
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByValLongStructPack16Explicit(LongStructPack16Explicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefLongStructPack16Explicit(ref LongStructPack16Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValLongStructPack16Explicit")]
static extern bool MarshalStructAsParam_AsExpByValInLongStructPack16Explicit([In] LongStructPack16Explicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefInLongStructPack16Explicit([In] ref LongStructPack16Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValLongStructPack16Explicit")]
static extern bool MarshalStructAsParam_AsExpByValOutLongStructPack16Explicit([Out] LongStructPack16Explicit str1);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByRefOutLongStructPack16Explicit(out LongStructPack16Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByValLongStructPack16Explicit")]
static extern bool MarshalStructAsParam_AsExpByValInOutLongStructPack16Explicit([In, Out] LongStructPack16Explicit str1);
[DllImport("MarshalStructAsParam", EntryPoint = "MarshalStructAsParam_AsExpByRefLongStructPack16Explicit")]
static extern bool MarshalStructAsParam_AsExpByRefInOutLongStructPack16Explicit([In, Out] ref LongStructPack16Explicit str1);
#endregion
[DllImport("MarshalStructAsParam")]
static extern LongStructPack16Explicit GetLongStruct(long l1, long l2);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByValOverlappingLongFloat(OverlappingLongFloat str, long expected);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByValOverlappingLongFloat(OverlappingLongFloat2 str, long expected);
[DllImport("MarshalStructAsParam")]
static extern bool MarshalStructAsParam_AsExpByValOverlappingMultipleEightByte(OverlappingMultipleEightbyte str, float i1, float i2, float i3);
[DllImport("MarshalStructAsParam")]
static extern float ProductHFA(ExplicitHFA hfa);
[DllImport("MarshalStructAsParam")]
static extern float ProductHFA(ExplicitFixedHFA hfa);
[DllImport("MarshalStructAsParam")]
static extern float ProductHFA(OverlappingHFA hfa);
#region Marshal Explicit struct method
[SecuritySafeCritical]
private static void MarshalStructAsParam_AsExpByVal(StructID id)
{
try
{
switch (id)
{
case StructID.INNER2Id:
INNER2 sourceINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
INNER2 cloneINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValINNER2...");
if (!MarshalStructAsParam_AsExpByValINNER2(sourceINNER2))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValINNER2.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateINNER2(sourceINNER2, cloneINNER2, "MarshalStructAsParam_AsExpByValINNER2"))
{
failures++;
}
break;
case StructID.InnerExplicitId:
InnerExplicit sourceInnerExplicit = new InnerExplicit();
sourceInnerExplicit.f1 = 1;
sourceInnerExplicit.f3 = "some string";
InnerExplicit cloneInnerExplicit = new InnerExplicit();
cloneInnerExplicit.f1 = 1;
cloneInnerExplicit.f3 = "some string";
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInnerExplicit...");
if (!MarshalStructAsParam_AsExpByValInnerExplicit(sourceInnerExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInnerExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerExplicit(sourceInnerExplicit, cloneInnerExplicit, "MarshalStructAsParam_AsExpByValInnerExplicit"))
{
failures++;
}
break;
case StructID.InnerArrayExplicitId:
InnerArrayExplicit sourceInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
InnerArrayExplicit cloneInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInnerArrayExplicit...");
if (!MarshalStructAsParam_AsExpByValInnerArrayExplicit(sourceInnerArrayExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInnerArrayExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerArrayExplicit(sourceInnerArrayExplicit, cloneInnerArrayExplicit, "MarshalStructAsParam_AsExpByValInnerArrayExplicit"))
{
failures++;
}
break;
case StructID.OUTER3Id:
OUTER3 sourceOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
OUTER3 cloneOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOUTER3...");
if (!MarshalStructAsParam_AsExpByValOUTER3(sourceOUTER3))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOUTER3.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateOUTER3(sourceOUTER3, cloneOUTER3, "MarshalStructAsParam_AsExpByValOUTER3"))
{
failures++;
}
break;
case StructID.UId:
U sourceU = Helper.NewU(Int32.MinValue, UInt32.MaxValue, new IntPtr(-32), new UIntPtr(32), short.MinValue, ushort.MaxValue, byte.MinValue, sbyte.MaxValue, long.MinValue, ulong.MaxValue, 32.0F, 3.2);
U cloneU = Helper.NewU(Int32.MinValue, UInt32.MaxValue, new IntPtr(-32), new UIntPtr(32), short.MinValue, ushort.MaxValue, byte.MinValue, sbyte.MaxValue, long.MinValue, ulong.MaxValue, 32.0F, 3.2);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValU...");
if (!MarshalStructAsParam_AsExpByValU(sourceU))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValU.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateU(sourceU, cloneU, "MarshalStructAsParam_AsExpByValU"))
{
failures++;
}
break;
case StructID.ByteStructPack2ExplicitId:
ByteStructPack2Explicit source_bspe = Helper.NewByteStructPack2Explicit(32, 32);
ByteStructPack2Explicit clone_bspe = Helper.NewByteStructPack2Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValByteStructPack2Explicit...");
if (!MarshalStructAsParam_AsExpByValByteStructPack2Explicit(source_bspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValByteStructPack2Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateByteStructPack2Explicit(source_bspe, clone_bspe, "MarshalStructAsParam_AsExpByValByteStructPack2Explicit"))
{
failures++;
}
break;
case StructID.ShortStructPack4ExplicitId:
ShortStructPack4Explicit source_sspe = Helper.NewShortStructPack4Explicit(32, 32);
ShortStructPack4Explicit clone_sspe = Helper.NewShortStructPack4Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValShortStructPack4Explicit...");
if (!MarshalStructAsParam_AsExpByValShortStructPack4Explicit(source_sspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValShortStructPack4Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateShortStructPack4Explicit(source_sspe, clone_sspe, "MarshalStructAsParam_AsExpByValShortStructPack4Explicit"))
{
failures++;
}
break;
case StructID.IntStructPack8ExplicitId:
IntStructPack8Explicit source_ispe = Helper.NewIntStructPack8Explicit(32, 32);
IntStructPack8Explicit clone_ispe = Helper.NewIntStructPack8Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValIntStructPack8Explicit...");
if (!MarshalStructAsParam_AsExpByValIntStructPack8Explicit(source_ispe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValIntStructPack8Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateIntStructPack8Explicit(source_ispe, clone_ispe, "MarshalStructAsParam_AsExpByValIntStructPack8Explicit"))
{
failures++;
}
break;
case StructID.LongStructPack16ExplicitId:
LongStructPack16Explicit sourceLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(32, 32);
LongStructPack16Explicit cloneLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValLongStructPack16Explicit...");
if (!MarshalStructAsParam_AsExpByValLongStructPack16Explicit(sourceLongStructPack16Explicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValLongStructPack16Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateLongStructPack16Explicit(sourceLongStructPack16Explicit, cloneLongStructPack16Explicit, "MarshalStructAsParam_AsExpByValLongStructPack16Explicit"))
{
failures++;
}
break;
case StructID.OverlappingLongFloatId:
OverlappingLongFloat overlappingLongFloat = new OverlappingLongFloat
{
l = 12345,
f = 12.45f
};
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOverlappingLongFloat...");
if (!MarshalStructAsParam_AsExpByValOverlappingLongFloat(overlappingLongFloat, overlappingLongFloat.l))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOverlappingLongFloat. Expected:True;Actual:False");
failures++;
}
OverlappingLongFloat2 overlappingLongFloat2 = new OverlappingLongFloat2
{
l = 12345,
f = 12.45f
};
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOverlappingLongFloat (Reversed field order)...");
if (!MarshalStructAsParam_AsExpByValOverlappingLongFloat(overlappingLongFloat2, overlappingLongFloat.l))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOverlappingLongFloat. Expected:True;Actual:False");
failures++;
}
break;
case StructID.OverlappingMultipleEightbyteId:
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOverlappingMultipleEightByte...");
OverlappingMultipleEightbyte overlappingMultipleEightbyte = new OverlappingMultipleEightbyte
{
arr = new float[3] { 1f, 400f, 623289f},
i = 1234
};
if (!MarshalStructAsParam_AsExpByValOverlappingMultipleEightByte(
overlappingMultipleEightbyte,
overlappingMultipleEightbyte.arr[0],
overlappingMultipleEightbyte.arr[1],
overlappingMultipleEightbyte.arr[2]))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOverlappingMultipleEightByte. Expected True;Actual:False");
failures++;
}
break;
case StructID.HFAId:
OverlappingHFA hfa = new OverlappingHFA
{
hfa = new HFA
{
f1 = 2.0f,
f2 = 10.5f,
f3 = 15.2f,
f4 = 0.12f
}
};
float expected = hfa.hfa.f1 * hfa.hfa.f2 * hfa.hfa.f3 * hfa.hfa.f4;
float actual;
Console.WriteLine("\tCalling ProductHFA with Explicit HFA.");
actual = ProductHFA(hfa.explicitHfa);
if (expected != actual)
{
Console.WriteLine($"\tFAILED! Expected {expected}. Actual {actual}");
failures++;
}
Console.WriteLine("\tCalling ProductHFA with Explicit Fixed HFA.");
actual = ProductHFA(hfa.explicitFixedHfa);
if (expected != actual)
{
Console.WriteLine($"\tFAILED! Expected {expected}. Actual {actual}");
failures++;
}
Console.WriteLine("\tCalling ProductHFA with Overlapping HFA.");
actual = ProductHFA(hfa);
if (expected != actual)
{
Console.WriteLine($"\tFAILED! Expected {expected}. Actual {actual}");
failures++;
}
break;
default:
Console.WriteLine("\tThere is not the struct id");
failures++;
break;
}
}
catch (Exception e)
{
Console.WriteLine("Unexpected Exception:" + e.ToString());
failures++;
}
}
[SecuritySafeCritical]
private static void MarshalStructAsParam_AsExpByRef(StructID id)
{
try
{
switch (id)
{
case StructID.INNER2Id:
INNER2 sourceINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
INNER2 changeINNER2 = Helper.NewINNER2(77, 77.0F, "changed string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefINNER2...");
if (!MarshalStructAsParam_AsExpByRefINNER2(ref sourceINNER2))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefINNER2.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateINNER2(sourceINNER2, changeINNER2, "MarshalStructAsParam_AsExpByRefINNER2"))
{
failures++;
}
break;
case StructID.InnerExplicitId:
InnerExplicit sourceInnerExplicit = new InnerExplicit();
sourceInnerExplicit.f1 = 1;
sourceInnerExplicit.f3 = "some string";
InnerExplicit changeInnerExplicit = new InnerExplicit();
changeInnerExplicit.f1 = 77;
changeInnerExplicit.f3 = "changed string";
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInnerExplicit...");
if (!MarshalStructAsParam_AsExpByRefInnerExplicit(ref sourceInnerExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInnerExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerExplicit(sourceInnerExplicit, changeInnerExplicit, "MarshalStructAsParam_AsExpByRefInnerExplicit"))
{
failures++;
}
break;
case StructID.InnerArrayExplicitId:
InnerArrayExplicit sourceInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
InnerArrayExplicit changeInnerArrayExplicit = Helper.NewInnerArrayExplicit(77, 77.0F, "change string1", "change string2");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInnerArrayExplicit...");
if (!MarshalStructAsParam_AsExpByRefInnerArrayExplicit(ref sourceInnerArrayExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInnerArrayExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerArrayExplicit(sourceInnerArrayExplicit, changeInnerArrayExplicit, "MarshalStructAsParam_AsExpByRefInnerArrayExplicit"))
{
failures++;
}
break;
case StructID.OUTER3Id:
OUTER3 sourceOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
OUTER3 changeOUTER3 = Helper.NewOUTER3(77, 77.0F, "changed string", "changed string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefOUTER3...");
if (!MarshalStructAsParam_AsExpByRefOUTER3(ref sourceOUTER3))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefOUTER3.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateOUTER3(sourceOUTER3, changeOUTER3, "MarshalStructAsParam_AsExpByRefOUTER3"))
{
failures++;
}
break;
case StructID.UId:
U sourceU = Helper.NewU(Int32.MinValue, UInt32.MaxValue, new IntPtr(-32), new UIntPtr(32), short.MinValue, ushort.MaxValue, byte.MinValue, sbyte.MaxValue, long.MinValue, ulong.MaxValue, 32.0F, 3.2);
U changeU = Helper.NewU(Int32.MaxValue, UInt32.MinValue, new IntPtr(-64), new UIntPtr(64), short.MaxValue, ushort.MinValue, byte.MaxValue, sbyte.MinValue, long.MaxValue, ulong.MinValue, 64.0F, 6.4);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefU...");
if (!MarshalStructAsParam_AsExpByRefU(ref sourceU))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefU.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateU(sourceU, changeU, "MarshalStructAsParam_AsExpByRefU"))
{
failures++;
}
break;
case StructID.ByteStructPack2ExplicitId:
ByteStructPack2Explicit source_bspe = Helper.NewByteStructPack2Explicit(32, 32);
ByteStructPack2Explicit change_bspe = Helper.NewByteStructPack2Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefByteStructPack2Explicit...");
if (!MarshalStructAsParam_AsExpByRefByteStructPack2Explicit(ref source_bspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefByteStructPack2Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateByteStructPack2Explicit(source_bspe, change_bspe, "MarshalStructAsParam_AsExpByRefByteStructPack2Explicit"))
{
failures++;
}
break;
case StructID.ShortStructPack4ExplicitId:
ShortStructPack4Explicit source_sspe = Helper.NewShortStructPack4Explicit(32, 32);
ShortStructPack4Explicit change_sspe = Helper.NewShortStructPack4Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefShortStructPack4Explicit...");
if (!MarshalStructAsParam_AsExpByRefShortStructPack4Explicit(ref source_sspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefShortStructPack4Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateShortStructPack4Explicit(source_sspe, change_sspe, "MarshalStructAsParam_AsExpByRefShortStructPack4Explicit"))
{
failures++;
}
break;
case StructID.IntStructPack8ExplicitId:
IntStructPack8Explicit source_ispe = Helper.NewIntStructPack8Explicit(32, 32);
IntStructPack8Explicit change_ispe = Helper.NewIntStructPack8Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefIntStructPack8Explicit...");
if (!MarshalStructAsParam_AsExpByRefIntStructPack8Explicit(ref source_ispe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefIntStructPack8Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateIntStructPack8Explicit(source_ispe, change_ispe, "MarshalStructAsParam_AsExpByRefIntStructPack8Explicit"))
{
failures++;
}
break;
case StructID.LongStructPack16ExplicitId:
LongStructPack16Explicit sourceLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(32, 32);
LongStructPack16Explicit changeLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefLongStructPack16Explicit...");
if (!MarshalStructAsParam_AsExpByRefLongStructPack16Explicit(ref sourceLongStructPack16Explicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefLongStructPack16Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateLongStructPack16Explicit(sourceLongStructPack16Explicit, changeLongStructPack16Explicit, "MarshalStructAsParam_AsExpByRefLongStructPack16Explicit"))
{
failures++;
}
break;
default:
Console.WriteLine("\tThere is not the struct id");
failures++;
break;
}
}
catch (Exception e)
{
Console.WriteLine("Unexpected Exception:" + e.ToString());
failures++;
}
}
[SecuritySafeCritical]
private static void MarshalStructAsParam_AsExpByValIn(StructID id)
{
try
{
switch (id)
{
case StructID.INNER2Id:
INNER2 sourceINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
INNER2 cloneINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInINNER2...");
if (!MarshalStructAsParam_AsExpByValInINNER2(sourceINNER2))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInINNER2.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateINNER2(sourceINNER2, cloneINNER2, "MarshalStructAsParam_AsExpByValInINNER2"))
{
failures++;
}
break;
case StructID.InnerExplicitId:
InnerExplicit sourceInnerExplicit = new InnerExplicit();
sourceInnerExplicit.f1 = 1;
sourceInnerExplicit.f3 = "some string";
InnerExplicit cloneInnerExplicit = new InnerExplicit();
cloneInnerExplicit.f1 = 1;
cloneInnerExplicit.f3 = "some string";
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInInnerExplicit...");
if (!MarshalStructAsParam_AsExpByValInInnerExplicit(sourceInnerExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInInnerExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerExplicit(sourceInnerExplicit, cloneInnerExplicit, "MarshalStructAsParam_AsExpByValInInnerExplicit"))
{
failures++;
}
break;
case StructID.InnerArrayExplicitId:
InnerArrayExplicit sourceInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
InnerArrayExplicit cloneInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInInnerArrayExplicit...");
if (!MarshalStructAsParam_AsExpByValInInnerArrayExplicit(sourceInnerArrayExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInInnerArrayExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerArrayExplicit(sourceInnerArrayExplicit, cloneInnerArrayExplicit, "MarshalStructAsParam_AsExpByValInInnerArrayExplicit"))
{
failures++;
}
break;
case StructID.OUTER3Id:
OUTER3 sourceOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
OUTER3 cloneOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInOUTER3...");
if (!MarshalStructAsParam_AsExpByValInOUTER3(sourceOUTER3))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInOUTER3.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateOUTER3(sourceOUTER3, cloneOUTER3, "MarshalStructAsParam_AsExpByValInOUTER3"))
{
failures++;
}
break;
case StructID.UId:
U sourceU = Helper.NewU(Int32.MinValue, UInt32.MaxValue, new IntPtr(-32), new UIntPtr(32), short.MinValue, ushort.MaxValue, byte.MinValue, sbyte.MaxValue, long.MinValue, ulong.MaxValue, 32.0F, 3.2);
U cloneU = Helper.NewU(Int32.MinValue, UInt32.MaxValue, new IntPtr(-32), new UIntPtr(32), short.MinValue, ushort.MaxValue, byte.MinValue, sbyte.MaxValue, long.MinValue, ulong.MaxValue, 32.0F, 3.2);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInU...");
if (!MarshalStructAsParam_AsExpByValInU(sourceU))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInU.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateU(sourceU, cloneU, "MarshalStructAsParam_AsExpByValInU"))
{
failures++;
}
break;
case StructID.ByteStructPack2ExplicitId:
ByteStructPack2Explicit source_bspe = Helper.NewByteStructPack2Explicit(32, 32);
ByteStructPack2Explicit clone_bspe = Helper.NewByteStructPack2Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInByteStructPack2Explicit...");
if (!MarshalStructAsParam_AsExpByValInByteStructPack2Explicit(source_bspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInByteStructPack2Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateByteStructPack2Explicit(source_bspe, clone_bspe, "MarshalStructAsParam_AsExpByValInByteStructPack2Explicit"))
{
failures++;
}
break;
case StructID.ShortStructPack4ExplicitId:
ShortStructPack4Explicit source_sspe = Helper.NewShortStructPack4Explicit(32, 32);
ShortStructPack4Explicit clone_sspe = Helper.NewShortStructPack4Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInShortStructPack4Explicit...");
if (!MarshalStructAsParam_AsExpByValInShortStructPack4Explicit(source_sspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInShortStructPack4Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateShortStructPack4Explicit(source_sspe, clone_sspe, "MarshalStructAsParam_AsExpByValInShortStructPack4Explicit"))
{
failures++;
}
break;
case StructID.IntStructPack8ExplicitId:
IntStructPack8Explicit source_ispe = Helper.NewIntStructPack8Explicit(32, 32);
IntStructPack8Explicit clone_ispe = Helper.NewIntStructPack8Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInIntStructPack8Explicit...");
if (!MarshalStructAsParam_AsExpByValInIntStructPack8Explicit(source_ispe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInIntStructPack8Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateIntStructPack8Explicit(source_ispe, clone_ispe, "MarshalStructAsParam_AsExpByValInIntStructPack8Explicit"))
{
failures++;
}
break;
case StructID.LongStructPack16ExplicitId:
LongStructPack16Explicit sourceLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(32, 32);
LongStructPack16Explicit cloneLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInLongStructPack16Explicit...");
if (!MarshalStructAsParam_AsExpByValInLongStructPack16Explicit(sourceLongStructPack16Explicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInLongStructPack16Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateLongStructPack16Explicit(sourceLongStructPack16Explicit, cloneLongStructPack16Explicit, "MarshalStructAsParam_AsExpByValInLongStructPack16Explicit"))
{
failures++;
}
break;
default:
Console.WriteLine("\tThere is not the struct id");
failures++;
break;
}
}
catch (Exception e)
{
Console.WriteLine("Unexpected Exception:" + e.ToString());
failures++;
}
}
[SecuritySafeCritical]
private static void MarshalStructAsParam_AsExpByRefIn(StructID id)
{
try
{
switch (id)
{
case StructID.INNER2Id:
INNER2 sourceINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
INNER2 changeINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInINNER2...");
if (!MarshalStructAsParam_AsExpByRefInINNER2(ref sourceINNER2))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInINNER2.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateINNER2(sourceINNER2, changeINNER2, "MarshalStructAsParam_AsExpByRefInINNER2"))
{
failures++;
}
break;
case StructID.InnerExplicitId:
InnerExplicit sourceInnerExplicit = new InnerExplicit();
sourceInnerExplicit.f1 = 1;
sourceInnerExplicit.f3 = "some string";
InnerExplicit changeInnerExplicit = new InnerExplicit();
changeInnerExplicit.f1 = 1;
changeInnerExplicit.f3 = "some string";
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInInnerExplicit...");
if (!MarshalStructAsParam_AsExpByRefInInnerExplicit(ref sourceInnerExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInInnerExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerExplicit(sourceInnerExplicit, changeInnerExplicit, "MarshalStructAsParam_AsExpByRefInInnerExplicit"))
{
failures++;
}
break;
case StructID.InnerArrayExplicitId:
InnerArrayExplicit sourceInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
InnerArrayExplicit changeInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInInnerArrayExplicit...");
if (!MarshalStructAsParam_AsExpByRefInInnerArrayExplicit(ref sourceInnerArrayExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInInnerArrayExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerArrayExplicit(sourceInnerArrayExplicit, changeInnerArrayExplicit, "MarshalStructAsParam_AsExpByRefInInnerArrayExplicit"))
{
failures++;
}
break;
case StructID.OUTER3Id:
OUTER3 sourceOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
OUTER3 changeOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInOUTER3...");
if (!MarshalStructAsParam_AsExpByRefInOUTER3(ref sourceOUTER3))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInOUTER3.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateOUTER3(sourceOUTER3, changeOUTER3, "MarshalStructAsParam_AsExpByRefInOUTER3"))
{
failures++;
}
break;
case StructID.UId:
U sourceU = Helper.NewU(Int32.MinValue, UInt32.MaxValue, new IntPtr(-32), new UIntPtr(32), short.MinValue, ushort.MaxValue, byte.MinValue, sbyte.MaxValue, long.MinValue, ulong.MaxValue, 32.0F, 3.2);
U changeU = Helper.NewU(Int32.MaxValue, UInt32.MinValue, new IntPtr(-64), new UIntPtr(64), short.MaxValue, ushort.MinValue, byte.MaxValue, sbyte.MinValue, long.MaxValue, ulong.MinValue, 64.0F, 6.4);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInU...");
if (!MarshalStructAsParam_AsExpByRefInU(ref sourceU))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInU.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateU(sourceU, changeU, "MarshalStructAsParam_AsExpByRefInU"))
{
failures++;
}
break;
case StructID.ByteStructPack2ExplicitId:
ByteStructPack2Explicit source_bspe = Helper.NewByteStructPack2Explicit(32, 32);
ByteStructPack2Explicit change_bspe = Helper.NewByteStructPack2Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInByteStructPack2Explicit...");
if (!MarshalStructAsParam_AsExpByRefInByteStructPack2Explicit(ref source_bspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInByteStructPack2Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateByteStructPack2Explicit(source_bspe, change_bspe, "MarshalStructAsParam_AsExpByRefInByteStructPack2Explicit"))
{
failures++;
}
break;
case StructID.ShortStructPack4ExplicitId:
ShortStructPack4Explicit source_sspe = Helper.NewShortStructPack4Explicit(32, 32);
ShortStructPack4Explicit change_sspe = Helper.NewShortStructPack4Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInShortStructPack4Explicit...");
if (!MarshalStructAsParam_AsExpByRefInShortStructPack4Explicit(ref source_sspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInShortStructPack4Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateShortStructPack4Explicit(source_sspe, change_sspe, "MarshalStructAsParam_AsExpByRefInShortStructPack4Explicit"))
{
failures++;
}
break;
case StructID.IntStructPack8ExplicitId:
IntStructPack8Explicit source_ispe = Helper.NewIntStructPack8Explicit(32, 32);
IntStructPack8Explicit change_ispe = Helper.NewIntStructPack8Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInIntStructPack8Explicit...");
if (!MarshalStructAsParam_AsExpByRefInIntStructPack8Explicit(ref source_ispe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInIntStructPack8Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateIntStructPack8Explicit(source_ispe, change_ispe, "MarshalStructAsParam_AsExpByRefInIntStructPack8Explicit"))
{
failures++;
}
break;
case StructID.LongStructPack16ExplicitId:
LongStructPack16Explicit sourceLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(32, 32);
LongStructPack16Explicit changeLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInLongStructPack16Explicit...");
if (!MarshalStructAsParam_AsExpByRefInLongStructPack16Explicit(ref sourceLongStructPack16Explicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInLongStructPack16Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateLongStructPack16Explicit(sourceLongStructPack16Explicit, changeLongStructPack16Explicit, "MarshalStructAsParam_AsExpByRefInLongStructPack16Explicit"))
{
failures++;
}
break;
default:
Console.WriteLine("\tThere is not the struct id");
failures++;
break;
}
}
catch (Exception e)
{
Console.WriteLine("Unexpected Exception:" + e.ToString());
failures++;
}
}
[SecuritySafeCritical]
private static void MarshalStructAsParam_AsExpByValOut(StructID id)
{
try
{
switch (id)
{
case StructID.INNER2Id:
INNER2 sourceINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
INNER2 cloneINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOutINNER2...");
if (!MarshalStructAsParam_AsExpByValOutINNER2(sourceINNER2))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOutINNER2.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateINNER2(sourceINNER2, cloneINNER2, "MarshalStructAsParam_AsExpByValOutINNER2"))
{
failures++;
}
break;
case StructID.InnerExplicitId:
InnerExplicit sourceInnerExplicit = new InnerExplicit();
sourceInnerExplicit.f1 = 1;
sourceInnerExplicit.f3 = "some string";
InnerExplicit cloneInnerExplicit = new InnerExplicit();
cloneInnerExplicit.f1 = 1;
cloneInnerExplicit.f3 = "some string";
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOutInnerExplicit...");
if (!MarshalStructAsParam_AsExpByValOutInnerExplicit(sourceInnerExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOutInnerExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerExplicit(sourceInnerExplicit, cloneInnerExplicit, "MarshalStructAsParam_AsExpByValOutInnerExplicit"))
{
failures++;
}
break;
case StructID.InnerArrayExplicitId:
InnerArrayExplicit sourceInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
InnerArrayExplicit cloneInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOutInnerArrayExplicit...");
if (!MarshalStructAsParam_AsExpByValOutInnerArrayExplicit(sourceInnerArrayExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOutInnerArrayExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerArrayExplicit(sourceInnerArrayExplicit, cloneInnerArrayExplicit, "MarshalStructAsParam_AsExpByValOutInnerArrayExplicit"))
{
failures++;
}
break;
case StructID.OUTER3Id:
OUTER3 sourceOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
OUTER3 cloneOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOutOUTER3...");
if (!MarshalStructAsParam_AsExpByValOutOUTER3(sourceOUTER3))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOutOUTER3.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateOUTER3(sourceOUTER3, cloneOUTER3, "MarshalStructAsParam_AsExpByValOutOUTER3"))
{
failures++;
}
break;
case StructID.UId:
U sourceU = Helper.NewU(Int32.MinValue, UInt32.MaxValue, new IntPtr(-32), new UIntPtr(32), short.MinValue, ushort.MaxValue, byte.MinValue, sbyte.MaxValue, long.MinValue, ulong.MaxValue, 32.0F, 3.2);
U cloneU = Helper.NewU(Int32.MinValue, UInt32.MaxValue, new IntPtr(-32), new UIntPtr(32), short.MinValue, ushort.MaxValue, byte.MinValue, sbyte.MaxValue, long.MinValue, ulong.MaxValue, 32.0F, 3.2);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOutU...");
if (!MarshalStructAsParam_AsExpByValOutU(sourceU))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOutU.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateU(sourceU, cloneU, "MarshalStructAsParam_AsExpByValOutU"))
{
failures++;
}
break;
case StructID.ByteStructPack2ExplicitId:
ByteStructPack2Explicit source_bspe = Helper.NewByteStructPack2Explicit(32, 32);
ByteStructPack2Explicit clone_bspe = Helper.NewByteStructPack2Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOutByteStructPack2Explicit...");
if (!MarshalStructAsParam_AsExpByValOutByteStructPack2Explicit(source_bspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOutByteStructPack2Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateByteStructPack2Explicit(source_bspe, clone_bspe, "MarshalStructAsParam_AsExpByValOutByteStructPack2Explicit"))
{
failures++;
}
break;
case StructID.ShortStructPack4ExplicitId:
ShortStructPack4Explicit source_sspe = Helper.NewShortStructPack4Explicit(32, 32);
ShortStructPack4Explicit clone_sspe = Helper.NewShortStructPack4Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOutShortStructPack4Explicit...");
if (!MarshalStructAsParam_AsExpByValOutShortStructPack4Explicit(source_sspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOutShortStructPack4Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateShortStructPack4Explicit(source_sspe, clone_sspe, "MarshalStructAsParam_AsExpByValOutShortStructPack4Explicit"))
{
failures++;
}
break;
case StructID.IntStructPack8ExplicitId:
IntStructPack8Explicit source_ispe = Helper.NewIntStructPack8Explicit(32, 32);
IntStructPack8Explicit clone_ispe = Helper.NewIntStructPack8Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOutIntStructPack8Explicit...");
if (!MarshalStructAsParam_AsExpByValOutIntStructPack8Explicit(source_ispe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOutIntStructPack8Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateIntStructPack8Explicit(source_ispe, clone_ispe, "MarshalStructAsParam_AsExpByValOutIntStructPack8Explicit"))
{
failures++;
}
break;
case StructID.LongStructPack16ExplicitId:
LongStructPack16Explicit sourceLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(32, 32);
LongStructPack16Explicit cloneLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValOutLongStructPack16Explicit...");
if (!MarshalStructAsParam_AsExpByValOutLongStructPack16Explicit(sourceLongStructPack16Explicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValOutLongStructPack16Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateLongStructPack16Explicit(sourceLongStructPack16Explicit, cloneLongStructPack16Explicit, "MarshalStructAsParam_AsExpByValOutLongStructPack16Explicit"))
{
failures++;
}
break;
default:
Console.WriteLine("\tThere is not the struct id");
failures++;
break;
}
}
catch (Exception e)
{
Console.WriteLine("Unexpected Exception:" + e.ToString());
failures++;
}
}
[SecuritySafeCritical]
private static void MarshalStructAsParam_AsExpByRefOut(StructID id)
{
try
{
switch (id)
{
case StructID.INNER2Id:
INNER2 sourceINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
INNER2 changeINNER2 = Helper.NewINNER2(77, 77.0F, "changed string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefOutINNER2...");
if (!MarshalStructAsParam_AsExpByRefOutINNER2(out sourceINNER2))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefOutINNER2.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateINNER2(sourceINNER2, changeINNER2, "MarshalStructAsParam_AsExpByRefOutINNER2"))
{
failures++;
}
break;
case StructID.InnerExplicitId:
InnerExplicit sourceInnerExplicit = new InnerExplicit();
sourceInnerExplicit.f1 = 1;
sourceInnerExplicit.f3 = "some string";
InnerExplicit changeInnerExplicit = new InnerExplicit();
changeInnerExplicit.f1 = 77;
changeInnerExplicit.f3 = "changed string";
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefOutInnerExplicit...");
if (!MarshalStructAsParam_AsExpByRefOutInnerExplicit(out sourceInnerExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefOutInnerExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerExplicit(sourceInnerExplicit, changeInnerExplicit, "MarshalStructAsParam_AsExpByRefOutInnerExplicit"))
{
failures++;
}
break;
case StructID.InnerArrayExplicitId:
InnerArrayExplicit sourceInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
InnerArrayExplicit changeInnerArrayExplicit = Helper.NewInnerArrayExplicit(77, 77.0F, "change string1", "change string2");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefOutInnerArrayExplicit...");
if (!MarshalStructAsParam_AsExpByRefOutInnerArrayExplicit(out sourceInnerArrayExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefOutInnerArrayExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerArrayExplicit(sourceInnerArrayExplicit, changeInnerArrayExplicit, "MarshalStructAsParam_AsExpByRefOutInnerArrayExplicit"))
{
failures++;
}
break;
case StructID.OUTER3Id:
OUTER3 sourceOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
OUTER3 changeOUTER3 = Helper.NewOUTER3(77, 77.0F, "changed string", "changed string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefOutOUTER3...");
if (!MarshalStructAsParam_AsExpByRefOutOUTER3(out sourceOUTER3))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefOutOUTER3.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateOUTER3(sourceOUTER3, changeOUTER3, "MarshalStructAsParam_AsExpByRefOutOUTER3"))
{
failures++;
}
break;
case StructID.UId:
U sourceU = Helper.NewU(Int32.MinValue, UInt32.MaxValue, new IntPtr(-32), new UIntPtr(32), short.MinValue, ushort.MaxValue, byte.MinValue, sbyte.MaxValue, long.MinValue, ulong.MaxValue, 32.0F, 3.2);
U changeU = Helper.NewU(Int32.MaxValue, UInt32.MinValue, new IntPtr(-64), new UIntPtr(64), short.MaxValue, ushort.MinValue, byte.MaxValue, sbyte.MinValue, long.MaxValue, ulong.MinValue, 64.0F, 6.4);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefOutU...");
if (!MarshalStructAsParam_AsExpByRefOutU(out sourceU))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefOutU.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateU(sourceU, changeU, "MarshalStructAsParam_AsExpByRefOutU"))
{
failures++;
}
break;
case StructID.ByteStructPack2ExplicitId:
ByteStructPack2Explicit source_bspe = Helper.NewByteStructPack2Explicit(32, 32);
ByteStructPack2Explicit change_bspe = Helper.NewByteStructPack2Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefOutByteStructPack2Explicit...");
if (!MarshalStructAsParam_AsExpByRefOutByteStructPack2Explicit(out source_bspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefOutByteStructPack2Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateByteStructPack2Explicit(source_bspe, change_bspe, "MarshalStructAsParam_AsExpByRefOutByteStructPack2Explicit"))
{
failures++;
}
break;
case StructID.ShortStructPack4ExplicitId:
ShortStructPack4Explicit source_sspe = Helper.NewShortStructPack4Explicit(32, 32);
ShortStructPack4Explicit change_sspe = Helper.NewShortStructPack4Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefOutShortStructPack4Explicit...");
if (!MarshalStructAsParam_AsExpByRefOutShortStructPack4Explicit(out source_sspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefOutShortStructPack4Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateShortStructPack4Explicit(source_sspe, change_sspe, "MarshalStructAsParam_AsExpByRefOutShortStructPack4Explicit"))
{
failures++;
}
break;
case StructID.IntStructPack8ExplicitId:
IntStructPack8Explicit source_ispe = Helper.NewIntStructPack8Explicit(32, 32);
IntStructPack8Explicit change_ispe = Helper.NewIntStructPack8Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefOutIntStructPack8Explicit...");
if (!MarshalStructAsParam_AsExpByRefOutIntStructPack8Explicit(out source_ispe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefOutIntStructPack8Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateIntStructPack8Explicit(source_ispe, change_ispe, "MarshalStructAsParam_AsExpByRefOutIntStructPack8Explicit"))
{
failures++;
}
break;
case StructID.LongStructPack16ExplicitId:
LongStructPack16Explicit sourceLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(32, 32);
LongStructPack16Explicit changeLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefOutLongStructPack16Explicit...");
if (!MarshalStructAsParam_AsExpByRefOutLongStructPack16Explicit(out sourceLongStructPack16Explicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefOutLongStructPack16Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateLongStructPack16Explicit(sourceLongStructPack16Explicit, changeLongStructPack16Explicit, "MarshalStructAsParam_AsExpByRefOutLongStructPack16Explicit"))
{
failures++;
}
break;
default:
Console.WriteLine("\tThere is not the struct id");
failures++;
break;
}
}
catch (Exception e)
{
Console.WriteLine("Unexpected Exception:" + e.ToString());
failures++;
}
}
[SecuritySafeCritical]
private static void MarshalStructAsParam_AsExpByValInOut(StructID id)
{
try
{
switch (id)
{
case StructID.INNER2Id:
INNER2 sourceINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
INNER2 cloneINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInOutINNER2...");
if (!MarshalStructAsParam_AsExpByValInOutINNER2(sourceINNER2))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInOutINNER2.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateINNER2(sourceINNER2, cloneINNER2, "MarshalStructAsParam_AsExpByValInOutINNER2"))
{
failures++;
}
break;
case StructID.InnerExplicitId:
InnerExplicit sourceInnerExplicit = new InnerExplicit();
sourceInnerExplicit.f1 = 1;
sourceInnerExplicit.f3 = "some string";
InnerExplicit cloneInnerExplicit = new InnerExplicit();
cloneInnerExplicit.f1 = 1;
cloneInnerExplicit.f3 = "some string";
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInOutInnerExplicit...");
if (!MarshalStructAsParam_AsExpByValInOutInnerExplicit(sourceInnerExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInOutInnerExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerExplicit(sourceInnerExplicit, cloneInnerExplicit, "MarshalStructAsParam_AsExpByValInOutInnerExplicit"))
{
failures++;
}
break;
case StructID.InnerArrayExplicitId:
InnerArrayExplicit sourceInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
InnerArrayExplicit cloneInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInOutInnerArrayExplicit...");
if (!MarshalStructAsParam_AsExpByValInOutInnerArrayExplicit(sourceInnerArrayExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInOutInnerArrayExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerArrayExplicit(sourceInnerArrayExplicit, cloneInnerArrayExplicit, "MarshalStructAsParam_AsExpByValInOutInnerArrayExplicit"))
{
failures++;
}
break;
case StructID.OUTER3Id:
OUTER3 sourceOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
OUTER3 cloneOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInOutOUTER3...");
if (!MarshalStructAsParam_AsExpByValInOutOUTER3(sourceOUTER3))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInOutOUTER3.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateOUTER3(sourceOUTER3, cloneOUTER3, "MarshalStructAsParam_AsExpByValInOutOUTER3"))
{
failures++;
}
break;
case StructID.UId:
U sourceU = Helper.NewU(Int32.MinValue, UInt32.MaxValue, new IntPtr(-32), new UIntPtr(32), short.MinValue, ushort.MaxValue, byte.MinValue, sbyte.MaxValue, long.MinValue, ulong.MaxValue, 32.0F, 3.2);
U cloneU = Helper.NewU(Int32.MinValue, UInt32.MaxValue, new IntPtr(-32), new UIntPtr(32), short.MinValue, ushort.MaxValue, byte.MinValue, sbyte.MaxValue, long.MinValue, ulong.MaxValue, 32.0F, 3.2);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInOutU...");
if (!MarshalStructAsParam_AsExpByValInOutU(sourceU))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInOutU.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateU(sourceU, cloneU, "MarshalStructAsParam_AsExpByValInOutU"))
{
failures++;
}
break;
case StructID.ByteStructPack2ExplicitId:
ByteStructPack2Explicit source_bspe = Helper.NewByteStructPack2Explicit(32, 32);
ByteStructPack2Explicit clone_bspe = Helper.NewByteStructPack2Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInOutByteStructPack2Explicit...");
if (!MarshalStructAsParam_AsExpByValInOutByteStructPack2Explicit(source_bspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInOutByteStructPack2Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateByteStructPack2Explicit(source_bspe, clone_bspe, "MarshalStructAsParam_AsExpByValInOutByteStructPack2Explicit"))
{
failures++;
}
break;
case StructID.ShortStructPack4ExplicitId:
ShortStructPack4Explicit source_sspe = Helper.NewShortStructPack4Explicit(32, 32);
ShortStructPack4Explicit clone_sspe = Helper.NewShortStructPack4Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInOutShortStructPack4Explicit...");
if (!MarshalStructAsParam_AsExpByValInOutShortStructPack4Explicit(source_sspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInOutShortStructPack4Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateShortStructPack4Explicit(source_sspe, clone_sspe, "MarshalStructAsParam_AsExpByValInOutShortStructPack4Explicit"))
{
failures++;
}
break;
case StructID.IntStructPack8ExplicitId:
IntStructPack8Explicit source_ispe = Helper.NewIntStructPack8Explicit(32, 32);
IntStructPack8Explicit clone_ispe = Helper.NewIntStructPack8Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInOutIntStructPack8Explicit...");
if (!MarshalStructAsParam_AsExpByValInOutIntStructPack8Explicit(source_ispe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInOutIntStructPack8Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateIntStructPack8Explicit(source_ispe, clone_ispe, "MarshalStructAsParam_AsExpByValInOutIntStructPack8Explicit"))
{
failures++;
}
break;
case StructID.LongStructPack16ExplicitId:
LongStructPack16Explicit sourceLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(32, 32);
LongStructPack16Explicit cloneLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(32, 32);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByValInOutLongStructPack16Explicit...");
if (!MarshalStructAsParam_AsExpByValInOutLongStructPack16Explicit(sourceLongStructPack16Explicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByValInOutLongStructPack16Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateLongStructPack16Explicit(sourceLongStructPack16Explicit, cloneLongStructPack16Explicit, "MarshalStructAsParam_AsExpByValInOutLongStructPack16Explicit"))
{
failures++;
}
break;
default:
Console.WriteLine("\tThere is not the struct id");
failures++;
break;
}
}
catch (Exception e)
{
Console.WriteLine("Unexpected Exception:" + e.ToString());
failures++;
}
}
[SecuritySafeCritical]
private static void MarshalStructAsParam_AsExpByRefInOut(StructID id)
{
try
{
switch (id)
{
case StructID.INNER2Id:
INNER2 sourceINNER2 = Helper.NewINNER2(1, 1.0F, "some string");
INNER2 changeINNER2 = Helper.NewINNER2(77, 77.0F, "changed string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInOutINNER2...");
if (!MarshalStructAsParam_AsExpByRefInOutINNER2(ref sourceINNER2))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInOutINNER2.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateINNER2(sourceINNER2, changeINNER2, "MarshalStructAsParam_AsExpByRefInOutINNER2"))
{
failures++;
}
break;
case StructID.InnerExplicitId:
InnerExplicit sourceInnerExplicit = new InnerExplicit();
sourceInnerExplicit.f1 = 1;
sourceInnerExplicit.f3 = "some string";
InnerExplicit changeInnerExplicit = new InnerExplicit();
changeInnerExplicit.f1 = 77;
changeInnerExplicit.f3 = "changed string";
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInOutInnerExplicit...");
if (!MarshalStructAsParam_AsExpByRefInOutInnerExplicit(ref sourceInnerExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInOutInnerExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerExplicit(sourceInnerExplicit, changeInnerExplicit, "MarshalStructAsParam_AsExpByRefInOutInnerExplicit"))
{
failures++;
}
break;
case StructID.InnerArrayExplicitId:
InnerArrayExplicit sourceInnerArrayExplicit = Helper.NewInnerArrayExplicit(1, 1.0F, "some string1", "some string2");
InnerArrayExplicit changeInnerArrayExplicit = Helper.NewInnerArrayExplicit(77, 77.0F, "change string1", "change string2");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInOutInnerArrayExplicit...");
if (!MarshalStructAsParam_AsExpByRefInOutInnerArrayExplicit(ref sourceInnerArrayExplicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInOutInnerArrayExplicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateInnerArrayExplicit(sourceInnerArrayExplicit, changeInnerArrayExplicit, "MarshalStructAsParam_AsExpByRefInOutInnerArrayExplicit"))
{
failures++;
}
break;
case StructID.OUTER3Id:
OUTER3 sourceOUTER3 = Helper.NewOUTER3(1, 1.0F, "some string", "some string");
OUTER3 changeOUTER3 = Helper.NewOUTER3(77, 77.0F, "changed string", "changed string");
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInOutOUTER3...");
if (!MarshalStructAsParam_AsExpByRefInOutOUTER3(ref sourceOUTER3))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInOutOUTER3.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateOUTER3(sourceOUTER3, changeOUTER3, "MarshalStructAsParam_AsExpByRefInOutOUTER3"))
{
failures++;
}
break;
case StructID.UId:
U sourceU = Helper.NewU(Int32.MinValue, UInt32.MaxValue, new IntPtr(-32), new UIntPtr(32), short.MinValue, ushort.MaxValue, byte.MinValue, sbyte.MaxValue, long.MinValue, ulong.MaxValue, 32.0F, 3.2);
U changeU = Helper.NewU(Int32.MaxValue, UInt32.MinValue, new IntPtr(-64), new UIntPtr(64), short.MaxValue, ushort.MinValue, byte.MaxValue, sbyte.MinValue, long.MaxValue, ulong.MinValue, 64.0F, 6.4);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInOutU...");
if (!MarshalStructAsParam_AsExpByRefInOutU(ref sourceU))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInOutU.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateU(sourceU, changeU, "MarshalStructAsParam_AsExpByRefInOutU"))
{
failures++;
}
break;
case StructID.ByteStructPack2ExplicitId:
ByteStructPack2Explicit source_bspe = Helper.NewByteStructPack2Explicit(32, 32);
ByteStructPack2Explicit change_bspe = Helper.NewByteStructPack2Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInOutByteStructPack2Explicit...");
if (!MarshalStructAsParam_AsExpByRefInOutByteStructPack2Explicit(ref source_bspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInOutByteStructPack2Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateByteStructPack2Explicit(source_bspe, change_bspe, "MarshalStructAsParam_AsExpByRefInOutByteStructPack2Explicit"))
{
failures++;
}
break;
case StructID.ShortStructPack4ExplicitId:
ShortStructPack4Explicit source_sspe = Helper.NewShortStructPack4Explicit(32, 32);
ShortStructPack4Explicit change_sspe = Helper.NewShortStructPack4Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInOutShortStructPack4Explicit...");
if (!MarshalStructAsParam_AsExpByRefInOutShortStructPack4Explicit(ref source_sspe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInOutShortStructPack4Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateShortStructPack4Explicit(source_sspe, change_sspe, "MarshalStructAsParam_AsExpByRefInOutShortStructPack4Explicit"))
{
failures++;
}
break;
case StructID.IntStructPack8ExplicitId:
IntStructPack8Explicit source_ispe = Helper.NewIntStructPack8Explicit(32, 32);
IntStructPack8Explicit change_ispe = Helper.NewIntStructPack8Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInOutIntStructPack8Explicit...");
if (!MarshalStructAsParam_AsExpByRefInOutIntStructPack8Explicit(ref source_ispe))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInOutIntStructPack8Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateIntStructPack8Explicit(source_ispe, change_ispe, "MarshalStructAsParam_AsExpByRefInOutIntStructPack8Explicit"))
{
failures++;
}
break;
case StructID.LongStructPack16ExplicitId:
LongStructPack16Explicit sourceLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(32, 32);
LongStructPack16Explicit changeLongStructPack16Explicit = Helper.NewLongStructPack16Explicit(64, 64);
Console.WriteLine("\tCalling MarshalStructAsParam_AsExpByRefInOutLongStructPack16Explicit...");
if (!MarshalStructAsParam_AsExpByRefInOutLongStructPack16Explicit(ref sourceLongStructPack16Explicit))
{
Console.WriteLine("\tFAILED! Managed to Native failed in MarshalStructAsParam_AsExpByRefInOutLongStructPack16Explicit.Expected:True;Actual:False");
failures++;
}
if (!Helper.ValidateLongStructPack16Explicit(sourceLongStructPack16Explicit, changeLongStructPack16Explicit, "MarshalStructAsParam_AsExpByRefInOutLongStructPack16Explicit"))
{
failures++;
}
break;
default:
Console.WriteLine("\tThere is not the struct id");
failures++;
break;
}
}
catch (Exception e)
{
Console.WriteLine("Unexpected Exception:" + e.ToString());
failures++;
}
}
#endregion
[SecuritySafeCritical]
private static void RunMarshalStructAsParamAsExpByVal()
{
Console.WriteLine("\nVerify marshal Explicit layout struct as param as ByVal");
MarshalStructAsParam_AsExpByVal(StructID.INNER2Id);
MarshalStructAsParam_AsExpByVal(StructID.InnerExplicitId);
MarshalStructAsParam_AsExpByVal(StructID.InnerArrayExplicitId);
MarshalStructAsParam_AsExpByVal(StructID.OUTER3Id);
MarshalStructAsParam_AsExpByVal(StructID.UId);
MarshalStructAsParam_AsExpByVal(StructID.ByteStructPack2ExplicitId);
MarshalStructAsParam_AsExpByVal(StructID.ShortStructPack4ExplicitId);
MarshalStructAsParam_AsExpByVal(StructID.IntStructPack8ExplicitId);
MarshalStructAsParam_AsExpByVal(StructID.LongStructPack16ExplicitId);
MarshalStructAsParam_AsExpByVal(StructID.OverlappingLongFloatId);
MarshalStructAsParam_AsExpByVal(StructID.OverlappingMultipleEightbyteId);
MarshalStructAsParam_AsExpByVal(StructID.HFAId);
}
[SecuritySafeCritical]
private static void RunMarshalStructAsParamAsExpByRef()
{
Console.WriteLine("\nVerify marshal Explicit layout struct as param as ByRef");
MarshalStructAsParam_AsExpByRef(StructID.INNER2Id);
MarshalStructAsParam_AsExpByRef(StructID.InnerExplicitId);
MarshalStructAsParam_AsExpByRef(StructID.InnerArrayExplicitId);
MarshalStructAsParam_AsExpByRef(StructID.OUTER3Id);
MarshalStructAsParam_AsExpByRef(StructID.UId);
MarshalStructAsParam_AsExpByRef(StructID.ByteStructPack2ExplicitId);
MarshalStructAsParam_AsExpByRef(StructID.ShortStructPack4ExplicitId);
MarshalStructAsParam_AsExpByRef(StructID.IntStructPack8ExplicitId);
MarshalStructAsParam_AsExpByRef(StructID.LongStructPack16ExplicitId);
}
[SecuritySafeCritical]
private static void RunMarshalStructAsParamAsExpByValIn()
{
Console.WriteLine("\nVerify marshal Explicit layout struct as param as ByValIn");
MarshalStructAsParam_AsExpByValIn(StructID.INNER2Id);
MarshalStructAsParam_AsExpByValIn(StructID.InnerExplicitId);
MarshalStructAsParam_AsExpByValIn(StructID.InnerArrayExplicitId);
MarshalStructAsParam_AsExpByValIn(StructID.OUTER3Id);
MarshalStructAsParam_AsExpByValIn(StructID.UId);
MarshalStructAsParam_AsExpByValIn(StructID.ByteStructPack2ExplicitId);
MarshalStructAsParam_AsExpByValIn(StructID.ShortStructPack4ExplicitId);
MarshalStructAsParam_AsExpByValIn(StructID.IntStructPack8ExplicitId);
MarshalStructAsParam_AsExpByValIn(StructID.LongStructPack16ExplicitId);
}
[SecuritySafeCritical]
private static void RunMarshalStructAsParamAsExpByRefIn()
{
Console.WriteLine("\nVerify marshal Explicit layout struct as param as ByRefIn");
MarshalStructAsParam_AsExpByRefIn(StructID.INNER2Id);
MarshalStructAsParam_AsExpByRefIn(StructID.InnerExplicitId);
MarshalStructAsParam_AsExpByRefIn(StructID.InnerArrayExplicitId);
MarshalStructAsParam_AsExpByRefIn(StructID.OUTER3Id);
MarshalStructAsParam_AsExpByRefIn(StructID.UId);
MarshalStructAsParam_AsExpByRefIn(StructID.ByteStructPack2ExplicitId);
MarshalStructAsParam_AsExpByRefIn(StructID.ShortStructPack4ExplicitId);
MarshalStructAsParam_AsExpByRefIn(StructID.IntStructPack8ExplicitId);
MarshalStructAsParam_AsExpByRefIn(StructID.LongStructPack16ExplicitId);
}
[SecuritySafeCritical]
private static void RunMarshalStructAsParamAsExpByValOut()
{
Console.WriteLine("\nVerify marshal Explicit layout struct as param as ByValOut");
MarshalStructAsParam_AsExpByValOut(StructID.INNER2Id);
MarshalStructAsParam_AsExpByValOut(StructID.InnerExplicitId);
MarshalStructAsParam_AsExpByValOut(StructID.InnerArrayExplicitId);
MarshalStructAsParam_AsExpByValOut(StructID.OUTER3Id);
MarshalStructAsParam_AsExpByValOut(StructID.UId);
MarshalStructAsParam_AsExpByValOut(StructID.ByteStructPack2ExplicitId);
MarshalStructAsParam_AsExpByValOut(StructID.ShortStructPack4ExplicitId);
MarshalStructAsParam_AsExpByValOut(StructID.IntStructPack8ExplicitId);
MarshalStructAsParam_AsExpByValOut(StructID.LongStructPack16ExplicitId);
}
[SecuritySafeCritical]
private static void RunMarshalStructAsParamAsExpByRefOut()
{
Console.WriteLine("\nVerify marshal Explicit layout struct as param as ByRefOut");
MarshalStructAsParam_AsExpByRefOut(StructID.INNER2Id);
MarshalStructAsParam_AsExpByRefOut(StructID.InnerExplicitId);
MarshalStructAsParam_AsExpByRefOut(StructID.InnerArrayExplicitId);
MarshalStructAsParam_AsExpByRefOut(StructID.OUTER3Id);
MarshalStructAsParam_AsExpByRefOut(StructID.UId);
MarshalStructAsParam_AsExpByRefOut(StructID.ByteStructPack2ExplicitId);
MarshalStructAsParam_AsExpByRefOut(StructID.ShortStructPack4ExplicitId);
MarshalStructAsParam_AsExpByRefOut(StructID.IntStructPack8ExplicitId);
MarshalStructAsParam_AsExpByRefOut(StructID.LongStructPack16ExplicitId);
}
[SecuritySafeCritical]
private static void RunMarshalStructAsParamAsExpByValInOut()
{
Console.WriteLine("\nVerify marshal Explicit layout struct as param as ByValInOut");
MarshalStructAsParam_AsExpByValInOut(StructID.INNER2Id);
MarshalStructAsParam_AsExpByValInOut(StructID.InnerExplicitId);
MarshalStructAsParam_AsExpByValInOut(StructID.InnerArrayExplicitId);
MarshalStructAsParam_AsExpByValInOut(StructID.OUTER3Id);
MarshalStructAsParam_AsExpByValInOut(StructID.UId);
MarshalStructAsParam_AsExpByValInOut(StructID.ByteStructPack2ExplicitId);
MarshalStructAsParam_AsExpByValInOut(StructID.ShortStructPack4ExplicitId);
MarshalStructAsParam_AsExpByValInOut(StructID.IntStructPack8ExplicitId);
MarshalStructAsParam_AsExpByValInOut(StructID.LongStructPack16ExplicitId);
}
[SecuritySafeCritical]
private static void RunMarshalStructAsParamAsExpByRefInOut()
{
Console.WriteLine("\nVerify marshal Explicit layout struct as param as ByRefInOut");
MarshalStructAsParam_AsExpByRefInOut(StructID.INNER2Id);
MarshalStructAsParam_AsExpByRefInOut(StructID.InnerExplicitId);
MarshalStructAsParam_AsExpByRefInOut(StructID.InnerArrayExplicitId);
MarshalStructAsParam_AsExpByRefInOut(StructID.OUTER3Id);
MarshalStructAsParam_AsExpByRefInOut(StructID.UId);
MarshalStructAsParam_AsExpByRefInOut(StructID.ByteStructPack2ExplicitId);
MarshalStructAsParam_AsExpByRefInOut(StructID.ShortStructPack4ExplicitId);
MarshalStructAsParam_AsExpByRefInOut(StructID.IntStructPack8ExplicitId);
MarshalStructAsParam_AsExpByRefInOut(StructID.LongStructPack16ExplicitId);
}
private static void RunMarshalStructAsReturn()
{
Console.WriteLine("\nVerify marshal Explicit layout struct as return.");
LongStructPack16Explicit longStruct = GetLongStruct(123456, 78910);
if(longStruct.l1 != 123456 || longStruct.l2 != 78910)
{
Console.WriteLine("Failed to return LongStructPack16Explicit.");
failures++;
}
}
}
| |
// 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.Network.Fluent.ApplicationGateway.Update
{
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayListener.Update;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayListener.UpdateDefinition;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewaySslCertificate.UpdateDefinition;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayProbe.Update;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayProbe.UpdateDefinition;
using Microsoft.Azure.Management.Network.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Network.Fluent.HasPublicIPAddress.Update;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackend.Update;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackend.UpdateDefinition;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayAuthenticationCertificate.UpdateDefinition;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.UpdateDefinition;
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRedirectConfiguration.Update;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRedirectConfiguration.UpdateDefinition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.HasSubnet.Update;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayFrontend.Update;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayFrontend.UpdateDefinition;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.Update;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayIPConfiguration.Update;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayIPConfiguration.UpdateDefinition;
/// <summary>
/// The stage of an application gateway update allowing to modify frontend listeners.
/// </summary>
public interface IWithListener
{
/// <summary>
/// Begins the definition of a new application gateway listener to be attached to the gateway.
/// </summary>
/// <param name="name">A unique name for the listener.</param>
/// <return>The first stage of the listener definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayListener.UpdateDefinition.IBlank<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate> DefineListener(string name);
/// <summary>
/// Begins the update of a listener.
/// </summary>
/// <param name="name">The name of an existing listener to update.</param>
/// <return>The next stage of the definition or null if the requested listener does not exist.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayListener.Update.IUpdate UpdateListener(string name);
/// <summary>
/// Removes a frontend listener from the application gateway.
/// Note that removing a listener referenced by other settings may break the application gateway.
/// </summary>
/// <param name="name">The name of the listener to remove.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutListener(string name);
}
/// <summary>
/// The stage of an application gateway update allowing to modify front end ports.
/// </summary>
public interface IWithFrontendPort
{
/// <summary>
/// Creates a front end port with an auto-generated name and the specified port number, unless one already exists.
/// </summary>
/// <param name="portNumber">A port number.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithFrontendPort(int portNumber);
/// <summary>
/// Creates a front end port with the specified name and port number, unless a port matching this name and/or number already exists.
/// </summary>
/// <param name="portNumber">A port number.</param>
/// <param name="name">The name to assign to the port.</param>
/// <return>The next stage of the definition, or null if a port matching either the name or the number, but not both, already exists.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithFrontendPort(int portNumber, string name);
/// <summary>
/// Removes the specified frontend port.
/// Note that removing a frontend port referenced by other settings may break the application gateway.
/// </summary>
/// <param name="name">The name of the frontend port to remove.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutFrontendPort(string name);
/// <summary>
/// Removes the specified frontend port.
/// Note that removing a frontend port referenced by other settings may break the application gateway.
/// </summary>
/// <param name="portNumber">The port number of the frontend port to remove.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutFrontendPort(int portNumber);
}
/// <summary>
/// The stage of an application gateway update allowing to modify SSL certificates.
/// </summary>
public interface IWithSslCert
{
/// <summary>
/// Removes the specified SSL certificate from the application gateway.
/// Note that removing a certificate referenced by other settings may break the application gateway.
/// </summary>
/// <param name="name">The name of the certificate to remove.</param>
/// <return>The next stage of the update.</return>
/// <deprecated>Use .withoutSslCertificate instead.</deprecated>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutCertificate(string name);
/// <summary>
/// Removes the specified SSL certificate from the application gateway.
/// Note that removing a certificate referenced by other settings may break the application gateway.
/// </summary>
/// <param name="name">The name of the certificate to remove.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutSslCertificate(string name);
/// <summary>
/// Begins the definition of a new application gateway SSL certificate to be attached to the gateway for use in frontend HTTPS listeners.
/// </summary>
/// <param name="name">A unique name for the certificate.</param>
/// <return>The first stage of the certificate definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewaySslCertificate.UpdateDefinition.IBlank<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate> DefineSslCertificate(string name);
}
/// <summary>
/// The stage of an application gateway update allowing to modify probes.
/// </summary>
public interface IWithProbe
{
/// <summary>
/// Begins the definition of a new probe.
/// </summary>
/// <param name="name">A unique name for the probe.</param>
/// <return>The first stage of a probe definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayProbe.UpdateDefinition.IBlank<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate> DefineProbe(string name);
/// <summary>
/// Removes a probe from the application gateway.
/// Any references to this probe from backend HTTP configurations will be automatically removed.
/// </summary>
/// <param name="name">The name of an existing probe.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutProbe(string name);
/// <summary>
/// Begins the update of an existing probe.
/// </summary>
/// <param name="name">The name of an existing probe.</param>
/// <return>The first stage of a probe update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayProbe.Update.IUpdate UpdateProbe(string name);
}
/// <summary>
/// The template for an application gateway update operation, containing all the settings that
/// can be modified.
/// </summary>
public interface IUpdate :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IAppliable<Microsoft.Azure.Management.Network.Fluent.IApplicationGateway>,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update.IUpdateWithTags<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate>,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithSize,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithInstanceCount,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithBackend,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithBackendHttpConfig,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithIPConfig,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithFrontend,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithPublicIPAddress,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithFrontendPort,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithSslCert,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithListener,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithRequestRoutingRule,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithExistingSubnet,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithProbe,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithDisabledSslProtocol,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithAuthenticationCertificate,
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithRedirectConfiguration
{
/// <summary>
/// Enables HTTP2 traffic on the Application Gateway.
/// </summary>
/// <returns>The next stage of the definition.</returns>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithEnableHttp2();
/// <summary>
/// Disables HTTP2 traffic on the Application Gateway.
/// </summary>
/// <returns>The next stage of the definition.</returns>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutEnableHttp2();
}
/// <summary>
/// The stage of an application gateway update allowing to specify a public IP address for the public frontend.
/// </summary>
public interface IWithPublicIPAddress :
Microsoft.Azure.Management.Network.Fluent.HasPublicIPAddress.Update.IWithPublicIPAddressNoDnsLabel<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate>
{
}
/// <summary>
/// The stage of an internal application gateway update allowing to make the application gateway accessible to its
/// virtual network.
/// </summary>
public interface IWithPrivateFrontend
{
/// <summary>
/// Enables a private (internal) default front end in the subnet containing the application gateway.
/// A front end with an automatically generated name will be created if none exists.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithPrivateFrontend();
/// <summary>
/// Specifies that no private, or internal, front end should be enabled.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutPrivateFrontend();
}
/// <summary>
/// The stage of an application gateway update allowing to modify backends.
/// </summary>
public interface IWithBackend
{
/// <summary>
/// Begins the definition of a new application gateway backend to be attached to the gateway.
/// </summary>
/// <param name="name">A unique name for the backend.</param>
/// <return>The first stage of the backend definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackend.UpdateDefinition.IBlank<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate> DefineBackend(string name);
/// <summary>
/// Removes the specified backend.
/// Note that removing a backend referenced by other settings may break the application gateway.
/// </summary>
/// <param name="backendName">The name of an existing backend on this application gateway.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutBackend(string backendName);
/// <summary>
/// Begins the update of an existing backend on this application gateway.
/// </summary>
/// <param name="name">The name of the backend.</param>
/// <return>The first stage of an update of the backend.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackend.Update.IUpdate UpdateBackend(string name);
/// <summary>
/// Ensures the specified IP address is not associated with any backend.
/// </summary>
/// <param name="ipAddress">An IP address.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutBackendIPAddress(string ipAddress);
/// <summary>
/// Ensures the specified fully qualified domain name (FQDN) is not associated with any backend.
/// </summary>
/// <param name="fqdn">A fully qualified domain name (FQDN).</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutBackendFqdn(string fqdn);
}
/// <summary>
/// The stage of an application gateway update allowing to manage authentication certificates for the backends to use.
/// </summary>
public interface IWithAuthenticationCertificate :
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithAuthenticationCertificateBeta
{
}
/// <summary>
/// The stage of an application gateway update allowing to modify backend HTTP configurations.
/// </summary>
public interface IWithBackendHttpConfig
{
/// <summary>
/// Removes the specified backend HTTP configuration from this application gateway.
/// Note that removing a backend HTTP configuration referenced by other settings may break the application gateway.
/// </summary>
/// <param name="name">The name of an existing backend HTTP configuration on this application gateway.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutBackendHttpConfiguration(string name);
/// <summary>
/// Begins the update of a backend HTTP configuration.
/// </summary>
/// <param name="name">The name of an existing backend HTTP configuration on this application gateway.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.Update.IUpdate UpdateBackendHttpConfiguration(string name);
/// <summary>
/// Begins the definition of a new application gateway backend HTTP configuration to be attached to the gateway.
/// </summary>
/// <param name="name">A unique name for the backend HTTP configuration.</param>
/// <return>The first stage of the backend HTTP configuration definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayBackendHttpConfiguration.UpdateDefinition.IBlank<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate> DefineBackendHttpConfiguration(string name);
}
/// <summary>
/// The stage of an application gateway update allowing to specify the capacity (number of instances) of
/// the application gateway.
/// </summary>
public interface IWithInstanceCount
{
/// <summary>
/// Specifies the capacity (number of instances) for the application gateway.
/// </summary>
/// <param name="instanceCount">The capacity as a number between 1 and 10 but also based on the limits imposed by the selected applicatiob gateway size.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithInstanceCount(int instanceCount);
}
/// <summary>
/// The stage of an application gateway update allowing to specify the size.
/// </summary>
public interface IWithSize
{
/// <summary>
/// Specifies the size of the application gateway to use within the context of the selected tier.
/// </summary>
/// <param name="size">An application gateway size name.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithSize(ApplicationGatewaySkuName size);
}
/// <summary>
/// The stage of an application gateway definition allowing to add a redirect configuration.
/// </summary>
public interface IWithRedirectConfiguration :
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithRedirectConfigurationBeta
{
}
/// <summary>
/// The stage of an application gateway definition allowing to specify the SSL protocols to disable.
/// </summary>
public interface IWithDisabledSslProtocol :
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IWithDisabledSslProtocolBeta
{
}
/// <summary>
/// The stage of an application gateway update allowing to specify the subnet the app gateway is getting
/// its private IP address from.
/// </summary>
public interface IWithExistingSubnet :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.HasSubnet.Update.IWithSubnet<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate>
{
/// <summary>
/// Specifies the subnet the application gateway gets its private IP address from.
/// This will create a new IP configuration, if it does not already exist.
/// Private (internal) frontends, if any have been enabled, will be configured to use this subnet as well.
/// </summary>
/// <param name="subnet">An existing subnet.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithExistingSubnet(ISubnet subnet);
/// <summary>
/// Specifies the subnet the application gateway gets its private IP address from.
/// This will create a new IP configuration, if it does not already exist.
/// Private (internal) front ends, if any have been enabled, will be configured to use this subnet as well.
/// </summary>
/// <param name="network">The virtual network the subnet is part of.</param>
/// <param name="subnetName">The name of a subnet within the selected network.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithExistingSubnet(INetwork network, string subnetName);
}
/// <summary>
/// The stage of an application gateway update allowing to modify frontend IP configurations.
/// </summary>
public interface IWithFrontend
{
/// <summary>
/// Begins the update of an existing front end IP configuration.
/// </summary>
/// <param name="frontendName">The name of an existing front end IP configuration.</param>
/// <return>The first stage of the front end IP configuration update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayFrontend.Update.IUpdate UpdateFrontend(string frontendName);
/// <summary>
/// Begins the definition of the default public front end IP configuration, creating one if it does not already exist.
/// </summary>
/// <return>The first stage of a front end definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayFrontend.UpdateDefinition.IBlank<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate> DefinePublicFrontend();
/// <summary>
/// Specifies that the application gateway should not be private, i.e. its endpoints should not be internally accessible
/// from within the virtual network.
/// Note that if there are any other settings referencing the private front end, removing it may break the application gateway.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutPrivateFrontend();
/// <summary>
/// Specifies that the application gateway should not be Internet-facing.
/// Note that if there are any other settings referencing the public front end, removing it may break the application gateway.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutPublicFrontend();
/// <summary>
/// Removes the specified front end IP configuration.
/// Note that removing a front end referenced by other settings may break the application gateway.
/// </summary>
/// <param name="frontendName">The name of the front end IP configuration to remove.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutFrontend(string frontendName);
/// <summary>
/// Begins the update of the public front end IP configuration, if it exists.
/// </summary>
/// <return>The first stage of a front end update or null if no public front end exists.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayFrontend.Update.IUpdate UpdatePublicFrontend();
/// <summary>
/// Begins the definition of the default private front end IP configuration, creating one if it does not already exist.
/// </summary>
/// <return>The first stage of a front end definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayFrontend.UpdateDefinition.IBlank<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate> DefinePrivateFrontend();
}
/// <summary>
/// The stage of an application gateway update allowing to modify request routing rules.
/// </summary>
public interface IWithRequestRoutingRule
{
/// <summary>
/// Begins the update of a request routing rule.
/// </summary>
/// <param name="name">The name of an existing request routing rule.</param>
/// <return>The first stage of a request routing rule update or null if the requested rule does not exist.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.Update.IUpdate UpdateRequestRoutingRule(string name);
/// <summary>
/// Begins the definition of a request routing rule for this application gateway.
/// </summary>
/// <param name="name">A unique name for the request routing rule.</param>
/// <return>The first stage of the request routing rule.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IBlank<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate> DefineRequestRoutingRule(string name);
/// <summary>
/// Removes a request routing rule from the application gateway.
/// </summary>
/// <param name="name">The name of the request routing rule to remove.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutRequestRoutingRule(string name);
}
/// <summary>
/// The stage of an application gateway update allowing to modify IP configurations.
/// </summary>
public interface IWithIPConfig
{
/// <summary>
/// Begins the update of an existing IP configuration.
/// </summary>
/// <param name="ipConfigurationName">The name of an existing IP configuration.</param>
/// <return>The first stage of an IP configuration update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayIPConfiguration.Update.IUpdate UpdateIPConfiguration(string ipConfigurationName);
/// <summary>
/// Removes the specified IP configuration.
/// Note that removing an IP configuration referenced by other settings may break the application gateway.
/// Also, there must be at least one IP configuration for the application gateway to function.
/// </summary>
/// <param name="ipConfigurationName">The name of the IP configuration to remove.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutIPConfiguration(string ipConfigurationName);
/// <summary>
/// Begins the update of the default IP configuration i.e. the only one IP configuration that exists, assuming only one exists.
/// </summary>
/// <return>The first stage of an IP configuration update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayIPConfiguration.Update.IUpdate UpdateDefaultIPConfiguration();
/// <summary>
/// Begins the definition of the default IP configuration.
/// If a default IP configuration already exists, it will be this is equivalent to <code>updateDefaultIPConfiguration()</code>.
/// </summary>
/// <return>The first stage of an IP configuration update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayIPConfiguration.UpdateDefinition.IBlank<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate> DefineDefaultIPConfiguration();
}
/// <summary>
/// The stage of an application gateway update allowing to manage authentication certificates for the backends to use.
/// </summary>
public interface IWithAuthenticationCertificateBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Begins the definition of a new application gateway authentication certificate to be attached to the gateway for use by the backends.
/// </summary>
/// <param name="name">A unique name for the certificate.</param>
/// <return>The first stage of the certificate definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayAuthenticationCertificate.UpdateDefinition.IBlank<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate> DefineAuthenticationCertificate(string name);
/// <summary>
/// Removes an existing application gateway authentication certificate.
/// </summary>
/// <param name="name">The name of an existing certificate.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutAuthenticationCertificate(string name);
}
/// <summary>
/// The stage of an application gateway definition allowing to add a redirect configuration.
/// </summary>
public interface IWithRedirectConfigurationBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Begins the definition of a new application gateway redirect configuration to be attached to the gateway.
/// </summary>
/// <param name="name">A unique name for the redirect configuration.</param>
/// <return>The first stage of the redirect configuration definition.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRedirectConfiguration.UpdateDefinition.IBlank<Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate> DefineRedirectConfiguration(string name);
/// <summary>
/// Begins the update of a redirect configuration.
/// </summary>
/// <param name="name">The name of an existing redirect configuration to update.</param>
/// <return>The next stage of the definition or null if the requested redirect configuration does not exist.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRedirectConfiguration.Update.IUpdate UpdateRedirectConfiguration(string name);
/// <summary>
/// Removes a redirect configuration from the application gateway.
/// Note that removing a redirect configuration referenced by other settings may break the application gateway.
/// </summary>
/// <param name="name">The name of the redirect configuration to remove.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutRedirectConfiguration(string name);
}
/// <summary>
/// The stage of an application gateway definition allowing to specify the SSL protocols to disable.
/// </summary>
public interface IWithDisabledSslProtocolBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Disables the specified SSL protocols.
/// </summary>
/// <param name="protocols">SSL protocols.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithDisabledSslProtocols(params ApplicationGatewaySslProtocol[] protocols);
/// <summary>
/// Enables the specified SSL protocol, if previously disabled.
/// </summary>
/// <param name="protocol">An SSL protocol.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol);
/// <summary>
/// Enables the specified SSL protocols, if previously disabled.
/// </summary>
/// <param name="protocols">SSL protocols.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutDisabledSslProtocols(params ApplicationGatewaySslProtocol[] protocols);
/// <summary>
/// Disables the specified SSL protocol.
/// </summary>
/// <param name="protocol">An SSL protocol.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithDisabledSslProtocol(ApplicationGatewaySslProtocol protocol);
/// <summary>
/// Enables all SSL protocols, if previously disabled.
/// </summary>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Update.IUpdate WithoutAnyDisabledSslProtocols();
}
}
| |
using EnvDTE;
using NuGet.PackageManagement.VisualStudio;
using NuGet.Resolver;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;
using System.Threading.Tasks;
using NuGet.PackageManagement;
using NuGet.Protocol.Core.Types;
using NuGet.Configuration;
using NuGet.ProjectManagement;
using NuGet.Packaging.Core;
using NuGet.Packaging;
namespace NuGetConsole.Host.PowerShell.Implementation
{
internal abstract class PowerShellHost : IHost, IPathExpansion, IDisposable
{
private static readonly object _initScriptsLock = new object();
private readonly string _name;
private PackageManagementContext _packageManagementContext;
private readonly IRunspaceManager _runspaceManager;
private readonly ISourceRepositoryProvider _sourceRepositoryProvider;
private readonly ISolutionManager _solutionManager;
private readonly ISettings _settings;
private readonly ISourceControlManagerProvider _sourceControlManagerProvider;
private readonly ICommonOperations _commonOperations;
private const string ActivePackageSourceKey = "activePackageSource";
private const string PackageSourceKey = "packageSources";
private const string SyncModeKey = "IsSyncMode";
private const string PackageManagementContextKey = "PackageManagementContext";
private const string DTEKey = "DTE";
private string _activePackageSource;
private DTE _dte;
private IConsole _activeConsole;
private RunspaceDispatcher _runspace;
private NuGetPSHost _nugetHost;
// indicates whether this host has been initialized.
// null = not initilized, true = initialized successfully, false = initialized unsuccessfully
private bool? _initialized;
// store the current (non-truncated) project names displayed in the project name combobox
private string[] _projectSafeNames;
// store the current command typed so far
private ComplexCommand _complexCommand;
List<SourceRepository> _sourceRepositories;
protected PowerShellHost(string name, IRunspaceManager runspaceManager)
{
_runspaceManager = runspaceManager;
// TODO: Take these as ctor arguments
_sourceRepositoryProvider = ServiceLocator.GetInstance<ISourceRepositoryProvider>();
_solutionManager = ServiceLocator.GetInstance<ISolutionManager>();
_settings = ServiceLocator.GetInstance<ISettings>();
_dte = ServiceLocator.GetInstance<DTE>();
_sourceControlManagerProvider = ServiceLocator.GetInstanceSafe<ISourceControlManagerProvider>();
_commonOperations = ServiceLocator.GetInstanceSafe<ICommonOperations>();
_packageManagementContext = new PackageManagementContext(_sourceRepositoryProvider, _solutionManager,
_settings, _sourceControlManagerProvider, _commonOperations);
_name = name;
IsCommandEnabled = true;
InitializeSources();
_sourceRepositoryProvider.PackageSourceProvider.PackageSourcesSaved += PackageSourceProvider_PackageSourcesSaved;
}
private void InitializeSources()
{
_sourceRepositories = _sourceRepositoryProvider
.GetRepositories()
.Where(repo => repo.PackageSource.IsEnabled)
.ToList();
_activePackageSource = _sourceRepositoryProvider.PackageSourceProvider.ActivePackageSourceName;
// check if active package source name is valid
var activeSource = _sourceRepositories.FirstOrDefault(
repo => StringComparer.CurrentCultureIgnoreCase.Equals(repo.PackageSource.Name, _activePackageSource));
if (activeSource == null)
{
// the name can't be found. Use the first source as active source.
activeSource = _sourceRepositories.FirstOrDefault();
}
if (activeSource != null)
{
_activePackageSource = activeSource.PackageSource.Name;
}
else
{
_activePackageSource = null;
}
}
#region Properties
protected Pipeline ExecutingPipeline { get; set; }
/// <summary>
/// The host is associated with a particular console on a per-command basis.
/// This gets set every time a command is executed on this host.
/// </summary>
protected IConsole ActiveConsole
{
get
{
return _activeConsole;
}
set
{
_activeConsole = value;
if (_nugetHost != null)
{
_nugetHost.ActiveConsole = value;
}
}
}
public bool IsCommandEnabled
{
get;
private set;
}
protected RunspaceDispatcher Runspace
{
get
{
return _runspace;
}
}
private ComplexCommand ComplexCommand
{
get
{
if (_complexCommand == null)
{
_complexCommand = new ComplexCommand((allLines, lastLine) =>
{
Collection<PSParseError> errors;
PSParser.Tokenize(allLines, out errors);
// If there is a parse error token whose END is past input END, consider
// it a multi-line command.
if (errors.Count > 0)
{
if (errors.Any(e => (e.Token.Start + e.Token.Length) >= allLines.Length))
{
return false;
}
}
return true;
});
}
return _complexCommand;
}
}
public string Prompt
{
get
{
return ComplexCommand.IsComplete ? EvaluatePrompt() : ">> ";
}
}
public PackageManagementContext PackageManagementContext
{
get
{
return _packageManagementContext;
}
set
{
_packageManagementContext = value;
}
}
#endregion
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private string EvaluatePrompt()
{
string prompt = "PM>";
try
{
PSObject output = this.Runspace.Invoke("prompt", null, outputResults: false).FirstOrDefault();
if (output != null)
{
string result = output.BaseObject.ToString();
if (!String.IsNullOrEmpty(result))
{
prompt = result;
}
}
}
catch (Exception ex)
{
ExceptionHelper.WriteToActivityLog(ex);
}
return prompt;
}
/// <summary>
/// Doing all necessary initialization works before the console accepts user inputs
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void Initialize(IConsole console)
{
ActiveConsole = console;
if (_initialized.HasValue)
{
if (_initialized.Value && console.ShowDisclaimerHeader)
{
DisplayDisclaimerAndHelpText();
}
}
else
{
try
{
Tuple<RunspaceDispatcher, NuGetPSHost> result = _runspaceManager.GetRunspace(console, _name);
_runspace = result.Item1;
_nugetHost = result.Item2;
_initialized = true;
if (console.ShowDisclaimerHeader)
{
DisplayDisclaimerAndHelpText();
}
UpdateWorkingDirectory();
ExecuteInitScripts();
// Hook up solution events
_solutionManager.SolutionOpened += (o, e) =>
{
Task.Factory.StartNew(() =>
{
UpdateWorkingDirectory();
ExecuteInitScripts();
},
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Default);
};
_solutionManager.SolutionClosed += (o, e) => UpdateWorkingDirectory();
_solutionManager.NuGetProjectAdded += (o, e) => UpdateWorkingDirectory();
_solutionManager.NuGetProjectRenamed += (o, e) => UpdateWorkingDirectory();
_solutionManager.NuGetProjectRemoved += (o, e) => UpdateWorkingDirectory();
// Set available private data on Host
SetPrivateDataOnHost(false);
}
catch (Exception ex)
{
// catch all exception as we don't want it to crash VS
_initialized = false;
IsCommandEnabled = false;
ReportError(ex);
ExceptionHelper.WriteToActivityLog(ex);
}
}
}
private void UpdateWorkingDirectory()
{
if (Runspace.RunspaceAvailability == RunspaceAvailability.Available)
{
// if there is no solution open, we set the active directory to be user profile folder
string targetDir = _solutionManager.IsSolutionOpen ?
_solutionManager.SolutionDirectory :
Environment.GetEnvironmentVariable("USERPROFILE");
Runspace.ChangePSDirectory(targetDir);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want execution of init scripts to crash our console.")]
private void ExecuteInitScripts()
{
// Fix for Bug 1426 Disallow ExecuteInitScripts from being executed concurrently by multiple threads.
lock (_initScriptsLock)
{
if (!_solutionManager.IsSolutionOpen)
{
return;
}
Debug.Assert(_settings != null);
if (_settings == null)
{
return;
}
try
{
// invoke init.ps1 files in the order of package dependency.
// if A -> B, we invoke B's init.ps1 before A's.
IEnumerable<NuGetProject> projects = _solutionManager.GetNuGetProjects();
NuGetPackageManager packageManager = new NuGetPackageManager(_sourceRepositoryProvider, _settings, _solutionManager);
List<PackageIdentity> sortedPackages = new List<PackageIdentity>();
foreach (NuGetProject project in projects)
{
// Skip project K projects.
if (project is NuGet.ProjectManagement.Projects.ProjectKNuGetProjectBase)
{
continue;
}
IEnumerable<PackageReference> installedRefs = project.GetInstalledPackagesAsync(CancellationToken.None).Result;
if (installedRefs != null && installedRefs.Any())
{
IEnumerable<PackageIdentity> installedPackages = packageManager.GetInstalledPackagesInDependencyOrder(project, new EmptyNuGetProjectContext(), CancellationToken.None).Result;
sortedPackages.AddRange(installedPackages);
}
}
// Get the path to the Packages folder.
string packagesFolderPath = packageManager.PackagesFolderSourceRepository.PackageSource.Source;
foreach (var package in sortedPackages)
{
PackagePathResolver packagePathResolver = new PackagePathResolver(packagesFolderPath);
string pathToPackage = packagePathResolver.GetInstalledPath(package);
string toolsPath = Path.Combine(pathToPackage, "tools");
AddPathToEnvironment(toolsPath);
Runspace.ExecuteScript(toolsPath, PowerShellScripts.Init, package);
}
}
catch (Exception ex)
{
// When Packages folder is not present, NuGetResolverInputException will be thrown
// as resolving DependencyInfo requires the presence of Packages folder.
if (ex.InnerException is NuGetResolverInputException)
{
// Silently fail.
}
else
{
// if execution of Init scripts fails, do not let it crash our console
ReportError(ex);
}
ExceptionHelper.WriteToActivityLog(ex);
}
}
}
private static void AddPathToEnvironment(string path)
{
if (Directory.Exists(path))
{
string environmentPath = Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Process);
environmentPath = environmentPath + ";" + path;
Environment.SetEnvironmentVariable("path", environmentPath, EnvironmentVariableTarget.Process);
}
}
protected abstract bool ExecuteHost(string fullCommand, string command, params object[] inputs);
public bool Execute(IConsole console, string command, params object[] inputs)
{
if (console == null)
{
throw new ArgumentNullException("console");
}
if (command == null)
{
throw new ArgumentNullException("command");
}
NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageManagerConsoleCommandExecutionBegin);
ActiveConsole = console;
string fullCommand;
if (ComplexCommand.AddLine(command, out fullCommand) && !string.IsNullOrEmpty(fullCommand))
{
return ExecuteHost(fullCommand, command, inputs);
}
return false; // constructing multi-line command
}
protected static void OnExecuteCommandEnd()
{
NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageManagerConsoleCommandExecutionEnd);
}
public void Abort()
{
if (ExecutingPipeline != null)
{
ExecutingPipeline.StopAsync();
}
ComplexCommand.Clear();
}
protected void SetPrivateDataOnHost(bool isSync)
{
SetPropertyValueOnHost(SyncModeKey, isSync);
SetPropertyValueOnHost(PackageManagementContextKey, _packageManagementContext);
SetPropertyValueOnHost(ActivePackageSourceKey, ActivePackageSource);
SetPropertyValueOnHost(DTEKey, _dte);
}
private void SetPropertyValueOnHost(string propertyName, object value)
{
if (_nugetHost != null)
{
PSPropertyInfo property = _nugetHost.PrivateData.Properties[propertyName];
if (property == null)
{
property = new PSNoteProperty(propertyName, value);
_nugetHost.PrivateData.Properties.Add(property);
}
else
{
property.Value = value;
}
}
}
public void SetDefaultRunspace()
{
Runspace.MakeDefault();
}
private void DisplayDisclaimerAndHelpText()
{
WriteLine(Resources.Console_DisclaimerText);
WriteLine();
WriteLine(String.Format(CultureInfo.CurrentCulture, Resources.PowerShellHostTitle, _nugetHost.Version.ToString()));
WriteLine();
WriteLine(Resources.Console_HelpText);
WriteLine();
}
protected void ReportError(ErrorRecord record)
{
WriteErrorLine(Runspace.ExtractErrorFromErrorRecord(record));
}
protected void ReportError(Exception exception)
{
exception = ExceptionHelper.Unwrap(exception);
WriteErrorLine(exception.Message);
}
private void WriteErrorLine(string message)
{
if (ActiveConsole != null)
{
ActiveConsole.Write(message + Environment.NewLine, System.Windows.Media.Colors.Red, null);
}
}
private void WriteLine(string message = "")
{
if (ActiveConsole != null)
{
ActiveConsole.WriteLine(message);
}
}
public string ActivePackageSource
{
get
{
return _activePackageSource;
}
set
{
_activePackageSource = value;
var source = _sourceRepositories
.Where(s => StringComparer.CurrentCultureIgnoreCase.Equals(_activePackageSource, s.PackageSource.Name))
.FirstOrDefault();
if (source != null)
{
_sourceRepositoryProvider.PackageSourceProvider.SaveActivePackageSource(source.PackageSource);
}
}
}
public string[] GetPackageSources()
{
return _sourceRepositories.Select(repo => repo.PackageSource.Name).ToArray();
}
private void PackageSourceProvider_PackageSourcesSaved(object sender, EventArgs e)
{
_sourceRepositories = _sourceRepositoryProvider
.GetRepositories()
.Where(repo => repo.PackageSource.IsEnabled)
.ToList();
string oldActiveSource = this.ActivePackageSource;
SetNewActiveSource(oldActiveSource);
}
private void SetNewActiveSource(string oldActiveSource)
{
if (!_sourceRepositories.Any())
{
ActivePackageSource = string.Empty;
}
else
{
if (oldActiveSource == null)
{
// use the first enabled source as the active source
ActivePackageSource = _sourceRepositories.First().PackageSource.Name;
}
else
{
var s = _sourceRepositories.FirstOrDefault(
p => StringComparer.CurrentCultureIgnoreCase.Equals(p.PackageSource.Name, oldActiveSource));
if (s == null)
{
// the old active source does not exist any more. In this case,
// use the first eneabled source as the active source.
ActivePackageSource = _sourceRepositories.First().PackageSource.Name;
}
else
{
// the old active source still exists. Keep it as the active source.
ActivePackageSource = s.PackageSource.Name;
}
}
}
}
public string DefaultProject
{
get
{
Debug.Assert(_solutionManager != null);
if (_solutionManager.DefaultNuGetProject == null)
{
return null;
}
return GetDisplayName(_solutionManager.DefaultNuGetProject);
}
}
public void SetDefaultProjectIndex(int selectedIndex)
{
Debug.Assert(_solutionManager != null);
if (_projectSafeNames != null && selectedIndex >= 0 && selectedIndex < _projectSafeNames.Length)
{
_solutionManager.DefaultNuGetProjectName = _projectSafeNames[selectedIndex];
}
else
{
_solutionManager.DefaultNuGetProjectName = null;
}
}
public string[] GetAvailableProjects()
{
Debug.Assert(_solutionManager != null);
var allProjects = _solutionManager.GetNuGetProjects();
_projectSafeNames = allProjects.Select(_solutionManager.GetNuGetProjectSafeName).ToArray();
var displayNames = GetDisplayNames(allProjects).ToArray();
Array.Sort(displayNames, _projectSafeNames, StringComparer.CurrentCultureIgnoreCase);
return _projectSafeNames;
}
private IEnumerable<string> GetDisplayNames(IEnumerable<NuGetProject> allProjects)
{
List<string> projectNames = new List<string>();
VSSolutionManager solutionManager = (VSSolutionManager)_solutionManager;
foreach (NuGetProject nuGetProject in allProjects)
{
string displayName = GetDisplayName(nuGetProject, solutionManager);
projectNames.Add(displayName);
}
return projectNames;
}
public string GetDisplayName(NuGetProject nuGetProject)
{
VSSolutionManager solutionManager = (VSSolutionManager)_solutionManager;
return GetDisplayName(nuGetProject, solutionManager);
}
public string GetDisplayName(NuGetProject nuGetProject, VSSolutionManager solutionManager)
{
string safeName = solutionManager.GetNuGetProjectSafeName(nuGetProject);
Project project = solutionManager.GetDTEProject(safeName);
return EnvDTEProjectUtility.GetDisplayName(project);
}
#region ITabExpansion
public string[] GetExpansions(string line, string lastWord)
{
var query = from s in Runspace.Invoke(
@"$__pc_args=@();$input|%{$__pc_args+=$_};if(Test-Path Function:\TabExpansion2){(TabExpansion2 $__pc_args[0] $__pc_args[0].length).CompletionMatches|%{$_.CompletionText}}else{TabExpansion $__pc_args[0] $__pc_args[1]};Remove-Variable __pc_args -Scope 0;",
new string[] { line, lastWord },
outputResults: false)
select (s == null ? null : s.ToString());
return query.ToArray();
}
#endregion
#region IPathExpansion
public SimpleExpansion GetPathExpansions(string line)
{
PSObject expansion = Runspace.Invoke(
"$input|%{$__pc_args=$_}; _TabExpansionPath $__pc_args; Remove-Variable __pc_args -Scope 0",
new object[] { line },
outputResults: false).FirstOrDefault();
if (expansion != null)
{
int replaceStart = (int)expansion.Properties["ReplaceStart"].Value;
IList<string> paths = ((IEnumerable<object>)expansion.Properties["Paths"].Value).Select(o => o.ToString()).ToList();
return new SimpleExpansion(replaceStart, line.Length - replaceStart, paths);
}
return null;
}
#endregion
#region IDisposable
public void Dispose()
{
if (_runspace != null)
{
_runspace.Dispose();
}
}
#endregion
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Params.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.Params
{
/// <java-name>
/// org/apache/http/params/HttpAbstractParamBean
/// </java-name>
[Dot42.DexImport("org/apache/http/params/HttpAbstractParamBean", AccessFlags = 1057)]
public abstract partial class HttpAbstractParamBean
/* scope: __dot42__ */
{
/// <java-name>
/// params
/// </java-name>
[Dot42.DexImport("params", "Lorg/apache/http/params/HttpParams;", AccessFlags = 20)]
protected internal readonly global::Org.Apache.Http.Params.IHttpParams Params;
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public HttpAbstractParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal HttpAbstractParamBean() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <java-name>
/// org/apache/http/params/HttpProtocolParamBean
/// </java-name>
[Dot42.DexImport("org/apache/http/params/HttpProtocolParamBean", AccessFlags = 33)]
public partial class HttpProtocolParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public HttpProtocolParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setHttpElementCharset
/// </java-name>
[Dot42.DexImport("setHttpElementCharset", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetHttpElementCharset(string httpElementCharset) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setContentCharset
/// </java-name>
[Dot42.DexImport("setContentCharset", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetContentCharset(string contentCharset) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setVersion
/// </java-name>
[Dot42.DexImport("setVersion", "(Lorg/apache/http/HttpVersion;)V", AccessFlags = 1)]
public virtual void SetVersion(global::Org.Apache.Http.HttpVersion version) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setUserAgent
/// </java-name>
[Dot42.DexImport("setUserAgent", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetUserAgent(string userAgent) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setUseExpectContinue
/// </java-name>
[Dot42.DexImport("setUseExpectContinue", "(Z)V", AccessFlags = 1)]
public virtual void SetUseExpectContinue(bool useExpectContinue) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal HttpProtocolParamBean() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>This class represents a collection of HTTP protocol parameters. Protocol parameters may be linked together to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the parent collection of parameters.</para><para><para></para><para></para><title>Revision:</title><para>610464 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/BasicHttpParams
/// </java-name>
[Dot42.DexImport("org/apache/http/params/BasicHttpParams", AccessFlags = 49)]
public sealed partial class BasicHttpParams : global::Org.Apache.Http.Params.AbstractHttpParams, global::Java.Io.ISerializable, global::Java.Lang.ICloneable
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public BasicHttpParams() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getParameter
/// </java-name>
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1)]
public override object GetParameter(string name) /* MethodBuilder.Create */
{
return default(object);
}
/// <java-name>
/// setParameter
/// </java-name>
[Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public override global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <summary>
/// <para>Removes the parameter with the specified name.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if the parameter existed and has been removed, false else. </para>
/// </returns>
/// <java-name>
/// removeParameter
/// </java-name>
[Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public override bool RemoveParameter(string name) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Assigns the value to all the parameter with the given names</para><para></para>
/// </summary>
/// <java-name>
/// setParameters
/// </java-name>
[Dot42.DexImport("setParameters", "([Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 1)]
public void SetParameters(string[] names, object value) /* MethodBuilder.Create */
{
}
/// <java-name>
/// isParameterSet
/// </java-name>
[Dot42.DexImport("isParameterSet", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public bool IsParameterSet(string name) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isParameterSetLocally
/// </java-name>
[Dot42.DexImport("isParameterSetLocally", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public bool IsParameterSetLocally(string name) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Removes all parameters from this collection. </para>
/// </summary>
/// <java-name>
/// clear
/// </java-name>
[Dot42.DexImport("clear", "()V", AccessFlags = 1)]
public void Clear() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a copy of these parameters. The implementation here instantiates BasicHttpParams, then calls copyParams(HttpParams) to populate the copy.</para><para></para>
/// </summary>
/// <returns>
/// <para>a new set of params holding a copy of the <b>local</b> parameters in this object. </para>
/// </returns>
/// <java-name>
/// copy
/// </java-name>
[Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public override global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)]
public object Clone() /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Copies the locally defined parameters to the argument parameters. This method is called from copy().</para><para></para>
/// </summary>
/// <java-name>
/// copyParams
/// </java-name>
[Dot42.DexImport("copyParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 4)]
internal void CopyParams(global::Org.Apache.Http.Params.IHttpParams target) /* MethodBuilder.Create */
{
}
}
/// <java-name>
/// org/apache/http/params/HttpConnectionParamBean
/// </java-name>
[Dot42.DexImport("org/apache/http/params/HttpConnectionParamBean", AccessFlags = 33)]
public partial class HttpConnectionParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public HttpConnectionParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setSoTimeout
/// </java-name>
[Dot42.DexImport("setSoTimeout", "(I)V", AccessFlags = 1)]
public virtual void SetSoTimeout(int soTimeout) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setTcpNoDelay
/// </java-name>
[Dot42.DexImport("setTcpNoDelay", "(Z)V", AccessFlags = 1)]
public virtual void SetTcpNoDelay(bool tcpNoDelay) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setSocketBufferSize
/// </java-name>
[Dot42.DexImport("setSocketBufferSize", "(I)V", AccessFlags = 1)]
public virtual void SetSocketBufferSize(int socketBufferSize) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setLinger
/// </java-name>
[Dot42.DexImport("setLinger", "(I)V", AccessFlags = 1)]
public virtual void SetLinger(int linger) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setConnectionTimeout
/// </java-name>
[Dot42.DexImport("setConnectionTimeout", "(I)V", AccessFlags = 1)]
public virtual void SetConnectionTimeout(int connectionTimeout) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setStaleCheckingEnabled
/// </java-name>
[Dot42.DexImport("setStaleCheckingEnabled", "(Z)V", AccessFlags = 1)]
public virtual void SetStaleCheckingEnabled(bool staleCheckingEnabled) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal HttpConnectionParamBean() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>This class implements an adaptor around the HttpParams interface to simplify manipulation of the HTTP protocol specific parameters. <br></br> Note that the <b>implements</b> relation to CoreProtocolPNames is for compatibility with existing application code only. References to the parameter names should use the interface, not this class.</para><para><para></para><para></para><title>Revision:</title><para>576089 </para></para><para><para>4.0</para><para>CoreProtocolPNames </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/HttpProtocolParams
/// </java-name>
[Dot42.DexImport("org/apache/http/params/HttpProtocolParams", AccessFlags = 49)]
public sealed partial class HttpProtocolParams : global::Org.Apache.Http.Params.ICoreProtocolPNames
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal HttpProtocolParams() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the charset to be used for writing HTTP headers. </para>
/// </summary>
/// <returns>
/// <para>The charset </para>
/// </returns>
/// <java-name>
/// getHttpElementCharset
/// </java-name>
[Dot42.DexImport("getHttpElementCharset", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetHttpElementCharset(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Sets the charset to be used for writing HTTP headers. </para>
/// </summary>
/// <java-name>
/// setHttpElementCharset
/// </java-name>
[Dot42.DexImport("setHttpElementCharset", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)]
public static void SetHttpElementCharset(global::Org.Apache.Http.Params.IHttpParams @params, string charset) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the default charset to be used for writing content body, when no charset explicitly specified. </para>
/// </summary>
/// <returns>
/// <para>The charset </para>
/// </returns>
/// <java-name>
/// getContentCharset
/// </java-name>
[Dot42.DexImport("getContentCharset", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetContentCharset(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Sets the default charset to be used for writing content body, when no charset explicitly specified. </para>
/// </summary>
/// <java-name>
/// setContentCharset
/// </java-name>
[Dot42.DexImport("setContentCharset", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)]
public static void SetContentCharset(global::Org.Apache.Http.Params.IHttpParams @params, string charset) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns protocol version to be used per default.</para><para></para>
/// </summary>
/// <returns>
/// <para>protocol version </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/ProtocolVersion;", AccessFlags = 9)]
public static global::Org.Apache.Http.ProtocolVersion GetVersion(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.ProtocolVersion);
}
/// <summary>
/// <para>Assigns the protocol version to be used by the HTTP methods that this collection of parameters applies to.</para><para></para>
/// </summary>
/// <java-name>
/// setVersion
/// </java-name>
[Dot42.DexImport("setVersion", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/ProtocolVersion;)V", AccessFlags = 9)]
public static void SetVersion(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.ProtocolVersion version) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getUserAgent
/// </java-name>
[Dot42.DexImport("getUserAgent", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetUserAgent(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// setUserAgent
/// </java-name>
[Dot42.DexImport("setUserAgent", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)]
public static void SetUserAgent(global::Org.Apache.Http.Params.IHttpParams @params, string useragent) /* MethodBuilder.Create */
{
}
/// <java-name>
/// useExpectContinue
/// </java-name>
[Dot42.DexImport("useExpectContinue", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)]
public static bool UseExpectContinue(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// setUseExpectContinue
/// </java-name>
[Dot42.DexImport("setUseExpectContinue", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)]
public static void SetUseExpectContinue(global::Org.Apache.Http.Params.IHttpParams @params, bool b) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Represents a collection of HTTP protocol and framework parameters.</para><para><para></para><para></para><title>Revision:</title><para>610763 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/HttpParams
/// </java-name>
[Dot42.DexImport("org/apache/http/params/HttpParams", AccessFlags = 1537)]
public partial interface IHttpParams
/* scope: __dot42__ */
{
/// <summary>
/// <para>Obtains the value of the given parameter.</para><para><para>setParameter(String, Object) </para></para>
/// </summary>
/// <returns>
/// <para>an object that represents the value of the parameter, <code>null</code> if the parameter is not set or if it is explicitly set to <code>null</code></para>
/// </returns>
/// <java-name>
/// getParameter
/// </java-name>
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1025)]
object GetParameter(string name) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Assigns the value to the parameter with the given name.</para><para></para>
/// </summary>
/// <java-name>
/// setParameter
/// </java-name>
[Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Creates a copy of these parameters.</para><para></para>
/// </summary>
/// <returns>
/// <para>a new set of parameters holding the same values as this one </para>
/// </returns>
/// <java-name>
/// copy
/// </java-name>
[Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Removes the parameter with the specified name.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if the parameter existed and has been removed, false else. </para>
/// </returns>
/// <java-name>
/// removeParameter
/// </java-name>
[Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
bool RemoveParameter(string name) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a Long parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setLongParameter(String, long) </para></para>
/// </summary>
/// <returns>
/// <para>a Long that represents the value of the parameter.</para>
/// </returns>
/// <java-name>
/// getLongParameter
/// </java-name>
[Dot42.DexImport("getLongParameter", "(Ljava/lang/String;J)J", AccessFlags = 1025)]
long GetLongParameter(string name, long defaultValue) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Assigns a Long to the parameter with the given name</para><para></para>
/// </summary>
/// <java-name>
/// setLongParameter
/// </java-name>
[Dot42.DexImport("setLongParameter", "(Ljava/lang/String;J)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams SetLongParameter(string name, long value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns an Integer parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setIntParameter(String, int) </para></para>
/// </summary>
/// <returns>
/// <para>a Integer that represents the value of the parameter.</para>
/// </returns>
/// <java-name>
/// getIntParameter
/// </java-name>
[Dot42.DexImport("getIntParameter", "(Ljava/lang/String;I)I", AccessFlags = 1025)]
int GetIntParameter(string name, int defaultValue) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Assigns an Integer to the parameter with the given name</para><para></para>
/// </summary>
/// <java-name>
/// setIntParameter
/// </java-name>
[Dot42.DexImport("setIntParameter", "(Ljava/lang/String;I)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams SetIntParameter(string name, int value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a Double parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setDoubleParameter(String, double) </para></para>
/// </summary>
/// <returns>
/// <para>a Double that represents the value of the parameter.</para>
/// </returns>
/// <java-name>
/// getDoubleParameter
/// </java-name>
[Dot42.DexImport("getDoubleParameter", "(Ljava/lang/String;D)D", AccessFlags = 1025)]
double GetDoubleParameter(string name, double defaultValue) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Assigns a Double to the parameter with the given name</para><para></para>
/// </summary>
/// <java-name>
/// setDoubleParameter
/// </java-name>
[Dot42.DexImport("setDoubleParameter", "(Ljava/lang/String;D)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams SetDoubleParameter(string name, double value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a Boolean parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setBooleanParameter(String, boolean) </para></para>
/// </summary>
/// <returns>
/// <para>a Boolean that represents the value of the parameter.</para>
/// </returns>
/// <java-name>
/// getBooleanParameter
/// </java-name>
[Dot42.DexImport("getBooleanParameter", "(Ljava/lang/String;Z)Z", AccessFlags = 1025)]
bool GetBooleanParameter(string name, bool defaultValue) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Assigns a Boolean to the parameter with the given name</para><para></para>
/// </summary>
/// <java-name>
/// setBooleanParameter
/// </java-name>
[Dot42.DexImport("setBooleanParameter", "(Ljava/lang/String;Z)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams SetBooleanParameter(string name, bool value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks if a boolean parameter is set to <code>true</code>.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the parameter is set to value <code>true</code>, <code>false</code> if it is not set or set to <code>false</code> </para>
/// </returns>
/// <java-name>
/// isParameterTrue
/// </java-name>
[Dot42.DexImport("isParameterTrue", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
bool IsParameterTrue(string name) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks if a boolean parameter is not set or <code>false</code>.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the parameter is either not set or set to value <code>false</code>, <code>false</code> if it is set to <code>true</code> </para>
/// </returns>
/// <java-name>
/// isParameterFalse
/// </java-name>
[Dot42.DexImport("isParameterFalse", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
bool IsParameterFalse(string name) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Abstract base class for parameter collections. Type specific setters and getters are mapped to the abstract, generic getters and setters.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para></para><title>Revision:</title><para>542224 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/AbstractHttpParams
/// </java-name>
[Dot42.DexImport("org/apache/http/params/AbstractHttpParams", AccessFlags = 1057)]
public abstract partial class AbstractHttpParams : global::Org.Apache.Http.Params.IHttpParams
/* scope: __dot42__ */
{
/// <summary>
/// <para>Instantiates parameters. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal AbstractHttpParams() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getLongParameter
/// </java-name>
[Dot42.DexImport("getLongParameter", "(Ljava/lang/String;J)J", AccessFlags = 1)]
public virtual long GetLongParameter(string name, long defaultValue) /* MethodBuilder.Create */
{
return default(long);
}
/// <java-name>
/// setLongParameter
/// </java-name>
[Dot42.DexImport("setLongParameter", "(Ljava/lang/String;J)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Params.IHttpParams SetLongParameter(string name, long value) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <java-name>
/// getIntParameter
/// </java-name>
[Dot42.DexImport("getIntParameter", "(Ljava/lang/String;I)I", AccessFlags = 1)]
public virtual int GetIntParameter(string name, int defaultValue) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// setIntParameter
/// </java-name>
[Dot42.DexImport("setIntParameter", "(Ljava/lang/String;I)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Params.IHttpParams SetIntParameter(string name, int value) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <java-name>
/// getDoubleParameter
/// </java-name>
[Dot42.DexImport("getDoubleParameter", "(Ljava/lang/String;D)D", AccessFlags = 1)]
public virtual double GetDoubleParameter(string name, double defaultValue) /* MethodBuilder.Create */
{
return default(double);
}
/// <java-name>
/// setDoubleParameter
/// </java-name>
[Dot42.DexImport("setDoubleParameter", "(Ljava/lang/String;D)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Params.IHttpParams SetDoubleParameter(string name, double value) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <java-name>
/// getBooleanParameter
/// </java-name>
[Dot42.DexImport("getBooleanParameter", "(Ljava/lang/String;Z)Z", AccessFlags = 1)]
public virtual bool GetBooleanParameter(string name, bool defaultValue) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// setBooleanParameter
/// </java-name>
[Dot42.DexImport("setBooleanParameter", "(Ljava/lang/String;Z)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Params.IHttpParams SetBooleanParameter(string name, bool value) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <java-name>
/// isParameterTrue
/// </java-name>
[Dot42.DexImport("isParameterTrue", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public virtual bool IsParameterTrue(string name) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isParameterFalse
/// </java-name>
[Dot42.DexImport("isParameterFalse", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public virtual bool IsParameterFalse(string name) /* MethodBuilder.Create */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/params/HttpParams", "getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1025)]
public virtual object GetParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(object);
}
[Dot42.DexImport("org/apache/http/params/HttpParams", "setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
public virtual global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[Dot42.DexImport("org/apache/http/params/HttpParams", "copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
public virtual global::Org.Apache.Http.Params.IHttpParams Copy() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[Dot42.DexImport("org/apache/http/params/HttpParams", "removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
public virtual bool RemoveParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
}
/// <summary>
/// <para>An adaptor for accessing connection parameters in HttpParams. <br></br> Note that the <b>implements</b> relation to CoreConnectionPNames is for compatibility with existing application code only. References to the parameter names should use the interface, not this class.</para><para><para></para><para></para><title>Revision:</title><para>576089 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/HttpConnectionParams
/// </java-name>
[Dot42.DexImport("org/apache/http/params/HttpConnectionParams", AccessFlags = 49)]
public sealed partial class HttpConnectionParams : global::Org.Apache.Http.Params.ICoreConnectionPNames
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal HttpConnectionParams() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters.</para><para></para>
/// </summary>
/// <returns>
/// <para>timeout in milliseconds </para>
/// </returns>
/// <java-name>
/// getSoTimeout
/// </java-name>
[Dot42.DexImport("getSoTimeout", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)]
public static int GetSoTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Sets the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters.</para><para></para>
/// </summary>
/// <java-name>
/// setSoTimeout
/// </java-name>
[Dot42.DexImport("setSoTimeout", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)]
public static void SetSoTimeout(global::Org.Apache.Http.Params.IHttpParams @params, int timeout) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests if Nagle's algorithm is to be used.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the Nagle's algorithm is to NOT be used (that is enable TCP_NODELAY), <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// getTcpNoDelay
/// </java-name>
[Dot42.DexImport("getTcpNoDelay", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)]
public static bool GetTcpNoDelay(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption.</para><para></para>
/// </summary>
/// <java-name>
/// setTcpNoDelay
/// </java-name>
[Dot42.DexImport("setTcpNoDelay", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)]
public static void SetTcpNoDelay(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getSocketBufferSize
/// </java-name>
[Dot42.DexImport("getSocketBufferSize", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)]
public static int GetSocketBufferSize(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// setSocketBufferSize
/// </java-name>
[Dot42.DexImport("setSocketBufferSize", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)]
public static void SetSocketBufferSize(global::Org.Apache.Http.Params.IHttpParams @params, int size) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns linger-on-close timeout. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>the linger-on-close timeout </para>
/// </returns>
/// <java-name>
/// getLinger
/// </java-name>
[Dot42.DexImport("getLinger", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)]
public static int GetLinger(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns linger-on-close timeout. This option disables/enables immediate return from a close() of a TCP Socket. Enabling this option with a non-zero Integer timeout means that a close() will block pending the transmission and acknowledgement of all data written to the peer, at which point the socket is closed gracefully. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used.</para><para></para>
/// </summary>
/// <java-name>
/// setLinger
/// </java-name>
[Dot42.DexImport("setLinger", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)]
public static void SetLinger(global::Org.Apache.Http.Params.IHttpParams @params, int value) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.</para><para></para>
/// </summary>
/// <returns>
/// <para>timeout in milliseconds. </para>
/// </returns>
/// <java-name>
/// getConnectionTimeout
/// </java-name>
[Dot42.DexImport("getConnectionTimeout", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)]
public static int GetConnectionTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Sets the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.</para><para></para>
/// </summary>
/// <java-name>
/// setConnectionTimeout
/// </java-name>
[Dot42.DexImport("setConnectionTimeout", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)]
public static void SetConnectionTimeout(global::Org.Apache.Http.Params.IHttpParams @params, int timeout) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if stale connection check is to be used, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isStaleCheckingEnabled
/// </java-name>
[Dot42.DexImport("isStaleCheckingEnabled", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)]
public static bool IsStaleCheckingEnabled(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Defines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.</para><para></para>
/// </summary>
/// <java-name>
/// setStaleCheckingEnabled
/// </java-name>
[Dot42.DexImport("setStaleCheckingEnabled", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)]
public static void SetStaleCheckingEnabled(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Defines parameter names for connections in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/CoreConnectionPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/params/CoreConnectionPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class ICoreConnectionPNamesConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Defines the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters. </para><para>This parameter expects a value of type Integer. </para><para><para>java.net.SocketOptions::SO_TIMEOUT </para></para>
/// </summary>
/// <java-name>
/// SO_TIMEOUT
/// </java-name>
[Dot42.DexImport("SO_TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)]
public const string SO_TIMEOUT = "http.socket.timeout";
/// <summary>
/// <para>Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption. </para><para>This parameter expects a value of type Boolean. </para><para><para>java.net.SocketOptions::TCP_NODELAY </para></para>
/// </summary>
/// <java-name>
/// TCP_NODELAY
/// </java-name>
[Dot42.DexImport("TCP_NODELAY", "Ljava/lang/String;", AccessFlags = 25)]
public const string TCP_NODELAY = "http.tcp.nodelay";
/// <summary>
/// <para>Determines the size of the internal socket buffer used to buffer data while receiving / transmitting HTTP messages. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// SOCKET_BUFFER_SIZE
/// </java-name>
[Dot42.DexImport("SOCKET_BUFFER_SIZE", "Ljava/lang/String;", AccessFlags = 25)]
public const string SOCKET_BUFFER_SIZE = "http.socket.buffer-size";
/// <summary>
/// <para>Sets SO_LINGER with the specified linger time in seconds. The maximum timeout value is platform specific. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used. The setting only affects socket close. </para><para>This parameter expects a value of type Integer. </para><para><para>java.net.SocketOptions::SO_LINGER </para></para>
/// </summary>
/// <java-name>
/// SO_LINGER
/// </java-name>
[Dot42.DexImport("SO_LINGER", "Ljava/lang/String;", AccessFlags = 25)]
public const string SO_LINGER = "http.socket.linger";
/// <summary>
/// <para>Determines the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// CONNECTION_TIMEOUT
/// </java-name>
[Dot42.DexImport("CONNECTION_TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)]
public const string CONNECTION_TIMEOUT = "http.connection.timeout";
/// <summary>
/// <para>Determines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side. </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// STALE_CONNECTION_CHECK
/// </java-name>
[Dot42.DexImport("STALE_CONNECTION_CHECK", "Ljava/lang/String;", AccessFlags = 25)]
public const string STALE_CONNECTION_CHECK = "http.connection.stalecheck";
/// <summary>
/// <para>Determines the maximum line length limit. If set to a positive value, any HTTP line exceeding this limit will cause an IOException. A negative or zero value will effectively disable the check. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// MAX_LINE_LENGTH
/// </java-name>
[Dot42.DexImport("MAX_LINE_LENGTH", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_LINE_LENGTH = "http.connection.max-line-length";
/// <summary>
/// <para>Determines the maximum HTTP header count allowed. If set to a positive value, the number of HTTP headers received from the data stream exceeding this limit will cause an IOException. A negative or zero value will effectively disable the check. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// MAX_HEADER_COUNT
/// </java-name>
[Dot42.DexImport("MAX_HEADER_COUNT", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_HEADER_COUNT = "http.connection.max-header-count";
}
/// <summary>
/// <para>Defines parameter names for connections in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/CoreConnectionPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/params/CoreConnectionPNames", AccessFlags = 1537)]
public partial interface ICoreConnectionPNames
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>Defines parameter names for protocol execution in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/CoreProtocolPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/params/CoreProtocolPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class ICoreProtocolPNamesConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Defines the protocol version used per default. </para><para>This parameter expects a value of type org.apache.http.ProtocolVersion. </para>
/// </summary>
/// <java-name>
/// PROTOCOL_VERSION
/// </java-name>
[Dot42.DexImport("PROTOCOL_VERSION", "Ljava/lang/String;", AccessFlags = 25)]
public const string PROTOCOL_VERSION = "http.protocol.version";
/// <summary>
/// <para>Defines the charset to be used for encoding HTTP protocol elements. </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// HTTP_ELEMENT_CHARSET
/// </java-name>
[Dot42.DexImport("HTTP_ELEMENT_CHARSET", "Ljava/lang/String;", AccessFlags = 25)]
public const string HTTP_ELEMENT_CHARSET = "http.protocol.element-charset";
/// <summary>
/// <para>Defines the charset to be used per default for encoding content body. </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// HTTP_CONTENT_CHARSET
/// </java-name>
[Dot42.DexImport("HTTP_CONTENT_CHARSET", "Ljava/lang/String;", AccessFlags = 25)]
public const string HTTP_CONTENT_CHARSET = "http.protocol.content-charset";
/// <summary>
/// <para>Defines the content of the <code>User-Agent</code> header. </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// USER_AGENT
/// </java-name>
[Dot42.DexImport("USER_AGENT", "Ljava/lang/String;", AccessFlags = 25)]
public const string USER_AGENT = "http.useragent";
/// <summary>
/// <para>Defines the content of the <code>Server</code> header. </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// ORIGIN_SERVER
/// </java-name>
[Dot42.DexImport("ORIGIN_SERVER", "Ljava/lang/String;", AccessFlags = 25)]
public const string ORIGIN_SERVER = "http.origin-server";
/// <summary>
/// <para>Defines whether responses with an invalid <code>Transfer-Encoding</code> header should be rejected. </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// STRICT_TRANSFER_ENCODING
/// </java-name>
[Dot42.DexImport("STRICT_TRANSFER_ENCODING", "Ljava/lang/String;", AccessFlags = 25)]
public const string STRICT_TRANSFER_ENCODING = "http.protocol.strict-transfer-encoding";
/// <summary>
/// <para>Activates 'Expect: 100-continue' handshake for the entity enclosing methods. The purpose of the 'Expect: 100-continue' handshake to allow a client that is sending a request message with a request body to determine if the origin server is willing to accept the request (based on the request headers) before the client sends the request body. </para><para>The use of the 'Expect: 100-continue' handshake can result in noticable peformance improvement for entity enclosing requests (such as POST and PUT) that require the target server's authentication. </para><para>'Expect: 100-continue' handshake should be used with caution, as it may cause problems with HTTP servers and proxies that do not support HTTP/1.1 protocol. </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// USE_EXPECT_CONTINUE
/// </java-name>
[Dot42.DexImport("USE_EXPECT_CONTINUE", "Ljava/lang/String;", AccessFlags = 25)]
public const string USE_EXPECT_CONTINUE = "http.protocol.expect-continue";
/// <summary>
/// <para>Defines the maximum period of time in milliseconds the client should spend waiting for a 100-continue response. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// WAIT_FOR_CONTINUE
/// </java-name>
[Dot42.DexImport("WAIT_FOR_CONTINUE", "Ljava/lang/String;", AccessFlags = 25)]
public const string WAIT_FOR_CONTINUE = "http.protocol.wait-for-continue";
}
/// <summary>
/// <para>Defines parameter names for protocol execution in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/CoreProtocolPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/params/CoreProtocolPNames", AccessFlags = 1537)]
public partial interface ICoreProtocolPNames
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>HttpParams implementation that delegates resolution of a parameter to the given default HttpParams instance if the parameter is not present in the local one. The state of the local collection can be mutated, whereas the default collection is treated as read-only.</para><para><para></para><para></para><title>Revision:</title><para>610763 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/DefaultedHttpParams
/// </java-name>
[Dot42.DexImport("org/apache/http/params/DefaultedHttpParams", AccessFlags = 49)]
public sealed partial class DefaultedHttpParams : global::Org.Apache.Http.Params.AbstractHttpParams
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public DefaultedHttpParams(global::Org.Apache.Http.Params.IHttpParams local, global::Org.Apache.Http.Params.IHttpParams defaults) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a copy of the local collection with the same default </para>
/// </summary>
/// <java-name>
/// copy
/// </java-name>
[Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public override global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <summary>
/// <para>Retrieves the value of the parameter from the local collection and, if the parameter is not set locally, delegates its resolution to the default collection. </para>
/// </summary>
/// <java-name>
/// getParameter
/// </java-name>
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1)]
public override object GetParameter(string name) /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Attempts to remove the parameter from the local collection. This method <b>does not</b> modify the default collection. </para>
/// </summary>
/// <java-name>
/// removeParameter
/// </java-name>
[Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public override bool RemoveParameter(string name) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Sets the parameter in the local collection. This method <b>does not</b> modify the default collection. </para>
/// </summary>
/// <java-name>
/// setParameter
/// </java-name>
[Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public override global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <java-name>
/// getDefaults
/// </java-name>
[Dot42.DexImport("getDefaults", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public global::Org.Apache.Http.Params.IHttpParams GetDefaults() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal DefaultedHttpParams() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getDefaults
/// </java-name>
public global::Org.Apache.Http.Params.IHttpParams Defaults
{
[Dot42.DexImport("getDefaults", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
get{ return GetDefaults(); }
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList
{
internal class ProjectExternalErrorReporter : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2
{
internal static readonly IReadOnlyList<string> CustomTags = ImmutableArray.Create(WellKnownDiagnosticTags.Telemetry);
internal static readonly IReadOnlyList<string> CompilerDiagnosticCustomTags = ImmutableArray.Create(WellKnownDiagnosticTags.Compiler, WellKnownDiagnosticTags.Telemetry);
private readonly ProjectId _projectId;
private readonly string _errorCodePrefix;
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly ExternalErrorDiagnosticUpdateSource _diagnosticProvider;
public ProjectExternalErrorReporter(ProjectId projectId, string errorCodePrefix, IServiceProvider serviceProvider)
{
_projectId = projectId;
_errorCodePrefix = errorCodePrefix;
_diagnosticProvider = serviceProvider.GetMefService<ExternalErrorDiagnosticUpdateSource>();
_workspace = serviceProvider.GetMefService<VisualStudioWorkspaceImpl>();
Debug.Assert(_diagnosticProvider != null);
Debug.Assert(_workspace != null);
}
public int AddNewErrors(IVsEnumExternalErrors pErrors)
{
var projectErrors = new HashSet<DiagnosticData>();
var documentErrorsMap = new Dictionary<DocumentId, HashSet<DiagnosticData>>();
var errors = new ExternalError[1];
uint fetched;
while (pErrors.Next(1, errors, out fetched) == VSConstants.S_OK && fetched == 1)
{
var error = errors[0];
DiagnosticData diagnostic;
if (error.bstrFileName != null)
{
diagnostic = CreateDocumentDiagnosticItem(error);
if (diagnostic != null)
{
var diagnostics = documentErrorsMap.GetOrAdd(diagnostic.DocumentId, _ => new HashSet<DiagnosticData>());
diagnostics.Add(diagnostic);
continue;
}
projectErrors.Add(CreateProjectDiagnosticItem(error));
}
else
{
projectErrors.Add(CreateProjectDiagnosticItem(error));
}
}
_diagnosticProvider.AddNewErrors(_projectId, projectErrors, documentErrorsMap);
return VSConstants.S_OK;
}
public int ClearAllErrors()
{
_diagnosticProvider.ClearErrors(_projectId);
return VSConstants.S_OK;
}
public int GetErrors(out IVsEnumExternalErrors pErrors)
{
pErrors = null;
Debug.Fail("This is not implemented, because no one called it.");
return VSConstants.E_NOTIMPL;
}
private DiagnosticData CreateProjectDiagnosticItem(ExternalError error)
{
return GetDiagnosticData(error);
}
private DiagnosticData CreateDocumentDiagnosticItem(ExternalError error)
{
var hostProject = _workspace.GetHostProject(_projectId);
if (!hostProject.ContainsFile(error.bstrFileName))
{
return null;
}
var hostDocument = hostProject.GetCurrentDocumentFromPath(error.bstrFileName);
var line = error.iLine;
var column = error.iCol;
var containedDocument = hostDocument as ContainedDocument;
if (containedDocument != null)
{
var span = new VsTextSpan
{
iStartLine = line,
iStartIndex = column,
iEndLine = line,
iEndIndex = column,
};
var spans = new VsTextSpan[1];
Marshal.ThrowExceptionForHR(containedDocument.ContainedLanguage.BufferCoordinator.MapPrimaryToSecondarySpan(
span,
spans));
line = spans[0].iStartLine;
column = spans[0].iStartIndex;
}
return GetDiagnosticData(error, hostDocument.Id, line, column);
}
public int ReportError(string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")]VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName)
{
ReportError2(bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, iLine, iColumn, bstrFileName);
return VSConstants.S_OK;
}
// TODO: Use PreserveSig instead of throwing these exceptions for common cases.
public void ReportError2(string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")]VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName)
{
if ((iEndLine >= 0 && iEndColumn >= 0) &&
((iEndLine < iStartLine) ||
(iEndLine == iStartLine && iEndColumn < iStartColumn)))
{
throw new ArgumentException(ServicesVSResources.EndPositionMustBeGreaterThanStart);
}
// We only handle errors that have positions. For the rest, we punt back to the
// project system.
if (iStartLine < 0 || iStartColumn < 0)
{
throw new NotImplementedException();
}
var hostProject = _workspace.GetHostProject(_projectId);
if (!hostProject.ContainsFile(bstrFileName))
{
throw new NotImplementedException();
}
var hostDocument = hostProject.GetCurrentDocumentFromPath(bstrFileName);
var priority = (VSTASKPRIORITY)nPriority;
DiagnosticSeverity severity;
switch (priority)
{
case VSTASKPRIORITY.TP_HIGH:
severity = DiagnosticSeverity.Error;
break;
case VSTASKPRIORITY.TP_NORMAL:
severity = DiagnosticSeverity.Warning;
break;
case VSTASKPRIORITY.TP_LOW:
severity = DiagnosticSeverity.Info;
break;
default:
throw new ArgumentException(ServicesVSResources.NotAValidValue, nameof(nPriority));
}
var diagnostic = GetDiagnosticData(
hostDocument.Id, bstrErrorId, bstrErrorMessage, severity,
null, iStartLine, iStartColumn, iEndLine, iEndColumn,
bstrFileName, iStartLine, iStartColumn, iEndLine, iEndColumn);
_diagnosticProvider.AddNewErrors(hostDocument.Id, diagnostic);
}
public int ClearErrors()
{
_diagnosticProvider.ClearErrors(_projectId);
return VSConstants.S_OK;
}
private string GetErrorId(ExternalError error)
{
return string.Format("{0}{1:0000}", _errorCodePrefix, error.iErrorID);
}
private static int GetWarningLevel(DiagnosticSeverity severity)
{
return severity == DiagnosticSeverity.Error ? 0 : 1;
}
private static DiagnosticSeverity GetDiagnosticSeverity(ExternalError error)
{
return error.fError != 0 ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning;
}
private DiagnosticData GetDiagnosticData(
ExternalError error, DocumentId id = null, int line = 0, int column = 0)
{
if (id != null)
{
// save error line/column (surface buffer location) as mapped line/column so that we can display
// right location on closed Venus file.
return GetDiagnosticData(
id, GetErrorId(error), error.bstrText, GetDiagnosticSeverity(error),
null, error.iLine, error.iCol, error.iLine, error.iCol, error.bstrFileName, line, column, line, column);
}
return GetDiagnosticData(
id, GetErrorId(error), error.bstrText, GetDiagnosticSeverity(error), null, 0, 0, 0, 0, null, 0, 0, 0, 0);
}
private static bool IsCompilerDiagnostic(string errorId)
{
if (!string.IsNullOrEmpty(errorId) && errorId.Length > 2)
{
var prefix = errorId.Substring(0, 2);
if (prefix.Equals("CS", StringComparison.OrdinalIgnoreCase) || prefix.Equals("BC", StringComparison.OrdinalIgnoreCase))
{
var suffix = errorId.Substring(2);
int id;
return int.TryParse(suffix, out id);
}
}
return false;
}
private static IReadOnlyList<string> GetCustomTags(string errorId)
{
return IsCompilerDiagnostic(errorId) ? CompilerDiagnosticCustomTags : CustomTags;
}
private DiagnosticData GetDiagnosticData(
DocumentId id, string errorId, string message, DiagnosticSeverity severity,
string mappedFilePath, int mappedStartLine, int mappedStartColumn, int mappedEndLine, int mappedEndColumn,
string originalFilePath, int originalStartLine, int originalStartColumn, int originalEndLine, int originalEndColumn)
{
return new DiagnosticData(
id: errorId,
category: WellKnownDiagnosticTags.Build,
message: message,
title: message,
enuMessageForBingSearch: message, // Unfortunately, there is no way to get ENU text for this since this is an external error.
severity: severity,
defaultSeverity: severity,
isEnabledByDefault: true,
warningLevel: GetWarningLevel(severity),
customTags: GetCustomTags(errorId),
properties: DiagnosticData.PropertiesForBuildDiagnostic,
workspace: _workspace,
projectId: _projectId,
location: new DiagnosticDataLocation(id,
sourceSpan: null,
originalFilePath: originalFilePath,
originalStartLine: originalStartLine,
originalStartColumn: originalStartColumn,
originalEndLine: originalEndLine,
originalEndColumn: originalEndColumn,
mappedFilePath: mappedFilePath,
mappedStartLine: mappedStartLine,
mappedStartColumn: mappedStartColumn,
mappedEndLine: mappedEndLine,
mappedEndColumn: mappedEndColumn));
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSLF.Record
{
using System;
using NPOI.Util;
using System.IO;
/**
* A ColorSchemeAtom (type 2032). Holds the 8 RGB values for the different
* colours of bits of text, that Makes up a given colour scheme.
* Slides (presumably) link to a given colour scheme atom, and that
* defines the colours to be used
*
* @author Nick Burch
*/
public class ColorSchemeAtom : RecordAtom
{
private byte[] _header;
private static long _type = 2032L;
private int backgroundColourRGB;
private int textAndLinesColourRGB;
private int shadowsColourRGB;
private int titleTextColourRGB;
private int FillsColourRGB;
private int accentColourRGB;
private int accentAndHyperlinkColourRGB;
private int accentAndFollowingHyperlinkColourRGB;
/** Fetch the RGB value for Background Colour */
public int GetBackgroundColourRGB() { return backgroundColourRGB; }
/** Set the RGB value for Background Colour */
public void SetBackgroundColourRGB(int rgb) { backgroundColourRGB = rgb; }
/** Fetch the RGB value for Text And Lines Colour */
public int GetTextAndLinesColourRGB() { return textAndLinesColourRGB; }
/** Set the RGB value for Text And Lines Colour */
public void SetTextAndLinesColourRGB(int rgb) { textAndLinesColourRGB = rgb; }
/** Fetch the RGB value for Shadows Colour */
public int GetShadowsColourRGB() { return shadowsColourRGB; }
/** Set the RGB value for Shadows Colour */
public void SetShadowsColourRGB(int rgb) { shadowsColourRGB = rgb; }
/** Fetch the RGB value for Title Text Colour */
public int GetTitleTextColourRGB() { return titleTextColourRGB; }
/** Set the RGB value for Title Text Colour */
public void SetTitleTextColourRGB(int rgb) { titleTextColourRGB = rgb; }
/** Fetch the RGB value for Fills Colour */
public int GetFillsColourRGB() { return FillsColourRGB; }
/** Set the RGB value for Fills Colour */
public void SetFillsColourRGB(int rgb) { FillsColourRGB = rgb; }
/** Fetch the RGB value for Accent Colour */
public int GetAccentColourRGB() { return accentColourRGB; }
/** Set the RGB value for Accent Colour */
public void SetAccentColourRGB(int rgb) { accentColourRGB = rgb; }
/** Fetch the RGB value for Accent And Hyperlink Colour */
public int GetAccentAndHyperlinkColourRGB()
{ return accentAndHyperlinkColourRGB; }
/** Set the RGB value for Accent And Hyperlink Colour */
public void SetAccentAndHyperlinkColourRGB(int rgb)
{ accentAndHyperlinkColourRGB = rgb; }
/** Fetch the RGB value for Accent And Following Hyperlink Colour */
public int GetAccentAndFollowingHyperlinkColourRGB()
{ return accentAndFollowingHyperlinkColourRGB; }
/** Set the RGB value for Accent And Following Hyperlink Colour */
public void SetAccentAndFollowingHyperlinkColourRGB(int rgb)
{ accentAndFollowingHyperlinkColourRGB = rgb; }
/* *************** record code follows ********************** */
/**
* For the Colour Scheme (ColorSchem) Atom
*/
protected ColorSchemeAtom(byte[] source, int start, int len)
{
// Sanity Checking - we're always 40 bytes long
if (len < 40)
{
len = 40;
if (source.Length - start < 40)
{
throw new Exception("Not enough data to form a ColorSchemeAtom (always 40 bytes long) - found " + (source.Length - start));
}
}
// Get the header
_header = new byte[8];
Array.Copy(source, start, _header, 0, 8);
// Grab the rgb values
backgroundColourRGB = LittleEndian.GetInt(source, start + 8 + 0);
textAndLinesColourRGB = LittleEndian.GetInt(source, start + 8 + 4);
shadowsColourRGB = LittleEndian.GetInt(source, start + 8 + 8);
titleTextColourRGB = LittleEndian.GetInt(source, start + 8 + 12);
FillsColourRGB = LittleEndian.GetInt(source, start + 8 + 16);
accentColourRGB = LittleEndian.GetInt(source, start + 8 + 20);
accentAndHyperlinkColourRGB = LittleEndian.GetInt(source, start + 8 + 24);
accentAndFollowingHyperlinkColourRGB = LittleEndian.GetInt(source, start + 8 + 28);
}
/**
* Create a new ColorSchemeAtom, to go with a new Slide
*/
public ColorSchemeAtom()
{
_header = new byte[8];
LittleEndian.PutUShort(_header, 0, 16);
LittleEndian.PutUShort(_header, 2, (int)_type);
LittleEndian.PutInt(_header, 4, 32);
// Setup the default rgb values
backgroundColourRGB = 16777215;
textAndLinesColourRGB = 0;
shadowsColourRGB = 8421504;
titleTextColourRGB = 0;
FillsColourRGB = 10079232;
accentColourRGB = 13382451;
accentAndHyperlinkColourRGB = 16764108;
accentAndFollowingHyperlinkColourRGB = 11711154;
}
/**
* We are of type 3999
*/
public override long RecordType
{
get { return _type; }
}
/**
* Convert from an integer RGB value to individual R, G, B 0-255 values
*/
public static byte[] SplitRGB(int rgb)
{
byte[] ret = new byte[3];
// Serialise to bytes, then grab the right ones out
MemoryStream baos = new MemoryStream();
WriteLittleEndian(rgb, baos);
byte[] b = baos.ToArray();
Array.Copy(b, 0, ret, 0, 3);
return ret;
}
/**
* Convert from split R, G, B values to an integer RGB value
*/
public static int JoinRGB(byte r, byte g, byte b)
{
return JoinRGB(new byte[] { r, g, b });
}
/**
* Convert from split R, G, B values to an integer RGB value
*/
public static int JoinRGB(byte[] rgb)
{
if (rgb.Length != 3)
{
throw new Exception("joinRGB accepts a byte array of 3 values, but got one of " + rgb.Length + " values!");
}
byte[] with_zero = new byte[4];
System.Array.Copy(rgb, 0, with_zero, 0, 3);
with_zero[3] = 0;
int ret = LittleEndian.GetInt(with_zero, 0);
return ret;
}
/**
* Write the contents of the record back, so it can be written
* to disk
*/
public override void WriteOut(Stream out1)
{
// Header - size or type unChanged
out1.Write(_header, (int)out1.Position, _header.Length);
// Write out the rgb values
WriteLittleEndian(backgroundColourRGB, out1);
WriteLittleEndian(textAndLinesColourRGB, out1);
WriteLittleEndian(shadowsColourRGB, out1);
WriteLittleEndian(titleTextColourRGB, out1);
WriteLittleEndian(FillsColourRGB, out1);
WriteLittleEndian(accentColourRGB, out1);
WriteLittleEndian(accentAndHyperlinkColourRGB, out1);
WriteLittleEndian(accentAndFollowingHyperlinkColourRGB, out1);
}
/**
* Returns color by its index
*
* @param idx 0-based color index
* @return color by its index
*/
public int GetColor(int idx)
{
int[] clr = {backgroundColourRGB, textAndLinesColourRGB, shadowsColourRGB, titleTextColourRGB,
FillsColourRGB, accentColourRGB, accentAndHyperlinkColourRGB, accentAndFollowingHyperlinkColourRGB};
return clr[idx];
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.