context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Collect of the most of the rarest mineral orbiting around the sun and out-compete your competitor.
// DO NOT MODIFY THIS FILE
// Never try to directly create an instance of this class, or modify its member variables.
// Instead, you should only be reading its variables and calling its functions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// <<-- Creer-Merge: usings -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add additional using(s) here
// <<-- /Creer-Merge: usings -->>
/// <summary>
/// Collect of the most of the rarest mineral orbiting around the sun and out-compete your competitor.
/// </summary>
namespace Joueur.cs.Games.Stardash
{
/// <summary>
/// Collect of the most of the rarest mineral orbiting around the sun and out-compete your competitor.
/// </summary>
public class Game : BaseGame
{
/// <summary>
/// The game version hash, used to compare if we are playing the same version on the server.
/// </summary>
new protected static string GameVersion = "0fa378e83ac567ebdf3e9805d3f130023f936e2740acda173d238b37f2b5d541";
#region Properties
/// <summary>
/// All the celestial bodies in the game. The first two are planets and the third is the sun. The fourth is the VP asteroid. Everything else is normal asteroids.
/// </summary>
public IList<Stardash.Body> Bodies { get; protected set; }
/// <summary>
/// The player whose turn it is currently. That player can send commands. Other players cannot.
/// </summary>
public Stardash.Player CurrentPlayer { get; protected set; }
/// <summary>
/// The current turn number, starting at 0 for the first player's turn.
/// </summary>
public int CurrentTurn { get; protected set; }
/// <summary>
/// The cost of dashing.
/// </summary>
public int DashCost { get; protected set; }
/// <summary>
/// The distance traveled each turn by dashing.
/// </summary>
public int DashDistance { get; protected set; }
/// <summary>
/// The value of every unit of genarium.
/// </summary>
public double GenariumValue { get; protected set; }
/// <summary>
/// A list of all jobs. The first element is corvette, second is missileboat, third is martyr, fourth is transport, and fifth is miner.
/// </summary>
public IList<Stardash.Job> Jobs { get; protected set; }
/// <summary>
/// The value of every unit of legendarium.
/// </summary>
public double LegendariumValue { get; protected set; }
/// <summary>
/// The highest amount of material, that can be in a asteroid.
/// </summary>
public int MaxAsteroid { get; protected set; }
/// <summary>
/// The maximum number of turns before the game will automatically end.
/// </summary>
public int MaxTurns { get; protected set; }
/// <summary>
/// The smallest amount of material, that can be in a asteroid.
/// </summary>
public int MinAsteroid { get; protected set; }
/// <summary>
/// The rate at which miners grab minerals from asteroids.
/// </summary>
public int MiningSpeed { get; protected set; }
/// <summary>
/// The amount of mythicite that spawns at the start of the game.
/// </summary>
public double MythiciteAmount { get; protected set; }
/// <summary>
/// The number of orbit updates you cannot mine the mithicite asteroid.
/// </summary>
public int OrbitsProtected { get; protected set; }
/// <summary>
/// The rarity modifier of the most common ore. This controls how much spawns.
/// </summary>
public double OreRarityGenarium { get; protected set; }
/// <summary>
/// The rarity modifier of the rarest ore. This controls how much spawns.
/// </summary>
public double OreRarityLegendarium { get; protected set; }
/// <summary>
/// The rarity modifier of the second rarest ore. This controls how much spawns.
/// </summary>
public double OreRarityRarium { get; protected set; }
/// <summary>
/// The amount of energy a planet can hold at once.
/// </summary>
public int PlanetEnergyCap { get; protected set; }
/// <summary>
/// The amount of energy the planets restore each round.
/// </summary>
public int PlanetRechargeRate { get; protected set; }
/// <summary>
/// List of all the players in the game.
/// </summary>
public IList<Stardash.Player> Players { get; protected set; }
/// <summary>
/// The standard size of ships.
/// </summary>
public int ProjectileRadius { get; protected set; }
/// <summary>
/// The amount of distance missiles travel through space.
/// </summary>
public int ProjectileSpeed { get; protected set; }
/// <summary>
/// Every projectile in the game.
/// </summary>
public IList<Stardash.Projectile> Projectiles { get; protected set; }
/// <summary>
/// The value of every unit of rarium.
/// </summary>
public double RariumValue { get; protected set; }
/// <summary>
/// The regeneration rate of asteroids.
/// </summary>
public double RegenerateRate { get; protected set; }
/// <summary>
/// A unique identifier for the game instance that is being played.
/// </summary>
public string Session { get; protected set; }
/// <summary>
/// The standard size of ships.
/// </summary>
public int ShipRadius { get; protected set; }
/// <summary>
/// The size of the map in the X direction.
/// </summary>
public int SizeX { get; protected set; }
/// <summary>
/// The size of the map in the Y direction.
/// </summary>
public int SizeY { get; protected set; }
/// <summary>
/// The amount of time (in nano-seconds) added after each player performs a turn.
/// </summary>
public int TimeAddedPerTurn { get; protected set; }
/// <summary>
/// The number of turns it takes for a asteroid to orbit the sun. (Asteroids move after each players turn).
/// </summary>
public int TurnsToOrbit { get; protected set; }
/// <summary>
/// Every Unit in the game.
/// </summary>
public IList<Stardash.Unit> Units { get; protected set; }
// <<-- Creer-Merge: properties -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add additional properties(s) here. None of them will be tracked or updated by the server.
// <<-- /Creer-Merge: properties -->>
#endregion
#region Methods
/// <summary>
/// Creates a new instance of Game. Used during game initialization, do not call directly.
/// </summary>
protected Game() : base()
{
this.Name = "Stardash";
this.Bodies = new List<Stardash.Body>();
this.Jobs = new List<Stardash.Job>();
this.Players = new List<Stardash.Player>();
this.Projectiles = new List<Stardash.Projectile>();
this.Units = new List<Stardash.Unit>();
}
// <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add additional method(s) here.
// <<-- /Creer-Merge: methods -->>
#endregion
}
}
| |
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Azure.Management.EventHub;
using Microsoft.Azure.Management.EventHub.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
namespace GeoDRClient
{
internal sealed class GeoDisasterRecoveryClient
{
public async Task<int> ExecuteAsync(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Invalid command");
return -1;
}
string command = args[0];
int status;
try
{
if (command.Equals("CreatePairing", StringComparison.OrdinalIgnoreCase))
{
status = await CreatePairingAsync(args);
}
else if (command.Equals("FailOver", StringComparison.OrdinalIgnoreCase))
{
status = await FailOverAsync(args);
}
else if (command.Equals("BreakPairing", StringComparison.OrdinalIgnoreCase))
{
status = await BreakPairingAsync(args);
}
else if (command.Equals("DeleteAlias", StringComparison.OrdinalIgnoreCase))
{
status = await DeleteAliasAsync(args);
}
else if (command.Equals("GetConnectionStrings", StringComparison.OrdinalIgnoreCase))
{
status = await GetConnectionStringsAsync(args);
}
else
{
Console.WriteLine("Invalid command");
status = -1;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error while executing '{command}'{Environment.NewLine}Exception: {ex}'");
status = -2;
}
return status;
}
private async Task<EventHubManagementClient> GetClientAsync(GeoDRConfig config)
{
var token = await GetAuthorizationHeaderAsync(config);
var creds = new TokenCredentials(token);
var client = new EventHubManagementClient(creds) { SubscriptionId = config.SubscriptionId };
return client;
}
private async Task<int> CreatePairingAsync(string[] args)
{
var config = LoadConfig(args[1]);
var client = await GetClientAsync(config);
// 1. Create Primary Namespace (optional)
await CreateOrUpdateNamespaceAsync(
client,
config.PrimaryResourceGroupName,
config.PrimaryNamespace,
config.PrimaryNamespaceLocation,
config.SkuName);
//// 2. Create Secondary Namespace
var secondaryNamespaceInfo = await CreateOrUpdateNamespaceAsync(
client,
config.SecondaryResourceGroupName,
config.SecondaryNamespace,
config.SecondaryNamespaceLocation,
config.SkuName);
// 3. Pair the namespaces to enable DR.
// If you re-run this program while namespaces are still paired this operation will fail with a bad request.
// This is because we block all updates on secondary namespaces once it is paired
ArmDisasterRecovery adr = await client.DisasterRecoveryConfigs.CreateOrUpdateAsync(
config.PrimaryResourceGroupName,
config.PrimaryNamespace,
config.Alias,
new ArmDisasterRecovery() { PartnerNamespace = secondaryNamespaceInfo.Id });
while (adr.ProvisioningState != ProvisioningStateDR.Succeeded)
{
Console.WriteLine($"Waiting for DR to be setup. Current State: {adr.ProvisioningState}");
adr = await client.DisasterRecoveryConfigs.GetAsync(
config.PrimaryResourceGroupName,
config.PrimaryNamespace,
config.Alias);
await Task.Delay(TimeSpan.FromSeconds(30));
}
Console.WriteLine($"Pairing namespaces completed. Details: {Environment.NewLine}{adr.ToJson()}");
// Perform verifications (optional)
const string eventHubName = "myEH1";
const string consumerGroupName = "myEH1-CG1";
const int syncingDelay = 60;
// Create an event hub and a consumer group within it. This is metadata and this metadata info replicates to the secondary namespace
// since we have established the Geo DR pairing earlier.
await client.EventHubs.CreateOrUpdateAsync(config.PrimaryResourceGroupName, config.PrimaryNamespace, eventHubName, new Eventhub());
await client.ConsumerGroups.CreateOrUpdateAsync(config.PrimaryResourceGroupName, config.PrimaryNamespace, eventHubName, consumerGroupName, new ConsumerGroup());
Console.WriteLine($"Waiting for {syncingDelay}s to allow metadata to sync across primary and secondary...");
await Task.Delay(TimeSpan.FromSeconds(syncingDelay));
// Verify that EventHubs and Consumer groups are present in secondary
var accessingEHFromSecondary = await client.EventHubs.GetAsync(config.SecondaryResourceGroupName, config.SecondaryNamespace, eventHubName);
Console.WriteLine($"{accessingEHFromSecondary.Name} successfully replicated");
var accessingCGFromSecondary = await client.ConsumerGroups.GetAsync(config.SecondaryResourceGroupName, config.SecondaryNamespace, eventHubName, consumerGroupName);
Console.WriteLine($"{accessingCGFromSecondary.Name} successfully replicated");
return 0;
}
private async Task<int> FailOverAsync(string[] args)
{
var config = LoadConfig(args[1]);
var client = await GetClientAsync(config);
// We perform Failover here
// Note that this Failover operations is ALWAYS run against the secondary (because primary might be down at time of failover)
Console.WriteLine("Performing failover to secondary namespace...");
await client.DisasterRecoveryConfigs.FailOverAsync(config.SecondaryResourceGroupName, config.SecondaryNamespace, config.Alias);
Console.WriteLine("Failover successfully completed");
// get alias connectionstrings
var accessKeys = await client.Namespaces.ListKeysAsync(config.PrimaryResourceGroupName, config.PrimaryNamespace, "RootManageSharedAccessKey");
var aliasPrimaryConnectionString = accessKeys.AliasPrimaryConnectionString;
var aliasSecondaryConnectionString = accessKeys.AliasSecondaryConnectionString;
return 0;
}
/// <summary>
/// In a Geo DR enabled namespace, the Event Hubs can be accessed only via the alias.
/// This is because, the alias can point to either the primary event hub or the failed over event hub
/// This way, the user doesn't have to adjust the connection strings in his/her apps to point to a
/// different event hub in the case of a failover.
/// </summary>
private async Task<int> GetConnectionStringsAsync(string[] args)
{
var config = LoadConfig(args[1]);
var client = await GetClientAsync(config);
Console.WriteLine("Getting connection strings...");
var accessKeys = await client.Namespaces.ListKeysAsync(config.PrimaryResourceGroupName, config.PrimaryNamespace, "RootManageSharedAccessKey");
var aliasPrimaryConnectionString = accessKeys.AliasPrimaryConnectionString;
var aliasSecondaryConnectionString = accessKeys.AliasSecondaryConnectionString;
Console.WriteLine($"Alias primary connection string: {Environment.NewLine}{aliasPrimaryConnectionString}");
Console.WriteLine($"Alias secondary connection string: {Environment.NewLine}{aliasSecondaryConnectionString}");
return 0;
}
private async Task<string> GetAuthorizationHeaderAsync(GeoDRConfig config)
{
var context = new AuthenticationContext($"{config.ActiveDirectoryAuthority}/{config.TenantId}");
AuthenticationResult result = await context.AcquireTokenAsync(
config.ResourceManagerUrl,
new ClientCredential(config.ClientId, config.ClientSecrets));
if (result == null)
{
throw new InvalidOperationException("Failed to obtain token for authentication");
}
string token = result.AccessToken;
return token;
}
private async Task<int> BreakPairingAsync(string[] args)
{
var config = LoadConfig(args[1]);
var client = await GetClientAsync(config);
await client.DisasterRecoveryConfigs.BreakPairingAsync(config.PrimaryResourceGroupName, config.PrimaryNamespace, config.Alias);
return 0;
}
private async Task<int> DeleteAliasAsync(string[] args)
{
var config = LoadConfig(args[1]);
var client = await GetClientAsync(config);
// Before the alias is deleted, pairing needs to be broken
await client.DisasterRecoveryConfigs.DeleteAsync(config.PrimaryResourceGroupName, config.PrimaryNamespace, config.Alias);
return 0;
}
/// <summary>
/// Loads a config file SPECIFIC to this sample program.
/// </summary>
private static GeoDRConfig LoadConfig(string jsonConfigFile)
{
if (jsonConfigFile == null)
{
throw new ArgumentNullException(nameof(jsonConfigFile));
}
if (string.IsNullOrWhiteSpace(jsonConfigFile))
{
throw new ArgumentException($"{nameof(jsonConfigFile)} cannot be null or whitespace");
}
var json = File.ReadAllText(jsonConfigFile);
var o = json.FromJson<GeoDRConfig>();
return o;
}
private static async Task<EHNamespace> CreateOrUpdateNamespaceAsync(
EventHubManagementClient client,
string rgName,
string ns,
string location,
string skuName)
{
var namespaceParams = new EHNamespace
{
Location = location,
Sku = new Sku
{
Tier = skuName,
Name = skuName
}
};
var namespace1 = await client.Namespaces.CreateOrUpdateAsync(rgName, ns, namespaceParams);
Console.WriteLine($"{namespace1.Name} create/update completed");
return namespace1;
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using EventStore.ClientAPI.Common.Utils;
using EventStore.ClientAPI.SystemData;
namespace EventStore.ClientAPI.Transport.Http
{
internal class HttpAsyncClient
{
private static readonly UTF8Encoding UTF8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
static HttpAsyncClient()
{
ServicePointManager.MaxServicePointIdleTime = 10000;
ServicePointManager.DefaultConnectionLimit = 800;
}
private readonly ILogger _log;
public HttpAsyncClient(ILogger log)
{
Ensure.NotNull(log, "log");
_log = log;
}
//TODO GFY
//this is a really really stupid way of doing this and it only works properly if
//the moons align correctly in the 7th slot of jupiter on a tuesday when mercury
//is rising. However it sort of works right now (unless you have proxies/dns/other
//problems. The easy solution is to use httpclient from portable libraries but
//it is currently limited in license to windows only.
private void TimeoutCallback(object state, bool timedOut)
{
if(timedOut)
{
var req = state as HttpWebRequest;
if(req != null)
{
req.Abort();
}
}
}
public void Get(string url, UserCredentials userCredentials, TimeSpan timeout,
Action<HttpResponse> onSuccess, Action<Exception> onException)
{
Ensure.NotNull(url, "url");
Ensure.NotNull(onSuccess, "onSuccess");
Ensure.NotNull(onException, "onException");
Receive(HttpMethod.Get, url, userCredentials, timeout, onSuccess, onException);
}
public void Post(string url, string body, string contentType, TimeSpan timeout, UserCredentials userCredentials,
Action<HttpResponse> onSuccess, Action<Exception> onException)
{
Ensure.NotNull(url, "url");
Ensure.NotNull(body, "body");
Ensure.NotNull(contentType, "contentType");
Ensure.NotNull(onSuccess, "onSuccess");
Ensure.NotNull(onException, "onException");
Send(HttpMethod.Post, url, body, contentType, userCredentials, timeout, onSuccess, onException);
}
public void Delete(string url, UserCredentials userCredentials, TimeSpan timeout,
Action<HttpResponse> onSuccess, Action<Exception> onException)
{
Ensure.NotNull(url, "url");
Ensure.NotNull(onSuccess, "onSuccess");
Ensure.NotNull(onException, "onException");
Receive(HttpMethod.Delete, url, userCredentials, timeout, onSuccess, onException);
}
public void Put(string url, string body, string contentType, UserCredentials userCredentials, TimeSpan timeout,
Action<HttpResponse> onSuccess, Action<Exception> onException)
{
Ensure.NotNull(url, "url");
Ensure.NotNull(body, "body");
Ensure.NotNull(contentType, "contentType");
Ensure.NotNull(onSuccess, "onSuccess");
Ensure.NotNull(onException, "onException");
Send(HttpMethod.Put, url, body, contentType, userCredentials, timeout, onSuccess, onException);
}
private void Receive(string method, string url, UserCredentials userCredentials, TimeSpan timeout,
Action<HttpResponse> onSuccess, Action<Exception> onException)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
#if __MonoCS__
request.KeepAlive = false;
request.Pipelined = false;
#else
request.KeepAlive = true;
request.Pipelined = true;
#endif
if (userCredentials != null)
AddAuthenticationHeader(request, userCredentials);
var result = request.BeginGetResponse(ResponseAcquired, new ClientOperationState(_log, request, onSuccess, onException));
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, request,
(int)timeout.TotalMilliseconds, true);
}
private void Send(string method, string url, string body, string contentType, UserCredentials userCredentials, TimeSpan timeout,
Action<HttpResponse> onSuccess, Action<Exception> onException)
{
var request = (HttpWebRequest)WebRequest.Create(url);
var bodyBytes = UTF8NoBom.GetBytes(body);
request.Method = method;
request.KeepAlive = true;
request.Pipelined = true;
request.ContentLength = bodyBytes.Length;
request.ContentType = contentType;
if (userCredentials != null)
AddAuthenticationHeader(request, userCredentials);
var state = new ClientOperationState(_log, request, onSuccess, onException);
state.InputStream = new MemoryStream(bodyBytes);
var result = request.BeginGetRequestStream(GotRequestStream, state);
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, request,
(int) timeout.TotalMilliseconds, true);
}
private void AddAuthenticationHeader(HttpWebRequest request, UserCredentials userCredentials)
{
Ensure.NotNull(userCredentials, "userCredentials");
var httpAuthentication = string.Format("{0}:{1}", userCredentials.Username, userCredentials.Password);
var encodedCredentials = Convert.ToBase64String(Helper.UTF8NoBom.GetBytes(httpAuthentication));
request.Headers.Add("Authorization", string.Format("Basic {0}", encodedCredentials));
}
private void ResponseAcquired(IAsyncResult ar)
{
var state = (ClientOperationState)ar.AsyncState;
try
{
var response = (HttpWebResponse)state.Request.EndGetResponseExtended(ar);
var networkStream = response.GetResponseStream();
if (networkStream == null) throw new Exception("Response stream was null.");
state.Response = new HttpResponse(response);
state.InputStream = networkStream;
state.OutputStream = new MemoryStream();
var copier = new AsyncStreamCopier<ClientOperationState>(state.InputStream, state.OutputStream, state);
copier.Completed += ResponseRead;
copier.Start();
}
catch (Exception e)
{
state.Dispose();
state.OnError(e);
}
}
private void ResponseRead(object sender, EventArgs eventArgs)
{
var copier = (AsyncStreamCopier<ClientOperationState>)sender;
var state = copier.AsyncState;
if (copier.Error != null)
{
state.Dispose();
state.OnError(copier.Error);
return;
}
state.OutputStream.Seek(0, SeekOrigin.Begin);
var memStream = (MemoryStream)state.OutputStream;
state.Response.Body = UTF8NoBom.GetString(memStream.GetBuffer(), 0, (int)memStream.Length);
state.Dispose();
state.OnSuccess(state.Response);
}
private void GotRequestStream(IAsyncResult ar)
{
var state = (ClientOperationState)ar.AsyncState;
try
{
var networkStream = state.Request.EndGetRequestStream(ar);
state.OutputStream = networkStream;
var copier = new AsyncStreamCopier<ClientOperationState>(state.InputStream, networkStream, state);
copier.Completed += RequestWrote;
copier.Start();
}
catch (Exception e)
{
state.Dispose();
state.OnError(e);
}
}
private void RequestWrote(object sender, EventArgs eventArgs)
{
var copier = (AsyncStreamCopier<ClientOperationState>)sender;
var state = copier.AsyncState;
var httpRequest = state.Request;
if (copier.Error != null)
{
state.Dispose();
state.OnError(copier.Error);
return;
}
state.Dispose();
httpRequest.BeginGetResponse(ResponseAcquired, state);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Discord.Commands.Builders;
using Discord.Logging;
namespace Discord.Commands
{
/// <summary>
/// Provides a framework for building Discord commands.
/// </summary>
/// <remarks>
/// <para>
/// The service provides a framework for building Discord commands both dynamically via runtime builders or
/// statically via compile-time modules. To create a command module at compile-time, see
/// <see cref="ModuleBase" /> (most common); otherwise, see <see cref="ModuleBuilder" />.
/// </para>
/// <para>
/// This service also provides several events for monitoring command usages; such as
/// <see cref="Discord.Commands.CommandService.Log" /> for any command-related log events, and
/// <see cref="Discord.Commands.CommandService.CommandExecuted" /> for information about commands that have
/// been successfully executed.
/// </para>
/// </remarks>
public class CommandService : IDisposable
{
/// <summary>
/// Occurs when a command-related information is received.
/// </summary>
public event Func<LogMessage, Task> Log { add { _logEvent.Add(value); } remove { _logEvent.Remove(value); } }
internal readonly AsyncEvent<Func<LogMessage, Task>> _logEvent = new AsyncEvent<Func<LogMessage, Task>>();
/// <summary>
/// Occurs when a command is successfully executed without any error.
/// </summary>
/// <remarks>
/// This event is fired when a command has been executed, successfully or not. When a command fails to
/// execute during parsing or precondition stage, the CommandInfo may not be returned.
/// </remarks>
public event Func<Optional<CommandInfo>, ICommandContext, IResult, Task> CommandExecuted { add { _commandExecutedEvent.Add(value); } remove { _commandExecutedEvent.Remove(value); } }
internal readonly AsyncEvent<Func<Optional<CommandInfo>, ICommandContext, IResult, Task>> _commandExecutedEvent = new AsyncEvent<Func<Optional<CommandInfo>, ICommandContext, IResult, Task>>();
private readonly SemaphoreSlim _moduleLock;
private readonly ConcurrentDictionary<Type, ModuleInfo> _typedModuleDefs;
private readonly ConcurrentDictionary<Type, ConcurrentDictionary<Type, TypeReader>> _typeReaders;
private readonly ConcurrentDictionary<Type, TypeReader> _defaultTypeReaders;
private readonly ImmutableList<(Type EntityType, Type TypeReaderType)> _entityTypeReaders;
private readonly HashSet<ModuleInfo> _moduleDefs;
private readonly CommandMap _map;
internal readonly bool _caseSensitive, _throwOnError, _ignoreExtraArgs;
internal readonly char _separatorChar;
internal readonly RunMode _defaultRunMode;
internal readonly Logger _cmdLogger;
internal readonly LogManager _logManager;
internal readonly IReadOnlyDictionary<char, char> _quotationMarkAliasMap;
internal bool _isDisposed;
/// <summary>
/// Represents all modules loaded within <see cref="CommandService"/>.
/// </summary>
public IEnumerable<ModuleInfo> Modules => _moduleDefs.Select(x => x);
/// <summary>
/// Represents all commands loaded within <see cref="CommandService"/>.
/// </summary>
public IEnumerable<CommandInfo> Commands => _moduleDefs.SelectMany(x => x.Commands);
/// <summary>
/// Represents all <see cref="TypeReader" /> loaded within <see cref="CommandService"/>.
/// </summary>
public ILookup<Type, TypeReader> TypeReaders => _typeReaders.SelectMany(x => x.Value.Select(y => new { y.Key, y.Value })).ToLookup(x => x.Key, x => x.Value);
/// <summary>
/// Initializes a new <see cref="CommandService"/> class.
/// </summary>
public CommandService() : this(new CommandServiceConfig()) { }
/// <summary>
/// Initializes a new <see cref="CommandService"/> class with the provided configuration.
/// </summary>
/// <param name="config">The configuration class.</param>
/// <exception cref="InvalidOperationException">
/// The <see cref="RunMode"/> cannot be set to <see cref="RunMode.Default"/>.
/// </exception>
public CommandService(CommandServiceConfig config)
{
_caseSensitive = config.CaseSensitiveCommands;
_throwOnError = config.ThrowOnError;
_ignoreExtraArgs = config.IgnoreExtraArgs;
_separatorChar = config.SeparatorChar;
_defaultRunMode = config.DefaultRunMode;
_quotationMarkAliasMap = (config.QuotationMarkAliasMap ?? new Dictionary<char, char>()).ToImmutableDictionary();
if (_defaultRunMode == RunMode.Default)
throw new InvalidOperationException("The default run mode cannot be set to Default.");
_logManager = new LogManager(config.LogLevel);
_logManager.Message += async msg => await _logEvent.InvokeAsync(msg).ConfigureAwait(false);
_cmdLogger = _logManager.CreateLogger("Command");
_moduleLock = new SemaphoreSlim(1, 1);
_typedModuleDefs = new ConcurrentDictionary<Type, ModuleInfo>();
_moduleDefs = new HashSet<ModuleInfo>();
_map = new CommandMap(this);
_typeReaders = new ConcurrentDictionary<Type, ConcurrentDictionary<Type, TypeReader>>();
_defaultTypeReaders = new ConcurrentDictionary<Type, TypeReader>();
foreach (var type in PrimitiveParsers.SupportedTypes)
{
_defaultTypeReaders[type] = PrimitiveTypeReader.Create(type);
_defaultTypeReaders[typeof(Nullable<>).MakeGenericType(type)] = NullableTypeReader.Create(type, _defaultTypeReaders[type]);
}
var tsreader = new TimeSpanTypeReader();
_defaultTypeReaders[typeof(TimeSpan)] = tsreader;
_defaultTypeReaders[typeof(TimeSpan?)] = NullableTypeReader.Create(typeof(TimeSpan), tsreader);
_defaultTypeReaders[typeof(string)] =
new PrimitiveTypeReader<string>((string x, out string y) => { y = x; return true; }, 0);
var entityTypeReaders = ImmutableList.CreateBuilder<(Type, Type)>();
entityTypeReaders.Add((typeof(IMessage), typeof(MessageTypeReader<>)));
entityTypeReaders.Add((typeof(IChannel), typeof(ChannelTypeReader<>)));
entityTypeReaders.Add((typeof(IRole), typeof(RoleTypeReader<>)));
entityTypeReaders.Add((typeof(IUser), typeof(UserTypeReader<>)));
_entityTypeReaders = entityTypeReaders.ToImmutable();
}
//Modules
public async Task<ModuleInfo> CreateModuleAsync(string primaryAlias, Action<ModuleBuilder> buildFunc)
{
await _moduleLock.WaitAsync().ConfigureAwait(false);
try
{
var builder = new ModuleBuilder(this, null, primaryAlias);
buildFunc(builder);
var module = builder.Build(this, null);
return LoadModuleInternal(module);
}
finally
{
_moduleLock.Release();
}
}
/// <summary>
/// Add a command module from a <see cref="Type" />.
/// </summary>
/// <example>
/// <para>The following example registers the module <c>MyModule</c> to <c>commandService</c>.</para>
/// <code language="cs">
/// await commandService.AddModuleAsync<MyModule>(serviceProvider);
/// </code>
/// </example>
/// <typeparam name="T">The type of module.</typeparam>
/// <param name="services">The <see cref="IServiceProvider"/> for your dependency injection solution if using one; otherwise, pass <c>null</c>.</param>
/// <exception cref="ArgumentException">This module has already been added.</exception>
/// <exception cref="InvalidOperationException">
/// The <see cref="ModuleInfo"/> fails to be built; an invalid type may have been provided.
/// </exception>
/// <returns>
/// A task that represents the asynchronous operation for adding the module. The task result contains the
/// built module.
/// </returns>
public Task<ModuleInfo> AddModuleAsync<T>(IServiceProvider services) => AddModuleAsync(typeof(T), services);
/// <summary>
/// Adds a command module from a <see cref="Type" />.
/// </summary>
/// <param name="type">The type of module.</param>
/// <param name="services">The <see cref="IServiceProvider" /> for your dependency injection solution if using one; otherwise, pass <c>null</c> .</param>
/// <exception cref="ArgumentException">This module has already been added.</exception>
/// <exception cref="InvalidOperationException">
/// The <see cref="ModuleInfo"/> fails to be built; an invalid type may have been provided.
/// </exception>
/// <returns>
/// A task that represents the asynchronous operation for adding the module. The task result contains the
/// built module.
/// </returns>
public async Task<ModuleInfo> AddModuleAsync(Type type, IServiceProvider services)
{
services = services ?? EmptyServiceProvider.Instance;
await _moduleLock.WaitAsync().ConfigureAwait(false);
try
{
var typeInfo = type.GetTypeInfo();
if (_typedModuleDefs.ContainsKey(type))
throw new ArgumentException("This module has already been added.");
var module = (await ModuleClassBuilder.BuildAsync(this, services, typeInfo).ConfigureAwait(false)).FirstOrDefault();
if (module.Value == default(ModuleInfo))
throw new InvalidOperationException($"Could not build the module {type.FullName}, did you pass an invalid type?");
_typedModuleDefs[module.Key] = module.Value;
return LoadModuleInternal(module.Value);
}
finally
{
_moduleLock.Release();
}
}
/// <summary>
/// Add command modules from an <see cref="Assembly"/>.
/// </summary>
/// <param name="assembly">The <see cref="Assembly"/> containing command modules.</param>
/// <param name="services">The <see cref="IServiceProvider"/> for your dependency injection solution if using one; otherwise, pass <c>null</c>.</param>
/// <returns>
/// A task that represents the asynchronous operation for adding the command modules. The task result
/// contains an enumerable collection of modules added.
/// </returns>
public async Task<IEnumerable<ModuleInfo>> AddModulesAsync(Assembly assembly, IServiceProvider services)
{
services = services ?? EmptyServiceProvider.Instance;
await _moduleLock.WaitAsync().ConfigureAwait(false);
try
{
var types = await ModuleClassBuilder.SearchAsync(assembly, this).ConfigureAwait(false);
var moduleDefs = await ModuleClassBuilder.BuildAsync(types, this, services).ConfigureAwait(false);
foreach (var info in moduleDefs)
{
_typedModuleDefs[info.Key] = info.Value;
LoadModuleInternal(info.Value);
}
return moduleDefs.Select(x => x.Value).ToImmutableArray();
}
finally
{
_moduleLock.Release();
}
}
private ModuleInfo LoadModuleInternal(ModuleInfo module)
{
_moduleDefs.Add(module);
foreach (var command in module.Commands)
_map.AddCommand(command);
foreach (var submodule in module.Submodules)
LoadModuleInternal(submodule);
return module;
}
/// <summary>
/// Removes the command module.
/// </summary>
/// <param name="module">The <see cref="ModuleInfo" /> to be removed from the service.</param>
/// <returns>
/// A task that represents the asynchronous removal operation. The task result contains a value that
/// indicates whether the <paramref name="module"/> is successfully removed.
/// </returns>
public async Task<bool> RemoveModuleAsync(ModuleInfo module)
{
await _moduleLock.WaitAsync().ConfigureAwait(false);
try
{
return RemoveModuleInternal(module);
}
finally
{
_moduleLock.Release();
}
}
/// <summary>
/// Removes the command module.
/// </summary>
/// <typeparam name="T">The <see cref="Type"/> of the module.</typeparam>
/// <returns>
/// A task that represents the asynchronous removal operation. The task result contains a value that
/// indicates whether the module is successfully removed.
/// </returns>
public Task<bool> RemoveModuleAsync<T>() => RemoveModuleAsync(typeof(T));
/// <summary>
/// Removes the command module.
/// </summary>
/// <param name="type">The <see cref="Type"/> of the module.</param>
/// <returns>
/// A task that represents the asynchronous removal operation. The task result contains a value that
/// indicates whether the module is successfully removed.
/// </returns>
public async Task<bool> RemoveModuleAsync(Type type)
{
await _moduleLock.WaitAsync().ConfigureAwait(false);
try
{
if (!_typedModuleDefs.TryRemove(type, out var module))
return false;
return RemoveModuleInternal(module);
}
finally
{
_moduleLock.Release();
}
}
private bool RemoveModuleInternal(ModuleInfo module)
{
if (!_moduleDefs.Remove(module))
return false;
foreach (var cmd in module.Commands)
_map.RemoveCommand(cmd);
foreach (var submodule in module.Submodules)
{
RemoveModuleInternal(submodule);
}
return true;
}
//Type Readers
/// <summary>
/// Adds a custom <see cref="TypeReader" /> to this <see cref="CommandService" /> for the supplied object
/// type.
/// If <typeparamref name="T" /> is a <see cref="ValueType" />, a nullable <see cref="TypeReader" /> will
/// also be added.
/// If a default <see cref="TypeReader" /> exists for <typeparamref name="T" />, a warning will be logged
/// and the default <see cref="TypeReader" /> will be replaced.
/// </summary>
/// <typeparam name="T">The object type to be read by the <see cref="TypeReader"/>.</typeparam>
/// <param name="reader">An instance of the <see cref="TypeReader" /> to be added.</param>
public void AddTypeReader<T>(TypeReader reader)
=> AddTypeReader(typeof(T), reader);
/// <summary>
/// Adds a custom <see cref="TypeReader" /> to this <see cref="CommandService" /> for the supplied object
/// type.
/// If <paramref name="type" /> is a <see cref="ValueType" />, a nullable <see cref="TypeReader" /> for the
/// value type will also be added.
/// If a default <see cref="TypeReader" /> exists for <paramref name="type" />, a warning will be logged and
/// the default <see cref="TypeReader" /> will be replaced.
/// </summary>
/// <param name="type">A <see cref="Type" /> instance for the type to be read.</param>
/// <param name="reader">An instance of the <see cref="TypeReader" /> to be added.</param>
public void AddTypeReader(Type type, TypeReader reader)
{
if (_defaultTypeReaders.ContainsKey(type))
_ = _cmdLogger.WarningAsync($"The default TypeReader for {type.FullName} was replaced by {reader.GetType().FullName}." +
"To suppress this message, use AddTypeReader<T>(reader, true).");
AddTypeReader(type, reader, true);
}
/// <summary>
/// Adds a custom <see cref="TypeReader" /> to this <see cref="CommandService" /> for the supplied object
/// type.
/// If <typeparamref name="T" /> is a <see cref="ValueType" />, a nullable <see cref="TypeReader" /> will
/// also be added.
/// </summary>
/// <typeparam name="T">The object type to be read by the <see cref="TypeReader"/>.</typeparam>
/// <param name="reader">An instance of the <see cref="TypeReader" /> to be added.</param>
/// <param name="replaceDefault">
/// Defines whether the <see cref="TypeReader"/> should replace the default one for
/// <see cref="Type" /> if it exists.
/// </param>
public void AddTypeReader<T>(TypeReader reader, bool replaceDefault)
=> AddTypeReader(typeof(T), reader, replaceDefault);
/// <summary>
/// Adds a custom <see cref="TypeReader" /> to this <see cref="CommandService" /> for the supplied object
/// type.
/// If <paramref name="type" /> is a <see cref="ValueType" />, a nullable <see cref="TypeReader" /> for the
/// value type will also be added.
/// </summary>
/// <param name="type">A <see cref="Type" /> instance for the type to be read.</param>
/// <param name="reader">An instance of the <see cref="TypeReader" /> to be added.</param>
/// <param name="replaceDefault">
/// Defines whether the <see cref="TypeReader"/> should replace the default one for <see cref="Type" /> if
/// it exists.
/// </param>
public void AddTypeReader(Type type, TypeReader reader, bool replaceDefault)
{
if (replaceDefault && HasDefaultTypeReader(type))
{
_defaultTypeReaders.AddOrUpdate(type, reader, (k, v) => reader);
if (type.GetTypeInfo().IsValueType)
{
var nullableType = typeof(Nullable<>).MakeGenericType(type);
var nullableReader = NullableTypeReader.Create(type, reader);
_defaultTypeReaders.AddOrUpdate(nullableType, nullableReader, (k, v) => nullableReader);
}
}
else
{
var readers = _typeReaders.GetOrAdd(type, x => new ConcurrentDictionary<Type, TypeReader>());
readers[reader.GetType()] = reader;
if (type.GetTypeInfo().IsValueType)
AddNullableTypeReader(type, reader);
}
}
internal bool HasDefaultTypeReader(Type type)
{
if (_defaultTypeReaders.ContainsKey(type))
return true;
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsEnum)
return true;
return _entityTypeReaders.Any(x => type == x.EntityType || typeInfo.ImplementedInterfaces.Contains(x.TypeReaderType));
}
internal void AddNullableTypeReader(Type valueType, TypeReader valueTypeReader)
{
var readers = _typeReaders.GetOrAdd(typeof(Nullable<>).MakeGenericType(valueType), x => new ConcurrentDictionary<Type, TypeReader>());
var nullableReader = NullableTypeReader.Create(valueType, valueTypeReader);
readers[nullableReader.GetType()] = nullableReader;
}
internal IDictionary<Type, TypeReader> GetTypeReaders(Type type)
{
if (_typeReaders.TryGetValue(type, out var definedTypeReaders))
return definedTypeReaders;
return null;
}
internal TypeReader GetDefaultTypeReader(Type type)
{
if (_defaultTypeReaders.TryGetValue(type, out var reader))
return reader;
var typeInfo = type.GetTypeInfo();
//Is this an enum?
if (typeInfo.IsEnum)
{
reader = EnumTypeReader.GetReader(type);
_defaultTypeReaders[type] = reader;
return reader;
}
//Is this an entity?
for (int i = 0; i < _entityTypeReaders.Count; i++)
{
if (type == _entityTypeReaders[i].EntityType || typeInfo.ImplementedInterfaces.Contains(_entityTypeReaders[i].EntityType))
{
reader = Activator.CreateInstance(_entityTypeReaders[i].TypeReaderType.MakeGenericType(type)) as TypeReader;
_defaultTypeReaders[type] = reader;
return reader;
}
}
return null;
}
//Execution
/// <summary>
/// Searches for the command.
/// </summary>
/// <param name="context">The context of the command.</param>
/// <param name="argPos">The position of which the command starts at.</param>
/// <returns>The result containing the matching commands.</returns>
public SearchResult Search(ICommandContext context, int argPos)
=> Search(context.Message.Content.Substring(argPos));
/// <summary>
/// Searches for the command.
/// </summary>
/// <param name="context">The context of the command.</param>
/// <param name="input">The command string.</param>
/// <returns>The result containing the matching commands.</returns>
public SearchResult Search(ICommandContext context, string input)
=> Search(input);
public SearchResult Search(string input)
{
string searchInput = _caseSensitive ? input : input.ToLowerInvariant();
var matches = _map.GetCommands(searchInput).OrderByDescending(x => x.Command.Priority).ToImmutableArray();
if (matches.Length > 0)
return SearchResult.FromSuccess(input, matches);
else
return SearchResult.FromError(CommandError.UnknownCommand, "Unknown command.");
}
/// <summary>
/// Executes the command.
/// </summary>
/// <param name="context">The context of the command.</param>
/// <param name="argPos">The position of which the command starts at.</param>
/// <param name="services">The service to be used in the command's dependency injection.</param>
/// <param name="multiMatchHandling">The handling mode when multiple command matches are found.</param>
/// <returns>
/// A task that represents the asynchronous execution operation. The task result contains the result of the
/// command execution.
/// </returns>
public Task<IResult> ExecuteAsync(ICommandContext context, int argPos, IServiceProvider services, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception)
=> ExecuteAsync(context, context.Message.Content.Substring(argPos), services, multiMatchHandling);
/// <summary>
/// Executes the command.
/// </summary>
/// <param name="context">The context of the command.</param>
/// <param name="input">The command string.</param>
/// <param name="services">The service to be used in the command's dependency injection.</param>
/// <param name="multiMatchHandling">The handling mode when multiple command matches are found.</param>
/// <returns>
/// A task that represents the asynchronous execution operation. The task result contains the result of the
/// command execution.
/// </returns>
public async Task<IResult> ExecuteAsync(ICommandContext context, string input, IServiceProvider services, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception)
{
services = services ?? EmptyServiceProvider.Instance;
var searchResult = Search(input);
if (!searchResult.IsSuccess)
{
await _commandExecutedEvent.InvokeAsync(Optional.Create<CommandInfo>(), context, searchResult).ConfigureAwait(false);
return searchResult;
}
var commands = searchResult.Commands;
var preconditionResults = new Dictionary<CommandMatch, PreconditionResult>();
foreach (var match in commands)
{
preconditionResults[match] = await match.Command.CheckPreconditionsAsync(context, services).ConfigureAwait(false);
}
var successfulPreconditions = preconditionResults
.Where(x => x.Value.IsSuccess)
.ToArray();
if (successfulPreconditions.Length == 0)
{
//All preconditions failed, return the one from the highest priority command
var bestCandidate = preconditionResults
.OrderByDescending(x => x.Key.Command.Priority)
.FirstOrDefault(x => !x.Value.IsSuccess);
await _commandExecutedEvent.InvokeAsync(bestCandidate.Key.Command, context, bestCandidate.Value).ConfigureAwait(false);
return bestCandidate.Value;
}
//If we get this far, at least one precondition was successful.
var parseResultsDict = new Dictionary<CommandMatch, ParseResult>();
foreach (var pair in successfulPreconditions)
{
var parseResult = await pair.Key.ParseAsync(context, searchResult, pair.Value, services).ConfigureAwait(false);
if (parseResult.Error == CommandError.MultipleMatches)
{
IReadOnlyList<TypeReaderValue> argList, paramList;
switch (multiMatchHandling)
{
case MultiMatchHandling.Best:
argList = parseResult.ArgValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToImmutableArray();
paramList = parseResult.ParamValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToImmutableArray();
parseResult = ParseResult.FromSuccess(argList, paramList);
break;
}
}
parseResultsDict[pair.Key] = parseResult;
}
// Calculates the 'score' of a command given a parse result
float CalculateScore(CommandMatch match, ParseResult parseResult)
{
float argValuesScore = 0, paramValuesScore = 0;
if (match.Command.Parameters.Count > 0)
{
var argValuesSum = parseResult.ArgValues?.Sum(x => x.Values.OrderByDescending(y => y.Score).FirstOrDefault().Score) ?? 0;
var paramValuesSum = parseResult.ParamValues?.Sum(x => x.Values.OrderByDescending(y => y.Score).FirstOrDefault().Score) ?? 0;
argValuesScore = argValuesSum / match.Command.Parameters.Count;
paramValuesScore = paramValuesSum / match.Command.Parameters.Count;
}
var totalArgsScore = (argValuesScore + paramValuesScore) / 2;
return match.Command.Priority + totalArgsScore * 0.99f;
}
//Order the parse results by their score so that we choose the most likely result to execute
var parseResults = parseResultsDict
.OrderByDescending(x => CalculateScore(x.Key, x.Value));
var successfulParses = parseResults
.Where(x => x.Value.IsSuccess)
.ToArray();
if (successfulParses.Length == 0)
{
//All parses failed, return the one from the highest priority command, using score as a tie breaker
var bestMatch = parseResults
.FirstOrDefault(x => !x.Value.IsSuccess);
await _commandExecutedEvent.InvokeAsync(bestMatch.Key.Command, context, bestMatch.Value).ConfigureAwait(false);
return bestMatch.Value;
}
//If we get this far, at least one parse was successful. Execute the most likely overload.
var chosenOverload = successfulParses[0];
var result = await chosenOverload.Key.ExecuteAsync(context, chosenOverload.Value, services).ConfigureAwait(false);
if (!result.IsSuccess && !(result is RuntimeResult || result is ExecuteResult)) // succesful results raise the event in CommandInfo#ExecuteInternalAsync (have to raise it there b/c deffered execution)
await _commandExecutedEvent.InvokeAsync(chosenOverload.Key.Command, context, result);
return result;
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
_moduleLock?.Dispose();
}
_isDisposed = true;
}
}
void IDisposable.Dispose()
{
Dispose(true);
}
}
}
| |
// 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.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.MetadataAsSource;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SymbolMapping;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.MetadataAsSource
{
[Export(typeof(IMetadataAsSourceFileService))]
internal class MetadataAsSourceFileService : IMetadataAsSourceFileService
{
/// <summary>
/// A lock to guard parallel accesses to this type. In practice, we presume that it's not
/// an important scenario that we can be generating multiple documents in parallel, and so
/// we simply take this lock around all public entrypoints to enforce sequential access.
/// </summary>
private readonly SemaphoreSlim _gate = new SemaphoreSlim(initialCount: 1);
/// <summary>
/// For a description of the key, see GetKeyAsync.
/// </summary>
private readonly Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo> _keyToInformation = new Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo>();
private readonly Dictionary<string, MetadataAsSourceGeneratedFileInfo> _generatedFilenameToInformation = new Dictionary<string, MetadataAsSourceGeneratedFileInfo>(StringComparer.OrdinalIgnoreCase);
private IBidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId> _openedDocumentIds = BidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId>.Empty;
private MetadataAsSourceWorkspace _workspace;
/// <summary>
/// We create a mutex so other processes can see if our directory is still alive. We destroy the mutex when
/// we purge our generated files.
/// </summary>
private Mutex _mutex;
private string _rootTemporaryPathWithGuid;
private readonly string _rootTemporaryPath;
public MetadataAsSourceFileService()
{
_rootTemporaryPath = Path.Combine(Path.GetTempPath(), "MetadataAsSource");
}
private static string CreateMutexName(string directoryName)
{
return "MetadataAsSource-" + directoryName;
}
private string GetRootPathWithGuid_NoLock()
{
if (_rootTemporaryPathWithGuid == null)
{
var guidString = Guid.NewGuid().ToString("N");
_rootTemporaryPathWithGuid = Path.Combine(_rootTemporaryPath, guidString);
_mutex = new Mutex(initiallyOwned: true, name: CreateMutexName(guidString));
}
return _rootTemporaryPathWithGuid;
}
public async Task<MetadataAsSourceFile> GetGeneratedFileAsync(Project project, ISymbol symbol, CancellationToken cancellationToken = default(CancellationToken))
{
if (project == null)
{
throw new ArgumentNullException(nameof(project));
}
if (symbol == null)
{
throw new ArgumentNullException(nameof(symbol));
}
if (symbol.Kind == SymbolKind.Namespace)
{
throw new ArgumentException(EditorFeaturesResources.symbol_cannot_be_a_namespace, nameof(symbol));
}
symbol = symbol.GetOriginalUnreducedDefinition();
MetadataAsSourceGeneratedFileInfo fileInfo;
Location navigateLocation = null;
var topLevelNamedType = MetadataAsSourceHelpers.GetTopLevelContainingNamedType(symbol);
var symbolId = SymbolKey.Create(symbol, cancellationToken);
using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
InitializeWorkspace(project);
var infoKey = await GetUniqueDocumentKey(project, topLevelNamedType, cancellationToken).ConfigureAwait(false);
fileInfo = _keyToInformation.GetOrAdd(infoKey, _ => new MetadataAsSourceGeneratedFileInfo(GetRootPathWithGuid_NoLock(), project, topLevelNamedType));
_generatedFilenameToInformation[fileInfo.TemporaryFilePath] = fileInfo;
if (!File.Exists(fileInfo.TemporaryFilePath))
{
// We need to generate this. First, we'll need a temporary project to do the generation into. We
// avoid loading the actual file from disk since it doesn't exist yet.
var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: false);
var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1)
.GetDocument(temporaryProjectInfoAndDocumentId.Item2);
var sourceFromMetadataService = temporaryDocument.Project.LanguageServices.GetService<IMetadataAsSourceService>();
temporaryDocument = await sourceFromMetadataService.AddSourceToAsync(temporaryDocument, symbol, cancellationToken).ConfigureAwait(false);
// We have the content, so write it out to disk
var text = await temporaryDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
// Create the directory. It's possible a parallel deletion is happening in another process, so we may have
// to retry this a few times.
var directoryToCreate = Path.GetDirectoryName(fileInfo.TemporaryFilePath);
while (!Directory.Exists(directoryToCreate))
{
try
{
Directory.CreateDirectory(directoryToCreate);
}
catch (DirectoryNotFoundException)
{
}
catch (UnauthorizedAccessException)
{
}
}
using (var textWriter = new StreamWriter(fileInfo.TemporaryFilePath, append: false, encoding: fileInfo.Encoding))
{
text.Write(textWriter);
}
// Mark read-only
new FileInfo(fileInfo.TemporaryFilePath).IsReadOnly = true;
// Locate the target in the thing we just created
navigateLocation = await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false);
}
// If we don't have a location yet, then that means we're re-using an existing file. In this case, we'll want to relocate the symbol.
if (navigateLocation == null)
{
navigateLocation = await RelocateSymbol_NoLock(fileInfo, symbolId, cancellationToken).ConfigureAwait(false);
}
}
var documentName = string.Format(
"{0} [{1}]",
topLevelNamedType.Name,
EditorFeaturesResources.from_metadata);
var documentTooltip = topLevelNamedType.ToDisplayString(new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces));
return new MetadataAsSourceFile(fileInfo.TemporaryFilePath, navigateLocation, documentName, documentTooltip);
}
private async Task<Location> RelocateSymbol_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo, SymbolKey symbolId, CancellationToken cancellationToken)
{
// We need to relocate the symbol in the already existing file. If the file is open, we can just
// reuse that workspace. Otherwise, we have to go spin up a temporary project to do the binding.
if (_openedDocumentIds.TryGetValue(fileInfo, out var openDocumentId))
{
// Awesome, it's already open. Let's try to grab a document for it
var document = _workspace.CurrentSolution.GetDocument(openDocumentId);
return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, document, cancellationToken).ConfigureAwait(false);
}
// Annoying case: the file is still on disk. Only real option here is to spin up a fake project to go and bind in.
var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true);
var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1)
.GetDocument(temporaryProjectInfoAndDocumentId.Item2);
return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false);
}
public bool TryAddDocumentToWorkspace(string filePath, ITextBuffer buffer)
{
using (_gate.DisposableWait())
{
if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo))
{
Contract.ThrowIfTrue(_openedDocumentIds.ContainsKey(fileInfo));
// We do own the file, so let's open it up in our workspace
var newProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true);
_workspace.OnProjectAdded(newProjectInfoAndDocumentId.Item1);
_workspace.OnDocumentOpened(newProjectInfoAndDocumentId.Item2, buffer.AsTextContainer());
_openedDocumentIds = _openedDocumentIds.Add(fileInfo, newProjectInfoAndDocumentId.Item2);
return true;
}
}
return false;
}
public bool TryRemoveDocumentFromWorkspace(string filePath)
{
using (_gate.DisposableWait())
{
if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo))
{
if (_openedDocumentIds.ContainsKey(fileInfo))
{
RemoveDocumentFromWorkspace_NoLock(fileInfo);
return true;
}
}
}
return false;
}
private void RemoveDocumentFromWorkspace_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo)
{
var documentId = _openedDocumentIds.GetValueOrDefault(fileInfo);
Contract.ThrowIfNull(documentId);
_workspace.OnDocumentClosed(documentId, new FileTextLoader(fileInfo.TemporaryFilePath, fileInfo.Encoding));
_workspace.OnProjectRemoved(documentId.ProjectId);
_openedDocumentIds = _openedDocumentIds.RemoveKey(fileInfo);
}
private async Task<UniqueDocumentKey> GetUniqueDocumentKey(Project project, INamedTypeSymbol topLevelNamedType, CancellationToken cancellationToken)
{
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var peMetadataReference = compilation.GetMetadataReference(topLevelNamedType.ContainingAssembly) as PortableExecutableReference;
if (peMetadataReference.FilePath != null)
{
return new UniqueDocumentKey(peMetadataReference.FilePath, project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken));
}
else
{
return new UniqueDocumentKey(topLevelNamedType.ContainingAssembly.Identity, project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken));
}
}
private void InitializeWorkspace(Project project)
{
if (_workspace == null)
{
_workspace = new MetadataAsSourceWorkspace(this, project.Solution.Workspace.Services.HostServices);
}
}
internal async Task<SymbolMappingResult> MapSymbolAsync(Document document, SymbolKey symbolId, CancellationToken cancellationToken)
{
MetadataAsSourceGeneratedFileInfo fileInfo;
using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
if (!_openedDocumentIds.TryGetKey(document.Id, out fileInfo))
{
return null;
}
}
// WARANING: do not touch any state fields outside the lock.
var solution = fileInfo.Workspace.CurrentSolution;
var project = solution.GetProject(fileInfo.SourceProjectId);
if (project == null)
{
return null;
}
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var resolutionResult = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken);
if (resolutionResult.Symbol == null)
{
return null;
}
return new SymbolMappingResult(project, resolutionResult.Symbol);
}
public void CleanupGeneratedFiles()
{
using (_gate.DisposableWait())
{
// Release our mutex to indicate we're no longer using our directory and reset state
if (_mutex != null)
{
_mutex.Dispose();
_mutex = null;
_rootTemporaryPathWithGuid = null;
}
// Clone the list so we don't break our own enumeration
var generatedFileInfoList = _generatedFilenameToInformation.Values.ToList();
foreach (var generatedFileInfo in generatedFileInfoList)
{
if (_openedDocumentIds.ContainsKey(generatedFileInfo))
{
RemoveDocumentFromWorkspace_NoLock(generatedFileInfo);
}
}
_generatedFilenameToInformation.Clear();
_keyToInformation.Clear();
Contract.ThrowIfFalse(_openedDocumentIds.IsEmpty);
try
{
if (Directory.Exists(_rootTemporaryPath))
{
bool deletedEverything = true;
// Let's look through directories to delete.
foreach (var directoryInfo in new DirectoryInfo(_rootTemporaryPath).EnumerateDirectories())
{
// Is there a mutex for this one?
if (Mutex.TryOpenExisting(CreateMutexName(directoryInfo.Name), out var acquiredMutex))
{
acquiredMutex.Dispose();
deletedEverything = false;
continue;
}
TryDeleteFolderWhichContainsReadOnlyFiles(directoryInfo.FullName);
}
if (deletedEverything)
{
Directory.Delete(_rootTemporaryPath);
}
}
}
catch (Exception)
{
}
}
}
private static void TryDeleteFolderWhichContainsReadOnlyFiles(string directoryPath)
{
try
{
foreach (var fileInfo in new DirectoryInfo(directoryPath).EnumerateFiles("*", SearchOption.AllDirectories))
{
fileInfo.IsReadOnly = false;
}
Directory.Delete(directoryPath, recursive: true);
}
catch (Exception)
{
}
}
public bool IsNavigableMetadataSymbol(ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Event:
case SymbolKind.Field:
case SymbolKind.Method:
case SymbolKind.NamedType:
case SymbolKind.Property:
case SymbolKind.Parameter:
return true;
}
return false;
}
private class UniqueDocumentKey : IEquatable<UniqueDocumentKey>
{
private static readonly IEqualityComparer<SymbolKey> s_symbolIdComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true);
/// <summary>
/// The path to the assembly. Null in the case of in-memory assemblies, where we then use assembly identity.
/// </summary>
private readonly string _filePath;
/// <summary>
/// Assembly identity. Only non-null if filePath is null, where it's an in-memory assembly.
/// </summary>
private readonly AssemblyIdentity _assemblyIdentity;
private readonly string _language;
private readonly SymbolKey _symbolId;
public UniqueDocumentKey(string filePath, string language, SymbolKey symbolId)
{
Contract.ThrowIfNull(filePath);
_filePath = filePath;
_language = language;
_symbolId = symbolId;
}
public UniqueDocumentKey(AssemblyIdentity assemblyIdentity, string language, SymbolKey symbolId)
{
Contract.ThrowIfNull(assemblyIdentity);
_assemblyIdentity = assemblyIdentity;
_language = language;
_symbolId = symbolId;
}
public bool Equals(UniqueDocumentKey other)
{
if (other == null)
{
return false;
}
return StringComparer.OrdinalIgnoreCase.Equals(_filePath, other._filePath) &&
object.Equals(_assemblyIdentity, other._assemblyIdentity) &&
_language == other._language &&
s_symbolIdComparer.Equals(_symbolId, other._symbolId);
}
public override bool Equals(object obj)
{
return Equals(obj as UniqueDocumentKey);
}
public override int GetHashCode()
{
return
Hash.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath ?? string.Empty),
Hash.Combine(_assemblyIdentity != null ? _assemblyIdentity.GetHashCode() : 0,
Hash.Combine(_language.GetHashCode(),
s_symbolIdComparer.GetHashCode(_symbolId))));
}
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using WebApplication.Data;
namespace WebApplication.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc2-20901");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("WebApplication.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
using System;
using System.IO;
using System.Reflection;
using ToolKit.Cryptography;
using Xunit;
namespace UnitTests.Cryptography
{
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1600:ElementsMustBeDocumented",
Justification = "Test Suites do not need XML Documentation.")]
public class SymmetricEncryptionTests
{
private static readonly string _assemblyPath =
Path.GetDirectoryName(Assembly.GetAssembly(typeof(SymmetricEncryptionTests)).Location)
+ Path.DirectorySeparatorChar;
private readonly EncryptionData _targetData;
private readonly string _targetString;
public SymmetricEncryptionTests()
{
_targetString = "The instinct of nearly all societies is to lock up anybody who is truly free. " +
"First, society begins by trying to beat you up. If this fails, they try to poison you. " +
"If this fails too, they finish by loading honors on your head." +
" - Jean Cocteau (1889-1963)";
_targetData = new EncryptionData(_targetString);
}
[Fact]
public void Constructor_Should_ThrowExceptionWhenInvalidProvider()
{
// Arrange
var provider = (SymmetricEncryption.Provider)8;
// Act & Assert
Assert.Throws<ArgumentException>(() => new SymmetricEncryption(provider));
}
[Fact]
public void Decrypt_Should_ReturnExpectedResult_When_ProvidedKeyAndInitializationVector()
{
// Arrange
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael);
var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael);
var iv = new EncryptionData("vector");
var key = new EncryptionData("privatekey");
// Act
var encrypted = e1.Encrypt(new EncryptionData(_targetString), key, iv);
var decrypted = e2.Decrypt(encrypted, key, iv);
// -- the data will be padded to the encryption block size, so we need to trim it back down.
var actual = decrypted.Text.Substring(0, _targetData.Bytes.Length);
// Assert
Assert.Equal(_targetString, actual);
}
[Fact]
public void Decrypt_Should_ReturnWrongData_When_CorrectInitializationVectorIsNotProvided()
{
// Arrange
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael);
var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
Key = e1.Key
};
// Act
var encrypted = e1.Encrypt(_targetData);
var actual = e2.Decrypt(encrypted);
// Assert
Assert.NotEqual(_targetData.Hex, actual.Hex);
}
[Fact]
public void Decrypt_Should_ReturnWrongData_When_ProvidedWrongKey()
{
// Arrange
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael);
var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
InitializationVector = e1.InitializationVector
};
// Act
var key = new EncryptionData("SecretKey");
var wrong = new EncryptionData("wrongkey");
var encrypted = e1.Encrypt(_targetData, key);
var actual = e2.Decrypt(encrypted, wrong);
// Assert
Assert.NotEqual(_targetData.Hex, actual.Hex);
}
[Fact]
public void Encrypt_Should_UseRandomInitializationVector_When_NoInitializationVectorProvided()
{
// Arrange
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael);
var expected = e1.InitializationVector;
// Act
e1.Encrypt(_targetData);
// Assert
Assert.Equal(expected, e1.InitializationVector);
}
[Fact]
public void Encrypt_Should_UseRandomKey_When_NoKeyProvided()
{
// Arrange
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael);
var expected = e1.Key;
// Act
e1.Encrypt(_targetData);
// Assert
Assert.Equal(expected, e1.Key);
}
[Fact]
public void EncryptWithRijndael_Should_ReturnExpectedResult_When_ProvidedExplicitKey()
{
// Arrange
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael);
var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
InitializationVector = e1.InitializationVector
};
var key = new EncryptionData("SecretKey");
// Act
var encrypted = e1.Encrypt(_targetData, key);
var decrypted = e2.Decrypt(encrypted, key);
// -- the data will be padded to the encryption block size, so we need to trim it back down.
var actual = decrypted.Text.Substring(0, _targetData.Bytes.Length);
// Assert
Assert.Equal(_targetString, actual);
}
[Fact]
public void EncryptWithRijndael_Should_ReturnExpectedResult_When_ProvidedKeyAndinitializationVector()
{
// Arrange
var key = new EncryptionData("SecretKey");
var vector = new EncryptionData("InitializationVector");
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
InitializationVector = vector
};
var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
InitializationVector = vector
};
// Act
var encrypted = e1.Encrypt(_targetData, key);
var decrypted = e2.Decrypt(encrypted, key);
// -- the data will be padded to the encryption block size, so we need to trim it back down.
var actual = decrypted.Text.Substring(0, _targetData.Bytes.Length);
// Assert
Assert.Equal(_targetString, actual);
}
[Fact]
public void EncryptWithRijndael_Should_ReturnExpectedResult_When_UsingAutoGeneratedKeys()
{
// Arrange
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael);
var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
InitializationVector = e1.InitializationVector
};
// Act
var encrypted = e1.Encrypt(new EncryptionData(_targetString));
var decrypted = e2.Decrypt(encrypted, e1.Key);
// -- the data will be padded to the encryption block size, so we need to trim it back down.
var actual = decrypted.Text.Substring(0, _targetData.Bytes.Length);
// Assert
Assert.Equal(_targetString, actual);
}
[Fact]
public void EncryptWithRijndael_Should_ReturnExpectedResult_When_UsingStreamAndExplicitKey()
{
// Arrange
var expected = "4F32AB797F0FCC782AAC0B4F4E5B1693";
var key = new EncryptionData("0nTheDownLow1");
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael);
var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
InitializationVector = e1.InitializationVector
};
EncryptionData encrypted;
EncryptionData decrypted;
// Act
// -- Encrypt to memory
using (var sr = new StreamReader($"{_assemblyPath}sample.doc"))
{
encrypted = e1.Encrypt(sr.BaseStream, key);
}
// -- Write encrypted date to new binary file.
using (var bw = new BinaryWriter(new StreamWriter($"{_assemblyPath}encrypted.dat").BaseStream))
{
bw.Write(encrypted.Bytes);
bw.Close();
}
// -- Decrypt the binary file
using (var sr = new StreamReader($"{_assemblyPath}encrypted.dat"))
{
decrypted = e2.Decrypt(sr.BaseStream, key);
}
File.Delete($"{_assemblyPath}encrypted.dat");
var h = new Hash(Hash.Provider.MD5);
var actual = h.Calculate(decrypted).Hex;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void EncryptWithRijndael_Should_ReturnExpectedResult_When_UsingStreamAndKeyAndInitializationVector()
{
// Arrange
var expected = "4F32AB797F0FCC782AAC0B4F4E5B1693";
var key = new EncryptionData("0nTheDownLow1");
var iv = new EncryptionData("vector");
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael);
var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael);
EncryptionData encrypted;
EncryptionData decrypted;
// Act
// -- Encrypt to memory
using (var sr = new StreamReader($"{_assemblyPath}sample.doc"))
{
encrypted = e1.Encrypt(sr.BaseStream, key, iv);
}
// -- Write encrypted date to new binary file.
using (var bw = new BinaryWriter(new StreamWriter($"{_assemblyPath}encrypted.dat").BaseStream))
{
bw.Write(encrypted.Bytes);
bw.Close();
}
// -- Decrypt the binary file
using (var sr = new StreamReader($"{_assemblyPath}encrypted.dat"))
{
decrypted = e2.Decrypt(sr.BaseStream, key, iv);
}
File.Delete($"{_assemblyPath}encrypted.dat");
var h = new Hash(Hash.Provider.MD5);
var actual = h.Calculate(decrypted).Hex;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void EncryptWithTripleDES_Should_ReturnExpectedResult_When_ProvidedKeysAndInitializationVector()
{
// Arrange
var key = new EncryptionData("SecretKey");
var vector = new EncryptionData("InitializationVector");
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.TripleDES)
{
InitializationVector = vector
};
var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.TripleDES)
{
InitializationVector = vector
};
// Act
var encrypted = e1.Encrypt(_targetData, key);
var decrypted = e2.Decrypt(encrypted, key);
// -- the data will be padded to the encryption block size, so we need to trim it back down.
var actual = decrypted.Text.Substring(0, _targetData.Bytes.Length);
// Assert
Assert.Equal(_targetString, actual);
}
[Fact]
public void EncryptWithTripleDES_Should_ReturnExpectedResult_When_UsingAutoGeneratedKeys()
{
// Arrange
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.TripleDES);
var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.TripleDES)
{
InitializationVector = e1.InitializationVector
};
// Act
var encrypted = e1.Encrypt(new EncryptionData(_targetString));
var decrypted = e2.Decrypt(encrypted, e1.Key);
// -- the data will be padded to the encryption block size, so we need to trim it back down.
var actual = decrypted.Text.Substring(0, _targetData.Bytes.Length);
// Assert
Assert.Equal(_targetString, actual);
}
[Fact]
public void EncryptWithTripleDES_Should_ReturnExpectedResult_When_UsingStream()
{
// Arrange
var expected = "B5293E7C53966F4388D6B420A27CEBD7";
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.TripleDES)
{
Key = new EncryptionData("Password, Yo!"),
InitializationVector = new EncryptionData("MyInitializationVector")
};
var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.TripleDES)
{
Key = new EncryptionData("Password, Yo!"),
InitializationVector = new EncryptionData("MyInitializationVector")
};
EncryptionData encrypted;
EncryptionData decrypted;
// Act
// -- Encrypt to memory
using (var sr = new StreamReader($"{_assemblyPath}gettysburg.txt"))
{
encrypted = e1.Encrypt(sr.BaseStream);
}
// -- Write encrypted date to new binary file.
using (var bw = new BinaryWriter(new StreamWriter($"{_assemblyPath}encrypted.dat").BaseStream))
{
bw.Write(encrypted.Bytes);
bw.Close();
}
// -- Decrypt the binary file
using (var sr = new StreamReader($"{_assemblyPath}encrypted.dat"))
{
decrypted = e2.Decrypt(sr.BaseStream);
}
File.Delete($"{_assemblyPath}encrypted.dat");
var h = new Hash(Hash.Provider.MD5);
var actual = h.Calculate(decrypted).Hex;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void InitializationVector_Should_ReturnExpected_When_VectorProvided()
{
// Arrange
var expected = new EncryptionData("UnitTest");
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
InitializationVector = expected
};
// Act
var actual = e1.InitializationVector;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void KeySizeBits_Should_ReturnExpectedResult_When_KeySizeBytesIsSet()
{
// Arrange
var expected = 128;
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
KeySizeBytes = 16
};
// Act
var actual = e1.KeySizeBits;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void KeySizeBytes_Should_ReturnExpectedResult_When_KeySizeBitsIsSet()
{
// Arrange
var expected = 16;
var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
KeySizeBits = 128
};
// Act
var actual = e1.KeySizeBytes;
// Assert
Assert.Equal(expected, actual);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using OpenLiveWriter.Localization;
using OpenLiveWriter.CoreServices;
using System.Xml;
using OpenLiveWriter.PostEditor.ContentSources.Common;
namespace OpenLiveWriter.PostEditor.Video.YouTube
{
internal class YouTubeVideoPublisher : IVideoPublisher
{
public const string CLIENT_CODE = "";
public const string DEVELOPER_KEY = "";
private static VideoProvider _youTubeVideoProvider;
public YouTubeVideoPublisher()
{
if (_youTubeVideoProvider == null)
{
foreach (VideoProvider videoProvider in VideoProviderHelper.VideoProviders)
{
if (videoProvider.IsYouTube)
{
_youTubeVideoProvider = videoProvider;
return;
}
}
}
}
public IStatusWatcher Publish(string title, string description, string tags, string categoryId, string categoryString, string permissionValue, string permissionString, string path)
{
YouTubeVideoUploader uploader = new YouTubeVideoUploader(path, YouTubeAuth.Instance.AuthToken, title, description, tags, categoryId, permissionValue, _youTubeVideoProvider.UrlAtomPattern);
uploader.Start();
return uploader;
}
public string Id
{
get
{
return ID;
}
}
public const string ID = "A5D392D0-9D77-4212-A823-E1FFBBD9A71C";
public string ServiceName
{
get
{
return Res.Get(StringId.Plugin_Video_Youtube_Publish_Name);
}
}
public override string ToString()
{
return ServiceName;
}
public string FormatTags(string rawTags)
{
return StringHelper.Join(rawTags.Trim().Split(new char[] { ',', ' ' }), ", ", true);
}
public Video GetVideo(string title, string description, string tags, string categoryId, string categoryString, string permissionValue, string permissionString)
{
// Make the video by the ID that we got back form soapbox
Video video = _youTubeVideoProvider.CreateBlankVideo();
video.Permission = permissionString;
// This lets the editor know that it should track the progress by the status watcher
video.IsUploading = true;
return video;
}
private List<CategoryItem> _categories;
public List<CategoryItem> Categories
{
get
{
if (_categories == null)
{
_categories = new List<CategoryItem>();
_categories.Add(new CategoryItem("Film", Res.Get(StringId.Plugin_Video_Publish_Categories_Film)));
_categories.Add(new CategoryItem("Autos", Res.Get(StringId.Plugin_Video_Publish_Categories_Autos)));
_categories.Add(new CategoryItem("Music", Res.Get(StringId.Plugin_Video_Publish_Categories_Music)));
_categories.Add(new CategoryItem("Animals", Res.Get(StringId.Plugin_Video_Publish_Categories_Animals)));
_categories.Add(new CategoryItem("Sports", Res.Get(StringId.Plugin_Video_Publish_Categories_Sports)));
_categories.Add(new CategoryItem("Travel", Res.Get(StringId.Plugin_Video_Publish_Categories_Travel)));
_categories.Add(new CategoryItem("People", Res.Get(StringId.Plugin_Video_Publish_Categories_Blogs)));
_categories.Add(new CategoryItem("Games", Res.Get(StringId.Plugin_Video_Publish_Categories_Games)));
_categories.Add(new CategoryItem("Comedy", Res.Get(StringId.Plugin_Video_Publish_Categories_Comedy)));
_categories.Add(new CategoryItem("People", Res.Get(StringId.Plugin_Video_Publish_Categories_People)));
_categories.Add(new CategoryItem("News", Res.Get(StringId.Plugin_Video_Publish_Categories_News)));
_categories.Add(new CategoryItem("Entertainment", Res.Get(StringId.Plugin_Video_Publish_Categories_Entertainment)));
_categories.Add(new CategoryItem("Education", Res.Get(StringId.Plugin_Video_Publish_Categories_Education)));
_categories.Add(new CategoryItem("Howto", Res.Get(StringId.Plugin_Video_Publish_Categories_How_To)));
_categories.Add(new CategoryItem("Nonprofit", Res.Get(StringId.Plugin_Video_Publish_Categories_Non_Profit)));
_categories.Add(new CategoryItem("Tech", Res.Get(StringId.Plugin_Video_Publish_Categories_Technology)));
_categories.Sort();
}
return _categories;
}
}
public string FileFilter
{
get
{
// There was a typo in the file filter where it was ,*.mov instead of ;*.mov, so we replace it at runtime
// This should be removed after we branch for M2
string filter = Res.Get(StringId.Plugin_Video_YouTube_Publish_Video_File_Open_Filter_Ext);
string[] parts = StringHelper.Split(filter, "|");
parts[1] = "*.avi;*.wmv;*.mpg;*.mpeg;*.mp4;*.mpeg4;*.mov;";
return StringHelper.Join(parts, "|");
}
}
public string AcceptanceText
{
get
{
return Res.Get(StringId.Plugin_Video_YouTube_Publish_Terms_Agree);
}
}
public string AcceptanceUrl
{
get
{
return GLink.Instance.YouTubeTermOfUse;
}
}
public string SafetyTipUrl
{
get
{
return GLink.Instance.YouTubeSafety;
}
}
public IStatusWatcher CreateStatusWatcher(Video video)
{
if (YouTubeAuth.Instance.IsLoggedIn)
{
YouTubeVideoUploader uploader = new YouTubeVideoUploader(YouTubeAuth.Instance.Username, YouTubeAuth.Instance.AuthToken, video.Id, _youTubeVideoProvider.UrlAtomFormat);
uploader.Start();
return uploader;
}
return null;
}
public void Init(MediaSmartContent media, IWin32Window DialogOwner, string blogId)
{
}
public string AcceptanceTitle
{
get
{
return Res.Get(StringId.Plugin_Video_Publish_Terms_View);
}
}
public string SafetyTipTitle
{
get
{
return Res.Get(StringId.Plugin_Video_Publish_Safety_View);
}
}
public IAuth Auth
{
get
{
return YouTubeAuth.Instance;
}
}
public Bitmap Image
{
get { throw new Exception("The method or operation is not implemented."); }
}
public void Dispose()
{
}
}
internal class YouTubeVideoUploader : AsyncOperation, IStatusWatcher
{
private readonly string _filePath;
private readonly string _authToken;
private readonly string _title;
private readonly string _description;
private readonly string _tags;
private readonly string _categoryId;
private readonly string _permissionValue;
private readonly string _urlAtomPattern;
// this is the url to the feed which contains the status for the video
private volatile string _updateUrl;
private volatile string _message;
private volatile VideoPublishStatus _status;
private volatile string _id;
private volatile CancelableStream _stream;
public YouTubeVideoUploader(string path, string authToken, string title, string description, string tags, string categoryId, string permissionValue, string urlAtomPattern)
: base(null)
{
_filePath = path;
_authToken = authToken;
_title = title;
_description = description;
_tags = tags;
_categoryId = categoryId;
_permissionValue = permissionValue;
_urlAtomPattern = urlAtomPattern;
}
public YouTubeVideoUploader(string username, string authToken, string videoId, string urlAtomFormat)
: base(null)
{
_filePath = String.Empty;
_authToken = authToken;
_title = String.Empty;
_description = String.Empty;
_tags = String.Empty;
_categoryId = String.Empty;
_permissionValue = String.Empty;
_updateUrl = urlAtomFormat.Replace("{user}", username).Replace("{videoId", videoId);
}
public PublishStatus Status
{
get
{
return new PublishStatus(_status, _message, _id);
}
}
public bool IsCancelable
{
get
{
return _status != VideoPublishStatus.Completed && YouTubeAuth.Instance.IsLoggedIn;
}
}
public void CancelPublish()
{
Cancel();
try
{
if (_stream != null)
{
_stream.Cancel();
_stream.Dispose();
_stream = null;
}
}
catch (NullReferenceException)
{
}
if (!string.IsNullOrEmpty(_updateUrl))
{
HttpWebRequest req = HttpRequestHelper.CreateHttpWebRequest(_updateUrl, true, -1, -1);
YouTubeUploadRequestHelper.AddSimpleHeader(req, _authToken);
req.Method = "DELETE";
req.GetResponse().Close();
}
}
public void Dispose()
{
Debug.Assert(_stream == null, "Failed to close file stream for YouTubeVideoPublisher.");
}
private string Upload()
{
HttpWebRequest req = HttpRequestHelper.CreateHttpWebRequest("http://uploads.gdata.youtube.com/feeds/api/users/default/uploads", true, -1, -1);
YouTubeUploadRequestHelper uploader = new YouTubeUploadRequestHelper(req);
uploader.AddHeader(_authToken, Path.GetFileName(Path.GetFileName(_filePath)));
uploader.Open();
uploader.AddXmlRequest(_title, _description, _tags, _categoryId, _permissionValue);
uploader.AddFile(_filePath);
uploader.Close();
try
{
using (_stream = new CancelableStream(new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
uploader.SendRequest(_stream);
}
}
finally
{
_stream = null;
}
string result;
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
using (StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
result = responseReader.ReadToEnd();
}
}
return result;
}
private XmlNamespaceManager _nsMgr;
private XmlNamespaceManager NamespaceManager
{
get
{
if (_nsMgr == null)
{
_nsMgr = new XmlNamespaceManager(new NameTable());
_nsMgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
_nsMgr.AddNamespace("gml", "http://www.opengis.net/gml");
_nsMgr.AddNamespace("georss", "http://www.w3.org/2005/Atom");
_nsMgr.AddNamespace("media", "http://search.yahoo.com/mrss/");
_nsMgr.AddNamespace("yt", "http://gdata.youtube.com/schemas/2007");
_nsMgr.AddNamespace("gd", "http://schemas.google.com/g/2005");
_nsMgr.AddNamespace("app", "http://purl.org/atom/app#");
}
return _nsMgr;
}
}
protected override void DoWork()
{
_status = VideoPublishStatus.LocalProcessing;
_message = Res.Get(StringId.VideoLoading);
try
{
if (string.IsNullOrEmpty(_updateUrl))
{
_message = Res.Get("Video" + _status);
string result;
try
{
result = Upload();
}
catch (WebException ex)
{
HandleWebException(ex);
return;
}
catch (Exception ex)
{
HandleException(ex);
return;
}
// Get the ID for this video
_id = ExtractIdFromResult(result);
}
_status = VideoPublishStatus.RemoteProcessing;
_message = String.Format(CultureInfo.CurrentCulture, Res.Get(StringId.VideoRemoteProcessing), Res.Get(StringId.Plugin_Video_Youtube_Publish_Name));
bool allow404 = true;
// Check to see if this video has been canceled already or is completed
while (_status != VideoPublishStatus.Completed && !CancelRequested)
{
try
{
// Check to see if the video has finished
if (IsVideoComepleted())
{
_status = VideoPublishStatus.Completed;
_message = Res.Get("Video" + _status);
return;
}
}
catch (WebException ex)
{
HttpWebResponse response = ex.Response as HttpWebResponse;
if (allow404 && response != null && response.StatusCode == HttpStatusCode.NotFound)
{
allow404 = false;
}
else
{
HandleWebException(ex);
return;
}
}
Thread.Sleep(30000);
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
private void HandleException(Exception ex)
{
Trace.WriteLine("Failed to upload video: " + ex);
_status = VideoPublishStatus.Error;
_message = Res.Get(StringId.YouTubeVideoError) + Environment.NewLine + Res.Get(StringId.VideoErrorTryAgain);
}
private void HandleWebException(WebException ex)
{
HttpRequestHelper.LogException(ex);
_status = VideoPublishStatus.Error;
if (ex.Status != WebExceptionStatus.ProtocolError)
_message = Res.Get(StringId.VideoNetworkError) + Environment.NewLine + Res.Get(StringId.VideoErrorTryAgain);
else
_message = Res.Get(StringId.YouTubeVideoError) + Environment.NewLine + Res.Get(StringId.VideoErrorTryAgain);
}
private bool IsVideoComepleted()
{
// Send a request to get the status
HttpWebRequest req = HttpRequestHelper.CreateHttpWebRequest(_updateUrl, true, -1, -1);
YouTubeUploadRequestHelper.AddSimpleHeader(req, _authToken);
string innerResult;
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
using (StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
innerResult = responseReader.ReadToEnd();
}
}
// Find the status elemnt
XmlDocument xmlDoc = new XmlDocument(NamespaceManager.NameTable);
xmlDoc.LoadXml(innerResult);
XmlNode stateNode = xmlDoc.SelectSingleNode("//atom:entry/app:control/yt:state", NamespaceManager);
// If there is no element with status, then the video is completed
if (stateNode == null)
{
_status = VideoPublishStatus.Completed;
_message = Res.Get("Video" + _status);
return true;
}
// Check to make sure the video doesnt have a bad status
string value = stateNode.Attributes["name"] != null ? stateNode.Attributes["name"].Value : "";
if (value == "rejected" || value == "failed")
{
throw new Exception(Res.Get("YouTube" + stateNode.Attributes["reasonCode"].Value));
}
return false;
}
private string ExtractIdFromResult(string result)
{
// Make sure we go some kind of result to work with
if (string.IsNullOrEmpty(result))
{
Trace.WriteLine("No result from YouTube upload.");
throw new Exception(Res.Get(StringId.YouTubeInvalidResult));
}
// Find the element that has a rel of self and tagname of link
XmlDocument xmlDoc = new XmlDocument(NamespaceManager.NameTable);
xmlDoc.LoadXml(result);
XmlNode selfNode = xmlDoc.SelectSingleNode("/atom:entry/atom:link[@rel='self']", NamespaceManager);
if (selfNode == null)
{
Trace.WriteLine("No rel=self in result from YouTube upload. Response: " + result);
throw new Exception(Res.Get(StringId.YouTubeInvalidResult));
}
// Set this as the url we can use to get status updates
_updateUrl = XmlHelper.GetUrl(selfNode, "@href", new Uri("http://uploads.gdata.youtube.com/feeds/api/users/default/uploads"));
if (string.IsNullOrEmpty(_updateUrl))
{
Trace.WriteLine("Could not get url for status updates. Response: " + result);
throw new Exception(Res.Get(StringId.YouTubeInvalidResult));
}
// Read the ID from the url
Match m = Regex.Match(_updateUrl, _urlAtomPattern);
if (!m.Success)
throw new Exception(Res.Get(StringId.YouTubeInvalidResult));
return m.Groups["id"].Value;
}
}
public class YouTubeUploadRequestHelper
{
private readonly string _boundary;
private readonly HttpWebRequest _request;
Stream _requestStream;
private MemoryStream _requestBodyTop = new MemoryStream();
private MemoryStream _requestBodyBottom = new MemoryStream();
private UTF8Encoding _utf8NoBOMEncoding = new UTF8Encoding(false);
internal YouTubeUploadRequestHelper(HttpWebRequest request)
{
_boundary = "--------------------------" + Guid.NewGuid().ToString().Replace("-", "");
_request = request;
_request.Method = "POST";
_request.ContentType = "multipart/related; boundary=\"" + _boundary + "\"";
}
internal void AddHeader(string authToken, string path)
{
AddSimpleHeader(_request, authToken);
_request.Headers.Add("Slug", path);
}
internal static void AddSimpleHeader(HttpWebRequest request, string authToken)
{
request.Headers.Add("Authorization", authToken);
//request.Headers.Add("X-GData-Client", YouTubeVideoPublisher.CLIENT_CODE);
request.Headers.Add("X-GData-Key", "key=" + YouTubeVideoPublisher.DEVELOPER_KEY);
}
internal void Open()
{
AddBoundary(true, _requestBodyTop);
}
internal void Close()
{
AddBoundary(false, _requestBodyBottom);
Write("--" + Environment.NewLine, _requestBodyBottom);
}
internal void AddBoundary(bool newLine, MemoryStream stream)
{
Write("--" + _boundary + (newLine ? Environment.NewLine : ""), stream);
}
internal void AddXmlRequest(string title, string description, string keywords, string category, string permission)
{
Write("Content-Type: application/atom+xml; charset=UTF-8" + Environment.NewLine + Environment.NewLine, _requestBodyTop);
MemoryStream xmlMemoryStream = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(xmlMemoryStream, Encoding.UTF8);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("entry", "http://www.w3.org/2005/Atom");
xmlWriter.WriteStartElement("media", "group", "http://search.yahoo.com/mrss/");
xmlWriter.WriteStartElement("media", "title", "http://search.yahoo.com/mrss/");
xmlWriter.WriteAttributeString("type", "plain");
xmlWriter.WriteString(title);
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("media", "description", "http://search.yahoo.com/mrss/");
xmlWriter.WriteAttributeString("type", "plain");
xmlWriter.WriteString(description);
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("media", "category", "http://search.yahoo.com/mrss/");
xmlWriter.WriteAttributeString("scheme", "http://gdata.youtube.com/schemas/2007/categories.cat");
xmlWriter.WriteString(category);
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("media", "keywords", "http://search.yahoo.com/mrss/");
xmlWriter.WriteString(keywords);
xmlWriter.WriteEndElement();
if (permission == "1")
{
xmlWriter.WriteStartElement("yt", "private", "http://gdata.youtube.com/schemas/2007");
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
xmlMemoryStream.Position = 0;
StreamReader sr = new StreamReader(xmlMemoryStream);
string newXML = sr.ReadToEnd();
Write(newXML + Environment.NewLine, _requestBodyTop);
AddBoundary(true, _requestBodyTop);
}
internal void AddFile(string filePath)
{
Write("Content-Type: " + MimeHelper.GetContentType(Path.GetExtension(filePath)) + Environment.NewLine, _requestBodyTop);
Write("Content-Transfer-Encoding: binary" + Environment.NewLine + Environment.NewLine, _requestBodyTop);
Write(Environment.NewLine, _requestBodyBottom);
}
private void Write(String s, MemoryStream stream)
{
byte[] newText = _utf8NoBOMEncoding.GetBytes(s);
stream.Write(newText, 0, newText.Length);
}
internal void SendRequest(CancelableStream stream)
{
_request.ContentLength = _requestBodyTop.Length + stream.Length + _requestBodyBottom.Length;
_request.AllowWriteStreamBuffering = false;
_requestStream = _request.GetRequestStream();
_requestStream.Write(_requestBodyTop.ToArray(), 0, (int)_requestBodyTop.Length);
StreamHelper.Transfer(stream, _requestStream, 8192, true);
_requestStream.Write(_requestBodyBottom.ToArray(), 0, (int)_requestBodyBottom.Length);
_requestStream.Close();
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
namespace Multiverse.Tools.WorldEditor
{
public class Property
{
public string Name;
public string Type;
public string Default;
public List<string> Enum;
}
public class NameValueTemplate
{
public string Name;
public bool Waypoint = false;
public bool Boundary = false;
public bool Road = false;
public bool Object = false;
public Dictionary<string, Property> properties;
}
public class NameValueTemplateCollection
{
Dictionary<string,NameValueTemplate> NameValueTemplates;
public NameValueTemplateCollection(string directoryName)
{
NameValueTemplates = new Dictionary<string, NameValueTemplate>();
if (Directory.Exists(directoryName))
{
foreach(string filename in Directory.GetFiles(directoryName))
{
if (filename.EndsWith(".xml") || filename.EndsWith(".Xml") || filename.EndsWith(".XML"))
{
TextReader r = new StreamReader(filename);
FromXML(r);
r.Close();
}
}
}
}
public List<string> List(string type)
{
List<string> list = new List<string>();
foreach (string Name in NameValueTemplates.Keys)
{
NameValueTemplate template;
NameValueTemplates.TryGetValue(Name, out template);
if (template != null)
{
if ((String.Equals(type, "Region") &&
template.Boundary) ||
(String.Equals(type, "Object") &&
template.Object) ||
(String.Equals(type, "Marker") &&
template.Waypoint) ||
(String.Equals(type, "Road") &&
template.Road))
{
list.Add(Name);
}
}
}
return list;
}
public List<string> NameValuePropertiesList(string templateName)
{
List<string> list = new List<string>();
NameValueTemplate template;
if (NameValueTemplates.TryGetValue(templateName, out template))
{
if (template != null)
{
foreach (string propertyName in template.properties.Keys)
{
list.Add(propertyName);
}
}
}
return list;
}
public string DefaultValue(string templateName, string propertyName)
{
NameValueTemplate template;
Property prop;
if (NameValueTemplates.TryGetValue(templateName, out template))
{
if ((template != null) && (template.properties.TryGetValue(propertyName, out prop)))
{
return prop.Default;
}
}
return "";
}
public string PropertyType(string templateName, string propertyName)
{
NameValueTemplate template;
Property prop;
if (NameValueTemplates.TryGetValue(templateName, out template))
{
if ((template != null) && (template.properties.TryGetValue(propertyName, out prop)))
{
return prop.Type;
}
}
return "";
}
public List<string> Enum(string typeName, string propertyName)
{
NameValueTemplate template;
Property prop;
if (NameValueTemplates.TryGetValue(typeName, out template))
{
if (template.properties.TryGetValue(propertyName, out prop))
{
return prop.Enum;
}
}
return null;
}
protected string parseTextNode(XmlTextReader r)
{
// read the value
r.Read();
if (r.NodeType == XmlNodeType.Whitespace)
{
while (r.NodeType == XmlNodeType.Whitespace)
{
r.Read();
}
}
if (r.NodeType != XmlNodeType.Text)
{
return (null);
}
string ret = r.Value;
// error out if we dont see an end element here
r.Read();
if (r.NodeType == XmlNodeType.Whitespace)
{
while (r.NodeType == XmlNodeType.Whitespace)
{
r.Read();
}
}
if (r.NodeType != XmlNodeType.EndElement)
{
// XXX - should generate an exception here?
return (null);
}
return (ret);
}
protected List<string> parseEnum(XmlTextReader r)
{
List<string> list = new List<string>();
while (r.Read())
{
if (r.NodeType == XmlNodeType.Whitespace)
{
continue;
}
if (r.NodeType == XmlNodeType.EndElement)
{
break;
}
if (r.NodeType == XmlNodeType.Element)
{
if (r.Name == "Value")
{
list.Add(parseTextNode(r));
}
}
if (r.NodeType != XmlNodeType.EndElement)
{
return null;
}
}
return list;
}
protected Dictionary<string, Property> parseTypeProperties(XmlTextReader r)
{
Dictionary<string, Property> props = new Dictionary<string, Property>();
while (r.Read())
{
if (r.NodeType == XmlNodeType.Whitespace)
{
continue;
}
if (r.NodeType == XmlNodeType.EndElement)
{
break;
}
if (r.NodeType == XmlNodeType.Element)
{
if (r.Name == "Property")
{
r.Read();
Property prop = parseTypeProperty(r);
props.Add(prop.Name, prop);
}
}
}
return props;
}
protected Property parseTypeProperty(XmlTextReader r)
{
Property prop = new Property();
while (r.Read())
{
if (r.NodeType == XmlNodeType.Whitespace)
{
continue;
}
if (r.NodeType == XmlNodeType.EndElement)
{
break;
}
if (r.NodeType == XmlNodeType.Element)
{
switch (r.Name)
{
case "Name":
prop.Name = parseTextNode(r);
break;
case "Type":
prop.Type = parseTextNode(r);
break;
case "Enums":
prop.Enum = parseEnum(r);
break;
case "Default":
prop.Default = parseTextNode(r);
break;
}
}
}
return prop;
}
private void parseObjectTypes(XmlTextReader r, NameValueTemplate template)
{
while (r.Read())
{
if (r.NodeType == XmlNodeType.Whitespace)
{
continue;
}
if (r.NodeType == XmlNodeType.Element)
{
switch (r.Name)
{
case "Marker":
template.Waypoint = true;
break;
case "Region":
template.Boundary = true;
break;
case "Road":
template.Road = true;
break;
case "StaticObject":
template.Object = true;
break;
}
}
if (r.NodeType == XmlNodeType.EndElement)
{
break;
}
}
}
protected Dictionary<string, NameValueTemplate> parseTemplate(XmlTextReader r)
{
NameValueTemplate template = new NameValueTemplate();
while (r.Read())
{
if (r.NodeType == XmlNodeType.Whitespace)
{
continue;
}
if (r.NodeType == XmlNodeType.Element)
{
switch (r.Name)
{
case "Name":
template.Name = parseTextNode(r);
break;
case "Properties":
r.Read();
template.properties = parseTypeProperties(r);
break;
case "ObjectTypes":
r.Read();
parseObjectTypes(r, template);
break;
}
}
}
NameValueTemplates.Add(template.Name, template);
return NameValueTemplates;
}
private void FromXML(TextReader t)
{
XmlTextReader r = new XmlTextReader(t);
while (r.Read())
{
if (r.NodeType == XmlNodeType.Whitespace)
{
continue;
}
// look for the start of the assets list
if (r.NodeType == XmlNodeType.Element)
{
if (r.Name == "NameValueTemplate")
{
// we found the list of assets, now parse it
parseTemplate(r);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.ObjectModel;
using System.Dynamic.Utils;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using DelegateHelpers = System.Linq.Expressions.Compiler.DelegateHelpers;
namespace System.Dynamic
{
/// <summary>
/// The dynamic call site binder that participates in the <see cref="DynamicMetaObject"/> binding protocol.
/// </summary>
/// <remarks>
/// The <see cref="CallSiteBinder"/> performs the binding of the dynamic operation using the runtime values
/// as input. On the other hand, the <see cref="DynamicMetaObjectBinder"/> participates in the <see cref="DynamicMetaObject"/>
/// binding protocol.
/// </remarks>
public abstract class DynamicMetaObjectBinder : CallSiteBinder
{
#region Public APIs
/// <summary>
/// Initializes a new instance of the <see cref="DynamicMetaObjectBinder"/> class.
/// </summary>
protected DynamicMetaObjectBinder()
{
}
/// <summary>
/// The result type of the operation.
/// </summary>
public virtual Type ReturnType
{
get { return typeof(object); }
}
/// <summary>
/// Performs the runtime binding of the dynamic operation on a set of arguments.
/// </summary>
/// <param name="args">An array of arguments to the dynamic operation.</param>
/// <param name="parameters">The array of <see cref="ParameterExpression"/> instances that represent the parameters of the call site in the binding process.</param>
/// <param name="returnLabel">A LabelTarget used to return the result of the dynamic binding.</param>
/// <returns>
/// An Expression that performs tests on the dynamic operation arguments, and
/// performs the dynamic operation if the tests are valid. If the tests fail on
/// subsequent occurrences of the dynamic operation, Bind will be called again
/// to produce a new <see cref="Expression"/> for the new argument types.
/// </returns>
public sealed override Expression Bind(object[] args, ReadOnlyCollection<ParameterExpression> parameters, LabelTarget returnLabel)
{
ContractUtils.RequiresNotNull(args, nameof(args));
ContractUtils.RequiresNotNull(parameters, nameof(parameters));
ContractUtils.RequiresNotNull(returnLabel, nameof(returnLabel));
if (args.Length == 0)
{
throw Error.OutOfRange("args.Length", 1);
}
if (parameters.Count == 0)
{
throw Error.OutOfRange("parameters.Count", 1);
}
if (args.Length != parameters.Count)
{
throw new ArgumentOutOfRangeException(nameof(args));
}
// Ensure that the binder's ReturnType matches CallSite's return
// type. We do this so meta objects and language binders can
// compose trees together without needing to insert converts.
Type expectedResult;
if (IsStandardBinder)
{
expectedResult = ReturnType;
if (returnLabel.Type != typeof(void) &&
!TypeUtils.AreReferenceAssignable(returnLabel.Type, expectedResult))
{
throw Error.BinderNotCompatibleWithCallSite(expectedResult, this, returnLabel.Type);
}
}
else
{
// Even for non-standard binders, we have to at least make sure
// it works with the CallSite's type to build the return.
expectedResult = returnLabel.Type;
}
DynamicMetaObject target = DynamicMetaObject.Create(args[0], parameters[0]);
DynamicMetaObject[] metaArgs = CreateArgumentMetaObjects(args, parameters);
DynamicMetaObject binding = Bind(target, metaArgs);
if (binding == null)
{
throw Error.BindingCannotBeNull();
}
Expression body = binding.Expression;
BindingRestrictions restrictions = binding.Restrictions;
// Ensure the result matches the expected result type.
if (expectedResult != typeof(void) &&
!TypeUtils.AreReferenceAssignable(expectedResult, body.Type))
{
//
// Blame the last person that handled the result: assume it's
// the dynamic object (if any), otherwise blame the language.
//
if (target.Value is IDynamicMetaObjectProvider)
{
throw Error.DynamicObjectResultNotAssignable(body.Type, target.Value.GetType(), this, expectedResult);
}
else
{
throw Error.DynamicBinderResultNotAssignable(body.Type, this, expectedResult);
}
}
// if the target is IDO, standard binders ask it to bind the rule so we may have a target-specific binding.
// it makes sense to restrict on the target's type in such cases.
// ideally IDO metaobjects should do this, but they often miss that type of "this" is significant.
if (IsStandardBinder && args[0] as IDynamicMetaObjectProvider != null)
{
if (restrictions == BindingRestrictions.Empty)
{
throw Error.DynamicBindingNeedsRestrictions(target.Value.GetType(), this);
}
}
// Add the return
if (body.NodeType != ExpressionType.Goto)
{
body = Expression.Return(returnLabel, body);
}
// Finally, add restrictions
if (restrictions != BindingRestrictions.Empty)
{
body = Expression.IfThen(restrictions.ToExpression(), body);
}
return body;
}
private static DynamicMetaObject[] CreateArgumentMetaObjects(object[] args, ReadOnlyCollection<ParameterExpression> parameters)
{
DynamicMetaObject[] mos;
if (args.Length != 1)
{
mos = new DynamicMetaObject[args.Length - 1];
for (int i = 1; i < args.Length; i++)
{
mos[i - 1] = DynamicMetaObject.Create(args[i], parameters[i]);
}
}
else
{
mos = DynamicMetaObject.EmptyMetaObjects;
}
return mos;
}
/// <summary>
/// When overridden in the derived class, performs the binding of the dynamic operation.
/// </summary>
/// <param name="target">The target of the dynamic operation.</param>
/// <param name="args">An array of arguments of the dynamic operation.</param>
/// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public abstract DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args);
/// <summary>
/// Gets an expression that will cause the binding to be updated. It
/// indicates that the expression's binding is no longer valid.
/// This is typically used when the "version" of a dynamic object has
/// changed.
/// </summary>
/// <param name="type">The <see cref="Expression.Type">Type</see> property of the resulting expression; any type is allowed.</param>
/// <returns>The update expression.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public Expression GetUpdateExpression(Type type)
{
return Expression.Goto(CallSiteBinder.UpdateLabel, type);
}
/// <summary>
/// Defers the binding of the operation until later time when the runtime values of all dynamic operation arguments have been computed.
/// </summary>
/// <param name="target">The target of the dynamic operation.</param>
/// <param name="args">An array of arguments of the dynamic operation.</param>
/// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public DynamicMetaObject Defer(DynamicMetaObject target, params DynamicMetaObject[] args)
{
ContractUtils.RequiresNotNull(target, nameof(target));
if (args == null)
{
return MakeDeferred(target.Restrictions, target);
}
else
{
return MakeDeferred(
target.Restrictions.Merge(BindingRestrictions.Combine(args)),
args.AddFirst(target)
);
}
}
/// <summary>
/// Defers the binding of the operation until later time when the runtime values of all dynamic operation arguments have been computed.
/// </summary>
/// <param name="args">An array of arguments of the dynamic operation.</param>
/// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public DynamicMetaObject Defer(params DynamicMetaObject[] args)
{
return MakeDeferred(BindingRestrictions.Combine(args), args);
}
private DynamicMetaObject MakeDeferred(BindingRestrictions rs, params DynamicMetaObject[] args)
{
var exprs = DynamicMetaObject.GetExpressions(args);
Type delegateType = DelegateHelpers.MakeDeferredSiteDelegate(args, ReturnType);
// Because we know the arguments match the delegate type (we just created the argument types)
// we go directly to DynamicExpression.Make to avoid a bunch of unnecessary argument validation
return new DynamicMetaObject(
DynamicExpression.Make(ReturnType, delegateType, this, new TrueReadOnlyCollection<Expression>(exprs)),
rs
);
}
#endregion
// used to detect standard MetaObjectBinders.
internal virtual bool IsStandardBinder
{
get
{
return false;
}
}
}
}
| |
using LambdicSql;
using LambdicSql.feat.Dapper;
using LambdicSql.SqlServer;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Data;
using System.Linq;
using Test.Helper;
using static LambdicSql.SqlServer.Symbol;
namespace Test
{
[TestClass]
public class TestSymbolFuncsDateAndTimeDataTypesAnd
{
public TestContext TestContext { get; set; }
public IDbConnection _connection;
[TestInitialize]
public void TestInitialize()
{
_connection = TestEnvironment.CreateConnection(TestContext);
_connection.Open();
}
[TestCleanup]
public void TestCleanup() => _connection.Dispose();
[TestMethod]
[Priority(1)]
public void Test_CurrentTimeStamp()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val = Current_TimeStamp()
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
CURRENT_TIMESTAMP AS Val");
}
[TestMethod]
[Priority(1)]
public void Test_DateAdd()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = DateAdd(DateAddElement.Year, 1, Current_TimeStamp()),
Val2 = DateAdd(DateAddElement.Quarter, 2, Current_TimeStamp()),
Val3 = DateAdd(DateAddElement.Month, 3, Current_TimeStamp()),
Val4 = DateAdd(DateAddElement.Dayofyear, 4, Current_TimeStamp()),
Val5 = DateAdd(DateAddElement.Day, 5, Current_TimeStamp()),
Val6 = DateAdd(DateAddElement.Week, 6, Current_TimeStamp()),
Val7 = DateAdd(DateAddElement.Weekday, 7, Current_TimeStamp()),
Val8 = DateAdd(DateAddElement.Hour, 8, Current_TimeStamp()),
Val9 = DateAdd(DateAddElement.Minute, 9, Current_TimeStamp()),
Val10 = DateAdd(DateAddElement.Second, 10, Current_TimeStamp()),
Val11 = DateAdd(DateAddElement.Millisecond, -11, SysDateTime()),
Val12 = DateAdd(DateAddElement.Microsecond, 12, SysDateTime()),
Val13 = DateAdd(DateAddElement.Nanosecond, -13, SysDateTime())
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DATEADD(YEAR, @p_0, CURRENT_TIMESTAMP) AS Val1,
DATEADD(QUARTER, @p_1, CURRENT_TIMESTAMP) AS Val2,
DATEADD(MONTH, @p_2, CURRENT_TIMESTAMP) AS Val3,
DATEADD(DAYOFYEAR, @p_3, CURRENT_TIMESTAMP) AS Val4,
DATEADD(DAY, @p_4, CURRENT_TIMESTAMP) AS Val5,
DATEADD(WEEK, @p_5, CURRENT_TIMESTAMP) AS Val6,
DATEADD(WEEKDAY, @p_6, CURRENT_TIMESTAMP) AS Val7,
DATEADD(HOUR, @p_7, CURRENT_TIMESTAMP) AS Val8,
DATEADD(MINUTE, @p_8, CURRENT_TIMESTAMP) AS Val9,
DATEADD(SECOND, @p_9, CURRENT_TIMESTAMP) AS Val10,
DATEADD(MILLISECOND, @p_10, SYSDATETIME()) AS Val11,
DATEADD(MICROSECOND, @p_11, SYSDATETIME()) AS Val12,
DATEADD(NANOSECOND, @p_12, SYSDATETIME()) AS Val13", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, 12, -13);
}
[TestMethod]
[Priority(1)]
public void Test_DateDiff()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = DateDiff(DateDiffElement.Year, Current_TimeStamp(), Current_TimeStamp()),
Val2 = DateDiff(DateDiffElement.Quarter, Current_TimeStamp(), Current_TimeStamp()),
Val3 = DateDiff(DateDiffElement.Month, Current_TimeStamp(), Current_TimeStamp()),
Val4 = DateDiff(DateDiffElement.Dayofyear, Current_TimeStamp(), SysDateTimeOffset()),
Val5 = DateDiff(DateDiffElement.Day, Current_TimeStamp(), SysDateTimeOffset()),
Val6 = DateDiff(DateDiffElement.Week, Current_TimeStamp(), SysDateTimeOffset()),
Val7 = DateDiff(DateDiffElement.Hour, SysDateTimeOffset(), Current_TimeStamp()),
Val8 = DateDiff(DateDiffElement.Minute, SysDateTimeOffset(), Current_TimeStamp()),
Val9 = DateDiff(DateDiffElement.Second, SysDateTimeOffset(), Current_TimeStamp()),
Val10 = DateDiff(DateDiffElement.Millisecond, SysDateTimeOffset(), SysDateTimeOffset()),
Val11 = DateDiff(DateDiffElement.Microsecond, SysDateTimeOffset(), SysDateTimeOffset()),
Val12 = DateDiff(DateDiffElement.Nanosecond, SysDateTimeOffset(), SysDateTimeOffset())
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DATEDIFF(YEAR, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) AS Val1,
DATEDIFF(QUARTER, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) AS Val2,
DATEDIFF(MONTH, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) AS Val3,
DATEDIFF(DAYOFYEAR, CURRENT_TIMESTAMP, SYSDATETIMEOFFSET()) AS Val4,
DATEDIFF(DAY, CURRENT_TIMESTAMP, SYSDATETIMEOFFSET()) AS Val5,
DATEDIFF(WEEK, CURRENT_TIMESTAMP, SYSDATETIMEOFFSET()) AS Val6,
DATEDIFF(HOUR, SYSDATETIMEOFFSET(), CURRENT_TIMESTAMP) AS Val7,
DATEDIFF(MINUTE, SYSDATETIMEOFFSET(), CURRENT_TIMESTAMP) AS Val8,
DATEDIFF(SECOND, SYSDATETIMEOFFSET(), CURRENT_TIMESTAMP) AS Val9,
DATEDIFF(MILLISECOND, SYSDATETIMEOFFSET(), SYSDATETIMEOFFSET()) AS Val10,
DATEDIFF(MICROSECOND, SYSDATETIMEOFFSET(), SYSDATETIMEOFFSET()) AS Val11,
DATEDIFF(NANOSECOND, SYSDATETIMEOFFSET(), SYSDATETIMEOFFSET()) AS Val12");
}
[TestMethod]
[Priority(1)]
public void Test_DateDiff_Big()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = DateDiff_Big(DateDiffElement.Year, Current_TimeStamp(), Current_TimeStamp()),
Val2 = DateDiff_Big(DateDiffElement.Quarter, Current_TimeStamp(), Current_TimeStamp()),
Val3 = DateDiff_Big(DateDiffElement.Month, Current_TimeStamp(), Current_TimeStamp()),
Val4 = DateDiff_Big(DateDiffElement.Dayofyear, Current_TimeStamp(), SysDateTimeOffset()),
Val5 = DateDiff_Big(DateDiffElement.Day, Current_TimeStamp(), SysDateTimeOffset()),
Val6 = DateDiff_Big(DateDiffElement.Week, Current_TimeStamp(), SysDateTimeOffset()),
Val7 = DateDiff_Big(DateDiffElement.Hour, SysDateTimeOffset(), Current_TimeStamp()),
Val8 = DateDiff_Big(DateDiffElement.Minute, SysDateTimeOffset(), Current_TimeStamp()),
Val9 = DateDiff_Big(DateDiffElement.Second, SysDateTimeOffset(), Current_TimeStamp()),
Val10 = DateDiff_Big(DateDiffElement.Millisecond, SysDateTimeOffset(), SysDateTimeOffset()),
Val11 = DateDiff_Big(DateDiffElement.Microsecond, SysDateTimeOffset(), SysDateTimeOffset()),
Val12 = DateDiff_Big(DateDiffElement.Nanosecond, SysDateTimeOffset(), SysDateTimeOffset())
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DATEDIFF_BIG(YEAR, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) AS Val1,
DATEDIFF_BIG(QUARTER, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) AS Val2,
DATEDIFF_BIG(MONTH, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) AS Val3,
DATEDIFF_BIG(DAYOFYEAR, CURRENT_TIMESTAMP, SYSDATETIMEOFFSET()) AS Val4,
DATEDIFF_BIG(DAY, CURRENT_TIMESTAMP, SYSDATETIMEOFFSET()) AS Val5,
DATEDIFF_BIG(WEEK, CURRENT_TIMESTAMP, SYSDATETIMEOFFSET()) AS Val6,
DATEDIFF_BIG(HOUR, SYSDATETIMEOFFSET(), CURRENT_TIMESTAMP) AS Val7,
DATEDIFF_BIG(MINUTE, SYSDATETIMEOFFSET(), CURRENT_TIMESTAMP) AS Val8,
DATEDIFF_BIG(SECOND, SYSDATETIMEOFFSET(), CURRENT_TIMESTAMP) AS Val9,
DATEDIFF_BIG(MILLISECOND, SYSDATETIMEOFFSET(), SYSDATETIMEOFFSET()) AS Val10,
DATEDIFF_BIG(MICROSECOND, SYSDATETIMEOFFSET(), SYSDATETIMEOFFSET()) AS Val11,
DATEDIFF_BIG(NANOSECOND, SYSDATETIMEOFFSET(), SYSDATETIMEOFFSET()) AS Val12");
}
[TestMethod]
[Priority(1)]
public void Test_DateFromParts()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = DateFromParts(2017, 4, 2)
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DATEFROMPARTS(@p_0, @p_1, @p_2) AS Val1", 2017, 4, 2);
}
[TestMethod]
[Priority(1)]
public void Test_DateName()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = DateName(DateNameElement.Year, Current_TimeStamp()),
Val2 = DateName(DateNameElement.Quarter, SysDateTimeOffset()),
Val3 = DateName(DateNameElement.Month, Current_TimeStamp()),
Val4 = DateName(DateNameElement.Dayofyear, SysDateTimeOffset()),
Val5 = DateName(DateNameElement.Day, Current_TimeStamp()),
Val6 = DateName(DateNameElement.Week, SysDateTimeOffset()),
Val7 = DateName(DateNameElement.Weekday, Current_TimeStamp()),
Val8 = DateName(DateNameElement.Hour, SysDateTimeOffset()),
Val9 = DateName(DateNameElement.Minute, Current_TimeStamp()),
Val10 = DateName(DateNameElement.Second, SysDateTimeOffset()),
Val11 = DateName(DateNameElement.Millisecond, Current_TimeStamp()),
Val12 = DateName(DateNameElement.Microsecond, SysDateTimeOffset()),
Val13 = DateName(DateNameElement.Nanosecond, Current_TimeStamp()),
Val14 = DateName(DateNameElement.TZOffset, SysDateTimeOffset()),
Val15 = DateName(DateNameElement.ISO_WEEK, Current_TimeStamp())
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DATENAME(YEAR, CURRENT_TIMESTAMP) AS Val1,
DATENAME(QUARTER, SYSDATETIMEOFFSET()) AS Val2,
DATENAME(MONTH, CURRENT_TIMESTAMP) AS Val3,
DATENAME(DAYOFYEAR, SYSDATETIMEOFFSET()) AS Val4,
DATENAME(DAY, CURRENT_TIMESTAMP) AS Val5,
DATENAME(WEEK, SYSDATETIMEOFFSET()) AS Val6,
DATENAME(WEEKDAY, CURRENT_TIMESTAMP) AS Val7,
DATENAME(HOUR, SYSDATETIMEOFFSET()) AS Val8,
DATENAME(MINUTE, CURRENT_TIMESTAMP) AS Val9,
DATENAME(SECOND, SYSDATETIMEOFFSET()) AS Val10,
DATENAME(MILLISECOND, CURRENT_TIMESTAMP) AS Val11,
DATENAME(MICROSECOND, SYSDATETIMEOFFSET()) AS Val12,
DATENAME(NANOSECOND, CURRENT_TIMESTAMP) AS Val13,
DATENAME(TZOFFSET, SYSDATETIMEOFFSET()) AS Val14,
DATENAME(ISO_WEEK, CURRENT_TIMESTAMP) AS Val15");
}
[TestMethod]
[Priority(1)]
public void Test_DatePart()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = DatePart(DatePartElement.Year, Current_TimeStamp()),
Val2 = DatePart(DatePartElement.Quarter, Current_TimeStamp()),
Val3 = DatePart(DatePartElement.Month, Current_TimeStamp()),
Val4 = DatePart(DatePartElement.Dayofyear, Current_TimeStamp()),
Val5 = DatePart(DatePartElement.Day, Current_TimeStamp()),
Val6 = DatePart(DatePartElement.Week, Current_TimeStamp()),
Val7 = DatePart(DatePartElement.Weekday, Current_TimeStamp()),
Val8 = DatePart(DatePartElement.Hour, Current_TimeStamp()),
Val9 = DatePart(DatePartElement.Minute, Current_TimeStamp()),
Val10 = DatePart(DatePartElement.Second, Current_TimeStamp()),
Val11 = DatePart(DatePartElement.Millisecond, SysDateTimeOffset()),
Val12 = DatePart(DatePartElement.Microsecond, SysDateTimeOffset()),
Val13 = DatePart(DatePartElement.Nanosecond, SysDateTimeOffset()),
Val14 = DatePart(DatePartElement.ISO_WEEK, Current_TimeStamp())
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DATEPART(YEAR, CURRENT_TIMESTAMP) AS Val1,
DATEPART(QUARTER, CURRENT_TIMESTAMP) AS Val2,
DATEPART(MONTH, CURRENT_TIMESTAMP) AS Val3,
DATEPART(DAYOFYEAR, CURRENT_TIMESTAMP) AS Val4,
DATEPART(DAY, CURRENT_TIMESTAMP) AS Val5,
DATEPART(WEEK, CURRENT_TIMESTAMP) AS Val6,
DATEPART(WEEKDAY, CURRENT_TIMESTAMP) AS Val7,
DATEPART(HOUR, CURRENT_TIMESTAMP) AS Val8,
DATEPART(MINUTE, CURRENT_TIMESTAMP) AS Val9,
DATEPART(SECOND, CURRENT_TIMESTAMP) AS Val10,
DATEPART(MILLISECOND, SYSDATETIMEOFFSET()) AS Val11,
DATEPART(MICROSECOND, SYSDATETIMEOFFSET()) AS Val12,
DATEPART(NANOSECOND, SYSDATETIMEOFFSET()) AS Val13,
DATEPART(ISO_WEEK, CURRENT_TIMESTAMP) AS Val14");
}
[TestMethod]
[Priority(1)]
public void Test_DateTime2FromParts()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = DateTime2FromParts(2017, 4, 2, 14, 45, 1, 0, 0)
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DATETIME2FROMPARTS(@p_0, @p_1, @p_2, @p_3, @p_4, @p_5, @p_6, 0) AS Val1", 2017, 4, 2, 14, 45, 1, 0);
}
[TestMethod]
[Priority(1)]
public void Test_DateTimeFromParts()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = DateTimeFromParts(2017, 4, 2, 14, 45, 1, 100)
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DATETIMEFROMPARTS(@p_0, @p_1, @p_2, @p_3, @p_4, @p_5, @p_6) AS Val1", 2017, 4, 2, 14, 45, 1, 100);
}
[TestMethod]
[Priority(1)]
public void Test_DateTimeOffsetFromParts()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = DateTimeOffsetFromParts(2017, 4, 2, 14, 45, 1, 0, 9, 0, 0)
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DATETIMEOFFSETFROMPARTS(@p_0, @p_1, @p_2, @p_3, @p_4, @p_5, @p_6, @p_7, @p_8, 0) AS Val1", 2017, 4, 2, 14, 45, 1, 0, 9, 0);
}
[TestMethod]
[Priority(1)]
public void Test_Day()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = Day(Current_TimeStamp()),
Val2 = Day(SysDateTimeOffset())
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DAY(CURRENT_TIMESTAMP) AS Val1,
DAY(SYSDATETIMEOFFSET()) AS Val2");
}
[TestMethod]
[Priority(1)]
public void Test_EOMonth()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = EOMonth(Current_TimeStamp()),
Val2 = EOMonth(Current_TimeStamp(), 1),
Val3 = EOMonth(SysDateTimeOffset()),
Val4 = EOMonth(SysDateTimeOffset(), -1)
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
EOMONTH(CURRENT_TIMESTAMP) AS Val1,
EOMONTH(CURRENT_TIMESTAMP, @p_0) AS Val2,
EOMONTH(SYSDATETIMEOFFSET()) AS Val3,
EOMONTH(SYSDATETIMEOFFSET(), @p_1) AS Val4", 1, -1);
}
[TestMethod]
[Priority(1)]
public void Test_GetDate()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val = GetDate()
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
GETDATE() AS Val");
}
[TestMethod]
[Priority(1)]
public void Test_GetUtcDate()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val = GetUtcDate()
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
GETUTCDATE() AS Val");
}
[TestMethod]
[Priority(1)]
public void Test_IsDate()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = IsDate("2017-04-01"),
Val2 = IsDate(null),
Val3 = IsDate(20170401),
Val4 = IsDate(Current_TimeStamp()),
Val5 = IsDate("2017-04-01 12:34:56.000")
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
ISDATE(@p_0) AS Val1,
ISDATE(@p_1) AS Val2,
ISDATE(@p_2) AS Val3,
ISDATE(CURRENT_TIMESTAMP) AS Val4,
ISDATE(@p_3) AS Val5", "2017-04-01", null, 20170401, "2017-04-01 12:34:56.000");
}
[TestMethod]
[Priority(1)]
public void Test_Month()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = Month(Current_TimeStamp()),
Val2 = Month(SysDateTimeOffset())
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
MONTH(CURRENT_TIMESTAMP) AS Val1,
MONTH(SYSDATETIMEOFFSET()) AS Val2");
}
[TestMethod]
[Priority(1)]
public void Test_SmallDateTimeFromParts()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = SmallDateTimeFromParts(2017, 4, 2, 14, 45)
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
SMALLDATETIMEFROMPARTS(@p_0, @p_1, @p_2, @p_3, @p_4) AS Val1", 2017, 4, 2, 14, 45);
}
[TestMethod]
[Priority(1)]
public void Test_SwitchOffset()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val = SwitchOffset(SysDateTimeOffset(), "-04:00")
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
SWITCHOFFSET(SYSDATETIMEOFFSET(), @p_0) AS Val", "-04:00");
}
[TestMethod]
[Priority(1)]
public void Test_SysDateTime()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val = SysDateTime()
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
SYSDATETIME() AS Val");
}
[TestMethod]
[Priority(1)]
public void Test_SysDateTimeOffset()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val = SysDateTimeOffset()
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
SYSDATETIMEOFFSET() AS Val");
}
[TestMethod]
[Priority(1)]
public void Test_SysUtcDateTime()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val = SysUtcDateTime()
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
SYSUTCDATETIME() AS Val");
}
[TestMethod]
[Priority(1)]
public void Test_TimeFromParts()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = TimeFromParts(14, 45, 1, 0, 0)
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
TIMEFROMPARTS(@p_0, @p_1, @p_2, @p_3, 0) AS Val1", 14, 45, 1, 0);
}
[TestMethod]
[Priority(1)]
public void Test_ToDateTimeOffset()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val = ToDateTimeOffset(Current_TimeStamp(), "-04:00")
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
TODATETIMEOFFSET(CURRENT_TIMESTAMP, @p_0) AS Val", "-04:00");
}
[TestMethod]
[Priority(1)]
public void Test_Year()
{
var sql = Db<DB>.Sql(db =>
Select(new
{
Val1 = Year(Current_TimeStamp()),
Val2 = Year(SysDateTimeOffset())
}));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
YEAR(CURRENT_TIMESTAMP) AS Val1,
YEAR(SYSDATETIMEOFFSET()) AS Val2");
}
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright [email protected]
// Copyright iced contributors
#if ENCODER && BLOCK_ENCODER
using System;
using System.Diagnostics;
namespace Iced.Intel.BlockEncoderInternal {
/// <summary>
/// Jcc instruction
/// </summary>
sealed class JccInstr : Instr {
readonly int bitness;
Instruction instruction;
TargetInstr targetInstr;
BlockData? pointerData;
InstrKind instrKind;
readonly uint shortInstructionSize;
readonly uint nearInstructionSize;
// Code:
// !jcc short skip ; negated jcc opcode
// jmp qword ptr [rip+mem]
// skip:
const uint longInstructionSize64 = 2 + CallOrJmpPointerDataInstructionSize64;
enum InstrKind {
Unchanged,
Short,
Near,
Long,
Uninitialized,
}
public JccInstr(BlockEncoder blockEncoder, Block block, in Instruction instruction)
: base(block, instruction.IP) {
bitness = blockEncoder.Bitness;
this.instruction = instruction;
instrKind = InstrKind.Uninitialized;
Instruction instrCopy;
if (!blockEncoder.FixBranches) {
instrKind = InstrKind.Unchanged;
instrCopy = instruction;
instrCopy.NearBranch64 = 0;
Size = blockEncoder.GetInstructionSize(instrCopy, 0);
}
else {
instrCopy = instruction;
instrCopy.InternalSetCodeNoCheck(instruction.Code.ToShortBranch());
instrCopy.NearBranch64 = 0;
shortInstructionSize = blockEncoder.GetInstructionSize(instrCopy, 0);
instrCopy = instruction;
instrCopy.InternalSetCodeNoCheck(instruction.Code.ToNearBranch());
instrCopy.NearBranch64 = 0;
nearInstructionSize = blockEncoder.GetInstructionSize(instrCopy, 0);
if (blockEncoder.Bitness == 64) {
// Make sure it's not shorter than the real instruction. It can happen if there are extra prefixes.
Size = Math.Max(nearInstructionSize, longInstructionSize64);
}
else
Size = nearInstructionSize;
}
}
public override void Initialize(BlockEncoder blockEncoder) {
targetInstr = blockEncoder.GetTarget(instruction.NearBranchTarget);
TryOptimize();
}
public override bool Optimize() => TryOptimize();
bool TryOptimize() {
if (instrKind == InstrKind.Unchanged || instrKind == InstrKind.Short)
return false;
var targetAddress = targetInstr.GetAddress();
var nextRip = IP + shortInstructionSize;
long diff = (long)(targetAddress - nextRip);
if (sbyte.MinValue <= diff && diff <= sbyte.MaxValue) {
if (pointerData is not null)
pointerData.IsValid = false;
instrKind = InstrKind.Short;
Size = shortInstructionSize;
return true;
}
// If it's in the same block, we assume the target is at most 2GB away.
bool useNear = bitness != 64 || targetInstr.IsInBlock(Block);
if (!useNear) {
targetAddress = targetInstr.GetAddress();
nextRip = IP + nearInstructionSize;
diff = (long)(targetAddress - nextRip);
useNear = int.MinValue <= diff && diff <= int.MaxValue;
}
if (useNear) {
if (pointerData is not null)
pointerData.IsValid = false;
instrKind = InstrKind.Near;
Size = nearInstructionSize;
return true;
}
if (pointerData is null)
pointerData = Block.AllocPointerLocation();
instrKind = InstrKind.Long;
return false;
}
public override string? TryEncode(Encoder encoder, out ConstantOffsets constantOffsets, out bool isOriginalInstruction) {
string? errorMessage;
switch (instrKind) {
case InstrKind.Unchanged:
case InstrKind.Short:
case InstrKind.Near:
isOriginalInstruction = true;
if (instrKind == InstrKind.Unchanged) {
// nothing
}
else if (instrKind == InstrKind.Short)
instruction.InternalSetCodeNoCheck(instruction.Code.ToShortBranch());
else {
Debug.Assert(instrKind == InstrKind.Near);
instruction.InternalSetCodeNoCheck(instruction.Code.ToNearBranch());
}
instruction.NearBranch64 = targetInstr.GetAddress();
if (!encoder.TryEncode(instruction, IP, out _, out errorMessage)) {
constantOffsets = default;
return CreateErrorMessage(errorMessage, instruction);
}
constantOffsets = encoder.GetConstantOffsets();
return null;
case InstrKind.Long:
Debug2.Assert(pointerData is not null);
isOriginalInstruction = false;
constantOffsets = default;
pointerData.Data = targetInstr.GetAddress();
var instr = new Instruction();
instr.InternalSetCodeNoCheck(ShortJccToNativeJcc(instruction.Code.NegateConditionCode().ToShortBranch(), encoder.Bitness));
instr.Op0Kind = OpKind.NearBranch64;
Debug.Assert(encoder.Bitness == 64);
Debug.Assert(longInstructionSize64 <= sbyte.MaxValue);
instr.NearBranch64 = IP + longInstructionSize64;
if (!encoder.TryEncode(instr, IP, out uint instrLen, out errorMessage))
return CreateErrorMessage(errorMessage, instruction);
errorMessage = EncodeBranchToPointerData(encoder, isCall: false, IP + (uint)instrLen, pointerData, out _, Size - (uint)instrLen);
if (errorMessage is not null)
return CreateErrorMessage(errorMessage, instruction);
return null;
case InstrKind.Uninitialized:
default:
throw new InvalidOperationException();
}
}
static Code ShortJccToNativeJcc(Code code, int bitness) {
Code c16, c32, c64;
switch (code) {
case Code.Jo_rel8_16:
case Code.Jo_rel8_32:
case Code.Jo_rel8_64:
c16 = Code.Jo_rel8_16;
c32 = Code.Jo_rel8_32;
c64 = Code.Jo_rel8_64;
break;
case Code.Jno_rel8_16:
case Code.Jno_rel8_32:
case Code.Jno_rel8_64:
c16 = Code.Jno_rel8_16;
c32 = Code.Jno_rel8_32;
c64 = Code.Jno_rel8_64;
break;
case Code.Jb_rel8_16:
case Code.Jb_rel8_32:
case Code.Jb_rel8_64:
c16 = Code.Jb_rel8_16;
c32 = Code.Jb_rel8_32;
c64 = Code.Jb_rel8_64;
break;
case Code.Jae_rel8_16:
case Code.Jae_rel8_32:
case Code.Jae_rel8_64:
c16 = Code.Jae_rel8_16;
c32 = Code.Jae_rel8_32;
c64 = Code.Jae_rel8_64;
break;
case Code.Je_rel8_16:
case Code.Je_rel8_32:
case Code.Je_rel8_64:
c16 = Code.Je_rel8_16;
c32 = Code.Je_rel8_32;
c64 = Code.Je_rel8_64;
break;
case Code.Jne_rel8_16:
case Code.Jne_rel8_32:
case Code.Jne_rel8_64:
c16 = Code.Jne_rel8_16;
c32 = Code.Jne_rel8_32;
c64 = Code.Jne_rel8_64;
break;
case Code.Jbe_rel8_16:
case Code.Jbe_rel8_32:
case Code.Jbe_rel8_64:
c16 = Code.Jbe_rel8_16;
c32 = Code.Jbe_rel8_32;
c64 = Code.Jbe_rel8_64;
break;
case Code.Ja_rel8_16:
case Code.Ja_rel8_32:
case Code.Ja_rel8_64:
c16 = Code.Ja_rel8_16;
c32 = Code.Ja_rel8_32;
c64 = Code.Ja_rel8_64;
break;
case Code.Js_rel8_16:
case Code.Js_rel8_32:
case Code.Js_rel8_64:
c16 = Code.Js_rel8_16;
c32 = Code.Js_rel8_32;
c64 = Code.Js_rel8_64;
break;
case Code.Jns_rel8_16:
case Code.Jns_rel8_32:
case Code.Jns_rel8_64:
c16 = Code.Jns_rel8_16;
c32 = Code.Jns_rel8_32;
c64 = Code.Jns_rel8_64;
break;
case Code.Jp_rel8_16:
case Code.Jp_rel8_32:
case Code.Jp_rel8_64:
c16 = Code.Jp_rel8_16;
c32 = Code.Jp_rel8_32;
c64 = Code.Jp_rel8_64;
break;
case Code.Jnp_rel8_16:
case Code.Jnp_rel8_32:
case Code.Jnp_rel8_64:
c16 = Code.Jnp_rel8_16;
c32 = Code.Jnp_rel8_32;
c64 = Code.Jnp_rel8_64;
break;
case Code.Jl_rel8_16:
case Code.Jl_rel8_32:
case Code.Jl_rel8_64:
c16 = Code.Jl_rel8_16;
c32 = Code.Jl_rel8_32;
c64 = Code.Jl_rel8_64;
break;
case Code.Jge_rel8_16:
case Code.Jge_rel8_32:
case Code.Jge_rel8_64:
c16 = Code.Jge_rel8_16;
c32 = Code.Jge_rel8_32;
c64 = Code.Jge_rel8_64;
break;
case Code.Jle_rel8_16:
case Code.Jle_rel8_32:
case Code.Jle_rel8_64:
c16 = Code.Jle_rel8_16;
c32 = Code.Jle_rel8_32;
c64 = Code.Jle_rel8_64;
break;
case Code.Jg_rel8_16:
case Code.Jg_rel8_32:
case Code.Jg_rel8_64:
c16 = Code.Jg_rel8_16;
c32 = Code.Jg_rel8_32;
c64 = Code.Jg_rel8_64;
break;
default:
throw new ArgumentOutOfRangeException(nameof(code));
}
return bitness switch {
16 => c16,
32 => c32,
64 => c64,
_ => throw new ArgumentOutOfRangeException(nameof(bitness)),
};
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Persistence.Repositories
{
internal class AuditRepository : PetaPocoRepositoryBase<int, IAuditItem>, IAuditRepository
{
public AuditRepository(IScopeUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax)
: base(work, cache, logger, sqlSyntax)
{
}
/// <summary>
/// Return the audit items as paged result
/// </summary>
/// <param name="query">
/// The query coming from the service
/// </param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecords"></param>
/// <param name="orderDirection"></param>
/// <param name="auditTypeFilter">
/// Since we currently do not have enum support with our expression parser, we cannot query on AuditType in the query or the custom filter
/// so we need to do that here
/// </param>
/// <param name="customFilter">
/// A user supplied custom filter
/// </param>
/// <returns></returns>
public IEnumerable<IAuditItem> GetPagedResultsByQuery(IQuery<IAuditItem> query, long pageIndex, int pageSize,
out long totalRecords, Direction orderDirection,
AuditType[] auditTypeFilter,
IQuery<IAuditItem> customFilter)
{
if (auditTypeFilter == null) auditTypeFilter = new AuditType[0];
var sql = GetBaseQuery(false);
if (query == null) query = new Query<IAuditItem>();
var translatorIds = new SqlTranslator<IAuditItem>(sql, query);
var translatedQuery = translatorIds.Translate();
var customFilterWheres = customFilter != null ? customFilter.GetWhereClauses().ToArray() : null;
var hasCustomFilter = customFilterWheres != null && customFilterWheres.Length > 0;
if (hasCustomFilter)
{
var filterSql = new Sql();
var first = true;
foreach (var filterClaus in customFilterWheres)
{
if (first == false)
{
filterSql.Append(" AND ");
}
filterSql.Append(string.Format("({0})", filterClaus.Item1), filterClaus.Item2);
first = false;
}
translatedQuery = GetFilteredSqlForPagedResults(translatedQuery, filterSql);
}
if (auditTypeFilter.Length > 0)
{
var filterSql = new Sql();
var first = true;
foreach (var filterClaus in auditTypeFilter)
{
if (first == false || hasCustomFilter)
{
filterSql.Append(" AND ");
}
filterSql.Append("(logHeader = @logHeader)", new {logHeader = filterClaus.ToString() });
first = false;
}
translatedQuery = GetFilteredSqlForPagedResults(translatedQuery, filterSql);
}
if (orderDirection == Direction.Descending)
translatedQuery.OrderByDescending("Datestamp");
else
translatedQuery.OrderBy("Datestamp");
// Get page of results and total count
var pagedResult = Database.Page<LogDto>(pageIndex + 1, pageSize, translatedQuery);
totalRecords = pagedResult.TotalItems;
var pages = pagedResult.Items.Select(
dto => new AuditItem(dto.Id, dto.Comment, Enum<AuditType>.Parse(dto.Header), dto.UserId)).ToArray();
//Mapping the DateStamp
for (int i = 0; i < pages.Length; i++)
{
pages[i].CreateDate = pagedResult.Items[i].Datestamp;
}
return pages;
}
protected override void PersistUpdatedItem(IAuditItem entity)
{
Database.Insert(new LogDto
{
Comment = entity.Comment,
Datestamp = DateTime.Now,
Header = entity.AuditType.ToString(),
NodeId = entity.Id,
UserId = entity.UserId
});
}
protected override Sql GetBaseQuery(bool isCount)
{
var sql = new Sql()
.Select(isCount ? "COUNT(*)" : "umbracoLog.id, umbracoLog.userId, umbracoLog.NodeId, umbracoLog.Datestamp, umbracoLog.logHeader, umbracoLog.logComment, umbracoUser.userName, umbracoUser.avatar as userAvatar")
.From<LogDto>(SqlSyntax);
if (isCount == false)
{
sql = sql.LeftJoin<UserDto>(SqlSyntax).On<UserDto, LogDto>(SqlSyntax, dto => dto.Id, dto => dto.UserId);
}
return sql;
}
#region Not Implemented - not needed currently
protected override void PersistNewItem(IAuditItem entity)
{
throw new NotImplementedException();
}
protected override IAuditItem PerformGet(int id)
{
throw new NotImplementedException();
}
protected override IEnumerable<IAuditItem> PerformGetAll(params int[] ids)
{
throw new NotImplementedException();
}
protected override IEnumerable<IAuditItem> PerformGetByQuery(IQuery<IAuditItem> query)
{
throw new NotImplementedException();
}
protected override string GetBaseWhereClause()
{
throw new NotImplementedException();
}
protected override IEnumerable<string> GetDeleteClauses()
{
throw new NotImplementedException();
}
protected override Guid NodeObjectTypeId
{
get { throw new NotImplementedException(); }
}
#endregion
private Sql GetFilteredSqlForPagedResults(Sql sql, Sql filterSql)
{
Sql filteredSql;
// Apply filter
if (filterSql != null)
{
var sqlFilter = " WHERE " + filterSql.SQL.TrimStart("AND ");
//NOTE: this is certainly strange - NPoco handles this much better but we need to re-create the sql
// instance a couple of times to get the parameter order correct, for some reason the first
// time the arguments don't show up correctly but the SQL argument parameter names are actually updated
// accordingly - so we re-create it again. In v8 we don't need to do this and it's already taken care of.
filteredSql = new Sql(sql.SQL, sql.Arguments);
var args = filteredSql.Arguments.Concat(filterSql.Arguments).ToArray();
filteredSql = new Sql(
string.Format("{0} {1}", filteredSql.SQL, sqlFilter),
args);
filteredSql = new Sql(filteredSql.SQL, args);
}
else
{
//copy to var so that the original isn't changed
filteredSql = new Sql(sql.SQL, sql.Arguments);
}
return filteredSql;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Drawing;
#if __UNIFIED__
using UIKit;
#else
using MonoTouch.UIKit;
#endif
#if __UNIFIED__
using RectangleF = CoreGraphics.CGRect;
using SizeF = CoreGraphics.CGSize;
using PointF = CoreGraphics.CGPoint;
#else
using nfloat = System.Single;
using nint = System.Int32;
using nuint = System.UInt32;
#endif
namespace Xamarin.Forms.Platform.iOS
{
public class CarouselPageRenderer : UIViewController, IVisualElementRenderer
{
bool _appeared;
Dictionary<Page, UIView> _containerMap;
bool _disposed;
EventTracker _events;
bool _ignoreNativeScrolling;
UIScrollView _scrollView;
VisualElementTracker _tracker;
public CarouselPageRenderer()
{
if (!Forms.IsiOS7OrNewer)
WantsFullScreenLayout = true;
}
protected CarouselPage Carousel
{
get { return (CarouselPage)Element; }
}
protected int SelectedIndex
{
get { return (int)(_scrollView.ContentOffset.X / _scrollView.Frame.Width); }
set { ScrollToPage(value); }
}
public VisualElement Element { get; private set; }
public event EventHandler<VisualElementChangedEventArgs> ElementChanged;
public SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
{
return NativeView.GetSizeRequest(widthConstraint, heightConstraint);
}
public UIView NativeView
{
get { return View; }
}
public void SetElement(VisualElement element)
{
VisualElement oldElement = Element;
Element = element;
_containerMap = new Dictionary<Page, UIView>();
OnElementChanged(new VisualElementChangedEventArgs(oldElement, element));
if (element != null)
element.SendViewInitialized(NativeView);
}
public void SetElementSize(Size size)
{
Element.Layout(new Rectangle(Element.X, Element.Y, size.Width, size.Height));
}
public UIViewController ViewController
{
get { return this; }
}
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
_ignoreNativeScrolling = false;
View.SetNeedsLayout();
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if (_appeared || _disposed)
return;
_appeared = true;
Carousel.SendAppearing();
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
if (!_appeared || _disposed)
return;
_appeared = false;
Carousel.SendDisappearing();
}
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
View.Frame = View.Superview.Bounds;
_scrollView.Frame = View.Bounds;
PositionChildren();
UpdateCurrentPage(false);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
_tracker = new VisualElementTracker(this);
_events = new EventTracker(this);
_events.LoadEvents(View);
_scrollView = new UIScrollView { ShowsHorizontalScrollIndicator = false };
_scrollView.DecelerationEnded += OnDecelerationEnded;
UpdateBackground();
View.Add(_scrollView);
for (var i = 0; i < Element.LogicalChildren.Count; i++)
{
Element element = Element.LogicalChildren[i];
var child = element as ContentPage;
if (child != null)
InsertPage(child, i);
}
PositionChildren();
Carousel.PropertyChanged += OnPropertyChanged;
Carousel.PagesChanged += OnPagesChanged;
}
public override void ViewDidUnload()
{
base.ViewDidUnload();
if (_scrollView != null)
_scrollView.DecelerationEnded -= OnDecelerationEnded;
if (Carousel != null)
{
Carousel.PropertyChanged -= OnPropertyChanged;
Carousel.PagesChanged -= OnPagesChanged;
}
}
public override void WillRotate(UIInterfaceOrientation toInterfaceOrientation, double duration)
{
_ignoreNativeScrolling = true;
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
if (_scrollView != null)
_scrollView.DecelerationEnded -= OnDecelerationEnded;
if (Carousel != null)
{
Carousel.PropertyChanged -= OnPropertyChanged;
Carousel.PagesChanged -= OnPagesChanged;
}
Platform.SetRenderer(Element, null);
Clear();
if (_scrollView != null)
{
_scrollView.DecelerationEnded -= OnDecelerationEnded;
_scrollView.RemoveFromSuperview();
_scrollView = null;
}
if (_appeared)
{
_appeared = false;
Carousel.SendDisappearing();
}
if (_events != null)
{
_events.Dispose();
_events = null;
}
if (_tracker != null)
{
_tracker.Dispose();
_tracker = null;
}
Element = null;
_disposed = true;
}
base.Dispose(disposing);
}
protected virtual void OnElementChanged(VisualElementChangedEventArgs e)
{
EventHandler<VisualElementChangedEventArgs> changed = ElementChanged;
if (changed != null)
changed(this, e);
}
void Clear()
{
foreach (KeyValuePair<Page, UIView> kvp in _containerMap)
{
kvp.Value.RemoveFromSuperview();
IVisualElementRenderer renderer = Platform.GetRenderer(kvp.Key);
if (renderer != null)
{
renderer.ViewController.RemoveFromParentViewController();
renderer.NativeView.RemoveFromSuperview();
Platform.SetRenderer(kvp.Key, null);
}
}
_containerMap.Clear();
}
void InsertPage(ContentPage page, int index)
{
IVisualElementRenderer renderer = Platform.GetRenderer(page);
if (renderer == null)
{
renderer = Platform.CreateRenderer(page);
Platform.SetRenderer(page, renderer);
}
UIView container = new PageContainer(page);
container.AddSubview(renderer.NativeView);
_containerMap[page] = container;
AddChildViewController(renderer.ViewController);
_scrollView.InsertSubview(container, index);
if ((index == 0 && SelectedIndex == 0) || (index < SelectedIndex))
ScrollToPage(SelectedIndex + 1, false);
}
void OnDecelerationEnded(object sender, EventArgs eventArgs)
{
if (_ignoreNativeScrolling || SelectedIndex >= Element.LogicalChildren.Count)
return;
Carousel.CurrentPage = (ContentPage)Element.LogicalChildren[SelectedIndex];
}
void OnPagesChanged(object sender, NotifyCollectionChangedEventArgs e)
{
_ignoreNativeScrolling = true;
NotifyCollectionChangedAction action = e.Apply((o, i, c) => InsertPage((ContentPage)o, i), (o, i) => RemovePage((ContentPage)o, i), Reset);
PositionChildren();
_ignoreNativeScrolling = false;
if (action == NotifyCollectionChangedAction.Reset)
{
int index = Carousel.CurrentPage != null ? CarouselPage.GetIndex(Carousel.CurrentPage) : 0;
if (index < 0)
index = 0;
ScrollToPage(index);
}
}
void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "CurrentPage")
UpdateCurrentPage();
else if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
UpdateBackground();
else if (e.PropertyName == Page.BackgroundImageProperty.PropertyName)
UpdateBackground();
}
void PositionChildren()
{
nfloat x = 0;
RectangleF bounds = View.Bounds;
foreach (ContentPage child in ((CarouselPage)Element).Children)
{
UIView container = _containerMap[child];
container.Frame = new RectangleF(x, bounds.Y, bounds.Width, bounds.Height);
x += bounds.Width;
}
_scrollView.PagingEnabled = true;
_scrollView.ContentSize = new SizeF(bounds.Width * ((CarouselPage)Element).Children.Count, bounds.Height);
}
void RemovePage(ContentPage page, int index)
{
UIView container = _containerMap[page];
container.RemoveFromSuperview();
_containerMap.Remove(page);
IVisualElementRenderer renderer = Platform.GetRenderer(page);
if (renderer == null)
return;
renderer.ViewController.RemoveFromParentViewController();
renderer.NativeView.RemoveFromSuperview();
}
void Reset()
{
Clear();
for (var i = 0; i < Element.LogicalChildren.Count; i++)
{
Element element = Element.LogicalChildren[i];
var child = element as ContentPage;
if (child != null)
InsertPage(child, i);
}
}
void ScrollToPage(int index, bool animated = true)
{
if (_scrollView.ContentOffset.X == index * _scrollView.Frame.Width)
return;
_scrollView.SetContentOffset(new PointF(index * _scrollView.Frame.Width, 0), animated);
}
void UpdateBackground()
{
string bgImage = ((Page)Element).BackgroundImage;
if (!string.IsNullOrEmpty(bgImage))
{
View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromBundle(bgImage));
return;
}
Color bgColor = Element.BackgroundColor;
if (bgColor.IsDefault)
View.BackgroundColor = UIColor.White;
else
View.BackgroundColor = bgColor.ToUIColor();
}
void UpdateCurrentPage(bool animated = true)
{
ContentPage current = Carousel.CurrentPage;
if (current != null)
ScrollToPage(CarouselPage.GetIndex(current), animated);
}
class PageContainer : UIView
{
public PageContainer(VisualElement element)
{
Element = element;
}
public VisualElement Element { get; }
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (Subviews.Length > 0)
Subviews[0].Frame = new RectangleF(0, 0, (float)Element.Width, (float)Element.Height);
}
}
}
}
| |
// 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.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// A class that represents a script that you can run.
///
/// Create a script using a language specific script class such as CSharpScript or VisualBasicScript.
/// </summary>
public abstract class Script
{
internal readonly ScriptCompiler Compiler;
internal readonly ScriptBuilder Builder;
private Compilation _lazyCompilation;
internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt)
{
Debug.Assert(code != null);
Debug.Assert(options != null);
Debug.Assert(compiler != null);
Debug.Assert(builder != null);
Compiler = compiler;
Builder = builder;
Previous = previousOpt;
Code = code;
Options = options;
GlobalsType = globalsTypeOpt;
}
internal static Script<T> CreateInitialScript<T>(ScriptCompiler compiler, string codeOpt, ScriptOptions optionsOpt, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoaderOpt)
{
return new Script<T>(compiler, new ScriptBuilder(assemblyLoaderOpt ?? new InteractiveAssemblyLoader()), codeOpt ?? "", optionsOpt ?? ScriptOptions.Default, globalsTypeOpt, previousOpt: null);
}
/// <summary>
/// A script that will run first when this script is run.
/// Any declarations made in the previous script can be referenced in this script.
/// The end state from running this script includes all declarations made by both scripts.
/// </summary>
public Script Previous { get; }
/// <summary>
/// The options used by this script.
/// </summary>
public ScriptOptions Options { get; }
/// <summary>
/// The source code of the script.
/// </summary>
public string Code { get; }
/// <summary>
/// The type of an object whose members can be accessed by the script as global variables.
/// </summary>
public Type GlobalsType { get; }
/// <summary>
/// The expected return type of the script.
/// </summary>
public abstract Type ReturnType { get; }
/// <summary>
/// Creates a new version of this script with the specified options.
/// </summary>
public Script WithOptions(ScriptOptions options) => WithOptionsInternal(options);
internal abstract Script WithOptionsInternal(ScriptOptions options);
/// <summary>
/// Continues the script with given code snippet.
/// </summary>
public Script<object> ContinueWith(string code, ScriptOptions options = null) =>
ContinueWith<object>(code, options);
/// <summary>
/// Continues the script with given code snippet.
/// </summary>
public Script<TResult> ContinueWith<TResult>(string code, ScriptOptions options = null) =>
new Script<TResult>(Compiler, Builder, code ?? "", options ?? InheritOptions(Options), GlobalsType, this);
private static ScriptOptions InheritOptions(ScriptOptions previous)
{
// don't inherit references or imports, they have already been applied:
return previous.
WithReferences(ImmutableArray<MetadataReference>.Empty).
WithImports(ImmutableArray<string>.Empty);
}
/// <summary>
/// Get's the <see cref="Compilation"/> that represents the semantics of the script.
/// </summary>
public Compilation GetCompilation()
{
if (_lazyCompilation == null)
{
var compilation = Compiler.CreateSubmission(this);
Interlocked.CompareExchange(ref _lazyCompilation, compilation, null);
}
return _lazyCompilation;
}
/// <summary>
/// Runs the script from the beginning and returns the result of the last code snippet.
/// </summary>
/// <param name="globals">
/// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script.
/// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The result of the last code snippet.</returns>
internal Task<object> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) =>
CommonEvaluateAsync(globals, cancellationToken);
internal abstract Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken);
/// <summary>
/// Runs the script from the beginning.
/// </summary>
/// <param name="globals">
/// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script.
/// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns>
public Task<ScriptState> RunAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) =>
CommonRunAsync(globals, cancellationToken);
internal abstract Task<ScriptState> CommonRunAsync(object globals, CancellationToken cancellationToken);
/// <summary>
/// Continue script execution from the specified state.
/// </summary>
/// <param name="previousState">
/// Previous state of the script execution.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns>
internal Task<ScriptState> ContinueAsync(ScriptState previousState, CancellationToken cancellationToken = default(CancellationToken)) =>
CommonContinueAsync(previousState, cancellationToken);
internal abstract Task<ScriptState> CommonContinueAsync(ScriptState previousState, CancellationToken cancellationToken);
/// <summary>
/// Forces the script through the compilation step.
/// If not called directly, the compilation step will occur on the first call to Run.
/// </summary>
public ImmutableArray<Diagnostic> Compile(CancellationToken cancellationToken = default(CancellationToken)) =>
CommonCompile(cancellationToken);
internal abstract ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken);
internal abstract Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken);
// Apply recursive alias <host> to the host assembly reference, so that we hide its namespaces and global types behind it.
internal static readonly MetadataReferenceProperties HostAssemblyReferenceProperties =
MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("<host>")).WithRecursiveAliases(true);
/// <summary>
/// Gets the references that need to be assigned to the compilation.
/// This can be different than the list of references defined by the <see cref="ScriptOptions"/> instance.
/// </summary>
internal ImmutableArray<MetadataReference> GetReferencesForCompilation(
CommonMessageProvider messageProvider,
DiagnosticBag diagnostics,
MetadataReference languageRuntimeReferenceOpt = null)
{
var resolver = Options.MetadataResolver;
var references = ArrayBuilder<MetadataReference>.GetInstance();
try
{
if (Previous == null)
{
var corLib = MetadataReference.CreateFromAssemblyInternal(typeof(object).GetTypeInfo().Assembly);
references.Add(corLib);
if (GlobalsType != null)
{
var globalsAssembly = GlobalsType.GetTypeInfo().Assembly;
// If the assembly doesn't have metadata (it's an in-memory or dynamic assembly),
// the host has to add reference to the metadata where globals type is located explicitly.
if (MetadataReference.HasMetadata(globalsAssembly))
{
references.Add(MetadataReference.CreateFromAssemblyInternal(globalsAssembly, HostAssemblyReferenceProperties));
}
}
if (languageRuntimeReferenceOpt != null)
{
references.Add(languageRuntimeReferenceOpt);
}
}
// add new references:
foreach (var reference in Options.MetadataReferences)
{
var unresolved = reference as UnresolvedMetadataReference;
if (unresolved != null)
{
var resolved = resolver.ResolveReference(unresolved.Reference, null, unresolved.Properties);
if (resolved.IsDefault)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MetadataFileNotFound, Location.None, unresolved.Reference));
}
else
{
references.AddRange(resolved);
}
}
else
{
references.Add(reference);
}
}
return references.ToImmutable();
}
finally
{
references.Free();
}
}
// TODO: remove
internal bool HasReturnValue()
{
return GetCompilation().HasSubmissionResult();
}
}
public sealed class Script<T> : Script
{
private ImmutableArray<Func<object[], Task>> _lazyPrecedingExecutors;
private Func<object[], Task<T>> _lazyExecutor;
internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt)
: base(compiler, builder, code, options, globalsTypeOpt, previousOpt)
{
}
public override Type ReturnType => typeof(T);
public new Script<T> WithOptions(ScriptOptions options)
{
return (options == Options) ? this : new Script<T>(Compiler, Builder, Code, options, GlobalsType, Previous);
}
internal override Script WithOptionsInternal(ScriptOptions options) => WithOptions(options);
internal override ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken)
{
// TODO: avoid throwing exception, report all diagnostics https://github.com/dotnet/roslyn/issues/5949
try
{
GetPrecedingExecutors(cancellationToken);
GetExecutor(cancellationToken);
return ImmutableArray.CreateRange(GetCompilation().GetDiagnostics(cancellationToken).Where(d => d.Severity == DiagnosticSeverity.Warning));
}
catch (CompilationErrorException e)
{
return ImmutableArray.CreateRange(e.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning));
}
}
internal override Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken)
=> GetExecutor(cancellationToken);
internal override Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken) =>
EvaluateAsync(globals, cancellationToken).CastAsync<T, object>();
internal override Task<ScriptState> CommonRunAsync(object globals, CancellationToken cancellationToken) =>
RunAsync(globals, cancellationToken).CastAsync<ScriptState<T>, ScriptState>();
internal override Task<ScriptState> CommonContinueAsync(ScriptState previousState, CancellationToken cancellationToken) =>
ContinueAsync(previousState, cancellationToken).CastAsync<ScriptState<T>, ScriptState>();
/// <exception cref="CompilationErrorException">Compilation has errors.</exception>
private Func<object[], Task<T>> GetExecutor(CancellationToken cancellationToken)
{
if (_lazyExecutor == null)
{
Interlocked.CompareExchange(ref _lazyExecutor, Builder.CreateExecutor<T>(Compiler, GetCompilation(), cancellationToken), null);
}
return _lazyExecutor;
}
/// <exception cref="CompilationErrorException">Compilation has errors.</exception>
private ImmutableArray<Func<object[], Task>> GetPrecedingExecutors(CancellationToken cancellationToken)
{
if (_lazyPrecedingExecutors.IsDefault)
{
var preceding = TryGetPrecedingExecutors(null, cancellationToken);
Debug.Assert(!preceding.IsDefault);
InterlockedOperations.Initialize(ref _lazyPrecedingExecutors, preceding);
}
return _lazyPrecedingExecutors;
}
/// <exception cref="CompilationErrorException">Compilation has errors.</exception>
private ImmutableArray<Func<object[], Task>> TryGetPrecedingExecutors(Script lastExecutedScriptInChainOpt, CancellationToken cancellationToken)
{
Script script = Previous;
if (script == lastExecutedScriptInChainOpt)
{
return ImmutableArray<Func<object[], Task>>.Empty;
}
var scriptsReversed = ArrayBuilder<Script>.GetInstance();
while (script != null && script != lastExecutedScriptInChainOpt)
{
scriptsReversed.Add(script);
script = script.Previous;
}
if (lastExecutedScriptInChainOpt != null && script != lastExecutedScriptInChainOpt)
{
scriptsReversed.Free();
return default(ImmutableArray<Func<object[], Task>>);
}
var executors = ArrayBuilder<Func<object[], Task>>.GetInstance(scriptsReversed.Count);
// We need to build executors in the order in which they are chained,
// so that assemblies created for the submissions are loaded in the correct order.
for (int i = scriptsReversed.Count - 1; i >= 0; i--)
{
executors.Add(scriptsReversed[i].CommonGetExecutor(cancellationToken));
}
return executors.ToImmutableAndFree();
}
/// <summary>
/// Runs the script from the beginning and returns the result of the last code snippet.
/// </summary>
/// <param name="globals">
/// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script.
/// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The result of the last code snippet.</returns>
internal new Task<T> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) =>
RunAsync(globals, cancellationToken).GetEvaluationResultAsync();
/// <summary>
/// Runs the script from the beginning.
/// </summary>
/// <param name="globals">
/// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script.
/// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns>
/// <exception cref="CompilationErrorException">Compilation has errors.</exception>
/// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match <see cref="Script.GlobalsType"/>.</exception>
public new Task<ScriptState<T>> RunAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken))
{
// The following validation and executor construction may throw;
// do so synchronously so that the exception is not wrapped in the task.
ValidateGlobals(globals, GlobalsType);
var executionState = ScriptExecutionState.Create(globals);
var precedingExecutors = GetPrecedingExecutors(cancellationToken);
var currentExecutor = GetExecutor(cancellationToken);
return RunSubmissionsAsync(executionState, precedingExecutors, currentExecutor, cancellationToken);
}
/// <summary>
/// Creates a delegate that will run this script from the beginning when invoked.
/// </summary>
/// <remarks>
/// The delegate doesn't hold on this script or its compilation.
/// </remarks>
public ScriptRunner<T> CreateDelegate(CancellationToken cancellationToken = default(CancellationToken))
{
var precedingExecutors = GetPrecedingExecutors(cancellationToken);
var currentExecutor = GetExecutor(cancellationToken);
var globalsType = GlobalsType;
return (globals, token) =>
{
ValidateGlobals(globals, globalsType);
return ScriptExecutionState.Create(globals).RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, token);
};
}
/// <summary>
/// Continue script execution from the specified state.
/// </summary>
/// <param name="previousState">
/// Previous state of the script execution.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns>
/// <exception cref="ArgumentNullException"><paramref name="previousState"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="previousState"/> is not a previous execution state of this script.</exception>
internal new Task<ScriptState<T>> ContinueAsync(ScriptState previousState, CancellationToken cancellationToken = default(CancellationToken))
{
// The following validation and executor construction may throw;
// do so synchronously so that the exception is not wrapped in the task.
if (previousState == null)
{
throw new ArgumentNullException(nameof(previousState));
}
if (previousState.Script == this)
{
// this state is already the output of running this script.
return Task.FromResult((ScriptState<T>)previousState);
}
var precedingExecutors = TryGetPrecedingExecutors(previousState.Script, cancellationToken);
if (precedingExecutors.IsDefault)
{
throw new ArgumentException(ScriptingResources.StartingStateIncompatible, nameof(previousState));
}
var currentExecutor = GetExecutor(cancellationToken);
ScriptExecutionState newExecutionState = previousState.ExecutionState.FreezeAndClone();
return RunSubmissionsAsync(newExecutionState, precedingExecutors, currentExecutor, cancellationToken);
}
private async Task<ScriptState<T>> RunSubmissionsAsync(ScriptExecutionState executionState, ImmutableArray<Func<object[], Task>> precedingExecutors, Func<object[], Task> currentExecutor, CancellationToken cancellationToken)
{
var result = await executionState.RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
return new ScriptState<T>(executionState, result, this);
}
private static void ValidateGlobals(object globals, Type globalsType)
{
if (globalsType != null)
{
if (globals == null)
{
throw new ArgumentException(ScriptingResources.ScriptRequiresGlobalVariables, nameof(globals));
}
var runtimeType = globals.GetType().GetTypeInfo();
var globalsTypeInfo = globalsType.GetTypeInfo();
if (!globalsTypeInfo.IsAssignableFrom(runtimeType))
{
throw new ArgumentException(string.Format(ScriptingResources.GlobalsNotAssignable, runtimeType, globalsTypeInfo), nameof(globals));
}
}
else if (globals != null)
{
throw new ArgumentException(ScriptingResources.GlobalVariablesWithoutGlobalType, nameof(globals));
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.Forms.dll
// Description: The core assembly for the DotSpatial 6.0 distribution.
// ********************************************************************************************************
//
// The Original Code is DotSpatial.dll
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 9/11/2009 11:22:40 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// DetailedLineSymbolDialog
/// </summary>
public class DetailedLineSymbolDialog : Form
{
#region Events
/// <summary>
/// Occurs whenever the apply changes button is clicked, or else when the ok button is clicked.
/// </summary>
public event EventHandler ChangesApplied;
#endregion
private DetailedLineSymbolControl detailedLineSymbolControl;
private DialogButtons dialogButtons1;
private Panel panel1;
#region Private Variables
/// <summary>
/// Required designer variable.
/// </summary>
private IContainer components = null;
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DetailedLineSymbolDialog));
this.panel1 = new System.Windows.Forms.Panel();
this.dialogButtons1 = new DotSpatial.Symbology.Forms.DialogButtons();
this.detailedLineSymbolControl = new DotSpatial.Symbology.Forms.DetailedLineSymbolControl();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Controls.Add(this.dialogButtons1);
this.panel1.Name = "panel1";
//
// dialogButtons1
//
resources.ApplyResources(this.dialogButtons1, "dialogButtons1");
this.dialogButtons1.Name = "dialogButtons1";
//
// detailedLineSymbolControl
//
resources.ApplyResources(this.detailedLineSymbolControl, "detailedLineSymbolControl");
this.detailedLineSymbolControl.Name = "detailedLineSymbolControl";
//
// DetailedLineSymbolDialog
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.detailedLineSymbolControl);
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.HelpButton = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DetailedLineSymbolDialog";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of CollectionPropertyGrid
/// </summary>
public DetailedLineSymbolDialog()
{
InitializeComponent();
Configure();
}
/// <summary>
/// Creates a new line symbol dialog where only the original is specified and the
/// duplicate is created.
/// </summary>
/// <param name="original"></param>
public DetailedLineSymbolDialog(ILineSymbolizer original)
{
InitializeComponent();
detailedLineSymbolControl.Initialize(original);
Configure();
}
private void Configure()
{
dialogButtons1.OkClicked += btnOk_Click;
dialogButtons1.CancelClicked += btnCancel_Click;
dialogButtons1.ApplyClicked += btnApply_Click;
}
#endregion
#region Methods
#endregion
#region Properties
/// <summary>
/// Gets or sets the symbolizer being used by this control.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ILineSymbolizer Symbolizer
{
get
{
if (detailedLineSymbolControl == null) return null;
return detailedLineSymbolControl.Symbolizer;
}
set
{
if (detailedLineSymbolControl == null) return;
detailedLineSymbolControl.Symbolizer = value;
}
}
#endregion
#region Events
#endregion
#region Event Handlers
private void btnApply_Click(object sender, EventArgs e)
{
OnApplyChanges();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
private void btnOk_Click(object sender, EventArgs e)
{
OnApplyChanges();
Close();
}
#endregion
#region Protected Methods
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Fires the ChangesApplied event
/// </summary>
protected virtual void OnApplyChanges()
{
detailedLineSymbolControl.ApplyChanges();
if (ChangesApplied != null) ChangesApplied(this, EventArgs.Empty);
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ElevationTile : MonoBehaviour
{
public GameObject[] tiles;
public GameObject xMarksTheSpot;
public GameObject hole;
public GameObject ropeLadder;
public GameObject chest;
public GameObject tent;
public GameObject randomItem;
public void SmoothElevation(List<Tile> tiles) {
Tile[,] tileMap = this.GetComponent<RoomManager>().tileMap;
int height = tileMap.GetLength(0);
int width = tileMap.GetLength(1);
bool smoothing = true;
while(smoothing) {
smoothing = false;
foreach (Tile tile in tiles) {
if (tile.x > 0 && tile.y > 0 && tile.x < width - 1 && tile.y < height - 1) {
for (int xDelta = -1; xDelta <= 1; xDelta++) {
for (int yDelta = -1; yDelta <= 1; yDelta++) {
if (tileMap[tile.x + xDelta, tile.y + yDelta].elevation + 1 < tile.elevation) {
tile.elevation--;
smoothing = true;
}
}
}
}
}
}
}
public void placeCliffTiles(List<Tile> tiles) {
Tile[,] tileMap = this.GetComponent<RoomManager>().tileMap;
int height = tileMap.GetLength(0);
int width = tileMap.GetLength(1);
foreach (Tile tile in tiles) {
int x = tile.x;
int y = tile.y;
bool lower = false;
List<int> walls = new List<int>();
for (int xDelta = -1; xDelta <= 1; xDelta++) {
for (int yDelta = -1; yDelta <= 1; yDelta++) {
if (x + xDelta >= 0 && y + yDelta >= 0 && x + xDelta < width && y + yDelta < height &&
tileMap[x + xDelta, y + yDelta].elevation > tileMap[x, y].elevation) {
lower = true;
walls.Add(xDelta + 1 + (yDelta + 1) * 3);
}
}
}
if (lower) {
if (tile.path) {
this.GetComponent<RoomManager>().SetGroundTile(this.tiles[0], x, y);
} else {
this.GetComponent<RoomManager>().PlaceItem(this.GetWallTile(walls), x, y);
// Plains needs a special ground tile for layering
if (tile.biome == this.GetComponent<PlainsTile>().getBiomeNumber()) {
GameObject flatSprite = this.GetComponent<PlainsTile>().getFlatGroundTile();
this.GetComponent<RoomManager>().SetGroundTile(flatSprite, x, y);
}
}
tile.blocking = true;
}
}
}
public GameObject GetTreasureTile() {
return this.xMarksTheSpot;
}
// DONT TOUCH MY MAGIC FUNCTION --Chris
private GameObject GenerateWallTile(List<int> walls) {
GameObject wallObject = new GameObject();
if (walls.Contains(1)) {
GameObject copy = Instantiate (this.tiles[1],
new Vector3(0f, 0f, 0f),
Quaternion.identity) as GameObject;
copy.transform.SetParent( wallObject.transform );
//this.tiles[1].transform.SetParent( wallObject.transform );
}
if (walls.Contains(7)) {
GameObject copy = Instantiate (this.tiles[5],
new Vector3(0f, 0f, 0f),
Quaternion.identity) as GameObject;
copy.transform.SetParent( wallObject.transform );
//copy.transform.position = new Vector3(0f, 0f, 0f);
//this.tiles[5].transform.SetParent( wallObject.transform );
}
if (walls.Contains(3)) {
GameObject copy = Instantiate (this.tiles[3],
new Vector3(0f, 0f, 0f),
Quaternion.identity) as GameObject;
copy.transform.SetParent( wallObject.transform );
//this.tiles[3].transform.SetParent( wallObject.transform );
}
if (walls.Contains(5)) {
GameObject copy = Instantiate (this.tiles[7],
new Vector3(0f, 0f, 0f),
Quaternion.identity) as GameObject;
copy.transform.SetParent( wallObject.transform );
//this.tiles[7].transform.SetParent( wallObject.transform );
}
if (walls.Contains(8) && !walls.Contains(7) && !walls.Contains(5)) {
GameObject copy = Instantiate (this.tiles[6],
new Vector3(0f, 0f, 0f),
Quaternion.identity) as GameObject;
copy.transform.SetParent( wallObject.transform );
//this.tiles[6].transform.SetParent( wallObject.transform );
}
if (walls.Contains(6) && !walls.Contains(7) && !walls.Contains(3)) {
GameObject copy = Instantiate (this.tiles[4],
new Vector3(0f, 0f, 0f),
Quaternion.identity) as GameObject;
copy.transform.SetParent( wallObject.transform );
//this.tiles[4].transform.SetParent( wallObject.transform );
}
if (walls.Contains(2) && !walls.Contains(1) && !walls.Contains(5)) {
GameObject copy = Instantiate (this.tiles[8],
new Vector3(0f, 0f, 0f),
Quaternion.identity) as GameObject;
copy.transform.SetParent( wallObject.transform );
//this.tiles[8].transform.SetParent( wallObject.transform );
}
if (walls.Contains(0) && !walls.Contains(1) && !walls.Contains(3)) {
GameObject copy = Instantiate (this.tiles[2],
new Vector3(0f, 0f, 0f),
Quaternion.identity) as GameObject;
copy.transform.SetParent( wallObject.transform );
//this.tiles[2].transform.SetParent( wallObject.transform );
}
/*if (walls.Contains(2)) {
if (walls.Contains(1) && walls.Contains(5)) {
return this.tiles[10];
} else if (walls.Contains(1)) {
if (walls.Contains(3)) {
return this.tiles[11];
} else {
return this.tiles[1];
}
} else if (walls.Contains(5)) {
if (walls.Contains(7)) {
return this.tiles[9];
} else {
return this.tiles[7];
}
} else {
return this.tiles[8];
}
} else if (walls.Contains(0)) {
if (walls.Contains(1) && walls.Contains(3)) {
return this.tiles[11];
} else if (walls.Contains(1)) {
return this.tiles[1];
} else if (walls.Contains(3)) {
if (walls.Contains(7)) {
return this.tiles[12];
} else {
return this.tiles[3];
}
} else {
return this.tiles[2];
}
} else if (walls.Contains(6)) {
if (walls.Contains(7) && walls.Contains(3)) {
return this.tiles[12];
} else if (walls.Contains(7)) {
return this.tiles[5];
} else if (walls.Contains(3)) {
return this.tiles[3];
} else {
return this.tiles[4];
}
} else if (walls.Contains(8)) {
if (walls.Contains(7) && walls.Contains(5)) {
return this.tiles[9];
} else if (walls.Contains(7)) {
return this.tiles[5];
} else if (walls.Contains(5)) {
return this.tiles[7];
} else {
return this.tiles[6];
}
}
if (walls.IndexOf(1) != -1) {
return this.tiles[1];
} else if (walls.IndexOf(3) != -1) {
return this.tiles[3];
} else if (walls.IndexOf(5) != -1) {
return this.tiles[7];
} else if (walls.IndexOf(7) != -1) {
return this.tiles[5];
}
print ("elevation placement probems --Show Chris your game if you see this");
return this.tiles[0];*/
return wallObject;
}
public static Dictionary<string, GameObject> wallsHash = new Dictionary<string, GameObject>();
private GameObject GetWallTile(List<int> walls) {
string key = "";
foreach (int number in walls) {
key += number;
}
GameObject newWall = null;
if (!ElevationTile.wallsHash.TryGetValue(key, out newWall)) {
newWall = this.GenerateWallTile(walls);
ElevationTile.wallsHash.Add(key, newWall);
}
return newWall;
}
public static void ClearWallsHash() {
foreach (GameObject wall in ElevationTile.wallsHash.Values) {
Destroy (wall);
}
ElevationTile.wallsHash = new Dictionary<string, GameObject>();
}
public GameObject GetXMarksTheSpot() {
return this.xMarksTheSpot;
}
public GameObject GetHole() {
return this.hole;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Test
{
public partial class ZipTest
{
[Fact]
public async Task CreateFromDirectoryNormal()
{
await TestCreateDirectory(zfolder("normal"), true);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(846, PlatformID.AnyUnix)]
{
await TestCreateDirectory(zfolder("unicode"), true);
}
}
private async Task TestCreateDirectory(string folderName, Boolean testWithBaseDir)
{
string noBaseDir = GetTmpFilePath();
ZipFile.CreateFromDirectory(folderName, noBaseDir);
await IsZipSameAsDirAsync(noBaseDir, folderName, ZipArchiveMode.Read, true, true);
if (testWithBaseDir)
{
string withBaseDir = GetTmpFilePath();
ZipFile.CreateFromDirectory(folderName, withBaseDir, CompressionLevel.Optimal, true);
SameExceptForBaseDir(noBaseDir, withBaseDir, folderName);
}
}
private static void SameExceptForBaseDir(string zipNoBaseDir, string zipBaseDir, string baseDir)
{
//b has the base dir
using (ZipArchive a = ZipFile.Open(zipNoBaseDir, ZipArchiveMode.Read),
b = ZipFile.Open(zipBaseDir, ZipArchiveMode.Read))
{
var aCount = a.Entries.Count;
var bCount = b.Entries.Count;
Assert.Equal(aCount, bCount);
int bIdx = 0;
foreach (ZipArchiveEntry aEntry in a.Entries)
{
ZipArchiveEntry bEntry = b.Entries[bIdx++];
Assert.Equal(Path.GetFileName(baseDir) + "/" + aEntry.FullName, bEntry.FullName);
Assert.Equal(aEntry.Name, bEntry.Name);
Assert.Equal(aEntry.Length, bEntry.Length);
Assert.Equal(aEntry.CompressedLength, bEntry.CompressedLength);
using (Stream aStream = aEntry.Open(), bStream = bEntry.Open())
{
StreamsEqual(aStream, bStream);
}
}
}
}
[Fact]
public void ExtractToDirectoryNormal()
{
TestExtract(zfile("normal.zip"), zfolder("normal"));
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(846, PlatformID.AnyUnix)]
{
TestExtract(zfile("unicode.zip"), zfolder("unicode"));
}
TestExtract(zfile("empty.zip"), zfolder("empty"));
TestExtract(zfile("explicitdir1.zip"), zfolder("explicitdir"));
TestExtract(zfile("explicitdir2.zip"), zfolder("explicitdir"));
TestExtract(zfile("appended.zip"), zfolder("small"));
TestExtract(zfile("prepended.zip"), zfolder("small"));
TestExtract(zfile("noexplicitdir.zip"), zfolder("explicitdir"));
}
private void TestExtract(string zipFileName, string folderName)
{
string tempFolder = GetTmpDirPath(true);
ZipFile.ExtractToDirectory(zipFileName, tempFolder);
DirsEqual(tempFolder, folderName);
Assert.Throws<ArgumentNullException>(() => ZipFile.ExtractToDirectory(null, tempFolder));
}
#region "Extension Methods"
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task CreateEntryFromFileTest(bool withCompressionLevel)
{
//add file
string testArchive = CreateTempCopyFile(zfile("normal.zip"));
using (ZipArchive archive = ZipFile.Open(testArchive, ZipArchiveMode.Update))
{
string entryName = "added.txt";
string sourceFilePath = zmodified(Path.Combine("addFile", entryName));
Assert.Throws<ArgumentNullException>(() => ((ZipArchive)null).CreateEntryFromFile(sourceFilePath, entryName));
Assert.Throws<ArgumentNullException>(() => archive.CreateEntryFromFile(null, entryName));
Assert.Throws<ArgumentNullException>(() => archive.CreateEntryFromFile(sourceFilePath, null));
ZipArchiveEntry e = withCompressionLevel ?
archive.CreateEntryFromFile(sourceFilePath, entryName) :
archive.CreateEntryFromFile(sourceFilePath, entryName, CompressionLevel.Fastest);
Assert.NotNull(e);
}
await IsZipSameAsDirAsync(testArchive, zmodified("addFile"), ZipArchiveMode.Read, true, true);
}
[Fact]
public void ExtractToFileTest()
{
using (ZipArchive archive = ZipFile.Open(zfile("normal.zip"), ZipArchiveMode.Read))
{
string file = GetTmpFilePath();
ZipArchiveEntry e = archive.GetEntry("first.txt");
Assert.Throws<ArgumentNullException>(() => ((ZipArchiveEntry)null).ExtractToFile(file));
Assert.Throws<ArgumentNullException>(() => e.ExtractToFile(null));
//extract when there is nothing there
e.ExtractToFile(file);
using (Stream fs = File.Open(file, FileMode.Open), es = e.Open())
{
StreamsEqual(fs, es);
}
Assert.Throws<IOException>(() => e.ExtractToFile(file, false));
//truncate file
using (Stream fs = File.Open(file, FileMode.Truncate)) { }
//now use overwrite mode
e.ExtractToFile(file, true);
using (Stream fs = File.Open(file, FileMode.Open), es = e.Open())
{
StreamsEqual(fs, es);
}
}
}
[Fact]
public void ExtractToDirectoryTest()
{
using (ZipArchive archive = ZipFile.Open(zfile("normal.zip"), ZipArchiveMode.Read))
{
string tempFolder = GetTmpDirPath(false);
Assert.Throws<ArgumentNullException>(() => ((ZipArchive)null).ExtractToDirectory(tempFolder));
Assert.Throws<ArgumentNullException>(() => archive.ExtractToDirectory(null));
archive.ExtractToDirectory(tempFolder);
DirsEqual(tempFolder, zfolder("normal"));
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(846, PlatformID.AnyUnix)]
{
using (ZipArchive archive = ZipFile.OpenRead(zfile("unicode.zip")))
{
string tempFolder = GetTmpDirPath(false);
archive.ExtractToDirectory(tempFolder);
DirsEqual(tempFolder, zfolder("unicode"));
}
}
}
[Fact]
public void CreatedEmptyDirectoriesRoundtrip()
{
DirectoryInfo rootDir = new DirectoryInfo(GetTmpDirPath(create: true));
rootDir.CreateSubdirectory("empty1");
string archivePath = GetTmpFilePath();
ZipFile.CreateFromDirectory(
rootDir.FullName, archivePath,
CompressionLevel.Optimal, false, Encoding.UTF8);
using (ZipArchive archive = ZipFile.OpenRead(archivePath))
{
Assert.Equal(1, archive.Entries.Count);
Assert.True(archive.Entries[0].FullName.StartsWith("empty1"));
}
}
[Fact]
public void CreatedEmptyRootDirectoryRoundtrips()
{
DirectoryInfo emptyRoot = new DirectoryInfo(GetTmpDirPath(create: true));
string archivePath = GetTmpFilePath();
ZipFile.CreateFromDirectory(
emptyRoot.FullName, archivePath,
CompressionLevel.Optimal, true);
using (ZipArchive archive = ZipFile.OpenRead(archivePath))
{
Assert.Equal(1, archive.Entries.Count);
}
}
#endregion
}
}
| |
namespace HtmlRenderer.Entities
{
/// <summary>
/// Defines HTML strings
/// </summary>
internal static class HtmlConstants
{
public const string A = "a";
// public const string ABBR = "ABBR";
// public const string ACRONYM = "ACRONYM";
// public const string ADDRESS = "ADDRESS";
// public const string APPLET = "APPLET";
// public const string AREA = "AREA";
// public const string B = "B";
// public const string BASE = "BASE";
// public const string BASEFONT = "BASEFONT";
// public const string BDO = "BDO";
// public const string BIG = "BIG";
// public const string BLOCKQUOTE = "BLOCKQUOTE";
// public const string BODY = "BODY";
// public const string BR = "BR";
// public const string BUTTON = "BUTTON";
public const string Caption = "caption";
// public const string CENTER = "CENTER";
// public const string CITE = "CITE";
// public const string CODE = "CODE";
public const string Col = "col";
public const string Colgroup = "colgroup";
public const string Display = "display";
// public const string DD = "DD";
// public const string DEL = "DEL";
// public const string DFN = "DFN";
// public const string DIR = "DIR";
// public const string DIV = "DIV";
// public const string DL = "DL";
// public const string DT = "DT";
// public const string EM = "EM";
// public const string FIELDSET = "FIELDSET";
public const string Font = "font";
// public const string FORM = "FORM";
// public const string FRAME = "FRAME";
// public const string FRAMESET = "FRAMESET";
// public const string H1 = "H1";
// public const string H2 = "H2";
// public const string H3 = "H3";
// public const string H4 = "H4";
// public const string H5 = "H5";
// public const string H6 = "H6";
// public const string HEAD = "HEAD";
public const string Hr = "hr";
// public const string HTML = "HTML";
// public const string I = "I";
public const string Iframe = "iframe";
public const string Img = "img";
// public const string INPUT = "INPUT";
// public const string INS = "INS";
// public const string ISINDEX = "ISINDEX";
// public const string KBD = "KBD";
// public const string LABEL = "LABEL";
// public const string LEGEND = "LEGEND";
public const string Li = "li";
// public const string LINK = "LINK";
// public const string MAP = "MAP";
// public const string MENU = "MENU";
// public const string META = "META";
// public const string NOFRAMES = "NOFRAMES";
// public const string NOSCRIPT = "NOSCRIPT";
// public const string OBJECT = "OBJECT";
// public const string OL = "OL";
// public const string OPTGROUP = "OPTGROUP";
// public const string OPTION = "OPTION";
// public const string P = "P";
// public const string PARAM = "PARAM";
// public const string PRE = "PRE";
// public const string Q = "Q";
// public const string S = "S";
// public const string SAMP = "SAMP";
// public const string SCRIPT = "SCRIPT";
// public const string SELECT = "SELECT";
// public const string SMALL = "SMALL";
// public const string SPAN = "SPAN";
// public const string STRIKE = "STRIKE";
// public const string STRONG = "STRONG";
public const string Style = "style";
// public const string SUB = "SUB";
// public const string SUP = "SUP";
public const string Table = "table";
public const string Tbody = "tbody";
public const string Td = "td";
// public const string TEXTAREA = "TEXTAREA";
public const string Tfoot = "tfoot";
public const string Th = "th";
public const string Thead = "thead";
// public const string TITLE = "TITLE";
public const string Tr = "tr";
// public const string TT = "TT";
// public const string U = "U";
// public const string UL = "UL";
// public const string VAR = "VAR";
// public const string abbr = "abbr";
// public const string accept = "accept";
// public const string accesskey = "accesskey";
// public const string action = "action";
public const string Align = "align";
// public const string alink = "alink";
// public const string alt = "alt";
// public const string archive = "archive";
// public const string axis = "axis";
public const string Background = "background";
public const string Bgcolor = "bgcolor";
public const string Border = "border";
public const string Bordercolor = "bordercolor";
public const string Cellpadding = "cellpadding";
public const string Cellspacing = "cellspacing";
// public const string char_ = "char";
// public const string charoff = "charoff";
// public const string charset = "charset";
// public const string checked_ = "checked";
// public const string cite = "cite";
public const string Class = "class";
// public const string classid = "classid";
// public const string clear = "clear";
// public const string code = "code";
// public const string codebase = "codebase";
// public const string codetype = "codetype";
public const string Color = "color";
// public const string cols = "cols";
// public const string colspan = "colspan";
// public const string compact = "compact";
// public const string content = "content";
// public const string coords = "coords";
// public const string data = "data";
// public const string datetime = "datetime";
// public const string declare = "declare";
// public const string defer = "defer";
public const string Dir = "dir";
// public const string disabled = "disabled";
// public const string enctype = "enctype";
public const string Face = "face";
// public const string for_ = "for";
// public const string frame = "frame";
// public const string frameborder = "frameborder";
// public const string headers = "headers";
public const string Height = "height";
public const string Href = "href";
// public const string hreflang = "hreflang";
public const string Hspace = "hspace";
// public const string http_equiv = "http-equiv";
// public const string id = "id";
// public const string ismap = "ismap";
// public const string label = "label";
// public const string lang = "lang";
// public const string language = "language";
// public const string link = "link";
// public const string longdesc = "longdesc";
// public const string marginheight = "marginheight";
// public const string marginwidth = "marginwidth";
// public const string maxlength = "maxlength";
// public const string media = "media";
// public const string method = "method";
// public const string multiple = "multiple";
// public const string name = "name";
// public const string nohref = "nohref";
// public const string noresize = "noresize";
// public const string noshade = "noshade";
public const string Nowrap = "nowrap";
// public const string object_ = "object";
// public const string onblur = "onblur";
// public const string onchange = "onchange";
// public const string onclick = "onclick";
// public const string ondblclick = "ondblclick";
// public const string onfocus = "onfocus";
// public const string onkeydown = "onkeydown";
// public const string onkeypress = "onkeypress";
// public const string onkeyup = "onkeyup";
// public const string onload = "onload";
// public const string onmousedown = "onmousedown";
// public const string onmousemove = "onmousemove";
// public const string onmouseout = "onmouseout";
// public const string onmouseover = "onmouseover";
// public const string onmouseup = "onmouseup";
// public const string onreset = "onreset";
// public const string onselect = "onselect";
// public const string onsubmit = "onsubmit";
// public const string onunload = "onunload";
// public const string profile = "profile";
// public const string prompt = "prompt";
// public const string readonly_ = "readonly";
// public const string rel = "rel";
// public const string rev = "rev";
// public const string rows = "rows";
// public const string rowspan = "rowspan";
// public const string rules = "rules";
// public const string scheme = "scheme";
// public const string scope = "scope";
// public const string scrolling = "scrolling";
// public const string selected = "selected";
// public const string shape = "shape";
public const string Size = "size";
// public const string span = "span";
// public const string src = "src";
// public const string standby = "standby";
// public const string start = "start";
// public const string style = "style";
// public const string summary = "summary";
// public const string tabindex = "tabindex";
// public const string target = "target";
// public const string text = "text";
// public const string title = "title";
// public const string type = "type";
// public const string usemap = "usemap";
public const string Valign = "valign";
// public const string value = "value";
// public const string valuetype = "valuetype";
// public const string version = "version";
// public const string vlink = "vlink";
public const string Vspace = "vspace";
public const string Width = "width";
public const string Left = "left";
public const string Right = "right";
// public const string top = "top";
public const string Center = "center";
// public const string middle = "middle";
// public const string bottom = "bottom";
public const string Justify = "justify";
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Capabilities;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
{
public class XmlRpcGroupsMessaging : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<Scene> m_sceneList = new List<Scene>();
private IMessageTransferModule m_msgTransferModule = null;
private IGroupsModule m_groupsModule = null;
// TODO: Move this off to the xmlrpc server
public Dictionary<Guid, List<Guid>> m_agentsInGroupSession = new Dictionary<Guid, List<Guid>>();
public Dictionary<Guid, List<Guid>> m_agentsDroppedSession = new Dictionary<Guid, List<Guid>>();
// Config Options
private bool m_groupMessagingEnabled = false;
private bool m_debugEnabled = true;
#region IRegionModuleBase Members
public void Initialize(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
{
// Do not run this module by default.
return;
}
else
{
if (!groupsConfig.GetBoolean("Enabled", false))
{
return;
}
if (groupsConfig.GetString("Module", "Default") != "XmlRpcGroups")
{
m_groupMessagingEnabled = false;
return;
}
m_groupMessagingEnabled = groupsConfig.GetBoolean("XmlRpcMessagingEnabled", true);
if (!m_groupMessagingEnabled)
{
return;
}
m_log.Info("[GROUPS-MESSAGING]: Initializing XmlRpcGroupsMessaging");
m_debugEnabled = groupsConfig.GetBoolean("XmlRpcDebugEnabled", true);
}
m_log.Info("[GROUPS-MESSAGING]: XmlRpcGroupsMessaging starting up");
}
public void AddRegion(Scene scene)
{
// NoOp
}
public void RegionLoaded(Scene scene)
{
if (!m_groupMessagingEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupsModule = scene.RequestModuleInterface<IGroupsModule>();
// No groups module, no groups messaging
if (m_groupsModule == null)
{
m_log.Error("[GROUPS-MESSAGING]: Could not get IGroupsModule, XmlRpcGroupsMessaging is now disabled.");
Close();
m_groupMessagingEnabled = false;
return;
}
m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
// No message transfer module, no groups messaging
if (m_msgTransferModule == null)
{
m_log.Error("[GROUPS-MESSAGING]: Could not get MessageTransferModule");
Close();
m_groupMessagingEnabled = false;
return;
}
m_sceneList.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
}
public void RemoveRegion(Scene scene)
{
if (!m_groupMessagingEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_sceneList.Remove(scene);
}
public void Close()
{
if (!m_groupMessagingEnabled)
return;
if (m_debugEnabled) m_log.Debug("[GROUPS-MESSAGING]: Shutting down XmlRpcGroupsMessaging module.");
foreach (Scene scene in m_sceneList)
{
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
}
m_sceneList.Clear();
m_groupsModule = null;
m_msgTransferModule = null;
}
public string Name
{
get { return "XmlRpcGroupsMessaging"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
#region ISharedRegionModule Members
public void PostInitialize()
{
// NoOp
}
#endregion
#region SimGridEventHandlers
private void OnNewClient(IClientAPI client)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: OnInstantMessage registered for {0}", client.Name);
client.OnInstantMessage += OnInstantMessage;
}
private void OnGridInstantMessage(GridInstantMessage msg)
{
// The instant message module will only deliver messages of dialog types:
// MessageFromAgent, StartTyping, StopTyping, MessageFromObject
//
// Any other message type will not be delivered to a client by the
// Instant Message Module
if (m_debugEnabled)
{
m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
DebugGridInstantMessage(msg);
}
// Incoming message from a group
if ((msg.fromGroup == true) &&
((msg.dialog == (byte)InstantMessageDialog.SessionSend)
|| (msg.dialog == (byte)InstantMessageDialog.SessionAdd)
|| (msg.dialog == (byte)InstantMessageDialog.SessionDrop)))
{
ProcessMessageFromGroupSession(msg);
}
}
private void ProcessMessageFromGroupSession(GridInstantMessage msg)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Session message from {0} going to agent {1}", msg.fromAgentName, msg.toAgentID);
switch (msg.dialog)
{
case (byte)InstantMessageDialog.SessionAdd:
AddAgentToGroupSession(msg.fromAgentID, msg.imSessionID);
break;
case (byte)InstantMessageDialog.SessionDrop:
RemoveAgentFromGroupSession(msg.fromAgentID, msg.imSessionID);
break;
case (byte)InstantMessageDialog.SessionSend:
if (!m_agentsInGroupSession.ContainsKey(msg.toAgentID)
&& !m_agentsDroppedSession.ContainsKey(msg.toAgentID))
{
// Agent not in session and hasn't dropped from session
// Add them to the session for now, and Invite them
AddAgentToGroupSession(msg.toAgentID, msg.imSessionID);
UUID toAgentID = new UUID(msg.toAgentID);
IClientAPI activeClient = GetActiveClient(toAgentID);
if (activeClient != null)
{
UUID groupID = new UUID(msg.fromAgentID);
GroupRecord groupInfo = m_groupsModule.GetGroupRecord(groupID);
if (groupInfo != null)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Sending chatterbox invite instant message");
// Force? open the group session dialog???
IEventQueue eq = activeClient.Scene.RequestModuleInterface<IEventQueue>();
eq.ChatterboxInvitation(
groupID
, groupInfo.GroupName
, new UUID(msg.fromAgentID)
, msg.message, new UUID(msg.toAgentID)
, msg.fromAgentName
, msg.dialog
, msg.timestamp
, msg.offline == 1
, (int)msg.ParentEstateID
, msg.Position
, 1
, new UUID(msg.imSessionID)
, msg.fromGroup
, Utils.StringToBytes(groupInfo.GroupName)
);
eq.ChatterBoxSessionAgentListUpdates(
new UUID(groupID)
, new UUID(msg.fromAgentID)
, new UUID(msg.fromAgentID)
, false //canVoiceChat
, false //isModerator
, false //text mute
, msg.dialog
);
((Scene)activeClient.Scene).EventManager.TriggerOnChatToClient(msg.message,
UUID.Parse(msg.fromAgentID.ToString()), UUID.Parse(msg.toAgentID.ToString()),
activeClient.Scene.RegionInfo.RegionID, msg.timestamp,
ChatToClientType.GroupMessage);
}
}
}
else if (!m_agentsDroppedSession.ContainsKey(msg.toAgentID))
{
// User hasn't dropped, so they're in the session,
// maybe we should deliver it.
IClientAPI client = GetActiveClient(new UUID(msg.toAgentID));
if (client != null)
{
// Deliver locally, directly
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Delivering to {0} locally", client.Name);
client.SendInstantMessage(msg);
}
else
{
m_log.WarnFormat("[GROUPS-MESSAGING]: Received a message over the grid for a client that isn't here: {0}", msg.toAgentID);
}
}
break;
default:
m_log.WarnFormat("[GROUPS-MESSAGING]: I don't know how to proccess a {0} message.", ((InstantMessageDialog)msg.dialog).ToString());
break;
}
}
#endregion
#region ClientEvents
private void RemoveAgentFromGroupSession(Guid agentID, Guid sessionID)
{
if (m_agentsInGroupSession.ContainsKey(sessionID))
{
// If in session remove
if (m_agentsInGroupSession[sessionID].Contains(agentID))
{
m_agentsInGroupSession[sessionID].Remove(agentID);
}
// If not in dropped list, add
if (!m_agentsDroppedSession[sessionID].Contains(agentID))
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Dropped {1} from session {0}", sessionID, agentID);
m_agentsDroppedSession[sessionID].Add(agentID);
}
}
}
private void AddAgentToGroupSession(Guid agentID, Guid sessionID)
{
// Add Session Status if it doesn't exist for this session
CreateGroupSessionTracking(sessionID);
// If nessesary, remove from dropped list
if (m_agentsDroppedSession[sessionID].Contains(agentID))
{
m_agentsDroppedSession[sessionID].Remove(agentID);
}
// If nessesary, add to in session list
if (!m_agentsInGroupSession[sessionID].Contains(agentID))
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Added {1} to session {0}", sessionID, agentID);
m_agentsInGroupSession[sessionID].Add(agentID);
}
}
private void CreateGroupSessionTracking(Guid sessionID)
{
if (!m_agentsInGroupSession.ContainsKey(sessionID))
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Creating session tracking for : {0}", sessionID);
m_agentsInGroupSession.Add(sessionID, new List<Guid>());
m_agentsDroppedSession.Add(sessionID, new List<Guid>());
}
}
private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im)
{
if (m_debugEnabled)
{
m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
DebugGridInstantMessage(im);
}
// Start group IM session
if ((im.dialog == (byte)InstantMessageDialog.SessionGroupStart))
{
UUID groupID = new UUID(im.toAgentID);
GroupRecord groupInfo = m_groupsModule.GetGroupRecord(groupID);
if (groupInfo != null)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Start Group Session for {0}", groupInfo.GroupName);
AddAgentToGroupSession(im.fromAgentID, im.imSessionID);
ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, groupID);
IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
queue.ChatterBoxSessionAgentListUpdates(
new UUID(groupID)
, new UUID(im.fromAgentID)
, new UUID(im.fromAgentID)
, false //canVoiceChat
, false //isModerator
, false //text mute
, im.dialog
);
}
}
// Send a message from locally connected client to a group
if ((im.dialog == (byte)InstantMessageDialog.SessionSend))
{
UUID groupID = new UUID(im.toAgentID);
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Send message to session for group {0} with session ID {1}", groupID, im.imSessionID.ToString());
SendMessageToGroup(remoteClient, im, groupID);
}
}
#endregion
private void SendMessageToGroup(IClientAPI remoteClient, GridInstantMessage im, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<UUID> muters;
IMuteListModule m_muteListModule = m_sceneList[0].RequestModuleInterface<IMuteListModule>();
if (m_muteListModule != null)
muters = m_muteListModule.GetInverseMuteList(remoteClient.AgentId);
else
muters = new List<UUID>();
foreach (GroupMembersData member in m_groupsModule.GroupMembersRequest(null, null, UUID.Zero, groupID))
{
if (m_agentsDroppedSession[im.imSessionID].Contains(member.AgentID.Guid))
{ // Don't deliver messages to people who have dropped this session
continue;
}
if (muters.Contains(member.AgentID))
{ // Don't deliver messages to people who have the sender muted.
continue;
}
// Copy Message
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = im.imSessionID;
msg.fromAgentName = im.fromAgentName;
msg.message = im.message;
msg.dialog = im.dialog;
msg.offline = im.offline;
msg.ParentEstateID = im.ParentEstateID;
msg.Position = im.Position;
msg.RegionID = im.RegionID;
msg.binaryBucket = im.binaryBucket;
msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
// Updat Pertinate fields to make it a "group message"
msg.fromAgentID = groupID.Guid;
msg.fromGroup = true;
msg.toAgentID = member.AgentID.Guid;
IClientAPI client = GetActiveClient(member.AgentID);
if (client == null)
{
// If they're not local, forward across the grid
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Delivering to {0} via Grid", member.AgentID);
m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { });
}
else
{
// Deliver locally, directly
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", client.Name);
ProcessMessageFromGroupSession(msg);
}
}
}
void ChatterBoxSessionStartReplyViaCaps(IClientAPI remoteClient, string groupName, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap moderatedMap = new OSDMap(4);
moderatedMap.Add("voice", OSD.FromBoolean(false));
OSDMap sessionMap = new OSDMap(4);
sessionMap.Add("moderated_mode", moderatedMap);
sessionMap.Add("session_name", OSD.FromString(groupName));
sessionMap.Add("type", OSD.FromInteger(0));
sessionMap.Add("voice_enabled", OSD.FromBoolean(false));
OSDMap bodyMap = new OSDMap(4);
bodyMap.Add("session_id", OSD.FromUUID(groupID));
bodyMap.Add("temp_session_id", OSD.FromUUID(groupID));
bodyMap.Add("success", OSD.FromBoolean(true));
bodyMap.Add("session_info", sessionMap);
IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
if (queue != null)
{
queue.Enqueue(EventQueueHelper.BuildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId);
}
}
private void DebugGridInstantMessage(GridInstantMessage im)
{
// Don't log any normal IMs (privacy!)
if (m_debugEnabled && im.dialog != (byte)InstantMessageDialog.MessageFromAgent)
{
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: fromGroup({0})", im.fromGroup ? "True" : "False");
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: Dialog({0})", ((InstantMessageDialog)im.dialog).ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: fromAgentID({0})", im.fromAgentID.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: fromAgentName({0})", im.fromAgentName.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: imSessionID({0})", im.imSessionID.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: message({0})", im.message.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: offline({0})", im.offline.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: toAgentID({0})", im.toAgentID.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: binaryBucket({0})", OpenMetaverse.Utils.BytesToHexString(im.binaryBucket, "BinaryBucket"));
}
}
#region Client Tools
/// <summary>
/// Try to find an active IClientAPI reference for agentID giving preference to root connections
/// </summary>
private IClientAPI GetActiveClient(UUID agentID)
{
IClientAPI child = null;
// Try root avatar first
foreach (Scene scene in m_sceneList)
{
if (scene.Entities.ContainsKey(agentID) &&
scene.Entities[agentID] is ScenePresence)
{
ScenePresence user = (ScenePresence)scene.Entities[agentID];
if (!user.IsChildAgent)
{
return user.ControllingClient;
}
else
{
child = user.ControllingClient;
}
}
}
// If we didn't find a root, then just return whichever child we found, or null if none
return child;
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2006 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 NUnit.TestUtilities;
using NUnit.TestUtilities.Collections;
using NUnit.TestUtilities.Comparers;
#if !SILVERLIGHT && !PORTABLE
using System.Data;
#endif
#if !NET_2_0
using System.Linq;
#endif
namespace NUnit.Framework.Assertions
{
/// <summary>
/// Test Library for the NUnit CollectionAssert class.
/// </summary>
[TestFixture()]
public class CollectionAssertTest
{
#region AllItemsAreInstancesOfType
[Test()]
public void ItemsOfType()
{
var collection = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AllItemsAreInstancesOfType(collection,typeof(string));
}
[Test]
public void ItemsOfTypeFailure()
{
var collection = new SimpleObjectCollection("x", "y", new object());
var expectedMessage =
" Expected: all items instance of <System.String>" + Environment.NewLine +
" But was: < \"x\", \"y\", <System.Object> >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreInstancesOfType(collection,typeof(string)));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#region AllItemsAreNotNull
[Test()]
public void ItemsNotNull()
{
var collection = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AllItemsAreNotNull(collection);
}
[Test]
public void ItemsNotNullFailure()
{
var collection = new SimpleObjectCollection("x", null, "z");
var expectedMessage =
" Expected: all items not null" + Environment.NewLine +
" But was: < \"x\", null, \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreNotNull(collection));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#region AllItemsAreUnique
[Test]
public void Unique_WithObjects()
{
CollectionAssert.AllItemsAreUnique(
new SimpleObjectCollection(new object(), new object(), new object()));
}
[Test]
public void Unique_WithStrings()
{
CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "z"));
}
[Test]
public void Unique_WithNull()
{
CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", null, "z"));
}
[Test]
public void UniqueFailure()
{
var expectedMessage =
" Expected: all items unique" + Environment.NewLine +
" But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "x")));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void UniqueFailure_WithTwoNulls()
{
Assert.Throws<AssertionException>(
() => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", null, "y", null, "z")));
}
#endregion
#region AreEqual
[Test]
public void AreEqual()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AreEqual(set1,set2);
CollectionAssert.AreEqual(set1,set2,new TestComparer());
Assert.AreEqual(set1,set2);
}
[Test]
public void AreEqualFailCount()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("x", "y", "z", "a");
var expectedMessage =
" Expected is <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements, actual is <NUnit.TestUtilities.Collections.SimpleObjectList> with 4 elements" + Environment.NewLine +
" Values differ at index [3]" + Environment.NewLine +
" Extra: < \"a\" >";
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2, new TestComparer()));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreEqualFail()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("x", "y", "a");
var expectedMessage =
" Expected and actual are both <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements" + Environment.NewLine +
" Values differ at index [2]" + Environment.NewLine +
" String lengths are both 1. Strings differ at index 0." + Environment.NewLine +
" Expected: \"z\"" + Environment.NewLine +
" But was: \"a\"" + Environment.NewLine +
" -----------^" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1,set2,new TestComparer()));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreEqual_HandlesNull()
{
object[] set1 = new object[3];
object[] set2 = new object[3];
CollectionAssert.AreEqual(set1,set2);
CollectionAssert.AreEqual(set1,set2,new TestComparer());
}
[Test]
public void EnsureComparerIsUsed()
{
// Create two collections
int[] array1 = new int[2];
int[] array2 = new int[2];
array1[0] = 4;
array1[1] = 5;
array2[0] = 99;
array2[1] = -99;
CollectionAssert.AreEqual(array1, array2, new AlwaysEqualComparer());
}
[Test]
public void AreEqual_UsingIterator()
{
int[] array = new int[] { 1, 2, 3 };
CollectionAssert.AreEqual(array, CountToThree());
}
IEnumerable CountToThree()
{
yield return 1;
yield return 2;
yield return 3;
}
[Test]
public void AreEqual_UsingIterator_Fails()
{
int[] array = new int[] { 1, 3, 5 };
AssertionException ex = Assert.Throws<AssertionException>(
delegate { CollectionAssert.AreEqual(array, CountToThree()); } );
Assert.That(ex.Message, Does.Contain("Values differ at index [1]").And.
Contains("Expected: 3").And.
Contains("But was: 2"));
}
#if !NET_2_0
[Test]
public void AreEqual_UsingLinqQuery()
{
int[] array = new int[] { 1, 2, 3 };
CollectionAssert.AreEqual(array, array.Select((item) => item));
}
[Test]
public void AreEqual_UsingLinqQuery_Fails()
{
int[] array = new int[] { 1, 2, 3 };
AssertionException ex = Assert.Throws<AssertionException>(
delegate { CollectionAssert.AreEqual(array, array.Select((item) => item * 2)); } );
Assert.That(ex.Message, Does.Contain("Values differ at index [0]").And.
Contains("Expected: 1").And.
Contains("But was: 2"));
}
#endif
#endregion
#region AreEquivalent
[Test]
public void Equivalent()
{
ICollection set1 = new SimpleObjectCollection("x", "y", "z");
ICollection set2 = new SimpleObjectCollection("z", "y", "x");
CollectionAssert.AreEquivalent(set1,set2);
}
[Test]
public void EquivalentFailOne()
{
ICollection set1 = new SimpleObjectCollection("x", "y", "z");
ICollection set2 = new SimpleObjectCollection("x", "y", "x");
var expectedMessage =
" Expected: equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void EquivalentFailTwo()
{
ICollection set1 = new SimpleObjectCollection("x", "y", "x");
ICollection set2 = new SimpleObjectCollection("x", "y", "z");
var expectedMessage =
" Expected: equivalent to < \"x\", \"y\", \"x\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreEquivalentHandlesNull()
{
ICollection set1 = new SimpleObjectCollection(null, "x", null, "z");
ICollection set2 = new SimpleObjectCollection("z", null, "x", null);
CollectionAssert.AreEquivalent(set1,set2);
}
#endregion
#region AreNotEqual
[Test]
public void AreNotEqual()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "x");
CollectionAssert.AreNotEqual(set1,set2);
CollectionAssert.AreNotEqual(set1,set2,new TestComparer());
CollectionAssert.AreNotEqual(set1,set2,"test");
CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test");
CollectionAssert.AreNotEqual(set1,set2,"test {0}","1");
CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test {0}","1");
}
[Test]
public void AreNotEqual_Fails()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "z");
var expectedMessage =
" Expected: not equal to < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEqual(set1, set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreNotEqual_HandlesNull()
{
object[] set1 = new object[3];
var set2 = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AreNotEqual(set1,set2);
CollectionAssert.AreNotEqual(set1,set2,new TestComparer());
}
#endregion
#region AreNotEquivalent
[Test]
public void NotEquivalent()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "x");
CollectionAssert.AreNotEquivalent(set1,set2);
}
[Test]
public void NotEquivalent_Fails()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "z", "y");
var expectedMessage =
" Expected: not equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEquivalent(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void NotEquivalentHandlesNull()
{
var set1 = new SimpleObjectCollection("x", null, "z");
var set2 = new SimpleObjectCollection("x", null, "x");
CollectionAssert.AreNotEquivalent(set1,set2);
}
#endregion
#region Contains
[Test]
public void Contains_IList()
{
var list = new SimpleObjectList("x", "y", "z");
CollectionAssert.Contains(list, "x");
}
[Test]
public void Contains_ICollection()
{
var collection = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.Contains(collection,"x");
}
[Test]
public void ContainsFails_ILIst()
{
var list = new SimpleObjectList("x", "y", "z");
var expectedMessage =
" Expected: collection containing \"a\"" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"a"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsFails_ICollection()
{
var collection = new SimpleObjectCollection("x", "y", "z");
var expectedMessage =
" Expected: collection containing \"a\"" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(collection,"a"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsFails_EmptyIList()
{
var list = new SimpleObjectList();
var expectedMessage =
" Expected: collection containing \"x\"" + Environment.NewLine +
" But was: <empty>" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"x"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsFails_EmptyICollection()
{
var ca = new SimpleObjectCollection(new object[0]);
var expectedMessage =
" Expected: collection containing \"x\"" + Environment.NewLine +
" But was: <empty>" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(ca,"x"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsNull_IList()
{
Object[] oa = new object[] { 1, 2, 3, null, 4, 5 };
CollectionAssert.Contains( oa, null );
}
[Test]
public void ContainsNull_ICollection()
{
var ca = new SimpleObjectCollection(new object[] { 1, 2, 3, null, 4, 5 });
CollectionAssert.Contains( ca, null );
}
#endregion
#region DoesNotContain
[Test]
public void DoesNotContain()
{
var list = new SimpleObjectList();
CollectionAssert.DoesNotContain(list,"a");
}
[Test]
public void DoesNotContain_Empty()
{
var list = new SimpleObjectList();
CollectionAssert.DoesNotContain(list,"x");
}
[Test]
public void DoesNotContain_Fails()
{
var list = new SimpleObjectList("x", "y", "z");
var expectedMessage =
" Expected: not collection containing \"y\"" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.DoesNotContain(list,"y"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#region IsSubsetOf
[Test]
public void IsSubsetOf()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z");
CollectionAssert.IsSubsetOf(set2,set1);
Assert.That(set2, Is.SubsetOf(set1));
}
[Test]
public void IsSubsetOf_Fails()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z", "a");
var expectedMessage =
" Expected: subset of < \"y\", \"z\", \"a\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsSubsetOf(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void IsSubsetOfHandlesNull()
{
var set1 = new SimpleObjectList("x", null, "z");
var set2 = new SimpleObjectList(null, "z");
CollectionAssert.IsSubsetOf(set2,set1);
Assert.That(set2, Is.SubsetOf(set1));
}
#endregion
#region IsNotSubsetOf
[Test]
public void IsNotSubsetOf()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z", "a");
CollectionAssert.IsNotSubsetOf(set1,set2);
Assert.That(set1, Is.Not.SubsetOf(set2));
}
[Test]
public void IsNotSubsetOf_Fails()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z");
var expectedMessage =
" Expected: not subset of < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsNotSubsetOf(set2,set1));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void IsNotSubsetOfHandlesNull()
{
var set1 = new SimpleObjectList("x", null, "z");
var set2 = new SimpleObjectList(null, "z", "a");
CollectionAssert.IsNotSubsetOf(set1,set2);
}
#endregion
#region IsOrdered
[Test]
public void IsOrdered()
{
var list = new SimpleObjectList("x", "y", "z");
CollectionAssert.IsOrdered(list);
}
[Test]
public void IsOrdered_Fails()
{
var list = new SimpleObjectList("x", "z", "y");
var expectedMessage =
" Expected: collection ordered" + Environment.NewLine +
" But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsOrdered(list));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void IsOrdered_Allows_adjacent_equal_values()
{
var list = new SimpleObjectList("x", "x", "z");
CollectionAssert.IsOrdered(list);
}
[Test]
public void IsOrdered_Handles_null()
{
var list = new SimpleObjectList("x", null, "z");
var ex = Assert.Throws<ArgumentNullException>(() => CollectionAssert.IsOrdered(list));
Assert.That(ex.Message, Does.Contain("index 1"));
}
[Test]
public void IsOrdered_ContainedTypesMustBeCompatible()
{
var list = new SimpleObjectList(1, "x");
Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list));
}
[Test]
public void IsOrdered_TypesMustImplementIComparable()
{
var list = new SimpleObjectList(new object(), new object());
Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list));
}
[Test]
public void IsOrdered_Handles_custom_comparison()
{
var list = new SimpleObjectList(new object(), new object());
CollectionAssert.IsOrdered(list, new AlwaysEqualComparer());
}
[Test]
public void IsOrdered_Handles_custom_comparison2()
{
var list = new SimpleObjectList(2, 1);
CollectionAssert.IsOrdered(list, new TestComparer());
}
#endregion
#region Equals
[Test]
public void EqualsFailsWhenUsed()
{
var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.Equals(string.Empty, string.Empty));
Assert.That(ex.Message, Does.StartWith("CollectionAssert.Equals should not be used for Assertions"));
}
[Test]
public void ReferenceEqualsFailsWhenUsed()
{
var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.ReferenceEquals(string.Empty, string.Empty));
Assert.That(ex.Message, Does.StartWith("CollectionAssert.ReferenceEquals should not be used for Assertions"));
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Threading;
using System.Text.RegularExpressions;
namespace Nohros.Net.Caching
{
/// <summary>
/// NCache is a wrapper around the buit-in .NET Cache object. It provides convenient methods to
/// manipulate objects on the cache. This class also provides a way to automatically refresh a
/// cached item a specific rate.
/// </summary>
public sealed class NCache
{
internal static readonly Cache cache_;
static int factor_ = 5;
const double kSecondFactor = 0.2; // default factor plus kSecondFactor must be equals to one.
const int kMinuteFactor = 12; // (int)(kSecondFactor * 60);
const int kHourFatcor = kMinuteFactor * 60;
const int kDayFactor = kHourFatcor * 24;
ICacheProvider cache_provider_;
#region .ctor
/// <summary>
/// Initializes a new instance of the <see cref="NCache"/> object.
/// </summary>
NCache() {
// attempt to initialize the cache provider that was specified in configuration.
// If the cache provider could not be instantiated the HttpCacheProvider will be
// used.
try {
}catch{}
factor_ = 5;
}
/// <summary>
/// Initializes the static members.
/// </summary>
static NCache() {
cache_ = HttpRuntime.Cache;
}
#endregion
/// <summary>
/// Removes items from the cache by using a regex pattern.
/// </summary>
/// <param name="pattern">The regex pattern used to remove the items from the cache.</param>
/// <remarks>
/// This method is not performant. It do a regex operation for each item in the cache. Do not use
/// it in a sensitive part of your code.
/// </remarks>
public static void RemoveByPattern(string pattern) {
IDictionaryEnumerator enumerator = cache_.GetEnumerator();
Regex regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
while(enumerator.MoveNext()) {
if (regex.IsMatch(enumerator.Key.ToString()))
cache_.Remove(enumerator.Key.ToString());
}
}
public static object Get(string key) {
return cache_[key];
}
#region static Add(...) overloads
/// <summary>
/// Adds the specified item to the <see cref="Cache"/> object.
/// </summary>
/// <param name="key">The cache key used to reference the item.</param>
/// <param name="obj">The item to be added to the cache.</param>
/// <remarks></remarks>
public static void Add(string key, object obj) {
Add(key, obj, 1, null);
}
/// <summary>
/// Adds the specified item to the <see cref="Cache"/> object with the specified expiration police.
/// </summary>
/// <param name="key">The cache key used to reference the item.</param>
/// <param name="obj">The item to be added to the cache.</param>
/// <param name="seconds">The interval between the time the added object was last accessed and the time
/// at which that object expires. If this value is the equivalent of 20 minutes, the object expires
/// and is removed from the cache 20 minutes after it is last accessed.</param>
public static void Add(string key, object obj, int seconds) {
Add(key, obj, seconds, null);
}
/// <summary>
/// Adds the specified item to the <see cref="Cache"/> object with dependencies.
/// </summary>
/// <param name="key">The cache key used to reference the item.</param>
/// <param name="obj">The item to be added to the cache.</param>
/// <param name="dep">The file or cache key dependencies for the item. When any dependencie changes, the
/// object becomes invalid and is removed from the cache. If there are no dependencies, this parameter
/// contains a null reference.</param>
public static void Add(string key, object obj, CacheDependency dep) {
Add(key, obj, MinuteFactor * 3, dep);
}
/// <summary>
/// Adds the specified item to the <see cref="Cache"/> object with expiration and priority policies.
/// </summary>
/// <param name="key">The cache key used to reference the item.</param>
/// <param name="obj">The item to be added to the cache.</param>
/// <param name="seconds">The interval between the time the added object was last accessed and the time
/// at which that object expires. If this value is the equivalent of 20 minutes, the object expires
/// and is removed from the cache 20 minutes after it is last accessed.</param>
/// <param name="priority">The relative cost of the object, as expressed by the <see cref="CacheItemPriority"/>
/// enumeration. The cache uses this value when it evicts objects; objects with a lower cost are removed from the
/// cache before objects with a higher cost.</param>
public static void Add(string key, object obj, int seconds, CacheItemPriority priority) {
Add(key, obj, seconds, priority, null);
}
/// <summary>
/// Adds the specified item to the <see cref="Cache"/> object with dependencies and expiration policy.
/// </summary>
/// <param name="key">The cache key used to reference the item.</param>
/// <param name="obj">The item to be added to the cache.</param>
/// <param name="seconds">The interval between the time the added object was last accessed and the time
/// at which that object expires. If this value is the equivalent of 20 minutes, the object expires
/// and is removed from the cache 20 minutes after it is last accessed.</param>
/// <param name="dep">The file or cache key dependencies for the item. When any dependencie changes, the
/// object becomes invalid and is removed from the cache. If there are no dependencies, this parameter
/// contains a null reference.</param>
public static void Add(string key, object obj, int seconds, CacheDependency dep) {
Add(key, obj, seconds, CacheItemPriority.Normal, dep);
}
/// <summary>
/// Adds the specified item to the <see cref="Cache"/> object with dependencies and expiration and priority
/// policies.
/// </summary>
/// <param name="key">The cache key used to reference the item.</param>
/// <param name="obj">The item to be added to the cache.</param>
/// <param name="seconds">The interval between the time the added object was last accessed and the time
/// at which that object expires. If this value is the equivalent of 20 minutes, the object expires
/// and is removed from the cache 20 minutes after it is last accessed.</param>
/// <param name="priority">The relative cost of the object, as expressed by the <see cref="CacheItemPriority"/>
/// enumeration. The cache uses this value when it evicts objects; objects with a lower cost are removed from the
/// cache before objects with a higher cost.</param>
/// <param name="dep">The file or cache key dependencies for the item. When any dependencie changes, the
/// object becomes invalid and is removed from the cache. If there are no dependencies, this parameter
/// contains a null reference.</param>
public static void Add(string key, object obj, int seconds, CacheItemPriority priority, CacheDependency dep) {
Add(key, obj, seconds, priority, dep);
}
/// <summary>
/// Adds the specified object to the <see cref="Cache"/> object with dependencies, expiration and priority
/// policies, and a delegate you can use to notify your application when the inserteditem is removed from
/// the cache.
/// </summary>
/// <param name="key">The cache key used to reference the item.</param>
/// <param name="obj">The item to be added to the cache.</param>
/// <param name="seconds">The interval(in seconds) between the time the added object was last accessed and the time at which
/// that object expires. If this value is the equivalent of 20 minutes, the object expires and is removed from
/// the cache 20 minutes after it is last accessed.</param>
/// <param name="dep">The file of cache key dependencies for the item. When any dependency changes, the object
/// becomes invalid and is removed from the cache. If there are no dependencies, this parameter contains null.</param>
/// <param name="priority">The relative cost of the object, as expressed by the <see cref="CacheItemPriority"/>
/// enumeration. The cache uses this value when it evicts objects; objects with a lower cost are removed from the
/// cache before objects with a higher cost.</param>
/// <param name="onRemoveCallback">A delegate that, if provided, is called when an object is removed from the cache. You
/// can use this to notify applications when their objects are deleted from the cache.</param>
public static void Add(string key, object obj, int seconds, CacheItemPriority priority, CacheDependency dep, CacheItemRemovedCallback onRemoveCallback) {
if (obj != null) {
cache_.Add(key, obj, dep, Cache.NoAbsoluteExpiration, TimeSpan.FromTicks(DateTime.Now.AddSeconds(seconds).Ticks), priority, onRemoveCallback);
}
}
#endregion
#region static Insert(...) overloads
public static void Insert(string key, object obj) {
Insert(key, obj, null, 1);
}
public static void Insert(string key, object obj, int seconds) {
Insert(key, obj, null, seconds);
}
public static void Insert(string key, object obj, CacheDependency dep) {
Insert(key, obj, dep, MinuteFactor * 3);
}
public static void Insert(string key, object obj, int seconds, CacheItemPriority priority) {
Insert(key, obj, null, seconds, priority);
}
public static void Insert(string key, object obj, CacheDependency dep, int seconds) {
Insert(key, obj, dep, seconds, CacheItemPriority.Normal);
}
public static void Insert(string key, object obj, CacheDependency dep, int seconds, CacheItemPriority priority) {
Insert(key, obj, dep, seconds, priority, null);
}
public static void Insert(string key, object obj, CacheDependency dep, int seconds, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback) {
Insert(key, obj, dep, DateTime.Now.AddSeconds((double)(Factor * seconds)), priority, onRemoveCallback);
}
public static void Insert(string key, object obj, CacheDependency dep, DateTime absolute_expiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback) {
if (obj != null) {
cache_.Insert(key, obj, dep, absolute_expiration, TimeSpan.Zero, priority, onRemoveCallback);
}
}
#endregion
internal static object InternalCallback(string key)
{
CacheEntry cacheEntry = null;
if (!CacheLockbox.TryGetCacheEntry(key, out cacheEntry))
return null;
CacheLoaderDelegate cacheLoader = cacheEntry.CacheLoader;
if (cacheLoader == null)
return null;
object obj2 = null;
try {
obj2 = cacheLoader();
} catch (Exception exception) {
if (cache_loader_error_delegate_ != null) {
try {
cache_loader_error_delegate_(key, exception);
}
catch { }
}
}
if (obj2 != null) {
Insert(key, obj2, null, (int)cacheEntry.RefreshInterval.TotalSeconds, CacheItemPriority.Normal, new CacheItemRemovedCallback(NCache.ItemRemovedCallback));
CacheLockbox.UpdateCacheEntry(key, DateTime.Now);
}
return obj2;
}
internal static void ItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
{
if (reason == CacheItemRemovedReason.Expired) {
CacheEntry cacheEntry = CacheLockbox.GetCacheEntry(key);
// If the sliding expirarion was not reached...
if(cacheEntry.LastUse.Add(cacheEntry.SlidingExpiration) > DateTime.Now) {
//... the object will be temporary inserted in cache...
cache_.Insert(key, value, null, DateTime.Now.Add(TimeSpan.FromSeconds(30.0)), TimeSpan.Zero, CacheItemPriority.Low, null);
//...reload and reinsert the item into the cache again.
ThreadPool.QueueUserWorkItem(delegate(object o) {
string s = o.ToString();
lock(CacheLockbox.GetInternalLock(s)) {
InternalCallback(s);
}
},key);
}
}
}
public static void Max(string key, object obj) {
Max(key, obj, null);
}
public static void Max(string key, object obj, CacheDependency dep) {
if (obj != null) {
cache_.Insert(key, obj, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.AboveNormal, null);
}
}
public static void MicroInsert(string key, object obj, int secondFactor) {
if (obj != null) {
cache_.Insert(key, obj, null, DateTime.Now.AddSeconds((double)(Factor * secondFactor)), TimeSpan.Zero);
}
}
public static void Permanent(string key, object obj) {
Permanent(key, obj, null);
}
public static void Permanent(string key, object obj, CacheDependency dep)
{
if (obj != null) {
cache_.Insert(key, obj, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.NotRemovable, null);
}
}
public static void Remove(string key)
{
cache_.Remove(key);
}
public static void ReSetFactor(int cacheFactor) {
Factor = cacheFactor;
}
public static int SecondFactorCalculate(int seconds)
{
return Convert.ToInt32(Math.Round((double)(seconds * SecondFactor)));
}
public static void SetCacheLoaderErrorHandler(CacheLoaderErrorDelegate handler) {
if (cache_loader_error_delegate_ != null)
throw new Exception("The CacheLoaderDelegate should only be set once whitin an application");
if (handler != null)
cache_loader_error_delegate_ = handler;
}
public static bool Update(string key)
{
object lck = CacheLockbox.GetInternalLock(key);
if (lck == null)
return false;
lock (lck)
InternalCallback(key);
return true;
}
public static object GetCacheEntryLock(string key)
{
return CacheLockbox.GetLock(key);
}
public static object GetCacheEntryLock(string key, int refreshIntervalSeconds, int slidingExpirationSeconds, CacheLoaderDelegate loaderDelegate)
{
return CacheLockbox.GetLock(key, TimeSpan.FromSeconds((double)(refreshIntervalSeconds * Factor)), TimeSpan.FromSeconds((double)(slidingExpirationSeconds * Factor)), loaderDelegate);
}
public static object GetCacheEntryLock(string key, TimeSpan refreshInterval, TimeSpan slidingExpiration, CacheLoaderDelegate loaderDelegate)
{
return CacheLockbox.GetLock(key, refreshInterval, slidingExpiration, loaderDelegate);
}
public static int CacheFactor
{
get { return factor_; }
}
}
#region Generic Cache
/// <summary>
/// Generic cache wrapper
/// </summary>
public class NCache<T> where T: class
{
/// <summary>
/// Default constructor
/// </summary>
private NCache() { }
/// <summary>
/// Retrieves the specified item from the NCache object.
/// </summary>
/// <param name="key">the identifier for the cache item to retrieve</param>
/// <returns>the retrieved cache item</returns>
/// <exception cref="KeyNotFoundException">the key does not exists in cache</exception>
public static T Get(string key)
{
CacheEntry entry = null;
if (CacheLockbox.TryGetCacheEntry(key, out entry))
{
lock (CacheLockbox.GetLock(key))
{
T local = (T)NCache.Get(key);
if (local == null)
local = (T)NCache.InternalCallback(key);
return local;
}
}
throw new Exception("CacheEntry for key" + key + "does not exist. Please call a different overload of NCahe<T>.Get() to set the CacheEntry properties_.");
}
/// <summary>
/// Retrieves the specified item from the NCache object.
/// </summary>
/// <param name="key">The cache key used to reference the item</param>
/// <param name="refreshIntervalSeconds"></param>
/// <param name="slidingExpirationSeconds">The interval between the time the added
/// object was last accessed and the time at which that object expires. If this value
/// is equivalent of 1 minute, the object expires and is removed from the cache 1 minute
/// after it is last accessed.
/// </param>
/// <param name="loaderDelegate">A delegate that, if provided, is called to reload the
/// object when it is removed from the cache.
/// </param>
/// <returns>The retrieved cache item, or null if the key is not found and the
/// <paramref name="loaderDelegate"/> was not supplied</returns>
public static T Get(string key, int refreshIntervalSeconds, int slidingExpirationSeconds, NCache.CacheLoaderDelegate loaderDelegate)
{
return NCache<T>.Get(key, TimeSpan.FromSeconds((double)(refreshIntervalSeconds * NCache.CacheFactor)), TimeSpan.FromSeconds((double)(slidingExpirationSeconds * NCache.CacheFactor)), loaderDelegate);
}
/// <summary>
/// Retrieves the specified item from the NCache object.
/// </summary>
/// <param name="key">The cache key used to reference the item</param>
/// <param name="refreshInterval"></param>
/// <param name="slidingExpiration">The interval between the time the added
/// object was last accessed and the time at which that object expires. If this value
/// is equivalent of 1 minute, the object expires and is removed from the cache 1 minute
/// after it is last accessed.
/// </param>
/// <param name="loaderDelegate">A delegate that, if provided, is called to reload the
/// object when it is removed from the cache.
/// </param>
/// <returns>The retrieved cache item, or null if the key is not found and the
/// <paramref name="loaderDelegate"/> was not supplied</returns>
/// <remarks>
/// If the key is not found this method tries to call the <paramref name="loaderDelegate"/> delegate to
/// load the object and then adds the result to the cache.
/// </remarks>
public static T Get(string key, TimeSpan refreshInterval, TimeSpan slidingExpiration, NCache.CacheLoaderDelegate loaderDelegate)
{
lock (CacheLockbox.GetLock(key, refreshInterval, slidingExpiration, loaderDelegate))
{
T local = (T)NCache.Get(key);
if (local == null)
local = (T)NCache.InternalCallback(key);
return local;
}
}
/// <summary>
/// Updates a cached object
/// </summary>
/// <param name="key">the identifier for the cached object</param>
/// <returns>true if the object is found and updated</returns>
/// <remarks>
/// The object will be update by using the loader delegate that was
/// specified when the object is added to cache.
/// </remarks>
public static bool Update(string key)
{
return NCache.Update(key);
}
}
#endregion
}
| |
#region Copyright (C) 2005 Rob Blackwell & Active Web Solutions.
//
// L Sharp .NET, a powerful lisp-based scripting language for .NET.
// Copyright (C) 2005 Rob Blackwell & Active Web Solutions.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free
// Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
#endregion
using System;
namespace LSharp
{
/// <summary>
/// LSharp primitives and utilities.
/// </summary>
public sealed class Primitives
{
Primitives(){}
public static bool Eql(object x, object y)
{
if ( x == null | y == null)
return x == y;
return (x.Equals(y));
}
public static bool Eql(Cons args)
{
object last = args.First();
foreach (object item in (Cons)args.Rest())
{
if (!(Eql(last,item)))
return false;
last = item;
}
return true;
}
public static bool Eq(Cons args)
{
object last = args.First();
foreach (object item in (Cons)args.Rest())
{
if (!(object.ReferenceEquals(last,item)))
return false;
last = item;
}
return true;
}
/// <summary>
/// Returns true if the given object is an atom, false otherwise
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static bool IsAtom(Object x)
{
if (x == null)
return true;
else
return !(x is Cons);
}
/// <summary>
/// Returns true if the Object is a List, false otherwise
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static bool IsList(Object x)
{
if (x == null)
return true;
else
return (x is Cons);
}
/// <summary>
/// Process the arguments passed to a closure, and add them to the given enviroment.
/// </summary>
/// <param name="argumentNameList">The list of names and kewords the closure was created with.</param>
/// <param name="argumentList">The arguments passed to the closure.</param>
/// <param name="localEnvironment">The closure's local variables.</param>
/// <returns>Nothing.</returns>
public static void ProcessArguments(Cons argumentNameList, Cons argumentList, Environment localEnvironment)
{
while (argumentNameList != null)
{
// Get the name for the closure's parameter. Then check to see if it's a keyword, if it is then
// process the keyword. Otherwise set up that parameter in the closure's enviroment with the
// caller specified value.
Symbol argumentName = (Symbol)argumentNameList.Car();
switch (argumentName.ToString())
{
case "&rest":
argumentName = (Symbol)argumentNameList.Cadr();
localEnvironment.AssignLocal(argumentName, argumentList);
argumentNameList = null;
argumentList = null;
break;
case "&optional":
ProcessOptionalArguments((Cons)argumentNameList.Cdr(), argumentList, localEnvironment);
argumentNameList = null;
argumentList = null;
break;
case "&key":
ProcessKeyArguments((Cons)argumentNameList.Cdr(), argumentList, localEnvironment);
argumentNameList = null;
argumentList = null;
break;
default:
if (argumentList == null)
{
throw new LSharpException("Not enough parameters given.");
}
localEnvironment.AssignLocal(argumentName, argumentList.Car());
argumentList = (Cons)argumentList.Cdr();
argumentNameList = (Cons)argumentNameList.Cdr();
break;
}
}
// Looks like the caller has supplied more parameters than the closure can use.
if (argumentList != null)
{
throw new LSharpException("Too many parameters given.");
}
}
private static void ProcessOptionalArguments(Cons argumentNameList, Cons argumentList,
Environment localEnvironment)
{
// We need to add all the arguments to the closure's environment.
while (argumentNameList != null)
{
Symbol argumentName = null;
object argumentValue = null;
// We need to get the name of the argument, it can either be just the name or, it can be
// it's own Cons with the name and an expression for the default value.
if (argumentNameList.Car() is Cons)
{
// It is a Cons, so extract the name and the default value.
argumentName = (Symbol)argumentNameList.Caar();
argumentValue = argumentNameList.Cadar();
}
else
{
argumentName = (Symbol)argumentNameList.Car();
}
// Now, if the caller has specified a value for this argument, get it now.
if (argumentList != null)
{
argumentValue = argumentList.Car();
argumentList = (Cons)argumentList.Cdr();
}
// Finally add the parameter to the closure's list and then move onto the next argument.
// Because the default can be any expression, we need to evaluate the value every time the
// function is called.
localEnvironment.AssignLocal(argumentName, Runtime.Eval(argumentValue, localEnvironment));
argumentNameList = (Cons)argumentNameList.Cdr();
}
// Looks like the caller has supplied more parameters than the closure can use.
if (argumentList != null)
{
throw new LSharpException("Too many parameters given.");
}
}
private static void ProcessKeyArguments(Cons argumentNameList, Cons argumentList,
Environment localEnvironment)
{
// Make sure that all of the defined key arguments are inserted to the local enviroment with their
// defaults.
while (argumentNameList != null)
{
Symbol argumentName = null;
object argumentValue = null;
// We need to get the name of the argument, it can either be just the name or, it can be
// it's own Cons with the name and an expression for the default value.
if (argumentNameList.Car() is Cons)
{
// It is a Cons, so extract the name and the default value. Because the default can be
// any expression, we need to evaluate the value every time the function is called.
argumentName = (Symbol)argumentNameList.Caar();
argumentValue = Runtime.Eval(argumentNameList.Cadar(), localEnvironment);
}
else
{
argumentName = (Symbol)argumentNameList.Car();
}
// Add this variable to the closure's environment, then advance to the next parameter.
localEnvironment.AssignLocal(argumentName, argumentValue);
argumentNameList = (Cons)argumentNameList.Cdr();
}
// Now that the parameters and their defaults have been added to the environment we can now
// process the supplied arguments.
while (argumentList != null)
{
// Because these are keyed parameters, the caller needs to specify the name of each
// parameter.
if (argumentList.Car().GetType() != typeof(Symbol))
{
throw new LSharpException("Key parameters must be specified by name.");
}
// Grab the current parameter and the value associated with it. Then make sure that this
// is a keyword.
Symbol keywordName = (Symbol)argumentList.Car();
object argumentValue = argumentList.Cadr();
if (keywordName.Name[0] != ':')
{
throw new LSharpException(keywordName + " is not a valid keyword.");
}
// Now that we know they supplied a keyword, create a symbol out of it and make sure that
// it exists.
//keywordName = new Symbol(keywordName.Name.Substring(1));
keywordName = Symbol.FromName(keywordName.Name.Substring(1));
if (localEnvironment.Contains(keywordName) == false)
{
throw new LSharpException(keywordName + " is not a recognised keyword.");
}
// Update the parameter with the value that the user specified and then move onto the next
// argument in the list.
localEnvironment.AssignLocal(keywordName, argumentValue);
argumentList = (Cons)argumentList.Cddr();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using MIGAZ.Models;
using MIGAZ.Models.ARM;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Forms;
namespace MIGAZ.Generator
{
public class TemplateGenerator
{
private ILogProvider _logProvider;
private IStatusProvider _statusProvider;
private ITelemetryProvider _telemetryProvider;
private ITokenProvider _tokenProvider;
private List<Resource> _resources;
private Dictionary<string, Parameter> _parameters;
private List<CopyBlobDetail> _copyBlobDetails;
private Dictionary<string, string> _processedItems;
public Dictionary<string, string> _storageAccountNames;
private AwsObjectRetriever _awsObjectRetriever;
public TemplateGenerator(ILogProvider logProvider, IStatusProvider statusProvider, AwsObjectRetriever awsObjectRetriever, ITelemetryProvider telemetryProvider)
{
_logProvider = logProvider;
_statusProvider = statusProvider;
_telemetryProvider = telemetryProvider;
//_tokenProvider = tokenProvider;
_awsObjectRetriever = awsObjectRetriever;
}
public void GenerateTemplate(AWSArtefacts artefacts, AwsObjectRetriever _awsObjectRetriever, StreamWriter templateWriter, Hashtable teleinfo)
{
_logProvider.WriteLog("GenerateTemplate", "Start");
app.Default.ExecutionId = Guid.NewGuid().ToString();
_resources = new List<Resource>();
_parameters = new Dictionary<string, Parameter>();
_processedItems = new Dictionary<string, string>();
_copyBlobDetails = new List<CopyBlobDetail>();
_storageAccountNames = new Dictionary<string, string>();
//var token = _tokenProvider.GetToken(tenantId);
_logProvider.WriteLog("GenerateTemplate", "Start processing selected virtual networks");
// process selected virtual networks
foreach (var virtualnetworkname in artefacts.VirtualNetworks)
{
_statusProvider.UpdateStatus("BUSY: Exporting Virtual Network...");
Application.DoEvents();
var vpcs = _awsObjectRetriever.Vpcs;
List<Amazon.EC2.Model.Subnet> subnets = _awsObjectRetriever.GetSubnets(virtualnetworkname.VpcId);
if (subnets != null)
{
var vpc = _awsObjectRetriever.Vpcs.Vpcs.Find(x => x.VpcId == virtualnetworkname.VpcId); // Picking the Subnets selected by the user out of all the available subnets
List<Amazon.EC2.Model.DhcpOptions> dhcpOptions = _awsObjectRetriever.getDhcpOptions(vpc.DhcpOptionsId);
//_awsRetriever.GetAwsResources("Dhcp Options", virtualnetworksite.SelectSingleNode("dhcpOptionsId").InnerText);
BuildVirtualNetworkObject(vpc, subnets, dhcpOptions,artefacts);
}
Application.DoEvents();
}
_logProvider.WriteLog("GenerateTemplate", "End processing selected Vpcs");
String storageAccountName = RandomString(22);
if (artefacts.Instances.Count > 0)
{
_logProvider.WriteLog("GenerateTemplate", "Start processing storage accounts");
BuildStorageAccountObject(storageAccountName);
_logProvider.WriteLog("GenerateTemplate", "End processing selected storage accounts");
}
_logProvider.WriteLog("GenerateTemplate", "Start processing selected Instances");
// process selected instances
foreach (var instance in artefacts.Instances)
{
_statusProvider.UpdateStatus("BUSY: Exporting Instances...");
Application.DoEvents();
var availableInstances = _awsObjectRetriever.Instances;
if (availableInstances != null)
{
// var selectedInstances = availableInstances.Reservations[0].Instances.Find(x => x.InstanceId == instance.InstanceId);
var selectedInstances = _awsObjectRetriever.getInstancebyId(instance.InstanceId);
List<NetworkProfile_NetworkInterface> networkinterfaces = new List<NetworkProfile_NetworkInterface>();
String vpcId = selectedInstances.Instances[0].VpcId.ToString();
//Process LBs
var LBs = _awsObjectRetriever.getLBs(vpcId);
string instanceLBName = "";
foreach (var LB in LBs)
{
foreach (var LBInstance in LB.Instances)
{
if ((LB.VPCId == vpcId) && (LBInstance.InstanceId == instance.InstanceId))
{
if(LB.Scheme == "internet-facing")
{
BuildPublicIPAddressObject(LB);
}
instanceLBName = LB.LoadBalancerName;
BuildLoadBalancerObject(LB, instance.InstanceId.ToString());
}
}
}
//Process Network Interface
BuildNetworkInterfaceObject(selectedInstances.Instances[0], ref networkinterfaces, LBs);
//Process EC2 Instance
BuildVirtualMachineObject(selectedInstances.Instances[0], networkinterfaces, storageAccountName, instanceLBName);
}
Application.DoEvents();
}
_logProvider.WriteLog("GenerateTemplate", "End processing selected cloud services and virtual machines");
Template template = new Template();
template.resources = _resources;
template.parameters = _parameters;
// save JSON template
_statusProvider.UpdateStatus("BUSY: saving JSON template");
Application.DoEvents();
string jsontext = JsonConvert.SerializeObject(template, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore });
jsontext = jsontext.Replace("schemalink", "$schema");
WriteStream(templateWriter, jsontext);
_logProvider.WriteLog("GenerateTemplate", "Write file export.json");
//post Telemetry Record to AWStoARMToolAPI
if (app.Default.AllowTelemetry)
{
_statusProvider.UpdateStatus("BUSY: saving telemetry information");
_telemetryProvider.PostTelemetryRecord(teleinfo["AccessKey"].ToString(), _processedItems, teleinfo["Region"].ToString());
}
_statusProvider.UpdateStatus("Ready");
_logProvider.WriteLog("GenerateTemplate", "End");
}
private void BuildPublicIPAddressObject(ref NetworkInterface networkinterface)
{
_logProvider.WriteLog("BuildPublicIPAddressObject", "Start");
string publicipaddress_name = networkinterface.name;
string publicipallocationmethod = "Dynamic";
Hashtable dnssettings = new Hashtable();
dnssettings.Add("domainNameLabel", (publicipaddress_name + app.Default.UniquenessSuffix).ToLower());
PublicIPAddress_Properties publicipaddress_properties = new PublicIPAddress_Properties();
publicipaddress_properties.dnsSettings = dnssettings;
publicipaddress_properties.publicIPAllocationMethod = publicipallocationmethod;
PublicIPAddress publicipaddress = new PublicIPAddress();
publicipaddress.name = networkinterface.name + "-PIP";
// publicipaddress.location = "";
publicipaddress.properties = publicipaddress_properties;
try // it fails if this public ip address was already processed. safe to continue.
{
_processedItems.Add("Microsoft.Network/publicIPAddresses/" + publicipaddress.name, publicipaddress.location);
_resources.Add(publicipaddress);
_logProvider.WriteLog("BuildPublicIPAddressObject", "Microsoft.Network/publicIPAddresses/" + publicipaddress.name);
}
catch { }
NetworkInterface_Properties networkinterface_properties = (NetworkInterface_Properties)networkinterface.properties;
networkinterface_properties.ipConfigurations[0].properties.publicIPAddress = new Reference();
networkinterface_properties.ipConfigurations[0].properties.publicIPAddress.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/publicIPAddresses/" + publicipaddress.name + "')]";
networkinterface.properties = networkinterface_properties;
networkinterface.dependsOn.Add(networkinterface_properties.ipConfigurations[0].properties.publicIPAddress.id);
_logProvider.WriteLog("BuildPublicIPAddressObject", "End");
}
private void BuildPublicIPAddressObject(dynamic resource)
{
_logProvider.WriteLog("BuildPublicIPAddressObject", "Start");
string publicipaddress_name = resource.LoadBalancerName + "-PIP";
string publicipallocationmethod = "Dynamic";
char[] delimiterChars = { '.' };
string LBDNS = resource.DNSName.Split(delimiterChars)[0].ToLower();
Hashtable dnssettings = new Hashtable();
dnssettings.Add("domainNameLabel", LBDNS);
PublicIPAddress_Properties publicipaddress_properties = new PublicIPAddress_Properties();
publicipaddress_properties.dnsSettings = dnssettings;
publicipaddress_properties.publicIPAllocationMethod = publicipallocationmethod;
PublicIPAddress publicipaddress = new PublicIPAddress();
publicipaddress.name = publicipaddress_name;
// publicipaddress.location = "";
publicipaddress.properties = publicipaddress_properties;
try // it fails if this public ip address was already processed. safe to continue.
{
_processedItems.Add("Microsoft.Network/publicIPAddresses/" + publicipaddress.name, publicipaddress.location);
_resources.Add(publicipaddress);
_logProvider.WriteLog("BuildPublicIPAddressObject", "Microsoft.Network/publicIPAddresses/" + publicipaddress.name);
}
catch { }
_logProvider.WriteLog("BuildPublicIPAddressObject", "End");
}
private void BuildAvailabilitySetObject(dynamic loadbalancer)
{
_logProvider.WriteLog("BuildAvailabilitySetObject", "Start");
AvailabilitySet availabilityset = new AvailabilitySet();
availabilityset.name = loadbalancer.name + "-AS";
try // it fails if this availability set was already processed. safe to continue.
{
_processedItems.Add("Microsoft.Compute/availabilitySets/" + availabilityset.name, availabilityset.location);
_resources.Add(availabilityset);
_logProvider.WriteLog("BuildAvailabilitySetObject", "Microsoft.Compute/availabilitySets/" + availabilityset.name);
}
catch { }
_logProvider.WriteLog("BuildAvailabilitySetObject", "End");
}
private void BuildLoadBalancerObject(dynamic LB,string instance)
{
_logProvider.WriteLog("BuildLoadBalancerObject", "Start");
LoadBalancer loadbalancer = new LoadBalancer();
loadbalancer.name = LB.LoadBalancerName;
FrontendIPConfiguration_Properties frontendipconfiguration_properties = new FrontendIPConfiguration_Properties();
//// if internal load balancer
if (LB.Scheme != "internet-facing")
{
string virtualnetworkname = GetVPCName(LB.VPCId);
var subnet = _awsObjectRetriever.getSubnetbyId(LB.Subnets[0]);
string subnetname = GetSubnetName(subnet[0]);
frontendipconfiguration_properties.privateIPAllocationMethod = "Static";
try
{
IPHostEntry host = Dns.GetHostEntry(LB.DNSName);
frontendipconfiguration_properties.privateIPAddress = host.AddressList[0].ToString();
}
catch
{
frontendipconfiguration_properties.privateIPAllocationMethod = "Dynamic";
}
List<string> dependson = new List<string>();
if (GetProcessedItem("Microsoft.Network/virtualNetworks/" + virtualnetworkname))
{
dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Network/virtualNetworks/" + virtualnetworkname + "')]");
}
loadbalancer.dependsOn = dependson;
Reference subnet_ref = new Reference();
subnet_ref.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/virtualNetworks/" + virtualnetworkname + "/subnets/" + subnetname + "')]";
frontendipconfiguration_properties.subnet = subnet_ref;
}
//// if external load balancer
else
{
List<string> dependson = new List<string>();
dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Network/publicIPAddresses/" + loadbalancer.name + "-PIP')]");
loadbalancer.dependsOn = dependson;
Reference publicipaddress_ref = new Reference();
publicipaddress_ref.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/publicIPAddresses/" + loadbalancer.name + "-PIP')]";
frontendipconfiguration_properties.publicIPAddress = publicipaddress_ref;
}
LoadBalancer_Properties loadbalancer_properties = new LoadBalancer_Properties();
FrontendIPConfiguration frontendipconfiguration = new FrontendIPConfiguration();
frontendipconfiguration.properties = frontendipconfiguration_properties;
List<FrontendIPConfiguration> frontendipconfigurations = new List<FrontendIPConfiguration>();
frontendipconfigurations.Add(frontendipconfiguration);
loadbalancer_properties.frontendIPConfigurations = frontendipconfigurations;
Hashtable backendaddresspool = new Hashtable();
backendaddresspool.Add("name", "default");
List<Hashtable> backendaddresspools = new List<Hashtable>();
backendaddresspools.Add(backendaddresspool);
loadbalancer_properties.backendAddressPools = backendaddresspools;
List<InboundNatRule> inboundnatrules = new List<InboundNatRule>();
List<LoadBalancingRule> loadbalancingrules = new List<LoadBalancingRule>();
List<Probe> probes = new List<Probe>();
foreach (var VM in LB.Instances)
{
if (VM.InstanceId == instance)
{
Hashtable virtualmachineinfo = new Hashtable();
virtualmachineinfo.Add("virtualmachinename", VM.InstanceId);
BuildLoadBalancerRules(VM.InstanceId, LB, ref inboundnatrules, ref loadbalancingrules, ref probes);
}
}
loadbalancer_properties.inboundNatRules = inboundnatrules;
loadbalancer_properties.loadBalancingRules = loadbalancingrules;
loadbalancer_properties.probes = probes;
loadbalancer.properties = loadbalancer_properties;
// Add the load balancer only if there is any Load Balancing rule or Inbound NAT rule
if (loadbalancingrules.Count > 0)
{
try // it fails if this load balancer was already processed. safe to continue.
{
_processedItems.Add("Microsoft.Network/loadBalancers/" + loadbalancer.name, loadbalancer.location);
_resources.Add(loadbalancer);
// Add an Availability Set per load balancer
BuildAvailabilitySetObject(loadbalancer);
_logProvider.WriteLog("BuildLoadBalancerObject", "Microsoft.Network/loadBalancers/" + loadbalancer.name);
}
catch { }
}
else
{
_logProvider.WriteLog("BuildLoadBalancerObject", "EMPTY Microsoft.Network/loadBalancers/" + loadbalancer.name);
}
_logProvider.WriteLog("BuildLoadBalancerObject", "End");
}
private void BuildLoadBalancerRules(String resource, dynamic LB, ref List<InboundNatRule> inboundnatrules, ref List<LoadBalancingRule> loadbalancingrules, ref List<Probe> probes)
{
_logProvider.WriteLog("BuildLoadBalancerRules", "Start");
string virtualmachinename = resource;
string loadbalancername = LB.LoadBalancerName;
// process Probe
Probe_Properties probe_properties = new Probe_Properties();
char[] delimiterChars = { ':' };
probe_properties.protocol = LB.HealthCheck.Target.Split(delimiterChars)[0];
if (probe_properties.protocol == "HTTP")
{
probe_properties.protocol = "Http";
}
else
{
probe_properties.protocol = "Tcp";
}
string portPath = LB.HealthCheck.Target.Split(delimiterChars)[1];
if (portPath.IndexOf("/") == -1)
{
probe_properties.port = Convert.ToInt64(portPath);
}
else
{
delimiterChars[0] = '/';
probe_properties.port = Convert.ToInt64(portPath.Split(delimiterChars)[0]);
probe_properties.requestPath = portPath.Split(delimiterChars)[1];
}
Probe probe = new Probe();
probe.name = probe_properties.protocol + "-" + probe_properties.port;
probe.properties = probe_properties;
try // fails if this probe already exists. safe to continue
{
_processedItems.Add("Microsoft.Network/loadBalancers/" + loadbalancername + "/probes/" + probe.name, "");
probes.Add(probe);
}
catch { }
// end process Probe
foreach (var rule in LB.ListenerDescriptions)
{
string protocol = "Tcp";
//if (rule.Listener.InstanceProtocol == "HTTP")
//{
// protocol = "Http";
//}
string name = protocol + "-" + rule.Listener.LoadBalancerPort;
// build load balancing rule
Reference frontendipconfiguration_ref = new Reference();
frontendipconfiguration_ref.id = "[concat(resourceGroup().id,'/providers/Microsoft.Network/loadBalancers/" + loadbalancername + "/frontendIPConfigurations/default')]";
Reference backendaddresspool_ref = new Reference();
backendaddresspool_ref.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/loadBalancers/" + loadbalancername + "/backendAddressPools/default')]";
Reference probe_ref = new Reference();
probe_ref.id = "[concat(resourceGroup().id,'/providers/Microsoft.Network/loadBalancers/" + loadbalancername + "/probes/" + probe.name + "')]";
LoadBalancingRule_Properties loadbalancingrule_properties = new LoadBalancingRule_Properties();
loadbalancingrule_properties.frontendIPConfiguration = frontendipconfiguration_ref;
loadbalancingrule_properties.backendAddressPool = backendaddresspool_ref;
loadbalancingrule_properties.probe = probe_ref;
loadbalancingrule_properties.frontendPort = rule.Listener.LoadBalancerPort;
loadbalancingrule_properties.backendPort = rule.Listener.InstancePort;
loadbalancingrule_properties.protocol = protocol;
LoadBalancingRule loadbalancingrule = new LoadBalancingRule();
loadbalancingrule.name = name;
loadbalancingrule.properties = loadbalancingrule_properties;
try // fails if this load balancing rule already exists. safe to continue
{
_processedItems.Add("Microsoft.Network/loadBalancers/" + loadbalancername + "/loadBalancingRules/" + loadbalancingrule.name, "");
loadbalancingrules.Add(loadbalancingrule);
_logProvider.WriteLog("BuildLoadBalancerRules", "Microsoft.Network/loadBalancers/" + loadbalancername + "/loadBalancingRules/" + loadbalancingrule.name);
}
catch { continue; }
}
_logProvider.WriteLog("BuildLoadBalancerRules", "End");
}
private void BuildVirtualNetworkObject(Amazon.EC2.Model.Vpc vpc, List<Amazon.EC2.Model.Subnet> subnetNode, List<Amazon.EC2.Model.DhcpOptions> dhcpNode, AWSArtefacts artefacts)
{
_logProvider.WriteLog("BuildVirtualNetworkObject", "Start");
List<string> dependson = new List<string>();
//Address spaces
List<string> addressprefixes = new List<string>();
addressprefixes.Add(vpc.CidrBlock);
AddressSpace addressspace = new AddressSpace();
addressspace.addressPrefixes = addressprefixes;
//DnsServers
List<string> dnsservers = new List<string>();
foreach (var dnsserver in dhcpNode)
{
foreach (var item in dnsserver.DhcpConfigurations)
{
if ((item.Key == "domain-name-servers") && (item.Values[0] != "AmazonProvidedDNS"))
{
foreach(var value in item.Values)
dnsservers.Add(value);
}
}
}
VirtualNetwork_dhcpOptions dhcpoptions = new VirtualNetwork_dhcpOptions();
if (dnsservers.Count > 0)
{
dhcpoptions.dnsServers = dnsservers;
}
else
{
dhcpoptions = null;
}
//VirtualNetworks
VirtualNetwork virtualnetwork = new VirtualNetwork();
virtualnetwork.name = GetVPCName(vpc.VpcId);
virtualnetwork.dependsOn = dependson;
List<Subnet> subnets = new List<Subnet>();
foreach (var subnetnode in subnetNode)
{
Subnet_Properties properties = new Subnet_Properties();
properties.addressPrefix = subnetnode.CidrBlock;
Subnet subnet = new Subnet();
//subnet.name = subnetnode.SubnetId;
subnet.name = GetSubnetName(subnetnode);
subnet.properties = properties;
subnets.Add(subnet);
//QUES: Single Sec group?
// add Network Security Group if exists - 2 subnets - each acl is associated with both
List<Amazon.EC2.Model.NetworkAcl> networkAcls = _awsObjectRetriever.getNetworkAcls(subnetnode.SubnetId);
List<Amazon.EC2.Model.RouteTable> routeTable = _awsObjectRetriever.getRouteTables(subnetnode.SubnetId);
//var nodes = networkAcls.SelectSingleNode("DescribeNetworkAclsResponse ").SelectSingleNode("networkAclSet").SelectNodes("item");
if (networkAcls.Count > 0)
{
NetworkSecurityGroup networksecuritygroup = BuildNetworkSecurityGroup(networkAcls[0]);
//NetworkSecurityGroup networksecuritygroup = BuildNetworkSecurityGroup(subnet.name);
// Add NSG reference to the subnet
Reference networksecuritygroup_ref = new Reference();
networksecuritygroup_ref.id = "[concat(resourceGroup().id,'/providers/Microsoft.Network/networkSecurityGroups/" + networksecuritygroup.name + "')]";
properties.networkSecurityGroup = networksecuritygroup_ref;
// Add NSG dependsOn to the Virtual Network object
if (!virtualnetwork.dependsOn.Contains(networksecuritygroup_ref.id))
{
virtualnetwork.dependsOn.Add(networksecuritygroup_ref.id);
}
}
if (routeTable.Count > 0)
{
RouteTable routetable = BuildRouteTable(routeTable[0]);
if (routetable.properties != null)
{
// Add Route Table reference to the subnet
Reference routetable_ref = new Reference();
routetable_ref.id = "[concat(resourceGroup().id,'/providers/Microsoft.Network/routeTables/" + routetable.name + "')]";
properties.routeTable = routetable_ref;
// Add Route Table dependsOn to the Virtual Network object
if (!virtualnetwork.dependsOn.Contains(routetable_ref.id))
{
virtualnetwork.dependsOn.Add(routetable_ref.id);
}
}
}
}
VirtualNetwork_Properties virtualnetwork_properties = new VirtualNetwork_Properties();
virtualnetwork_properties.addressSpace = addressspace;
virtualnetwork_properties.subnets = subnets;
virtualnetwork_properties.dhcpOptions = dhcpoptions;
virtualnetwork.properties = virtualnetwork_properties;
_processedItems.Add("Microsoft.Network/virtualNetworks/" + virtualnetwork.name, virtualnetwork.location);
_resources.Add(virtualnetwork);
_logProvider.WriteLog("BuildVirtualNetworkObject", "Microsoft.Network/virtualNetworks/" + virtualnetwork.name);
_logProvider.WriteLog("BuildVirtualNetworkObject", "End");
}
private NetworkSecurityGroup BuildNetworkSecurityGroup(Amazon.EC2.Model.NetworkAcl securitygroup)
{
_logProvider.WriteLog("BuildNetworkSecurityGroup", "Start");
Hashtable nsginfo = new Hashtable();
nsginfo.Add("name", GetSGName(securitygroup));
//XmlDocument resource = _awsRetriever.GetAwsResources("DescribeNetworkAcls", "");
NetworkSecurityGroup networksecuritygroup = new NetworkSecurityGroup();
networksecuritygroup.name = GetSGName(securitygroup);
//networksecuritygroup.location = securitygroup.SelectSingleNode("//Location").InnerText;
NetworkSecurityGroup_Properties networksecuritygroup_properties = new NetworkSecurityGroup_Properties();
networksecuritygroup_properties.securityRules = new List<SecurityRule>();
// for each rule
foreach (var rule in securitygroup.Entries)
{
string ruleDirection = "";
if (rule.Egress == true)
ruleDirection = "Outbound";
else if (rule.Egress == false)
ruleDirection = "Inbound";
SecurityRule_Properties securityrule_properties = new SecurityRule_Properties(); //Name -Inbound_32, Outbound_100
//securityrule_properties.description = rule.SelectSingleNode("Name").InnerText;
securityrule_properties.direction = ruleDirection;
if (rule.RuleNumber > 4096)
securityrule_properties.priority = 4096;
else
{
securityrule_properties.priority = rule.RuleNumber;//RuleNum
securityrule_properties.access = rule.RuleAction; //ruleAction
securityrule_properties.sourceAddressPrefix = rule.CidrBlock; //cidrBlock
securityrule_properties.destinationAddressPrefix = "0.0.0.0/0";
if (rule.Protocol == "6")
securityrule_properties.protocol = "tcp";
else if (rule.Protocol == "17")
securityrule_properties.protocol = "udp";
else
securityrule_properties.protocol = "*";
if (rule.PortRange != null)
{
int from, to;
from = rule.PortRange.From;
to = rule.PortRange.To;
if (from == to)
securityrule_properties.sourcePortRange = from.ToString();
else
securityrule_properties.sourcePortRange = from + "-" + to;
// number, number-num, * - if portrange not available - from and to tags of port range tag
}
else
{
securityrule_properties.sourcePortRange = "*";
}
securityrule_properties.destinationPortRange = "*";
SecurityRule securityrule = new SecurityRule();
securityrule.name = (ruleDirection + "-" + rule.RuleNumber);
securityrule.properties = securityrule_properties;
networksecuritygroup_properties.securityRules.Add(securityrule);
networksecuritygroup.properties = networksecuritygroup_properties;
}
}
try // it fails if this network security group was already processed. safe to continue.
{
_processedItems.Add("Microsoft.Network/networkSecurityGroups/" + networksecuritygroup.name, networksecuritygroup.location);
_resources.Add(networksecuritygroup);
_logProvider.WriteLog("BuildNetworkSecurityGroup", "Microsoft.Network/networkSecurityGroups/" + networksecuritygroup.name);
}
catch { }
_logProvider.WriteLog("BuildNetworkSecurityGroup", "End");
return networksecuritygroup;
}
private NetworkSecurityGroup BuildNetworkSecurityGroup(Amazon.EC2.Model.GroupIdentifier securitygroupidentifier, ref NetworkInterface networkinterface)
{
_logProvider.WriteLog("BuildNetworkSecurityGroup", "Start");
NetworkSecurityGroup networksecuritygroup = new NetworkSecurityGroup();
networksecuritygroup.name = securitygroupidentifier.GroupName;
NetworkSecurityGroup_Properties networksecuritygroup_properties = new NetworkSecurityGroup_Properties();
networksecuritygroup_properties.securityRules = new List<SecurityRule>();
long inboundPriority = 100;
long outboundPriority = 101;
Amazon.EC2.Model.SecurityGroup securitygroup = _awsObjectRetriever.getSecurityGroup(securitygroupidentifier.GroupId);
// process inbound rules
foreach (Amazon.EC2.Model.IpPermission ippermission in securitygroup.IpPermissions)
{
SecurityRule securityrule = new SecurityRule();
securityrule.name = ("Inbound-" + inboundPriority);
securityrule.properties = new SecurityRule_Properties();
SecurityRule_Properties securityrule_properties = new SecurityRule_Properties();
securityrule_properties.direction = "Inbound";
securityrule_properties.access = "Allow";
securityrule_properties.sourcePortRange = "*";
securityrule_properties.destinationAddressPrefix = "0.0.0.0/0";
securityrule_properties.priority = inboundPriority;
inboundPriority = inboundPriority + 100;
if (ippermission.IpProtocol == "tcp")
{
securityrule_properties.protocol = "Tcp";
}
else if (ippermission.IpProtocol == "udp")
{
securityrule_properties.protocol = "Udp";
}
else
{
securityrule_properties.protocol = "*";
}
securityrule_properties.sourceAddressPrefix = ippermission.IpRanges[0];
securityrule_properties.destinationPortRange = "*";
if (ippermission.ToPort > 0)
{
securityrule_properties.destinationPortRange = ippermission.ToPort.ToString();
}
securityrule.properties = securityrule_properties;
networksecuritygroup_properties.securityRules.Add(securityrule);
}
// process outbound rules
foreach (Amazon.EC2.Model.IpPermission ippermissionegress in securitygroup.IpPermissionsEgress)
{
SecurityRule securityrule = new SecurityRule();
securityrule.name = ("Outbound-" + outboundPriority);
securityrule.properties = new SecurityRule_Properties();
SecurityRule_Properties securityrule_properties = new SecurityRule_Properties();
securityrule_properties.direction = "Outbound";
securityrule_properties.access = "Allow";
securityrule_properties.sourceAddressPrefix = "0.0.0.0/0";
securityrule_properties.sourcePortRange = "*";
securityrule_properties.priority = outboundPriority;
outboundPriority = outboundPriority + 100;
if (ippermissionegress.IpProtocol == "tcp")
{
securityrule_properties.protocol = "Tcp";
}
else if (ippermissionegress.IpProtocol == "udp")
{
securityrule_properties.protocol = "Udp";
}
else
{
securityrule_properties.protocol = "*";
}
securityrule_properties.destinationAddressPrefix = ippermissionegress.IpRanges[0];
securityrule_properties.destinationPortRange = "*";
if (ippermissionegress.ToPort > 0)
{
securityrule_properties.destinationPortRange = ippermissionegress.ToPort.ToString();
}
securityrule.properties = securityrule_properties;
networksecuritygroup_properties.securityRules.Add(securityrule);
}
networksecuritygroup.properties = networksecuritygroup_properties;
try // it fails if this network security group was already processed. safe to continue.
{
_processedItems.Add("Microsoft.Network/networkSecurityGroups/" + networksecuritygroup.name, networksecuritygroup.location);
_resources.Add(networksecuritygroup);
_logProvider.WriteLog("BuildNetworkSecurityGroup", "Microsoft.Network/networkSecurityGroups/" + networksecuritygroup.name);
}
catch { }
_logProvider.WriteLog("BuildNetworkSecurityGroup", "End");
return networksecuritygroup;
}
private RouteTable BuildRouteTable(Amazon.EC2.Model.RouteTable routeTable)
{
_logProvider.WriteLog("BuildRouteTable", "Start");
Hashtable info = new Hashtable();
info.Add("name", GetRouteName(routeTable));
// XmlDocument resource = _awsRetriever.GetAwsResources("RouteTable", subscriptionId, info, token);
RouteTable routetable = new RouteTable();
routetable.name = GetRouteName(routeTable);
// routetable.location = resource.SelectSingleNode("//Location").InnerText;
RouteTable_Properties routetable_properties = new RouteTable_Properties();
routetable_properties.routes = new List<Route>();
foreach (var rule in routeTable.Routes)
{
var GWResults = _awsObjectRetriever.getInternetGW(rule.GatewayId);
if ((((rule.DestinationCidrBlock == "0.0.0.0/0") && (GWResults.Count == 0)) || (rule.DestinationCidrBlock != "0.0.0.0/0")) && (rule.GatewayId != "local"))
{
Route_Properties route_properties = new Route_Properties();
route_properties.addressPrefix = rule.DestinationCidrBlock;
switch (rule.GatewayId)
{
case "local":
route_properties.nextHopType = "VnetLocal";
break;
case "Null":
route_properties.nextHopType = "None";
break;
}
// route_properties.nextHopIpAddress = routenode.SelectSingleNode("NextHopType/IpAddress").InnerText;
Route route = new Route();
route.name = rule.GatewayId;
route.properties = route_properties;
routetable_properties.routes.Add(route);
routetable.properties = routetable_properties;
}
}
if (!_resources.Contains(routetable) && routetable_properties.routes.Count !=0)
{
try
{
_processedItems.Add("Microsoft.Network/routeTables/" + routetable.name, routetable.location);
_resources.Add(routetable);
_logProvider.WriteLog("BuildRouteTable", "Microsoft.Network/routeTables/" + routetable.name);
}
catch
{ }
}
_logProvider.WriteLog("BuildRouteTable", "End");
return routetable;
}
private void BuildNetworkInterfaceObject(dynamic resource, ref List<NetworkProfile_NetworkInterface> networkinterfaces, dynamic LBs)
{
_logProvider.WriteLog("BuildNetworkInterfaceObject", "Start");
string virtualmachinename = GetInstanceName(resource);
string virtualnetworkname = GetVPCName(resource.VpcId);
foreach (var additionalnetworkinterface in resource.NetworkInterfaces)
{
Hashtable NWInfo = new Hashtable();
NWInfo.Add("networkinterfaceId", additionalnetworkinterface.NetworkInterfaceId);
//Getting Subnet Details
string SubnetId = additionalnetworkinterface.SubnetId;
var Subdetails = _awsObjectRetriever.getSubnetbyId(SubnetId);
string subnet_name = GetSubnetName(Subdetails[0]);
Reference subnet_ref = new Reference();
subnet_ref.id = "[concat(resourceGroup().id,'/providers/Microsoft.Network/virtualNetworks/" + virtualnetworkname + "/subnets/" + subnet_name + "')]";
string privateIPAllocationMethod = "Static";
string privateIPAddress = additionalnetworkinterface.PrivateIpAddress;
List<string> dependson = new List<string>();
if (GetProcessedItem("Microsoft.Network/virtualNetworks/" + virtualnetworkname))
{
dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Network/virtualNetworks/" + virtualnetworkname + "')]");
}
// Get the list of endpoints
List<Reference> loadBalancerBackendAddressPools = new List<Reference>();
List<Reference> loadBalancerInboundNatRules = new List<Reference>();
foreach (var LB in LBs)
{
foreach (var LBInstance in LB.Instances)
{
if ((LB.VPCId == resource.VpcId) && (LBInstance.InstanceId == resource.InstanceId))
{
string loadbalancername = LB.LoadBalancerName;
string BAPoolName = "default";
Reference loadBalancerBackendAddressPool = new Reference();
loadBalancerBackendAddressPool.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/loadBalancers/" + loadbalancername + "/backendAddressPools/" + BAPoolName + "')]";
loadBalancerBackendAddressPools.Add(loadBalancerBackendAddressPool);
dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Network/loadBalancers/" + loadbalancername + "')]");
}
}
}
IpConfiguration_Properties ipconfiguration_properties = new IpConfiguration_Properties();
ipconfiguration_properties.privateIPAllocationMethod = privateIPAllocationMethod;
ipconfiguration_properties.privateIPAddress = privateIPAddress;
ipconfiguration_properties.subnet = subnet_ref;
ipconfiguration_properties.loadBalancerInboundNatRules = loadBalancerInboundNatRules;
ipconfiguration_properties.loadBalancerBackendAddressPools = loadBalancerBackendAddressPools;
string ipconfiguration_name = "ipconfig1";
IpConfiguration ipconfiguration = new IpConfiguration();
ipconfiguration.name = ipconfiguration_name;
ipconfiguration.properties = ipconfiguration_properties;
List<IpConfiguration> ipConfigurations = new List<IpConfiguration>();
ipConfigurations.Add(ipconfiguration);
NetworkInterface_Properties networkinterface_properties = new NetworkInterface_Properties();
networkinterface_properties.ipConfigurations = ipConfigurations;
networkinterface_properties.enableIPForwarding = (resource.SourceDestCheck == true) ? false : (resource.SourceDestCheck == false) ? true : false;
// networkinterface_properties.enableIPForwarding = resource.SourceDestCheck;
var NICDetails = _awsObjectRetriever.getNICbyId(additionalnetworkinterface.NetworkInterfaceId);
string networkinterfacename = GetNICName(NICDetails[0]);
string networkinterface_name = networkinterfacename;
NetworkInterface networkinterface = new NetworkInterface();
networkinterface.name = networkinterface_name;
// networkinterface.location = "";
networkinterface.properties = networkinterface_properties;
networkinterface.dependsOn = dependson;
NetworkProfile_NetworkInterface_Properties networkinterface_ref_properties = new NetworkProfile_NetworkInterface_Properties();
networkinterface_ref_properties.primary = additionalnetworkinterface.PrivateIpAddresses[0].Primary;
NetworkProfile_NetworkInterface networkinterface_ref = new NetworkProfile_NetworkInterface();
networkinterface_ref.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/networkInterfaces/" + networkinterface.name + "')]";
networkinterface_ref.properties = networkinterface_ref_properties;
if (resource.PublicIpAddress != null)
{
BuildPublicIPAddressObject(ref networkinterface);
}
// Process Network Interface Security Group
foreach (var group in additionalnetworkinterface.Groups)
{
NetworkSecurityGroup networksecuritygroup = new NetworkSecurityGroup();
networksecuritygroup = BuildNetworkSecurityGroup(group, ref networkinterface);
networkinterface_properties.NetworkSecurityGroup = new Reference();
networkinterface_properties.NetworkSecurityGroup.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/networkSecurityGroups/" + networksecuritygroup.name + "')]";
networkinterface.dependsOn.Add(networkinterface_properties.NetworkSecurityGroup.id);
networkinterface.properties = networkinterface_properties;
}
try
{
_processedItems.Add("Microsoft.Network/networkInterfaces/" + networkinterface.name, networkinterface.location);
networkinterfaces.Add(networkinterface_ref);
_resources.Add(networkinterface);
_logProvider.WriteLog("BuildNetworkInterfaceObject", "Microsoft.Network/networkInterfaces/" + networkinterface.name);
}
catch
{
}
}
_logProvider.WriteLog("BuildNetworkInterfaceObject", "End");
}
private void BuildVirtualMachineObject(Amazon.EC2.Model.Instance selectedInstance, List<NetworkProfile_NetworkInterface> networkinterfaces, String newstorageaccountname, string instanceLBName)
{
_logProvider.WriteLog("BuildVirtualMachineObject", "Start");
string virtualmachinename = GetInstanceName(selectedInstance);
newstorageaccountname = GetNewStorageAccountName(newstorageaccountname);
var NICDetails = _awsObjectRetriever.getNICbyId(selectedInstance.NetworkInterfaces[0].NetworkInterfaceId);
string networkinterfacename = GetNICName(NICDetails[0]);
string ostype;
if (selectedInstance.Platform == null)
{
ostype = "Linux";
}
else
{
ostype = selectedInstance.Platform;
}
Hashtable storageaccountdependencies = new Hashtable();
storageaccountdependencies.Add(newstorageaccountname, "");
HardwareProfile hardwareprofile = new HardwareProfile();
hardwareprofile.vmSize = GetVMSize(selectedInstance.InstanceType.Value);
NetworkProfile networkprofile = new NetworkProfile();
networkprofile.networkInterfaces = networkinterfaces;
Vhd vhd = new Vhd();
vhd.uri = "http://" + newstorageaccountname + ".blob.core.windows.net/vhds/" + virtualmachinename + "-" + "osdisk0.vhd";
//CHECK
OsDisk osdisk = new OsDisk();
osdisk.name = virtualmachinename + selectedInstance.RootDeviceName.Replace("/", "_");
osdisk.vhd = vhd;
osdisk.caching = "ReadOnly";
ImageReference imagereference = new ImageReference();
OsProfile osprofile = new OsProfile();
// if the tool is configured to create new VMs with empty data disks
if (app.Default.BuildEmpty)
{
osdisk.createOption = "FromImage";
osprofile.computerName = virtualmachinename;
osprofile.adminUsername = "[parameters('adminUsername')]";
osprofile.adminPassword = "[parameters('adminPassword')]";
if (!_parameters.ContainsKey("adminUsername"))
{
Parameter parameter = new Parameter();
parameter.type = "string";
_parameters.Add("adminUsername", parameter);
}
if (!_parameters.ContainsKey("adminPassword"))
{
Parameter parameter = new Parameter();
parameter.type = "securestring";
_parameters.Add("adminPassword", parameter);
}
if (ostype == "Windows")
{
imagereference.publisher = "MicrosoftWindowsServer";
imagereference.offer = "WindowsServer";
imagereference.sku = "2012-R2-Datacenter";
imagereference.version = "latest";
}
else if (ostype == "Linux")
{
imagereference.publisher = "Canonical";
imagereference.offer = "UbuntuServer";
imagereference.sku = "16.04.0-LTS";
imagereference.version = "latest";
}
else
{
imagereference.publisher = "<publisher>";
imagereference.offer = "<offer>";
imagereference.sku = "<sku>";
imagereference.version = "<version>";
}
}
// if the tool is configured to attach copied disks
else
{
osdisk.createOption = "Attach";
osdisk.osType = ostype;
// Block of code to help copying the blobs to the new storage accounts
Hashtable storageaccountinfo = new Hashtable();
//storageaccountinfo.Add("name", oldstorageaccountname);
}
// process data disks
List<DataDisk> datadisks = new List<DataDisk>();
int currentLun = 0;
foreach(var disk in selectedInstance.BlockDeviceMappings)
{
if(disk.DeviceName != selectedInstance.RootDeviceName)
{
DataDisk datadisk = new DataDisk();
datadisk.name = virtualmachinename + disk.DeviceName.Substring(0).Replace("/", "_");
datadisk.caching = "ReadOnly";
datadisk.diskSizeGB = _awsObjectRetriever.GetVolume(disk.Ebs.VolumeId)[0].Size;
datadisk.lun = currentLun++;
if (app.Default.BuildEmpty)
{
datadisk.createOption = "Empty";
}
else
{
datadisk.createOption = "Attach";
}
vhd = new Vhd();
vhd.uri = "http://" + newstorageaccountname + ".blob.core.windows.net/vhds/" + virtualmachinename + "-" + datadisk.name + ".vhd";
datadisk.vhd = vhd;
try { storageaccountdependencies.Add(newstorageaccountname, ""); }
catch { }
datadisks.Add(datadisk);
}
}
StorageProfile storageprofile = new StorageProfile();
if (app.Default.BuildEmpty) { storageprofile.imageReference = imagereference; }
storageprofile.osDisk = osdisk;
storageprofile.dataDisks = datadisks;
VirtualMachine_Properties virtualmachine_properties = new VirtualMachine_Properties();
virtualmachine_properties.hardwareProfile = hardwareprofile;
if (app.Default.BuildEmpty) { virtualmachine_properties.osProfile = osprofile; }
virtualmachine_properties.networkProfile = networkprofile;
virtualmachine_properties.storageProfile = storageprofile;
List<string> dependson = new List<string>();
dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Network/networkInterfaces/" + networkinterfacename + "')]");
// Availability Set
if (instanceLBName != "")
{
string availabilitysetname = instanceLBName + "-AS";
Reference availabilityset = new Reference();
availabilityset.id = "[concat(resourceGroup().id, '/providers/Microsoft.Compute/availabilitySets/" + availabilitysetname + "')]";
virtualmachine_properties.availabilitySet = availabilityset;
dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Compute/availabilitySets/" + availabilitysetname + "')]");
}
foreach (DictionaryEntry storageaccountdependency in storageaccountdependencies)
{
if (GetProcessedItem("Microsoft.Storage/storageAccounts/" + storageaccountdependency.Key))
{
dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Storage/storageAccounts/" + storageaccountdependency.Key + "')]");
}
}
VirtualMachine virtualmachine = new VirtualMachine();
virtualmachine.name = virtualmachinename;
//virtualmachine.location = virtualmachineinfo["location"].ToString();
virtualmachine.properties = virtualmachine_properties;
virtualmachine.dependsOn = dependson;
virtualmachine.resources = new List<Resource>();
//if (extension_iaasdiagnostics != null) { virtualmachine.resources.Add(extension_iaasdiagnostics); }
_processedItems.Add("Microsoft.Compute/virtualMachines/" + virtualmachine.name, virtualmachine.location);
_resources.Add(virtualmachine);
_logProvider.WriteLog("BuildVirtualMachineObject", "Microsoft.Compute/virtualMachines/" + virtualmachine.name);
_logProvider.WriteLog("BuildVirtualMachineObject", "End");
}
private void BuildStorageAccountObject(String StorageAccountName)
{
_logProvider.WriteLog("BuildStorageAccountObject", "Start");
StorageAccount_Properties storageaccount_properties = new StorageAccount_Properties();
storageaccount_properties.accountType = "Standard_LRS" ;
StorageAccount storageaccount = new StorageAccount();
storageaccount.name = GetNewStorageAccountName(StorageAccountName);
// storageaccount.location = "";
storageaccount.properties = storageaccount_properties;
_processedItems.Add("Microsoft.Storage/storageAccounts/" + storageaccount.name, storageaccount.location);
_resources.Add(storageaccount);
_logProvider.WriteLog("BuildStorageAccountObject", "Microsoft.Storage/storageAccounts/" + storageaccount.name);
_logProvider.WriteLog("BuildStorageAccountObject", "End");
}
private void WriteStream(StreamWriter writer, string text)
{
writer.Write(text);
writer.Close();
}
private bool GetProcessedItem(string processeditem)
{
if (_processedItems.ContainsKey(processeditem))
{
return true;
}
else
{
return false;
}
}
// convert an hex string into byte array
public static byte[] StrToByteArray(string str)
{
Dictionary<string, byte> hexindex = new Dictionary<string, byte>();
for (int i = 0; i <= 255; i++)
hexindex.Add(i.ToString("X2"), (byte)i);
List<byte> hexres = new List<byte>();
for (int i = 0; i < str.Length; i += 2)
hexres.Add(hexindex[str.Substring(i, 2)]);
return hexres.ToArray();
}
public static string Base64Decode(string base64EncodedData)
{
byte[] base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
public static string Base64Encode(string plainText)
{
byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
private string GetNewStorageAccountName(string oldStorageAccountName)
{
string newStorageAccountName = "";
if (_storageAccountNames.ContainsKey(oldStorageAccountName))
{
_storageAccountNames.TryGetValue(oldStorageAccountName, out newStorageAccountName);
}
else
{
newStorageAccountName = oldStorageAccountName + app.Default.UniquenessSuffix;
if (newStorageAccountName.Length > 24)
{
string randomString = Guid.NewGuid().ToString("N").Substring(0, 4);
newStorageAccountName = newStorageAccountName.Substring(0, (24 - randomString.Length - app.Default.UniquenessSuffix.Length)) + randomString + app.Default.UniquenessSuffix;
}
_storageAccountNames.Add(oldStorageAccountName, newStorageAccountName);
}
return newStorageAccountName;
}
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
private string GetSubnetName(dynamic Subnet)
{
string SubName = Subnet.SubnetId.Replace(' ', '-');
foreach (var tag in Subnet.Tags)
{
if (tag.Key == "Name")
{
SubName = tag.Value;
}
}
return SubName;
}
private string GetRouteName(dynamic Route)
{
//RouteTableId
string RouteName = Route.RouteTableId.Replace(' ', '-');
foreach (var tag in Route.Tags)
{
if (tag.Key == "Name")
{
RouteName = tag.Value;
}
}
return RouteName;
}
private string GetSGName(dynamic SG)
{
string SGName = SG.NetworkAclId.Replace(' ', '-');
foreach (var tag in SG.Tags)
{
if (tag.Key == "Name")
{
SGName = tag.Value;
}
}
return SGName;
}
private string GetInstanceName(dynamic Instance)
{
string InstanceName = Instance.InstanceId.Replace(' ', '-');
foreach (var tag in Instance.Tags)
{
if (tag.Key == "Name")
{
InstanceName = tag.Value;
}
}
return InstanceName;
}
private string GetNICName(dynamic NIC)
{
string NICName = NIC.NetworkInterfaceId.Replace(' ', '-');
foreach (var tag in NIC.TagSet)
{
if (tag.Key == "Name")
{
NICName = tag.Value;
}
}
return NICName;
}
private string GetVPCName(string VpcId)
{
var VPC = _awsObjectRetriever.getVPCbyId(VpcId);
string VPCName = VPC[0].VpcId;
foreach (var tag in VPC[0].Tags)
{
if (tag.Key == "Name")
{
VPCName = tag.Value.Replace(" ","-");
}
}
return VPCName;
}
private string GetVMSize(string instancetype)
{
Dictionary<string, string> VMSizeTable = new Dictionary<string, string>();
VMSizeTable.Add("t2.nano", "Standard_A0");
VMSizeTable.Add("t2.micro", "Standard_A1");
VMSizeTable.Add("t2.small", "Standard_A1_v2");
VMSizeTable.Add("t2.medium", "Standard_A2_v2");
VMSizeTable.Add("t2.large", "Standard_A2m_v2");
VMSizeTable.Add("t2.xlarge", "Standard_A4m_v2");
VMSizeTable.Add("t2.2xlarge", "Standard_A8m_v2");
VMSizeTable.Add("m4.large", "Standard_DS2_v2");
VMSizeTable.Add("m4.xlarge", "Standard_DS3_v2");
VMSizeTable.Add("m4.2xlarge", "Standard_DS4_v2");
VMSizeTable.Add("m4.4xlarge", "Standard_DS5_v2");
VMSizeTable.Add("m4.10xlarge", "Standard_DS15_v2");
VMSizeTable.Add("m4.16xlarge", "Standard_DS15_v2");
VMSizeTable.Add("m3.medium", "Standard_DS1_v2");
VMSizeTable.Add("m3.large", "Standard_DS2_v2");
VMSizeTable.Add("m3.xlarge", "Standard_DS3_v2");
VMSizeTable.Add("m3.2xlarge", "Standard_DS4_v2");
VMSizeTable.Add("c4.large", "Standard_F2s");
VMSizeTable.Add("c4.xlarge", "Standard_F4s");
VMSizeTable.Add("c4.2xlarge", "Standard_F8s");
VMSizeTable.Add("c4.4xlarge", "Standard_F16s");
VMSizeTable.Add("c4.8xlarge", "Standard_F16s");
VMSizeTable.Add("c3.large", "Standard_F2s");
VMSizeTable.Add("c3.xlarge", "Standard_F4s");
VMSizeTable.Add("c3.2xlarge", "Standard_F8s");
VMSizeTable.Add("c3.4xlarge", "Standard_F16s");
VMSizeTable.Add("c3.8xlarge", "Standard_F16s");
VMSizeTable.Add("g2.2xlarge", "Standard_NC6");
VMSizeTable.Add("g2.8xlarge", "Standard_NC24");
VMSizeTable.Add("r4.large", "Standard_DS11_v2");
VMSizeTable.Add("r4.xlarge", "Standard_DS12_v2");
VMSizeTable.Add("r4.2xlarge", "Standard_DS13_v2");
VMSizeTable.Add("r4.4xlarge", "Standard_DS14_v2");
VMSizeTable.Add("r4.8xlarge", "Standard_GS5");
VMSizeTable.Add("r4.16xlarge", "Standard_GS5");
VMSizeTable.Add("r3.large", "Standard_DS11_v2");
VMSizeTable.Add("r3.xlarge", "Standard_DS12_v2");
VMSizeTable.Add("r3.2xlarge", "Standard_DS13_v2");
VMSizeTable.Add("r3.4xlarge", "Standard_DS14_v2");
VMSizeTable.Add("r3.8xlarge", "Standard_GS5");
VMSizeTable.Add("x1.16xlarge", "Standard_GS5");
VMSizeTable.Add("x1.32xlarge", "Standard_GS5");
VMSizeTable.Add("d2.xlarge", "Standard_DS12_v2");
VMSizeTable.Add("d2.2xlarge", "Standard_DS13_v2");
VMSizeTable.Add("d2.4xlarge", "Standard_DS14_v2");
VMSizeTable.Add("d2.8xlarge", "Standard_GS5");
VMSizeTable.Add("i2.xlarge", "Standard_DS12_v2");
VMSizeTable.Add("i2.2xlarge", "Standard_DS13_v2");
VMSizeTable.Add("i2.4xlarge", "Standard_DS14_v2");
VMSizeTable.Add("i2.8xlarge", "Standard_GS5");
if (VMSizeTable.ContainsKey(instancetype))
{
return VMSizeTable[instancetype];
}
else
{
return "Standard_DS2_v2";
}
}
}
}
| |
// 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.Tasks;
using System;
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Versioning;
namespace System.Xml
{
// Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents
// that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification.
public abstract partial class XmlWriter : IDisposable
{
// Write methods
// Writes out the XML declaration with the version "1.0".
public virtual Task WriteStartDocumentAsync()
{
throw NotImplemented.ByDesign;
}
//Writes out the XML declaration with the version "1.0" and the specified standalone attribute.
public virtual Task WriteStartDocumentAsync(bool standalone)
{
throw NotImplemented.ByDesign;
}
//Closes any open elements or attributes and puts the writer back in the Start state.
public virtual Task WriteEndDocumentAsync()
{
throw NotImplemented.ByDesign;
}
// Writes out the DOCTYPE declaration with the specified name and optional attributes.
public virtual Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset)
{
throw NotImplemented.ByDesign;
}
// Writes out the specified start tag and associates it with the given namespace and prefix.
public virtual Task WriteStartElementAsync(string prefix, string localName, string ns)
{
throw NotImplemented.ByDesign;
}
// Closes one element and pops the corresponding namespace scope.
public virtual Task WriteEndElementAsync()
{
throw NotImplemented.ByDesign;
}
// Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>.
public virtual Task WriteFullEndElementAsync()
{
throw NotImplemented.ByDesign;
}
// Writes out the attribute with the specified LocalName, value, and NamespaceURI.
// Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value.
public Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value)
{
Task task = WriteStartAttributeAsync(prefix, localName, ns);
if (task.IsSuccess())
{
return WriteStringAsync(value).CallTaskFuncWhenFinishAsync(thisRef => thisRef.WriteEndAttributeAsync(), this);
}
else
{
return WriteAttributeStringAsyncHelper(task, value);
}
}
private async Task WriteAttributeStringAsyncHelper(Task task, string value)
{
await task.ConfigureAwait(false);
await WriteStringAsync(value).ConfigureAwait(false);
await WriteEndAttributeAsync().ConfigureAwait(false);
}
// Writes the start of an attribute.
protected internal virtual Task WriteStartAttributeAsync(string prefix, string localName, string ns)
{
throw NotImplemented.ByDesign;
}
// Closes the attribute opened by WriteStartAttribute call.
protected internal virtual Task WriteEndAttributeAsync()
{
throw NotImplemented.ByDesign;
}
// Writes out a <![CDATA[...]]>; block containing the specified text.
public virtual Task WriteCDataAsync(string text)
{
throw NotImplemented.ByDesign;
}
// Writes out a comment <!--...-->; containing the specified text.
public virtual Task WriteCommentAsync(string text)
{
throw NotImplemented.ByDesign;
}
// Writes out a processing instruction with a space between the name and text as follows: <?name text?>
public virtual Task WriteProcessingInstructionAsync(string name, string text)
{
throw NotImplemented.ByDesign;
}
// Writes out an entity reference as follows: "&"+name+";".
public virtual Task WriteEntityRefAsync(string name)
{
throw NotImplemented.ByDesign;
}
// Forces the generation of a character entity for the specified Unicode character value.
public virtual Task WriteCharEntityAsync(char ch)
{
throw NotImplemented.ByDesign;
}
// Writes out the given whitespace.
public virtual Task WriteWhitespaceAsync(string ws)
{
throw NotImplemented.ByDesign;
}
// Writes out the specified text content.
public virtual Task WriteStringAsync(string text)
{
throw NotImplemented.ByDesign;
}
// Write out the given surrogate pair as an entity reference.
public virtual Task WriteSurrogateCharEntityAsync(char lowChar, char highChar)
{
throw NotImplemented.ByDesign;
}
// Writes out the specified text content.
public virtual Task WriteCharsAsync(char[] buffer, int index, int count)
{
throw NotImplemented.ByDesign;
}
// Writes raw markup from the given character buffer.
public virtual Task WriteRawAsync(char[] buffer, int index, int count)
{
throw NotImplemented.ByDesign;
}
// Writes raw markup from the given string.
public virtual Task WriteRawAsync(string data)
{
throw NotImplemented.ByDesign;
}
// Encodes the specified binary bytes as base64 and writes out the resulting text.
public virtual Task WriteBase64Async(byte[] buffer, int index, int count)
{
throw NotImplemented.ByDesign;
}
// Encodes the specified binary bytes as binhex and writes out the resulting text.
public virtual Task WriteBinHexAsync(byte[] buffer, int index, int count)
{
return BinHexEncoder.EncodeAsync(buffer, index, count, this);
}
// Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader.
public virtual Task FlushAsync()
{
throw NotImplemented.ByDesign;
}
// Scalar Value Methods
// Writes out the specified name, ensuring it is a valid NmToken according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual Task WriteNmTokenAsync(string name)
{
if (name == null || name.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyName);
}
return WriteStringAsync(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException));
}
// Writes out the specified name, ensuring it is a valid Name according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual Task WriteNameAsync(string name)
{
return WriteStringAsync(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException));
}
// Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
public virtual async Task WriteQualifiedNameAsync(string localName, string ns)
{
if (ns != null && ns.Length > 0)
{
string prefix = LookupPrefix(ns);
if (prefix == null)
{
throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
}
await WriteStringAsync(prefix).ConfigureAwait(false);
await WriteStringAsync(":").ConfigureAwait(false);
}
await WriteStringAsync(localName).ConfigureAwait(false);
}
// XmlReader Helper Methods
// Writes out all the attributes found at the current position in the specified XmlReader.
public virtual async Task WriteAttributesAsync(XmlReader reader, bool defattr)
{
if (null == reader)
{
throw new ArgumentNullException(nameof(reader));
}
if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.XmlDeclaration)
{
if (reader.MoveToFirstAttribute())
{
await WriteAttributesAsync(reader, defattr).ConfigureAwait(false);
reader.MoveToElement();
}
}
else if (reader.NodeType != XmlNodeType.Attribute)
{
throw new XmlException(SR.Xml_InvalidPosition, string.Empty);
}
else
{
do
{
// we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault.
// If either of these is true and defattr=false, we should not write the attribute out
if (defattr || !reader.IsDefaultInternal)
{
await WriteStartAttributeAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false);
while (reader.ReadAttributeValue())
{
if (reader.NodeType == XmlNodeType.EntityReference)
{
await WriteEntityRefAsync(reader.Name).ConfigureAwait(false);
}
else
{
await WriteStringAsync(reader.Value).ConfigureAwait(false);
}
}
await WriteEndAttributeAsync().ConfigureAwait(false);
}
}
while (reader.MoveToNextAttribute());
}
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
public virtual Task WriteNodeAsync(XmlReader reader, bool defattr)
{
if (null == reader)
{
throw new ArgumentNullException(nameof(reader));
}
if (reader.Settings != null && reader.Settings.Async)
{
return WriteNodeAsync_CallAsyncReader(reader, defattr);
}
else
{
return WriteNodeAsync_CallSyncReader(reader, defattr);
}
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
//use sync methods on the reader
internal async Task WriteNodeAsync_CallSyncReader(XmlReader reader, bool defattr)
{
bool canReadChunk = reader.CanReadValueChunk;
int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth;
do
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
await WriteStartElementAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false);
await WriteAttributesAsync(reader, defattr).ConfigureAwait(false);
if (reader.IsEmptyElement)
{
await WriteEndElementAsync().ConfigureAwait(false);
break;
}
break;
case XmlNodeType.Text:
if (canReadChunk)
{
if (_writeNodeBuffer == null)
{
_writeNodeBuffer = new char[WriteNodeBufferSize];
}
int read;
while ((read = reader.ReadValueChunk(_writeNodeBuffer, 0, WriteNodeBufferSize)) > 0)
{
await this.WriteCharsAsync(_writeNodeBuffer, 0, read).ConfigureAwait(false);
}
}
else
{
await WriteStringAsync(reader.Value).ConfigureAwait(false);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
await WriteWhitespaceAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.CDATA:
await WriteCDataAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.EntityReference:
await WriteEntityRefAsync(reader.Name).ConfigureAwait(false);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
await WriteProcessingInstructionAsync(reader.Name, reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.DocumentType:
await WriteDocTypeAsync(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.Comment:
await WriteCommentAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.EndElement:
await WriteFullEndElementAsync().ConfigureAwait(false);
break;
}
} while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)));
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
//use async methods on the reader
internal async Task WriteNodeAsync_CallAsyncReader(XmlReader reader, bool defattr)
{
bool canReadChunk = reader.CanReadValueChunk;
int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth;
do
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
await WriteStartElementAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false);
await WriteAttributesAsync(reader, defattr).ConfigureAwait(false);
if (reader.IsEmptyElement)
{
await WriteEndElementAsync().ConfigureAwait(false);
break;
}
break;
case XmlNodeType.Text:
if (canReadChunk)
{
if (_writeNodeBuffer == null)
{
_writeNodeBuffer = new char[WriteNodeBufferSize];
}
int read;
while ((read = await reader.ReadValueChunkAsync(_writeNodeBuffer, 0, WriteNodeBufferSize).ConfigureAwait(false)) > 0)
{
await this.WriteCharsAsync(_writeNodeBuffer, 0, read).ConfigureAwait(false);
}
}
else
{
//reader.Value may block on Text or WhiteSpace node, use GetValueAsync
await WriteStringAsync(await reader.GetValueAsync().ConfigureAwait(false)).ConfigureAwait(false);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
await WriteWhitespaceAsync(await reader.GetValueAsync().ConfigureAwait(false)).ConfigureAwait(false);
break;
case XmlNodeType.CDATA:
await WriteCDataAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.EntityReference:
await WriteEntityRefAsync(reader.Name).ConfigureAwait(false);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
await WriteProcessingInstructionAsync(reader.Name, reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.DocumentType:
await WriteDocTypeAsync(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.Comment:
await WriteCommentAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.EndElement:
await WriteFullEndElementAsync().ConfigureAwait(false);
break;
}
} while (await reader.ReadAsync().ConfigureAwait(false) && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)));
}
// Element Helper Methods
// Writes out an attribute with the specified name, namespace URI, and string value.
public async Task WriteElementStringAsync(string prefix, String localName, String ns, String value)
{
await WriteStartElementAsync(prefix, localName, ns).ConfigureAwait(false);
if (null != value && 0 != value.Length)
{
await WriteStringAsync(value).ConfigureAwait(false);
}
await WriteEndElementAsync().ConfigureAwait(false);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
public class MutexTests : RemoteExecutorTestBase
{
private const int FailedWaitTimeout = 30000;
[Fact]
public void Ctor_ConstructWaitRelease()
{
using (Mutex m = new Mutex())
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
}
using (Mutex m = new Mutex(false))
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
}
using (Mutex m = new Mutex(true))
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
m.ReleaseMutex();
}
}
[Fact]
public void Ctor_InvalidName()
{
Assert.Throws<ArgumentException>(() => new Mutex(false, new string('a', 1000)));
}
[Fact]
public void Ctor_ValidName()
{
string name = Guid.NewGuid().ToString("N");
bool createdNew;
using (Mutex m1 = new Mutex(false, name, out createdNew))
{
Assert.True(createdNew);
using (Mutex m2 = new Mutex(false, name, out createdNew))
{
Assert.False(createdNew);
}
}
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Semaphore s = new Semaphore(1, 1, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => new Mutex(false, name));
}
}
[Fact]
public void OpenExisting()
{
string name = Guid.NewGuid().ToString("N");
Mutex resultHandle;
Assert.False(Mutex.TryOpenExisting(name, out resultHandle));
using (Mutex m1 = new Mutex(false, name))
{
using (Mutex m2 = Mutex.OpenExisting(name))
{
Assert.True(m1.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m1.ReleaseMutex();
Assert.True(m2.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m2.ReleaseMutex();
}
Assert.True(Mutex.TryOpenExisting(name, out resultHandle));
Assert.NotNull(resultHandle);
resultHandle.Dispose();
}
}
[Fact]
public void OpenExisting_InvalidNames()
{
Assert.Throws<ArgumentNullException>("name", () => Mutex.OpenExisting(null));
Assert.Throws<ArgumentException>(() => Mutex.OpenExisting(string.Empty));
Assert.Throws<ArgumentException>(() => Mutex.OpenExisting(new string('a', 10000)));
}
[Fact]
public void OpenExisting_UnavailableName()
{
string name = Guid.NewGuid().ToString("N");
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
Mutex ignored;
Assert.False(Mutex.TryOpenExisting(name, out ignored));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Semaphore sema = new Semaphore(1, 1, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
Mutex ignored;
Assert.False(Mutex.TryOpenExisting(name, out ignored));
}
}
public static IEnumerable<object[]> AbandonExisting_MemberData()
{
var nameGuidStr = Guid.NewGuid().ToString("N");
for (int waitType = 0; waitType < 2; ++waitType) // 0 == WaitOne, 1 == WaitAny
{
yield return new object[] { null, waitType };
foreach (var namePrefix in new[] { string.Empty, "Local\\", "Global\\" })
{
yield return new object[] { namePrefix + nameGuidStr, waitType };
}
}
}
[Theory]
[MemberData(nameof(AbandonExisting_MemberData))]
public void AbandonExisting(string name, int waitType)
{
using (var m = new Mutex(false, name))
{
Task t = Task.Factory.StartNew(() =>
{
Assert.True(m.WaitOne(FailedWaitTimeout));
// don't release the mutex; abandon it on this thread
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
t.Wait();
switch (waitType)
{
case 0: // WaitOne
Assert.Throws<AbandonedMutexException>(() => m.WaitOne(FailedWaitTimeout));
break;
case 1: // WaitAny
AbandonedMutexException ame = Assert.Throws<AbandonedMutexException>(() => WaitHandle.WaitAny(new[] { m }, FailedWaitTimeout));
Assert.Equal(0, ame.MutexIndex);
Assert.Equal(m, ame.Mutex);
break;
}
}
}
[Theory]
[InlineData("")]
[InlineData("Local\\")]
[InlineData("Global\\")]
public void CrossProcess_NamedMutex_ProtectedFileAccessAtomic(string prefix)
{
string mutexName = prefix + Guid.NewGuid().ToString("N");
string fileName = GetTestFilePath();
Func<string, string, int> otherProcess = (m, f) =>
{
using (var mutex = Mutex.OpenExisting(m))
{
mutex.WaitOne();
try { File.WriteAllText(f, "0"); }
finally { mutex.ReleaseMutex(); }
IncrementValueInFileNTimes(mutex, f, 10);
}
return SuccessExitCode;
};
using (var mutex = new Mutex(false, mutexName))
using (var remote = RemoteInvoke(otherProcess, mutexName, fileName))
{
SpinWait.SpinUntil(() => File.Exists(fileName));
IncrementValueInFileNTimes(mutex, fileName, 10);
}
Assert.Equal(20, int.Parse(File.ReadAllText(fileName)));
}
private static void IncrementValueInFileNTimes(Mutex mutex, string fileName, int n)
{
for (int i = 0; i < n; i++)
{
mutex.WaitOne();
try
{
int current = int.Parse(File.ReadAllText(fileName));
Thread.Sleep(10);
File.WriteAllText(fileName, (current + 1).ToString());
}
finally { mutex.ReleaseMutex(); }
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using FluentAssertions;
using Microsoft.Its.Domain.Serialization;
using Microsoft.Its.Recipes;
using Newtonsoft.Json;
using NUnit.Framework;
using Assert = NUnit.Framework.Assert;
namespace Microsoft.Its.Domain.Tests
{
[TestFixture]
public class ObjectIdTests
{
[Test]
public void Id_round_trips_correctly_through_json_serializer()
{
var obj = new Widget
{
Id = 123
};
var json = obj.ToJson();
var obj2 = json.FromJsonTo<Widget>();
obj2.Id.Value.Should().Be(123);
}
[Test]
public void Value_cannot_be_set_to_default()
{
Assert.Throws<ArgumentException>(() => new WidgetId(0));
Assert.Throws<ArgumentException>(() => new GenericObjectId<Guid>(Guid.Empty));
}
[Test]
public void Two_instances_of_ObjectId_having_the_same_underlying_value_are_equal()
{
Guid guid = Guid.NewGuid();
var id1 = new GenericObjectId<Guid>(guid);
var id2 = new GenericObjectId<Guid>(guid);
(id1 == id2).Should().BeTrue();
(id2 == id1).Should().BeTrue();
(id1.Equals(id2)).Should().BeTrue();
(id2.Equals(id1)).Should().BeTrue();
(Equals(id1, id2)).Should().BeTrue();
}
[Test]
public void Two_instances_of_type_derived_from_ObjectId_having_the_same_underlying_value_are_equal()
{
var id = Any.Int();
var id1 = new WidgetId(id);
var id2 = new WidgetId(id);
(id1 == id2).Should().BeTrue();
(id2 == id1).Should().BeTrue();
(id1.Equals(id2)).Should().BeTrue();
(id2.Equals(id1)).Should().BeTrue();
(Equals(id1, id2)).Should().BeTrue();
}
[Test]
public void An_ObjectId_is_equal_to_a_primitive_of_its_underlying_value()
{
var i = Any.Int();
var objectId = new GenericObjectId<int>(i);
(objectId == i).Should().BeTrue();
// (i == objectId).Should().BeTrue();
(objectId.Equals(i)).Should().BeTrue();
// (i.Equals(objectId)).Should().BeTrue();
(Equals(objectId, i)).Should().BeTrue();
}
[Test]
public void An_instance_of_a_type_derived_from_ObjectId_is_equal_to_a_primitive_of_its_underlying_value()
{
var i = Any.Int();
var objectId = new WidgetId(i);
(objectId == i).Should().BeTrue();
// (i == objectId).Should().BeTrue();
(objectId.Equals(i)).Should().BeTrue();
// (i.Equals(objectId)).Should().BeTrue();
(Equals(objectId, i)).Should().BeTrue();
}
[Test]
public void Two_ObjectIds_have_the_same_HashCode_if_created_with_the_same_underlying_value()
{
Guid guid = Guid.NewGuid();
var id1 = new GenericObjectId<Guid>(guid);
var id2 = new GenericObjectId<Guid>(guid);
id1.GetHashCode().Should().Be(id2.GetHashCode());
}
[Test]
public void ToString_returns_Value_ToString()
{
var id = new GenericObjectId<string>("hello");
id.ToString().Should().Be("hello");
}
[Test]
public void ObjectId_of_String_serializes_to_a_JSON_primitive()
{
var json = JsonConvert.SerializeObject(new GenericObjectId<string>("hello"));
json.Should().Be("\"hello\"");
}
[Test]
public void ObjectId_of_String_derived_classes_deserialize_from_JSON_primitives()
{
var json = "\"hello\"";
var s = JsonConvert.DeserializeObject<GenericObjectId<string>>(json);
s.Value.Should().Be("hello");
}
[Test]
public void ObjectId_of_String_derived_classes_deserialize_from_JSON_objects()
{
var json = "{\"Value\":\"hello\"}";
var s = JsonConvert.DeserializeObject<GenericObjectId<string>>(json);
s.Value.Should().Be("hello");
}
[Test]
public void ObjectId_of_int_serializes_to_a_JSON_primitive()
{
var json = JsonConvert.SerializeObject(new GenericObjectId<int>(1));
json.Should().Be("1");
}
[Test]
public void ObjectId_of_int_derived_classes_deserialize_from_JSON_primitives()
{
var json = "1";
var s = JsonConvert.DeserializeObject<GenericObjectId<int>>(json);
s.Value.Should().Be(1);
}
[Test]
public void ObjectId_of_int_derived_classes_deserialize_from_JSON_objects()
{
var json = "{\"Value\":1}";
var s = JsonConvert.DeserializeObject<GenericObjectId<int>>(json);
s.Value.Should().Be(1);
}
[Test]
public void ObjectId_of_int_correctly_serializes_to_null()
{
GenericObjectId<int> id = null;
var s = JsonConvert.SerializeObject(id);
s.Should().Be("null");
}
[Test]
public void ObjectId_of_int_correctly_deserialized_from_null()
{
var json = "{\"Id\":null}";
var s = JsonConvert.DeserializeObject<Widget>(json);
s.Id.Should().Be(null);
}
}
public class Widget
{
public WidgetId Id { get; set; }
}
public class GenericObjectId<T> : ObjectId<T>
{
public GenericObjectId(T value) : base(value)
{
}
}
public class WidgetId : ObjectId<int>
{
public WidgetId(int value) : base(value)
{
}
public static implicit operator WidgetId(int value)
{
return new WidgetId(value);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
internal static partial class Interop
{
internal enum SecurityStatus
{
// Success / Informational
OK = 0x00000000,
ContinueNeeded = unchecked((int)0x00090312),
CompleteNeeded = unchecked((int)0x00090313),
CompAndContinue = unchecked((int)0x00090314),
ContextExpired = unchecked((int)0x00090317),
CredentialsNeeded = unchecked((int)0x00090320),
Renegotiate = unchecked((int)0x00090321),
// Errors
OutOfMemory = unchecked((int)0x80090300),
InvalidHandle = unchecked((int)0x80090301),
Unsupported = unchecked((int)0x80090302),
TargetUnknown = unchecked((int)0x80090303),
InternalError = unchecked((int)0x80090304),
PackageNotFound = unchecked((int)0x80090305),
NotOwner = unchecked((int)0x80090306),
CannotInstall = unchecked((int)0x80090307),
InvalidToken = unchecked((int)0x80090308),
CannotPack = unchecked((int)0x80090309),
QopNotSupported = unchecked((int)0x8009030A),
NoImpersonation = unchecked((int)0x8009030B),
LogonDenied = unchecked((int)0x8009030C),
UnknownCredentials = unchecked((int)0x8009030D),
NoCredentials = unchecked((int)0x8009030E),
MessageAltered = unchecked((int)0x8009030F),
OutOfSequence = unchecked((int)0x80090310),
NoAuthenticatingAuthority = unchecked((int)0x80090311),
IncompleteMessage = unchecked((int)0x80090318),
IncompleteCredentials = unchecked((int)0x80090320),
BufferNotEnough = unchecked((int)0x80090321),
WrongPrincipal = unchecked((int)0x80090322),
TimeSkew = unchecked((int)0x80090324),
UntrustedRoot = unchecked((int)0x80090325),
IllegalMessage = unchecked((int)0x80090326),
CertUnknown = unchecked((int)0x80090327),
CertExpired = unchecked((int)0x80090328),
AlgorithmMismatch = unchecked((int)0x80090331),
SecurityQosFailed = unchecked((int)0x80090332),
SmartcardLogonRequired = unchecked((int)0x8009033E),
UnsupportedPreauth = unchecked((int)0x80090343),
BadBinding = unchecked((int)0x80090346)
}
#if TRACE_VERBOSE
internal static string MapSecurityStatus(uint statusCode)
{
switch (statusCode)
{
case 0: return "0";
case 0x80090001: return "NTE_BAD_UID";
case 0x80090002: return "NTE_BAD_HASH";
case 0x80090003: return "NTE_BAD_KEY";
case 0x80090004: return "NTE_BAD_LEN";
case 0x80090005: return "NTE_BAD_DATA";
case 0x80090006: return "NTE_BAD_SIGNATURE";
case 0x80090007: return "NTE_BAD_VER";
case 0x80090008: return "NTE_BAD_ALGID";
case 0x80090009: return "NTE_BAD_FLAGS";
case 0x8009000A: return "NTE_BAD_TYPE";
case 0x8009000B: return "NTE_BAD_KEY_STATE";
case 0x8009000C: return "NTE_BAD_HASH_STATE";
case 0x8009000D: return "NTE_NO_KEY";
case 0x8009000E: return "NTE_NO_MEMORY";
case 0x8009000F: return "NTE_EXISTS";
case 0x80090010: return "NTE_PERM";
case 0x80090011: return "NTE_NOT_FOUND";
case 0x80090012: return "NTE_DOUBLE_ENCRYPT";
case 0x80090013: return "NTE_BAD_PROVIDER";
case 0x80090014: return "NTE_BAD_PROV_TYPE";
case 0x80090015: return "NTE_BAD_PUBLIC_KEY";
case 0x80090016: return "NTE_BAD_KEYSET";
case 0x80090017: return "NTE_PROV_TYPE_NOT_DEF";
case 0x80090018: return "NTE_PROV_TYPE_ENTRY_BAD";
case 0x80090019: return "NTE_KEYSET_NOT_DEF";
case 0x8009001A: return "NTE_KEYSET_ENTRY_BAD";
case 0x8009001B: return "NTE_PROV_TYPE_NO_MATCH";
case 0x8009001C: return "NTE_SIGNATURE_FILE_BAD";
case 0x8009001D: return "NTE_PROVIDER_DLL_FAIL";
case 0x8009001E: return "NTE_PROV_DLL_NOT_FOUND";
case 0x8009001F: return "NTE_BAD_KEYSET_PARAM";
case 0x80090020: return "NTE_FAIL";
case 0x80090021: return "NTE_SYS_ERR";
case 0x80090022: return "NTE_SILENT_CONTEXT";
case 0x80090023: return "NTE_TOKEN_KEYSET_STORAGE_FULL";
case 0x80090024: return "NTE_TEMPORARY_PROFILE";
case 0x80090025: return "NTE_FIXEDPARAMETER";
case 0x80090300: return "SEC_E_INSUFFICIENT_MEMORY";
case 0x80090301: return "SEC_E_INVALID_HANDLE";
case 0x80090302: return "SEC_E_UNSUPPORTED_FUNCTION";
case 0x80090303: return "SEC_E_TARGET_UNKNOWN";
case 0x80090304: return "SEC_E_INTERNAL_ERROR";
case 0x80090305: return "SEC_E_SECPKG_NOT_FOUND";
case 0x80090306: return "SEC_E_NOT_OWNER";
case 0x80090307: return "SEC_E_CANNOT_INSTALL";
case 0x80090308: return "SEC_E_INVALID_TOKEN";
case 0x80090309: return "SEC_E_CANNOT_PACK";
case 0x8009030A: return "SEC_E_QOP_NOT_SUPPORTED";
case 0x8009030B: return "SEC_E_NO_IMPERSONATION";
case 0x8009030C: return "SEC_E_LOGON_DENIED";
case 0x8009030D: return "SEC_E_UNKNOWN_CREDENTIALS";
case 0x8009030E: return "SEC_E_NO_CREDENTIALS";
case 0x8009030F: return "SEC_E_MESSAGE_ALTERED";
case 0x80090310: return "SEC_E_OUT_OF_SEQUENCE";
case 0x80090311: return "SEC_E_NO_AUTHENTICATING_AUTHORITY";
case 0x00090312: return "SEC_I_CONTINUE_NEEDED";
case 0x00090313: return "SEC_I_COMPLETE_NEEDED";
case 0x00090314: return "SEC_I_COMPLETE_AND_CONTINUE";
case 0x00090315: return "SEC_I_LOCAL_LOGON";
case 0x80090316: return "SEC_E_BAD_PKGID";
case 0x80090317: return "SEC_E_CONTEXT_EXPIRED";
case 0x00090317: return "SEC_I_CONTEXT_EXPIRED";
case 0x80090318: return "SEC_E_INCOMPLETE_MESSAGE";
case 0x80090320: return "SEC_E_INCOMPLETE_CREDENTIALS";
case 0x80090321: return "SEC_E_BUFFER_TOO_SMALL";
case 0x00090320: return "SEC_I_INCOMPLETE_CREDENTIALS";
case 0x00090321: return "SEC_I_RENEGOTIATE";
case 0x80090322: return "SEC_E_WRONG_PRINCIPAL";
case 0x00090323: return "SEC_I_NO_LSA_CONTEXT";
case 0x80090324: return "SEC_E_TIME_SKEW";
case 0x80090325: return "SEC_E_UNTRUSTED_ROOT";
case 0x80090326: return "SEC_E_ILLEGAL_MESSAGE";
case 0x80090327: return "SEC_E_CERT_UNKNOWN";
case 0x80090328: return "SEC_E_CERT_EXPIRED";
case 0x80090329: return "SEC_E_ENCRYPT_FAILURE";
case 0x80090330: return "SEC_E_DECRYPT_FAILURE";
case 0x80090331: return "SEC_E_ALGORITHM_MISMATCH";
case 0x80090332: return "SEC_E_SECURITY_QOS_FAILED";
case 0x80090333: return "SEC_E_UNFINISHED_CONTEXT_DELETED";
case 0x80090334: return "SEC_E_NO_TGT_REPLY";
case 0x80090335: return "SEC_E_NO_IP_ADDRESSES";
case 0x80090336: return "SEC_E_WRONG_CREDENTIAL_HANDLE";
case 0x80090337: return "SEC_E_CRYPTO_SYSTEM_INVALID";
case 0x80090338: return "SEC_E_MAX_REFERRALS_EXCEEDED";
case 0x80090339: return "SEC_E_MUST_BE_KDC";
case 0x8009033A: return "SEC_E_STRONG_CRYPTO_NOT_SUPPORTED";
case 0x8009033B: return "SEC_E_TOO_MANY_PRINCIPALS";
case 0x8009033C: return "SEC_E_NO_PA_DATA";
case 0x8009033D: return "SEC_E_PKINIT_NAME_MISMATCH";
case 0x8009033E: return "SEC_E_SMARTCARD_LOGON_REQUIRED";
case 0x8009033F: return "SEC_E_SHUTDOWN_IN_PROGRESS";
case 0x80090340: return "SEC_E_KDC_INVALID_REQUEST";
case 0x80090341: return "SEC_E_KDC_UNABLE_TO_REFER";
case 0x80090342: return "SEC_E_KDC_UNKNOWN_ETYPE";
case 0x80090343: return "SEC_E_UNSUPPORTED_PREAUTH";
case 0x80090345: return "SEC_E_DELEGATION_REQUIRED";
case 0x80090346: return "SEC_E_BAD_BINDINGS";
case 0x80090347: return "SEC_E_MULTIPLE_ACCOUNTS";
case 0x80090348: return "SEC_E_NO_KERB_KEY";
case 0x80091001: return "CRYPT_E_MSG_ERROR";
case 0x80091002: return "CRYPT_E_UNKNOWN_ALGO";
case 0x80091003: return "CRYPT_E_OID_FORMAT";
case 0x80091004: return "CRYPT_E_INVALID_MSG_TYPE";
case 0x80091005: return "CRYPT_E_UNEXPECTED_ENCODING";
case 0x80091006: return "CRYPT_E_AUTH_ATTR_MISSING";
case 0x80091007: return "CRYPT_E_HASH_VALUE";
case 0x80091008: return "CRYPT_E_INVALID_INDEX";
case 0x80091009: return "CRYPT_E_ALREADY_DECRYPTED";
case 0x8009100A: return "CRYPT_E_NOT_DECRYPTED";
case 0x8009100B: return "CRYPT_E_RECIPIENT_NOT_FOUND";
case 0x8009100C: return "CRYPT_E_CONTROL_TYPE";
case 0x8009100D: return "CRYPT_E_ISSUER_SERIALNUMBER";
case 0x8009100E: return "CRYPT_E_SIGNER_NOT_FOUND";
case 0x8009100F: return "CRYPT_E_ATTRIBUTES_MISSING";
case 0x80091010: return "CRYPT_E_STREAM_MSG_NOT_READY";
case 0x80091011: return "CRYPT_E_STREAM_INSUFFICIENT_DATA";
case 0x00091012: return "CRYPT_I_NEW_PROTECTION_REQUIRED";
case 0x80092001: return "CRYPT_E_BAD_LEN";
case 0x80092002: return "CRYPT_E_BAD_ENCODE";
case 0x80092003: return "CRYPT_E_FILE_ERROR";
case 0x80092004: return "CRYPT_E_NOT_FOUND";
case 0x80092005: return "CRYPT_E_EXISTS";
case 0x80092006: return "CRYPT_E_NO_PROVIDER";
case 0x80092007: return "CRYPT_E_SELF_SIGNED";
case 0x80092008: return "CRYPT_E_DELETED_PREV";
case 0x80092009: return "CRYPT_E_NO_MATCH";
case 0x8009200A: return "CRYPT_E_UNEXPECTED_MSG_TYPE";
case 0x8009200B: return "CRYPT_E_NO_KEY_PROPERTY";
case 0x8009200C: return "CRYPT_E_NO_DECRYPT_CERT";
case 0x8009200D: return "CRYPT_E_BAD_MSG";
case 0x8009200E: return "CRYPT_E_NO_SIGNER";
case 0x8009200F: return "CRYPT_E_PENDING_CLOSE";
case 0x80092010: return "CRYPT_E_REVOKED";
case 0x80092011: return "CRYPT_E_NO_REVOCATION_DLL";
case 0x80092012: return "CRYPT_E_NO_REVOCATION_CHECK";
case 0x80092013: return "CRYPT_E_REVOCATION_OFFLINE";
case 0x80092014: return "CRYPT_E_NOT_IN_REVOCATION_DATABASE";
case 0x80092020: return "CRYPT_E_INVALID_NUMERIC_STRING";
case 0x80092021: return "CRYPT_E_INVALID_PRINTABLE_STRING";
case 0x80092022: return "CRYPT_E_INVALID_IA5_STRING";
case 0x80092023: return "CRYPT_E_INVALID_X500_STRING";
case 0x80092024: return "CRYPT_E_NOT_CHAR_STRING";
case 0x80092025: return "CRYPT_E_FILERESIZED";
case 0x80092026: return "CRYPT_E_SECURITY_SETTINGS";
case 0x80092027: return "CRYPT_E_NO_VERIFY_USAGE_DLL";
case 0x80092028: return "CRYPT_E_NO_VERIFY_USAGE_CHECK";
case 0x80092029: return "CRYPT_E_VERIFY_USAGE_OFFLINE";
case 0x8009202A: return "CRYPT_E_NOT_IN_CTL";
case 0x8009202B: return "CRYPT_E_NO_TRUSTED_SIGNER";
case 0x8009202C: return "CRYPT_E_MISSING_PUBKEY_PARA";
case 0x80093000: return "CRYPT_E_OSS_ERROR";
case 0x80093001: return "OSS_MORE_BUF";
case 0x80093002: return "OSS_NEGATIVE_UINTEGER";
case 0x80093003: return "OSS_PDU_RANGE";
case 0x80093004: return "OSS_MORE_INPUT";
case 0x80093005: return "OSS_DATA_ERROR";
case 0x80093006: return "OSS_BAD_ARG";
case 0x80093007: return "OSS_BAD_VERSION";
case 0x80093008: return "OSS_OUT_MEMORY";
case 0x80093009: return "OSS_PDU_MISMATCH";
case 0x8009300A: return "OSS_LIMITED";
case 0x8009300B: return "OSS_BAD_PTR";
case 0x8009300C: return "OSS_BAD_TIME";
case 0x8009300D: return "OSS_INDEFINITE_NOT_SUPPORTED";
case 0x8009300E: return "OSS_MEM_ERROR";
case 0x8009300F: return "OSS_BAD_TABLE";
case 0x80093010: return "OSS_TOO_LONG";
case 0x80093011: return "OSS_CONSTRAINT_VIOLATED";
case 0x80093012: return "OSS_FATAL_ERROR";
case 0x80093013: return "OSS_ACCESS_SERIALIZATION_ERROR";
case 0x80093014: return "OSS_NULL_TBL";
case 0x80093015: return "OSS_NULL_FCN";
case 0x80093016: return "OSS_BAD_ENCRULES";
case 0x80093017: return "OSS_UNAVAIL_ENCRULES";
case 0x80093018: return "OSS_CANT_OPEN_TRACE_WINDOW";
case 0x80093019: return "OSS_UNIMPLEMENTED";
case 0x8009301A: return "OSS_OID_DLL_NOT_LINKED";
case 0x8009301B: return "OSS_CANT_OPEN_TRACE_FILE";
case 0x8009301C: return "OSS_TRACE_FILE_ALREADY_OPEN";
case 0x8009301D: return "OSS_TABLE_MISMATCH";
case 0x8009301E: return "OSS_TYPE_NOT_SUPPORTED";
case 0x8009301F: return "OSS_REAL_DLL_NOT_LINKED";
case 0x80093020: return "OSS_REAL_CODE_NOT_LINKED";
case 0x80093021: return "OSS_OUT_OF_RANGE";
case 0x80093022: return "OSS_COPIER_DLL_NOT_LINKED";
case 0x80093023: return "OSS_CONSTRAINT_DLL_NOT_LINKED";
case 0x80093024: return "OSS_COMPARATOR_DLL_NOT_LINKED";
case 0x80093025: return "OSS_COMPARATOR_CODE_NOT_LINKED";
case 0x80093026: return "OSS_MEM_MGR_DLL_NOT_LINKED";
case 0x80093027: return "OSS_PDV_DLL_NOT_LINKED";
case 0x80093028: return "OSS_PDV_CODE_NOT_LINKED";
case 0x80093029: return "OSS_API_DLL_NOT_LINKED";
case 0x8009302A: return "OSS_BERDER_DLL_NOT_LINKED";
case 0x8009302B: return "OSS_PER_DLL_NOT_LINKED";
case 0x8009302C: return "OSS_OPEN_TYPE_ERROR";
case 0x8009302D: return "OSS_MUTEX_NOT_CREATED";
case 0x8009302E: return "OSS_CANT_CLOSE_TRACE_FILE";
case 0x80093100: return "CRYPT_E_ASN1_ERROR";
case 0x80093101: return "CRYPT_E_ASN1_INTERNAL";
case 0x80093102: return "CRYPT_E_ASN1_EOD";
case 0x80093103: return "CRYPT_E_ASN1_CORRUPT";
case 0x80093104: return "CRYPT_E_ASN1_LARGE";
case 0x80093105: return "CRYPT_E_ASN1_CONSTRAINT";
case 0x80093106: return "CRYPT_E_ASN1_MEMORY";
case 0x80093107: return "CRYPT_E_ASN1_OVERFLOW";
case 0x80093108: return "CRYPT_E_ASN1_BADPDU";
case 0x80093109: return "CRYPT_E_ASN1_BADARGS";
case 0x8009310A: return "CRYPT_E_ASN1_BADREAL";
case 0x8009310B: return "CRYPT_E_ASN1_BADTAG";
case 0x8009310C: return "CRYPT_E_ASN1_CHOICE";
case 0x8009310D: return "CRYPT_E_ASN1_RULE";
case 0x8009310E: return "CRYPT_E_ASN1_UTF8";
case 0x80093133: return "CRYPT_E_ASN1_PDU_TYPE";
case 0x80093134: return "CRYPT_E_ASN1_NYI";
case 0x80093201: return "CRYPT_E_ASN1_EXTENDED";
case 0x80093202: return "CRYPT_E_ASN1_NOEOD";
case 0x80094001: return "CERTSRV_E_BAD_REQUESTSUBJECT";
case 0x80094002: return "CERTSRV_E_NO_REQUEST";
case 0x80094003: return "CERTSRV_E_BAD_REQUESTSTATUS";
case 0x80094004: return "CERTSRV_E_PROPERTY_EMPTY";
case 0x80094005: return "CERTSRV_E_INVALID_CA_CERTIFICATE";
case 0x80094006: return "CERTSRV_E_SERVER_SUSPENDED";
case 0x80094007: return "CERTSRV_E_ENCODING_LENGTH";
case 0x80094008: return "CERTSRV_E_ROLECONFLICT";
case 0x80094009: return "CERTSRV_E_RESTRICTEDOFFICER";
case 0x8009400A: return "CERTSRV_E_KEY_ARCHIVAL_NOT_CONFIGURED";
case 0x8009400B: return "CERTSRV_E_NO_VALID_KRA";
case 0x8009400C: return "CERTSRV_E_BAD_REQUEST_KEY_ARCHIVAL";
case 0x80094800: return "CERTSRV_E_UNSUPPORTED_CERT_TYPE";
case 0x80094801: return "CERTSRV_E_NO_CERT_TYPE";
case 0x80094802: return "CERTSRV_E_TEMPLATE_CONFLICT";
case 0x80096001: return "TRUST_E_SYSTEM_ERROR";
case 0x80096002: return "TRUST_E_NO_SIGNER_CERT";
case 0x80096003: return "TRUST_E_COUNTER_SIGNER";
case 0x80096004: return "TRUST_E_CERT_SIGNATURE";
case 0x80096005: return "TRUST_E_TIME_STAMP";
case 0x80096010: return "TRUST_E_BAD_DIGEST";
case 0x80096019: return "TRUST_E_BASIC_CONSTRAINTS";
case 0x8009601E: return "TRUST_E_FINANCIAL_CRITERIA";
case 0x80097001: return "MSSIPOTF_E_OUTOFMEMRANGE";
case 0x80097002: return "MSSIPOTF_E_CANTGETOBJECT";
case 0x80097003: return "MSSIPOTF_E_NOHEADTABLE";
case 0x80097004: return "MSSIPOTF_E_BAD_MAGICNUMBER";
case 0x80097005: return "MSSIPOTF_E_BAD_OFFSET_TABLE";
case 0x80097006: return "MSSIPOTF_E_TABLE_TAGORDER";
case 0x80097007: return "MSSIPOTF_E_TABLE_LONGWORD";
case 0x80097008: return "MSSIPOTF_E_BAD_FIRST_TABLE_PLACEMENT";
case 0x80097009: return "MSSIPOTF_E_TABLES_OVERLAP";
case 0x8009700A: return "MSSIPOTF_E_TABLE_PADBYTES";
case 0x8009700B: return "MSSIPOTF_E_FILETOOSMALL";
case 0x8009700C: return "MSSIPOTF_E_TABLE_CHECKSUM";
case 0x8009700D: return "MSSIPOTF_E_FILE_CHECKSUM";
case 0x80097010: return "MSSIPOTF_E_FAILED_POLICY";
case 0x80097011: return "MSSIPOTF_E_FAILED_HINTS_CHECK";
case 0x80097012: return "MSSIPOTF_E_NOT_OPENTYPE";
case 0x80097013: return "MSSIPOTF_E_FILE";
case 0x80097014: return "MSSIPOTF_E_CRYPT";
case 0x80097015: return "MSSIPOTF_E_BADVERSION";
case 0x80097016: return "MSSIPOTF_E_DSIG_STRUCTURE";
case 0x80097017: return "MSSIPOTF_E_PCONST_CHECK";
case 0x80097018: return "MSSIPOTF_E_STRUCTURE";
case 0x800B0001: return "TRUST_E_PROVIDER_UNKNOWN";
case 0x800B0002: return "TRUST_E_ACTION_UNKNOWN";
case 0x800B0003: return "TRUST_E_SUBJECT_FORM_UNKNOWN";
case 0x800B0004: return "TRUST_E_SUBJECT_NOT_TRUSTED";
case 0x800B0005: return "DIGSIG_E_ENCODE";
case 0x800B0006: return "DIGSIG_E_DECODE";
case 0x800B0007: return "DIGSIG_E_EXTENSIBILITY";
case 0x800B0008: return "DIGSIG_E_CRYPTO";
case 0x800B0009: return "PERSIST_E_SIZEDEFINITE";
case 0x800B000A: return "PERSIST_E_SIZEINDEFINITE";
case 0x800B000B: return "PERSIST_E_NOTSELFSIZING";
case 0x800B0100: return "TRUST_E_NOSIGNATURE";
case 0x800B0101: return "CERT_E_EXPIRED";
case 0x800B0102: return "CERT_E_VALIDITYPERIODNESTING";
case 0x800B0103: return "CERT_E_ROLE";
case 0x800B0104: return "CERT_E_PATHLENCONST";
case 0x800B0105: return "CERT_E_CRITICAL";
case 0x800B0106: return "CERT_E_PURPOSE";
case 0x800B0107: return "CERT_E_ISSUERCHAINING";
case 0x800B0108: return "CERT_E_MALFORMED";
case 0x800B0109: return "CERT_E_UNTRUSTEDROOT";
case 0x800B010A: return "CERT_E_CHAINING";
case 0x800B010B: return "TRUST_E_FAIL";
case 0x800B010C: return "CERT_E_REVOKED";
case 0x800B010D: return "CERT_E_UNTRUSTEDTESTROOT";
case 0x800B010E: return "CERT_E_REVOCATION_FAILURE";
case 0x800B010F: return "CERT_E_CN_NO_MATCH";
case 0x800B0110: return "CERT_E_WRONG_USAGE";
case 0x800B0111: return "TRUST_E_EXPLICIT_DISTRUST";
case 0x800B0112: return "CERT_E_UNTRUSTEDCA";
case 0x800B0113: return "CERT_E_INVALID_POLICY";
case 0x800B0114: return "CERT_E_INVALID_NAME";
}
return string.Format("0x{0:x} [{1}]", statusCode, statusCode);
}
#endif // TRACE_VERBOSE
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Sql.Models;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// database backups.
/// </summary>
public partial interface IDatabaseBackupOperations
{
/// <summary>
/// Begins creating or updating an Azure SQL Server backup
/// LongTermRetention vault. To determine the status of the operation
/// call GetBackupLongTermRetentionVaultOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Server
/// belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Server on which the database is hosted.
/// </param>
/// <param name='backupLongTermRetentionVaultName'>
/// The name of the Azure SQL Server backup LongTermRetention vault.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating a backup
/// LongTermRetention vault.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
Task<BackupLongTermRetentionVaultCreateOrUpdateResponse> BeginCreateOrUpdateBackupLongTermRetentionVaultAsync(string resourceGroupName, string serverName, string backupLongTermRetentionVaultName, BackupLongTermRetentionVaultCreateOrUpdateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Begins creating or updating an Azure SQL Server backup
/// LongTermRetention policy. To determine the status of the operation
/// call GetDatabaseBackupLongTermRetentionPolicyOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Server
/// belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Server on which the database is hosted.
/// </param>
/// <param name='databaseName'>
/// The name of the Azure SQL Database to be operated on.
/// </param>
/// <param name='backupLongTermRetentionPolicyName'>
/// The name of the Azure SQL Database backup LongTermRetention policy.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating a database backup
/// LongTermRetention policy.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
Task<DatabaseBackupLongTermRetentionPolicyCreateOrUpdateResponse> BeginCreateOrUpdateDatabaseBackupLongTermRetentionPolicyAsync(string resourceGroupName, string serverName, string databaseName, string backupLongTermRetentionPolicyName, DatabaseBackupLongTermRetentionPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Creates or updates an Azure SQL Server backup LongTermRetention
/// vault.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Server on which the database is hosted.
/// </param>
/// <param name='backupLongTermRetentionVaultName'>
/// The name of the Azure SQL Server backup LongTermRetention vault.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating a backup
/// LongTermRetention vault.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
Task<BackupLongTermRetentionVaultCreateOrUpdateResponse> CreateOrUpdateBackupLongTermRetentionVaultAsync(string resourceGroupName, string serverName, string backupLongTermRetentionVaultName, BackupLongTermRetentionVaultCreateOrUpdateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Creates or updates an Azure SQL Database backup LongTermRetention
/// policy.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Server on which the database is hosted.
/// </param>
/// <param name='databaseName'>
/// The name of the Azure SQL Database to be operated on (Updated or
/// created).
/// </param>
/// <param name='backupLongTermRetentionPolicyName'>
/// The name of the Azure SQL Database backup LongTermRetention policy.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating a database backup
/// LongTermRetention policy.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
Task<DatabaseBackupLongTermRetentionPolicyCreateOrUpdateResponse> CreateOrUpdateDatabaseBackupLongTermRetentionPolicyAsync(string resourceGroupName, string serverName, string databaseName, string backupLongTermRetentionPolicyName, DatabaseBackupLongTermRetentionPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Returns an Azure SQL Server backup LongTermRetention vault
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the resource belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server.
/// </param>
/// <param name='backupLongTermRetentionVaultName'>
/// The name of the Azure SQL Database backup LongTermRetention vault.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Server backup
/// LongTermRetention vault request.
/// </returns>
Task<BackupLongTermRetentionVaultGetResponse> GetBackupLongTermRetentionVaultAsync(string resourceGroupName, string serverName, string backupLongTermRetentionVaultName, CancellationToken cancellationToken);
/// <summary>
/// Gets the status of an Azure Sql Server backup LongTermRetention
/// vault create or update operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
Task<BackupLongTermRetentionVaultCreateOrUpdateResponse> GetBackupLongTermRetentionVaultOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Returns an Azure SQL Database backup LongTermRetention policy
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the resource belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server.
/// </param>
/// <param name='databaseName'>
/// The name of the Azure SQL Database.
/// </param>
/// <param name='backupLongTermRetentionPolicyName'>
/// The name of the Azure SQL Database backup LongTermRetention policy.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database backup
/// LongTermRetention policy request.
/// </returns>
Task<DatabaseBackupLongTermRetentionPolicyGetResponse> GetDatabaseBackupLongTermRetentionPolicyAsync(string resourceGroupName, string serverName, string databaseName, string backupLongTermRetentionPolicyName, CancellationToken cancellationToken);
/// <summary>
/// Gets the status of an Azure Sql Database backup LongTermRetention
/// policy create or update operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
Task<DatabaseBackupLongTermRetentionPolicyCreateOrUpdateResponse> GetDatabaseBackupLongTermRetentionPolicyOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Returns an Azure SQL deleted database backup (a resource
/// representing a deleted database that can be restored).
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server to retrieve deleted
/// databases for.
/// </param>
/// <param name='databaseName'>
/// The name of the Azure SQL Database to retrieve deleted databases
/// for.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database deleted
/// database backup request.
/// </returns>
Task<DeletedDatabaseBackupGetResponse> GetDeletedDatabaseBackupAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken);
/// <summary>
/// Returns an Azure SQL Database geo backup.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server to retrieve geo backups
/// for.
/// </param>
/// <param name='databaseName'>
/// The name of the Azure SQL Database to retrieve geo backups for.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database geo backup
/// request.
/// </returns>
Task<GeoBackupGetResponse> GetGeoBackupAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken);
/// <summary>
/// Returns a list of Azure SQL Server backup LongTermRetention vaults
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the resource belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Server.
/// </param>
/// <param name='databaseName'>
/// The name of the Azure SQL Database.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Server backup
/// LongTermRetention vault request.
/// </returns>
Task<BackupLongTermRetentionVaultListResponse> ListBackupLongTermRetentionVaultsAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken);
/// <summary>
/// Returns a list of Azure SQL Database backup LongTermRetention
/// policies
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the resource belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Server.
/// </param>
/// <param name='databaseName'>
/// The name of the Azure SQL Database.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database backup
/// LongTermRetention policy request.
/// </returns>
Task<DatabaseBackupLongTermRetentionPolicyListResponse> ListDatabaseBackupLongTermRetentionPoliciesAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken);
/// <summary>
/// Returns a list of Azure SQL deleted database backups (a resource
/// representing a deleted database that can be restored).
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server to retrieve deleted
/// databases for.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database deleted
/// database backups request.
/// </returns>
Task<DeletedDatabaseBackupListResponse> ListDeletedDatabaseBackupsAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken);
/// <summary>
/// Returns a list of Azure SQL Database geo backups.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server to retrieve geo backups
/// for.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database geo backups
/// request.
/// </returns>
Task<GeoBackupListResponse> ListGeoBackupsAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken);
/// <summary>
/// Returns a list of Azure SQL Database restore points.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// The name of the Azure SQL Database from which to retrieve available
/// restore points.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database restore points
/// request.
/// </returns>
Task<RestorePointListResponse> ListRestorePointsAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken);
}
}
| |
// ------------------------------------------------------------------------------------
// 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 *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR
// NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------------------
using Amqp;
using Amqp.Framing;
using Amqp.Types;
using System;
using System.Text;
using System.Threading;
#if NETFX || NETFX35 || DOTNET
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#endif
namespace Test.Amqp
{
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestClass]
#endif
public class LinkTests
{
TestTarget testTarget = new TestTarget();
static LinkTests()
{
Connection.DisableServerCertValidation = true;
// uncomment the following to write frame traces
//Trace.TraceLevel = TraceLevel.Frame;
//Trace.TraceListener = (f, a) => System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a));
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_BasicSendReceive()
{
string testName = "BasicSendReceive";
const int nMsgs = 200;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message("msg" + i);
message.Properties = new Properties() { GroupId = "abcdefg" };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
receiver.Accept(message);
}
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ConnectionFrameSize()
{
string testName = "ConnectionFrameSize";
const int nMsgs = 200;
int frameSize = 4 * 1024;
Connection connection = new Connection(testTarget.Address, null, new Open() { ContainerId = "c1", MaxFrameSize = (uint)frameSize }, null);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message(new string('A', frameSize + (i - nMsgs / 2)));
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
string value = (string)message.Body;
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}x{1}", value[0], value.Length);
receiver.Accept(message);
}
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ConnectionChannelMax()
{
ushort channelMax = 5;
Connection connection = new Connection(
testTarget.Address,
null,
new Open() { ContainerId = "ConnectionChannelMax", HostName = testTarget.Address.Host, ChannelMax = channelMax },
(c, o) => Trace.WriteLine(TraceLevel.Verbose, "{0}", o));
for (int i = 0; i <= channelMax; i++)
{
Session session = new Session(connection);
}
try
{
Session session = new Session(connection);
Fx.Assert(false, "Created more sessions than allowed.");
}
catch (AmqpException exception)
{
Fx.Assert(exception.Error.Condition.Equals((Symbol)ErrorCode.NotAllowed), "Wrong error code");
}
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ConnectionWithIPAddress()
{
string testName = "ConnectionWithIPAddress";
const int nMsgs = 20;
// If the test target is 'localhost' then verify that '127.0.0.1' also works.
if (testTarget.Address.Host != "localhost")
{
Trace.WriteLine(TraceLevel.Verbose,
"Test {0} skipped. Test target '{1}' is not 'localhost'.",
testName, testTarget.Address.Host);
return;
}
Address address2 = new Address("127.0.0.1", testTarget.Address.Port,
testTarget.Address.User, testTarget.Address.Password,
testTarget.Address.Path, testTarget.Address.Scheme);
Connection connection = new Connection(address2);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message("msg" + i);
message.Properties = new Properties() { GroupId = "abcdefg" };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
receiver.Accept(message);
}
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ConnectionRemoteProperties()
{
string testName = "ConnectionRemoteProperties";
ManualResetEvent opened = new ManualResetEvent(false);
Open remoteOpen = null;
OnOpened onOpen = (c, o) =>
{
remoteOpen = o;
opened.Set();
};
Open open = new Open()
{
ContainerId = testName,
Properties = new Fields() { { new Symbol("p1"), "abcd" } },
DesiredCapabilities = new Symbol[] { new Symbol("dc1"), new Symbol("dc2") },
OfferedCapabilities = new Symbol[] { new Symbol("oc") }
};
Connection connection = new Connection(testTarget.Address, null, open, onOpen);
opened.WaitOne(10000);
connection.Close();
Assert.IsTrue(remoteOpen != null, "remote open not set");
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_OnMessage()
{
string testName = "OnMessage";
const int nMsgs = 200;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
ManualResetEvent done = new ManualResetEvent(false);
int received = 0;
receiver.Start(10, (link, m) =>
{
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", m.ApplicationProperties["sn"]);
link.Accept(m);
received++;
if (received == nMsgs)
{
done.Set();
}
});
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message()
{
BodySection = new Data() { Binary = Encoding.UTF8.GetBytes("msg" + i) }
};
message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
int last = -1;
while (!done.WaitOne(10000) && received > last)
{
last = received;
}
sender.Close();
receiver.Close();
session.Close();
connection.Close();
Assert.AreEqual(nMsgs, received, "not all messages are received.");
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_CloseBusyReceiver()
{
string testName = "CloseBusyReceiver";
const int nMsgs = 20;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message();
message.Properties = new Properties() { MessageId = "msg" + i };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
ManualResetEvent closed = new ManualResetEvent(false);
receiver.Closed += (o, e) => closed.Set();
receiver.Start(
nMsgs,
(r, m) =>
{
if (m.Properties.MessageId == "msg0") r.Close(0);
});
Assert.IsTrue(closed.WaitOne(10000));
ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver2.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId);
receiver2.Accept(message);
}
receiver2.Close();
sender.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ReleaseMessage()
{
string testName = "ReleaseMessage";
const int nMsgs = 20;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message();
message.Properties = new Properties() { MessageId = "msg" + i };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId);
if (i % 2 == 0)
{
receiver.Accept(message);
}
else
{
receiver.Release(message);
}
}
receiver.Close();
ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs / 2; ++i)
{
Message message = receiver2.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId);
receiver2.Accept(message);
}
receiver2.Close();
sender.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_SendAck()
{
string testName = "SendAck";
const int nMsgs = 20;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
ManualResetEvent done = new ManualResetEvent(false);
OutcomeCallback callback = (m, o, s) =>
{
Trace.WriteLine(TraceLevel.Verbose, "send complete: sn {0} outcome {1}", m.ApplicationProperties["sn"], o.Descriptor.Name);
if ((int)m.ApplicationProperties["sn"] == (nMsgs - 1))
{
done.Set();
}
};
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message();
message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, callback, null);
}
done.WaitOne(10000);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
receiver.Accept(message);
}
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ReceiveWaiter()
{
string testName = "ReceiveWaiter";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
ManualResetEvent gotMessage = new ManualResetEvent(false);
Fx.StartThread(() =>
{
Message message = receiver.Receive();
if (message != null)
{
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId);
receiver.Accept(message);
gotMessage.Set();
}
});
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
Message msg = new Message() { Properties = new Properties() { MessageId = "123456" } };
sender.Send(msg, null, null);
Assert.IsTrue(gotMessage.WaitOne(5000), "No message was received");
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ReceiveWithFilter()
{
string testName = "ReceiveWithFilter";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
Message message = new Message("I can match a filter");
message.Properties = new Properties() { GroupId = "abcdefg" };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = 100;
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
sender.Send(message, null, null);
// update the filter descriptor and expression according to the broker
Map filters = new Map();
// JMS selector filter: code = 0x0000468C00000004L, symbol="apache.org:selector-filter:string"
filters.Add(new Symbol("f1"), new DescribedValue(new Symbol("apache.org:selector-filter:string"), "sn = 100"));
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, new Source() { Address = testTarget.Path, FilterSet = filters }, null);
Message message2 = receiver.Receive();
receiver.Accept(message2);
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_LinkCloseWithPendingSend()
{
string testName = "LinkCloseWithPendingSend";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
bool cancelled = false;
Message message = new Message("released");
sender.Send(message, (m, o, s) => cancelled = true, null);
sender.Close(0);
// assume that Close is called before connection/link is open so message is still queued in link
// but this is not very reliable, so just do a best effort check
if (cancelled)
{
Trace.WriteLine(TraceLevel.Verbose, "The send was cancelled as expected");
}
else
{
Trace.WriteLine(TraceLevel.Verbose, "The send was not cancelled as expected. This can happen if close call loses the race");
}
try
{
message = new Message("failed");
sender.Send(message, (m, o, s) => cancelled = true, null);
Assert.IsTrue(false, "Send should fail after link is closed");
}
catch (AmqpException exception)
{
Trace.WriteLine(TraceLevel.Verbose, "Caught exception: ", exception.Error);
}
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_SynchronousSend()
{
string testName = "SynchronousSend";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
Message message = new Message("hello");
sender.Send(message, 60000);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
message = receiver.Receive();
Assert.IsTrue(message != null, "no message was received.");
receiver.Accept(message);
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_DynamicSenderLink()
{
string testName = "DynamicSenderLink";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
string targetAddress = null;
OnAttached onAttached = (link, attach) =>
{
targetAddress = ((Target)attach.Target).Address;
};
SenderLink sender = new SenderLink(session, "sender-" + testName, new Target() { Dynamic = true }, onAttached);
Message message = new Message("hello");
sender.Send(message, 60000);
Assert.IsTrue(targetAddress != null, "dynamic target not attached");
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, targetAddress);
message = receiver.Receive();
Assert.IsTrue(message != null, "no message was received.");
receiver.Accept(message);
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_DynamicReceiverLink()
{
string testName = "DynamicReceiverLink";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
string remoteSource = null;
ManualResetEvent attached = new ManualResetEvent(false);
OnAttached onAttached = (link, attach) => { remoteSource = ((Source)attach.Source).Address; attached.Set(); };
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, new Source() { Dynamic = true }, onAttached);
attached.WaitOne(10000);
Assert.IsTrue(remoteSource != null, "dynamic source not attached");
SenderLink sender = new SenderLink(session, "sender-" + testName, remoteSource);
Message message = new Message("hello");
sender.Send(message, 60000);
message = receiver.Receive();
Assert.IsTrue(message != null, "no message was received.");
receiver.Accept(message);
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_RequestResponse()
{
string testName = "RequestResponse";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
// server app: the request handler
ReceiverLink requestLink = new ReceiverLink(session, "srv.requester-" + testName, testTarget.Path);
requestLink.Start(10, (l, m) =>
{
l.Accept(m);
// got a request, send back a reply
SenderLink sender = new SenderLink(session, "srv.replier-" + testName, m.Properties.ReplyTo);
Message reply = new Message("received");
reply.Properties = new Properties() { CorrelationId = m.Properties.MessageId };
sender.Send(reply, (a, b, c) => ((Link)c).Close(0), sender);
});
// client: setup a temp queue and waits for responses
OnAttached onAttached = (l, at) =>
{
// client: sends a request to the request queue, specifies the temp queue as the reply queue
SenderLink sender = new SenderLink(session, "cli.requester-" + testName, testTarget.Path);
Message request = new Message("hello");
request.Properties = new Properties() { MessageId = "request1", ReplyTo = ((Source)at.Source).Address };
sender.Send(request, (a, b, c) => ((Link)c).Close(0), sender);
};
ReceiverLink responseLink = new ReceiverLink(session, "cli.responder-" + testName, new Source() { Dynamic = true }, onAttached);
Message response = responseLink.Receive();
Assert.IsTrue(response != null, "no response was received");
responseLink.Accept(response);
requestLink.Close();
responseLink.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_AdvancedLinkFlowControl()
{
string testName = "AdvancedLinkFlowControl";
int nMsgs = 20;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message();
message.Properties = new Properties() { MessageId = "msg" + i };
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
receiver.SetCredit(2, false);
Message m1 = receiver.Receive();
Message m2 = receiver.Receive();
Assert.AreEqual("msg0", m1.Properties.MessageId);
Assert.AreEqual("msg1", m2.Properties.MessageId);
receiver.Accept(m1);
receiver.Accept(m2);
ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, testTarget.Path);
receiver2.SetCredit(2, false);
Message m3 = receiver2.Receive();
Message m4 = receiver2.Receive();
Assert.AreEqual("msg2", m3.Properties.MessageId);
Assert.AreEqual("msg3", m4.Properties.MessageId);
receiver2.Accept(m3);
receiver2.Accept(m4);
receiver.SetCredit(4);
for (int i = 4; i < nMsgs; i++)
{
Message m = receiver.Receive();
Assert.AreEqual("msg" + i, m.Properties.MessageId);
receiver.Accept(m);
}
sender.Close();
receiver.Close();
receiver2.Close();
session.Close();
connection.Close();
}
/// <summary>
/// This test proves that issue #14 is fixed.
/// https://github.com/Azure/amqpnetlite/issues/14
/// </summary>
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_SendEmptyMessage()
{
string testName = "SendEmptyMessage";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
bool threwArgEx = false;
try
{
sender.Send(new Message());
}
catch (ArgumentException)
{
threwArgEx = true;
}
finally
{
sender.Close();
session.Close();
connection.Close();
}
Assert.IsTrue(threwArgEx, "Should throw an argument exception when sending an empty message.");
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ConnectionCreateClose()
{
Connection connection = new Connection(testTarget.Address);
connection.Close();
Assert.IsTrue(connection.Error == null, "connection has error!");
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_SessionCreateClose()
{
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
session.Close(0);
connection.Close();
Assert.IsTrue(connection.Error == null, "connection has error!");
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_LinkCreateClose()
{
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender", testTarget.Path);
ReceiverLink receiver = new ReceiverLink(session, "receiver", testTarget.Path);
sender.Close(0);
receiver.Close(0);
session.Close(0);
connection.Close();
Assert.IsTrue(connection.Error == null, "connection has error!");
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_LinkReopen()
{
string testName = "LinkReopen";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender", testTarget.Path);
sender.Send(new Message("test") { Properties = new Properties() { MessageId = testName } });
sender.Close();
sender = new SenderLink(session, "sender", testTarget.Path);
sender.Send(new Message("test2") { Properties = new Properties() { MessageId = testName } });
sender.Close();
ReceiverLink receiver = new ReceiverLink(session, "receiver", testTarget.Path);
for (int i = 1; i <= 2; i++)
{
var m = receiver.Receive();
Assert.IsTrue(m != null, "Didn't receive message " + i);
receiver.Accept(m);
}
session.Close(0);
connection.Close();
Assert.IsTrue(connection.Error == null, "connection has error!");
}
}
}
| |
using System;
using System.IO;
using System.Text;
using Elasticsearch.Net.Tests.Unit.Memory.Helpers;
using Elasticsearch.Net.Tests.Unit.Responses.Helpers;
using Elasticsearch.Net.Tests.Unit.Stubs;
using FluentAssertions;
using NUnit.Framework;
namespace Elasticsearch.Net.Tests.Unit.Memory
{
[TestFixture]
public class ResponseCodePathsMemoryTests : ResponseCodePathsMemoryTestsBase
{
[Test]
[TestCase("hello world")]
public void Typed_Ok_DiscardResponse(object responseValue)
{
using (var request = new MemorySetup<StandardResponse>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
this.ShouldDirectlyStream(request);
}
[Test]
[TestCase("hello world")]
public void Typed_Ok_KeepResponse(object responseValue)
{
using (var request = new MemorySetup<StandardResponse>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
this.ShouldStreamOfCopy(request);
}
[Test]
[TestCase("hello world")]
public void Typed_Bad_DiscardResponse(object responseValue)
{
using (var request = new MemorySetup<StandardResponse>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
this.ShouldDirectlyStream(request, false);
}
[Test]
[TestCase("hello world")]
public void Typed_Bad_KeepResponse(object responseValue)
{
using (var request = new MemorySetup<StandardResponse>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
this.ShouldStreamOfCopy(request, false);
}
[Test]
[TestCase("hello world")]
public void DynamicDictionary_Ok_DiscardResponse(object responseValue)
{
using (var request = new MemorySetup<DynamicDictionary>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Ok(settings, response: stream),
client => client.Info()
))
this.ShouldDirectlyStream(request);
}
[Test]
[TestCase("hello world")]
public void DynamicDictionary_Ok_KeepResponse(object responseValue)
{
using (var request = new MemorySetup<DynamicDictionary>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Ok(settings, response: stream),
client => client.Info()
))
this.ShouldStreamOfCopy(request);
}
[Test]
[TestCase("hello world")]
public void DynamicDictionary_Bad_DiscardResponse(object responseValue)
{
using (var request = new MemorySetup<DynamicDictionary>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Bad(settings, response: stream),
client => client.Info()
))
this.ShouldDirectlyStream(request, false);
}
[Test]
[TestCase("hello world")]
public void DynamicDictionary_Bad_KeepResponse(object responseValue)
{
using (var request = new MemorySetup<DynamicDictionary>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Bad(settings, response: stream),
client => client.Info()
))
this.ShouldStreamOfCopy(request, false);
}
[Test, TestCase(505123)]
public void ByteArray_Ok_DiscardResponse(object responseValue)
{
using (var request = new MemorySetup<byte[]>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
this.ShouldStreamOfCopy(request, keepRaw: false);
}
[Test, TestCase(505123)]
public void ByteArray_Ok_KeepResponse(object responseValue)
{
using (var request = new MemorySetup<byte[]>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
this.ShouldStreamOfCopy(request);
}
[Test, TestCase(505123)]
public void ByteArray_Bad_DiscardResponse(object responseValue)
{
using (var request = new MemorySetup<byte[]>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
this.ShouldStreamOfCopy(request, success: false, keepRaw: false);
}
[Test, TestCase(505123)]
public void ByteArray_Bad_KeepResponse(object responseValue)
{
using (var request = new MemorySetup<byte[]>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
this.ShouldStreamOfCopy(request, success: false);
}
[Test, TestCase(505123)]
public void String_Ok_DiscardResponse(object responseValue)
{
using (var request = new MemorySetup<string>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
this.ShouldStreamOfCopy(request, keepRaw: false);
}
[Test, TestCase(505123)]
public void String_Ok_KeepResponse(object responseValue)
{
using (var request = new MemorySetup<string>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
this.ShouldStreamOfCopy(request);
}
[Test, TestCase(505123)]
public void String_Bad_DiscardResponse(object responseValue)
{
using (var request = new MemorySetup<string>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
this.ShouldStreamOfCopy(request, success: false, keepRaw: false);
}
[Test, TestCase(505123)]
public void String_Bad_KeepResponse(object responseValue)
{
using (var request = new MemorySetup<string>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
this.ShouldStreamOfCopy(request, false);
}
[Test, TestCase(505123)]
public void Stream_Ok_DiscardResponse(object responseValue)
{
using (var request = new MemorySetup<Stream>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
this.ShouldDirectlyStream(request);
}
[Test, TestCase(505123)]
public void Stream_Ok_KeepResponse(object responseValue)
{
using (var request = new MemorySetup<Stream>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
this.ShouldDirectlyStream(request, success: true);
}
[Test, TestCase(505123)]
public void Stream_Bad_DiscardResponse(object responseValue)
{
using (var request = new MemorySetup<Stream>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
this.ShouldDirectlyStream(request, success: false);
}
[Test, TestCase(505123)]
public void Stream_Bad_KeepResponse(object responseValue)
{
using (var request = new MemorySetup<Stream>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
this.ShouldDirectlyStream(request, success: false);
}
[Test, TestCase(505123)]
public void VoidResponse_Ok_DiscardResponse(object responseValue)
{
using (var request = new MemorySetup<VoidResponse>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
//voidResponse NEVER reads the body so Raw is always false
//and no intermediate stream should be created
this.ShouldDirectlyStream(request);
}
[Test, TestCase(505123)]
public void VoidResponse_Ok_KeepResponse(object responseValue)
{
using (var request = new MemorySetup<VoidResponse>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
//voidResponse NEVER reads the body so Raw is always false
//and no intermediate stream should be created
this.ShouldDirectlyStream(request);
}
[Test, TestCase(505123)]
public void VoidResponse_Bad_DiscardResponse(object responseValue)
{
using (var request = new MemorySetup<VoidResponse>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
//voidResponse NEVER reads the body so Raw is always false
this.ShouldDirectlyStream(request, success: false);
}
[Test, TestCase(505123)]
public void VoidResponse_Bad_KeepResponse(object responseValue)
{
using (var request = new MemorySetup<VoidResponse>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
//voidResponse NEVER reads the body so Raw is always false
//and no intermediate stream should be created
this.ShouldDirectlyStream(request, success: false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using IronPython.Runtime.Exceptions;
using Microsoft.Scripting.Hosting;
namespace RevitPythonShell.RpsRuntime
{
/// <summary>
/// A stream to write output to...
/// This can be passed into the python interpreter to render all output to.
/// Only a minimal subset is actually implemented - this is all we really
/// expect to use.
/// </summary>
public class ScriptOutputStream: Stream
{
private readonly ScriptOutput _gui;
private readonly ScriptEngine _engine;
private int _bomCharsLeft; // we want to get rid of pesky UTF8-BOM-Chars on write
private readonly Queue<MemoryStream> _completedLines; // one memorystream per line of input
private MemoryStream _inputBuffer;
public ScriptOutputStream(ScriptOutput gui, ScriptEngine engine)
{
_gui = gui;
_engine = engine;
_gui.txtStdOut.KeyPress += KeyPressEventHandler;
_gui.txtStdOut.KeyDown += KeyDownEventHandler;
//_gui.Closing += ClosingEventHandler;
//_gui.Closed += ClosedEventHandler;
_gui.txtStdOut.Focus();
_completedLines = new Queue<MemoryStream>();
_inputBuffer = new MemoryStream();
_bomCharsLeft = 3; //0xef, 0xbb, 0xbf for UTF-8 (see http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding)
}
void ClosedEventHandler(object sender, EventArgs e)
{
_engine.Runtime.Shutdown();
_completedLines.Enqueue(new MemoryStream());
}
/// <summary>
/// Terminate reading from STDIN.
/// FIXME: this doesn't work!
/// </summary>
private void ClosingEventHandler(object sender, System.ComponentModel.CancelEventArgs e)
{
_engine.Runtime.Shutdown();
_completedLines.Enqueue(new MemoryStream());
}
/// <summary>
/// Complete a line when the enter key is pressed. Also
/// try to emulate a nice control window. This is going to be a big gigantic pile
/// of ifs, sigh.
/// </summary>
void KeyDownEventHandler(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
var line = _inputBuffer;
var newLine = new byte[] {/*0x0d,*/ 0x0a};
line.Write(newLine, 0, newLine.Length); // append new-line
line.Seek(0, SeekOrigin.Begin); // rewind the line for later reading...
_completedLines.Enqueue(line);
_inputBuffer = new MemoryStream();
}
else if (e.KeyCode == Keys.Back || e.KeyCode == Keys.Left)
{
// remove last character from input buffer
if (_inputBuffer.Position > 0)
{
var line = new MemoryStream();
line.Write(_inputBuffer.GetBuffer(), 0, (int)(_inputBuffer.Position - 1));
_inputBuffer = line;
_gui.txtStdOut.Text = _gui.txtStdOut.Text.Substring(0, _gui.txtStdOut.Text.Length - 1);
_gui.txtStdOut.SelectionStart = _gui.txtStdOut.Text.Length;
_gui.txtStdOut.ScrollToCaret();
}
// do not pass backspace / left on to txtStdOut
e.Handled = true;
}
else if (e.KeyCode == Keys.Right)
{
// do not move right ever...
e.Handled = true;
}
}
/// <summary>
/// Stash away any printable characters for later...
/// </summary>
void KeyPressEventHandler(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar))
{
var bytes = Encoding.UTF8.GetBytes(new[] {e.KeyChar});
_inputBuffer.Write(bytes, 0, bytes.Length);
_gui.txtStdOut.Focus();
}
else
{
if (e.KeyChar == '\r')
{
// user pressed enter
_gui.txtStdOut.Text += "\r\n";
_gui.txtStdOut.SelectionStart = _gui.txtStdOut.Text.Length;
_gui.txtStdOut.Focus();
}
// pretend we have handled this key (so using arrows does not confuse the user)
e.Handled = true;
}
}
/// <summary>
/// Append the text in the buffer to gui.txtStdOut
/// </summary>
public override void Write(byte[] buffer, int offset, int count)
{
lock (this)
{
if (_gui.IsDisposed)
{
return;
}
while (_bomCharsLeft > 0 && count > 0)
{
_bomCharsLeft--;
count--;
offset++;
}
var actualBuffer = new byte[count];
Array.Copy(buffer, offset, actualBuffer, 0, count);
var text = Encoding.UTF8.GetString(actualBuffer);
Debug.WriteLine(text);
_gui.BeginInvoke((Action)delegate()
{
_gui.txtStdOut.AppendText(text);
_gui.txtStdOut.SelectionStart = _gui.txtStdOut.Text.Length;
_gui.txtStdOut.ScrollToCaret();
});
Application.DoEvents();
}
}
public override void Flush()
{
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
/// <summary>
/// Read from the _inputBuffer, block until a new line has been entered...
/// </summary>
public override int Read(byte[] buffer, int offset, int count)
{
while (_completedLines.Count < 1)
{
if (_gui.Visible == false)
{
throw new EndOfStreamException();
}
// wait for user to complete a line
Application.DoEvents();
Thread.Sleep(10);
}
var line = _completedLines.Dequeue();
return line.Read(buffer, offset, count);
}
public override bool CanRead
{
get { return !_gui.IsDisposed; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override long Length
{
get { return _gui.txtStdOut.Text.Length; }
}
public override long Position
{
get { return 0; }
set { }
}
}
}
| |
using UnityEngine;
using System.Collections;
[System.Serializable]
public class InstantGuiElementPos
{
public int left;
public int right;
public int top;
public int bottom;
public bool isStyle;
public InstantGuiElementPos ( int l , int r , int t , int b ){ left=l; right=r; top=t; bottom=b; }
public InstantGuiElementPos ( int l , int r , int t , int b , bool st ){ left=l; right=r; top=t; bottom=b; isStyle=st; }
public InstantGuiElementPos ( InstantGuiElementPos s ){ left=s.left; right=s.right; top=s.top; bottom=s.bottom; }
public Rect ToRect (){ return new Rect (left, top, right-left, bottom-top); }
public Rect ToRect ( float scale ){ return new Rect (left*scale, top*scale, (right-left)*scale, (bottom-top)*scale); }
public new string ToString (){ return ("InstantGuiElementPos left:"+left.ToString()+" right:"+right.ToString()+" top:"+top.ToString()+" bottom:"+bottom.ToString()); }
public Vector2 GetCenter (){ return new Vector2(left+(right-left)*0.5f , top+(bottom-top)*0.5f); }
public void Set ( int l , int r , int t , int b ){ left=l; right=r; top=t; bottom=b; }
public void Set ( InstantGuiElementPos s ){ left=s.left; right=s.right; top=s.top; bottom=s.bottom; }
public int GetWidth (){ return right-left; }
public int GetHeight (){ return bottom-top; }
public void Add ( InstantGuiElementPos e ){
left += e.left;
right += e.right;
top += e.top;
bottom += e.bottom;
}
public void Subtract ( InstantGuiElementPos e2 ){
left -= e2.left;
right -= e2.right;
top -= e2.top;
bottom -= e2.bottom;
}
//transforming relative pos to absolute
static public InstantGuiElementPos GetRelativeAbsolute ( InstantGuiElementPos parent , InstantGuiElementPos relative ){
return new InstantGuiElementPos (
Mathf.RoundToInt(parent.left + ((parent.right-parent.left) * relative.left * 0.01f)),
Mathf.RoundToInt(parent.left + ((parent.right-parent.left) * relative.right * 0.01f)),
Mathf.RoundToInt(parent.top + ((parent.bottom-parent.top) * relative.top * 0.01f)),
Mathf.RoundToInt(parent.top + ((parent.bottom-parent.top) * relative.bottom * 0.01f)) );
}
static public Vector2 ScreenPointToRelative ( InstantGuiElementPos parent , Vector2 point ){
return new Vector2 (
(point.x-parent.left)/(parent.right-parent.left)*100.0f,
(point.y-parent.top)/(parent.bottom-parent.top)*100.0f );
}
static public bool Equals ( InstantGuiElementPos e1 , InstantGuiElementPos e2 ){
return (e1.left==e2.left && e1.right==e2.right && e1.top==e2.top && e1.bottom==e2.bottom);
}
public void GetAbsolute ( InstantGuiElementPos parent , InstantGuiElementPos relative , InstantGuiElementPos offset ){
InstantGuiElementPos relativeAbsolute = GetRelativeAbsolute(parent, relative);
left = relativeAbsolute.left + offset.left;
right = relativeAbsolute.right + offset.right;
top = relativeAbsolute.top + offset.top;
bottom = relativeAbsolute.bottom + offset.bottom;
}
public void GetOffset ( InstantGuiElementPos parent , InstantGuiElementPos relative , InstantGuiElementPos absolute ){
InstantGuiElementPos relativeAbsolute = GetRelativeAbsolute(parent, relative);
left = absolute.left - relativeAbsolute.left;
right = absolute.right - relativeAbsolute.right;
top = absolute.top - relativeAbsolute.top;
bottom = absolute.bottom - relativeAbsolute.bottom;
//Subtract(relativeAbsolute);
}
public void GetRelative ( InstantGuiElementPos parent , InstantGuiElementPos absolute , InstantGuiElementPos offset ){
InstantGuiElementPos relativeAbsolute = new InstantGuiElementPos(absolute);
relativeAbsolute.Subtract(offset);
left = ((relativeAbsolute.left-parent.left)/(parent.right-parent.left))*100;
right = ((relativeAbsolute.right-parent.left)/(parent.right-parent.left))*100;
top = ((relativeAbsolute.top-parent.top)/(parent.bottom-parent.top))*100;
bottom = ((relativeAbsolute.bottom-parent.top)/(parent.bottom-parent.top))*100;
}
public InstantGuiElementPos Clone()
{
return (InstantGuiElementPos)this.MemberwiseClone();
}
}
public enum MessageRecievers {none=0, current=1, upwards=2, broadcast=3, gameObject=4, all=5}
[System.Serializable]
public class InstantGuiActivator
{
public GameObject[] enableObjects = new GameObject[0];
public GameObject[] disableObjects = new GameObject[0];
public string message;
public MessageRecievers messageRecievers = MessageRecievers.upwards;
public GameObject messageGameObject;
public bool messageInEditor = false;
public bool guiDraw; //used in IGInspector
float guiScrollPos;
public void Activate ( MonoBehaviour control)
{
for (int i=0;i<enableObjects.Length;i++)
if (enableObjects[i]!=null)
enableObjects[i].SetActive(true);
for (int i=0;i<disableObjects.Length;i++)
if (disableObjects[i]!=null)
disableObjects[i].SetActive(false);
if (message!=null && message.Length!=0 && (Application.isPlaying || messageInEditor))
switch (messageRecievers)
{
case MessageRecievers.current: control.gameObject.SendMessage(message, control, SendMessageOptions.DontRequireReceiver); break;
case MessageRecievers.upwards: control.gameObject.SendMessageUpwards(message, control, SendMessageOptions.DontRequireReceiver); break;
case MessageRecievers.broadcast: control.gameObject.BroadcastMessage(message, control, SendMessageOptions.DontRequireReceiver); break;
case MessageRecievers.gameObject: if (messageGameObject!=null) messageGameObject.SendMessage(message, control, SendMessageOptions.DontRequireReceiver); break;
case MessageRecievers.all:
GameObject[] allObjs = (GameObject[])GameObject.FindObjectsOfType(typeof(GameObject));
for (int i=0;i<allObjs.Length;i++) allObjs[i].SendMessage(message, control, SendMessageOptions.DontRequireReceiver);
break;
}
}
}
[ExecuteInEditMode]
public class InstantGui : MonoBehaviour
{
static public float Invert ( float input ){ return height-input; }
static public Vector2 Invert ( Vector2 input ){ return new Vector2(input.x, Invert(input.y)); }
static public Vector3 Invert ( Vector3 input ){ return new Vector3(input.x, Invert(input.y), input.z); }
static public Rect Invert ( Rect input ){ return new Rect(input.x, height-input.y-input.height, input.width, input.height); }
static public InstantGuiElement pointed;
static public InstantGui instance;
public InstantGuiElement element;
static public float scale = 1;
#if UNITY_EDITOR
private UnityEditor.EditorWindow gameView; //to get screen size in editor.
#endif
static public int width;
static public int height;
static public int oldScreenWidth;
static public int oldScreenHeight;
static public void CreateRoot ()
{
GameObject rootobj = new GameObject ("InstantGUI");
InstantGui.instance = rootobj.AddComponent<InstantGui>();
InstantGui.instance.element = rootobj.AddComponent<InstantGuiElement>();
InstantGui.instance.element.relative = new InstantGuiElementPos(0,100,0,100);
InstantGui.instance.element.offset = new InstantGuiElementPos(0,0,0,0);
InstantGui.instance.element.lockPosition = true;
}
static public void ForceUpdate (){
if (!instance) instance = (InstantGui)GameObject.FindObjectOfType(typeof(InstantGui));
instance.Update();
}
//Aligning all elements and calculating hover
public void Update ()
{
//if (updateTime > 0.1f && updateTimeLeft > 0) { updateTimeLeft-=Time.deltaTime; return; }
//updateTimeLeft = updateTime;
//if (!element)
element = GetComponent<InstantGuiElement>();
pointed = null;
//getting game view size
#if UNITY_EDITOR
/*
if (!gameView)
{
System.Type type = System.Type.GetType("UnityEditor.GameView,UnityEditor");
System.Reflection.MethodInfo GetMainGameView = type.GetMethod("GetMainGameView",System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
gameView = (UnityEditor.EditorWindow)GetMainGameView.Invoke(null,null);
}
width = (int)gameView.position.width;
height = (int)gameView.position.height-16;
*/
//It is not possible to use Screen.height from an OnInspectorGUI (returns inspector height)
string[] res = UnityEditor.UnityStats.screenRes.Split('x');
width = int.Parse(res[0]);
height = int.Parse(res[1]);
#else
width = Screen.width;
height = Screen.height;
#endif
Profiler.BeginSample ("CheckChildren");
element.CheckChildren();
Profiler.EndSample ();
Profiler.BeginSample ("Align");
element.Align();
Profiler.EndSample ();
Profiler.BeginSample ("Prevent Zero Size");
//element.PreventZeroSize();
Profiler.EndSample ();
Profiler.BeginSample ("Point");
element.Point();
Profiler.EndSample ();
Profiler.BeginSample ("Action");
element.Action();
Profiler.EndSample ();
Profiler.BeginSample ("Style");
element.ApplyStyle();
Profiler.EndSample ();
oldScreenWidth = Screen.width;
oldScreenHeight = Screen.height;
}
//selecting element
#if UNITY_EDITOR
public void OnGUI ()
{
if (!UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
{
InstantGuiElement selectedElement = null;
if (UnityEditor.Selection.activeGameObject!=null) selectedElement = UnityEditor.Selection.activeGameObject.GetComponent<InstantGuiElement>();
if (Event.current.isMouse && Event.current.button == 0)
{
if (!selectedElement) //selecting element only when no element selected. Otherwise it is done from Frame
{
GetComponent<InstantGuiElement>().Point(true);
if (pointed!=null && pointed.gameObject != null) UnityEditor.Selection.activeGameObject = pointed.gameObject;
selectedElement = pointed;
}
}
//editing and drawing frame
if (selectedElement!=null)
{
if (Event.current.isMouse || Event.current.isKey || Event.current.type == EventType.ValidateCommand) InstantGuiFrame.EditFrame(selectedElement);
if (InstantGuiFrame.drawFrames && Event.current.type == EventType.Repaint) InstantGuiFrame.DrawFrame(selectedElement);
//removing element on delete
if (Event.current.keyCode == KeyCode.Delete) StartCoroutine(selectedElement.YieldAndDestroy());
}
//making gui repaint
if (Event.current.type == EventType.Repaint)
{
UnityEditor.EditorUtility.SetDirty(this);
}
}
}
#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.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing Properties.
/// </summary>
internal partial class PropertiesOperations : IServiceOperations<ApiManagementClient>, IPropertiesOperations
{
/// <summary>
/// Initializes a new instance of the PropertiesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal PropertiesOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates new property.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='propId'>
/// Required. Identifier of the property.
/// </param>
/// <param name='parameters'>
/// Required. Create parameters.
/// </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> CreateAsync(string resourceGroupName, string serviceName, string propId, PropertyCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (propId == null)
{
throw new ArgumentNullException("propId");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Name.Length > 256)
{
throw new ArgumentOutOfRangeException("parameters.Name");
}
if (parameters.Value == null)
{
throw new ArgumentNullException("parameters.Value");
}
if (parameters.Value.Length > 4096)
{
throw new ArgumentOutOfRangeException("parameters.Value");
}
// 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("serviceName", serviceName);
tracingParameters.Add("propId", propId);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", 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.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/properties/";
url = url + Uri.EscapeDataString(propId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
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.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject propertyCreateParametersValue = new JObject();
requestDoc = propertyCreateParametersValue;
propertyCreateParametersValue["name"] = parameters.Name;
propertyCreateParametersValue["value"] = parameters.Value;
if (parameters.Tags != null)
{
if (parameters.Tags is ILazyCollection == false || ((ILazyCollection)parameters.Tags).IsInitialized)
{
JArray tagsArray = new JArray();
foreach (string tagsItem in parameters.Tags)
{
tagsArray.Add(tagsItem);
}
propertyCreateParametersValue["tags"] = tagsArray;
}
}
propertyCreateParametersValue["secret"] = parameters.Secret;
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
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>
/// Deletes specific property from the the Api Management service
/// instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='propId'>
/// Required. Identifier of the property.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </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 serviceName, string propId, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (propId == null)
{
throw new ArgumentNullException("propId");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// 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("serviceName", serviceName);
tracingParameters.Add("propId", propId);
tracingParameters.Add("etag", etag);
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.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/properties/";
url = url + Uri.EscapeDataString(propId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// 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>
/// Gets specific property.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='propId'>
/// Required. Identifier of the property.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Get Property operation response details.
/// </returns>
public async Task<PropertyGetResponse> GetAsync(string resourceGroupName, string serviceName, string propId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (propId == null)
{
throw new ArgumentNullException("propId");
}
// 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("serviceName", serviceName);
tracingParameters.Add("propId", propId);
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.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/properties/";
url = url + Uri.EscapeDataString(propId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
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
PropertyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new PropertyGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
PropertyContract valueInstance = new PropertyContract();
result.Value = valueInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
valueInstance.IdPath = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
valueInstance.Name = nameInstance;
}
JToken valueValue = responseDoc["value"];
if (valueValue != null && valueValue.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue);
valueInstance.Value = valueInstance2;
}
JToken tagsArray = responseDoc["tags"];
if (tagsArray != null && tagsArray.Type != JTokenType.Null)
{
foreach (JToken tagsValue in ((JArray)tagsArray))
{
valueInstance.Tags.Add(((string)tagsValue));
}
}
JToken secretValue = responseDoc["secret"];
if (secretValue != null && secretValue.Type != JTokenType.Null)
{
bool secretInstance = ((bool)secretValue);
valueInstance.Secret = secretInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
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>
/// List all properties.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Properties operation response details.
/// </returns>
public async Task<PropertiesListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
// 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("serviceName", serviceName);
tracingParameters.Add("query", query);
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.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/properties";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
List<string> odataFilter = new List<string>();
if (query != null && query.Filter != null)
{
odataFilter.Add(Uri.EscapeDataString(query.Filter));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (query != null && query.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
}
if (query != null && query.Skip != null)
{
queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
}
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
PropertiesListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new PropertiesListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
PropertyPaged resultInstance = new PropertyPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
PropertyContract propertyContractInstance = new PropertyContract();
resultInstance.Values.Add(propertyContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
propertyContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
propertyContractInstance.Name = nameInstance;
}
JToken valueValue2 = valueValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
propertyContractInstance.Value = valueInstance;
}
JToken tagsArray = valueValue["tags"];
if (tagsArray != null && tagsArray.Type != JTokenType.Null)
{
foreach (JToken tagsValue in ((JArray)tagsArray))
{
propertyContractInstance.Tags.Add(((string)tagsValue));
}
}
JToken secretValue = valueValue["secret"];
if (secretValue != null && secretValue.Type != JTokenType.Null)
{
bool secretInstance = ((bool)secretValue);
propertyContractInstance.Secret = secretInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List next properties page.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Properties operation response details.
/// </returns>
public async Task<PropertiesListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// 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
PropertiesListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new PropertiesListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
PropertyPaged resultInstance = new PropertyPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
PropertyContract propertyContractInstance = new PropertyContract();
resultInstance.Values.Add(propertyContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
propertyContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
propertyContractInstance.Name = nameInstance;
}
JToken valueValue2 = valueValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
propertyContractInstance.Value = valueInstance;
}
JToken tagsArray = valueValue["tags"];
if (tagsArray != null && tagsArray.Type != JTokenType.Null)
{
foreach (JToken tagsValue in ((JArray)tagsArray))
{
propertyContractInstance.Tags.Add(((string)tagsValue));
}
}
JToken secretValue = valueValue["secret"];
if (secretValue != null && secretValue.Type != JTokenType.Null)
{
bool secretInstance = ((bool)secretValue);
propertyContractInstance.Secret = secretInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Patches specific property.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='propId'>
/// Required. Identifier of the property.
/// </param>
/// <param name='parameters'>
/// Required. Update parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </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> UpdateAsync(string resourceGroupName, string serviceName, string propId, PropertyUpdateParameters parameters, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (propId == null)
{
throw new ArgumentNullException("propId");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name != null && parameters.Name.Length > 256)
{
throw new ArgumentOutOfRangeException("parameters.Name");
}
if (parameters.Value != null && parameters.Value.Length > 4096)
{
throw new ArgumentOutOfRangeException("parameters.Value");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// 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("serviceName", serviceName);
tracingParameters.Add("propId", propId);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", 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.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/properties/";
url = url + Uri.EscapeDataString(propId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject propertyUpdateParametersValue = new JObject();
requestDoc = propertyUpdateParametersValue;
if (parameters.Name != null)
{
propertyUpdateParametersValue["name"] = parameters.Name;
}
if (parameters.Value != null)
{
propertyUpdateParametersValue["value"] = parameters.Value;
}
if (parameters.Tags != null)
{
if (parameters.Tags is ILazyCollection == false || ((ILazyCollection)parameters.Tags).IsInitialized)
{
JArray tagsArray = new JArray();
foreach (string tagsItem in parameters.Tags)
{
tagsArray.Add(tagsItem);
}
propertyUpdateParametersValue["tags"] = tagsArray;
}
}
if (parameters.Secret != null)
{
propertyUpdateParametersValue["secret"] = parameters.Secret.Value;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
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();
}
}
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Web.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.AspNet.MembersInjectors;
using Microsoft.Scripting.AspNet.Util;
namespace Microsoft.Scripting.AspNet {
internal interface IBuildProvider {
ScriptEngine GetScriptEngine();
string GetScriptCode();
BuildResult CreateBuildResult(CompiledCode compiledCode, string scriptVirtualPath);
}
internal static class EngineHelper {
private const string ScriptFolderName = "App_Script";
internal static string s_scriptFolder;
private static bool s_appScriptDirChanged;
private static ScriptRuntime s_scriptEnvironment;
private static string[] s_fileExtensions;
private static string[] s_languageIds;
static EngineHelper() {
// Add the App_Script folder to the path to allow script files to be imported from there
string appPath = System.Web.HttpRuntime.AppDomainAppPath;
s_scriptFolder = Path.Combine(appPath, ScriptFolderName);
var setup = ScriptRuntimeSetup.ReadConfiguration();
// Set the host type
setup.HostType = typeof(WebScriptHost);
setup.Options["SearchPaths"] = new string[] { s_scriptFolder };
s_scriptEnvironment = new ScriptRuntime(setup);
s_scriptEnvironment.LoadAssembly(typeof(ControlMembersInjector).Assembly); // for our member injectors
// Register for notifications when something in App_Script changes
FileChangeNotifier.Register(s_scriptFolder, OnAppScriptFileChanged);
List<string> fileExtensions = new List<string>();
foreach (var language in s_scriptEnvironment.Setup.LanguageSetups) {
fileExtensions.AddRange(language.FileExtensions);
}
s_fileExtensions = Array.ConvertAll(fileExtensions.ToArray(), e => e.ToLower());
List<string> simpleNames = new List<string>();
foreach (var language in s_scriptEnvironment.Setup.LanguageSetups) {
simpleNames.AddRange(language.Names);
}
s_languageIds = Array.ConvertAll(simpleNames.ToArray(), n => n.ToLower());
}
internal static ScriptRuntime ScriptRuntime { get { return s_scriptEnvironment; } }
internal static string[] FileExtensions { get { return s_fileExtensions; } }
internal static bool IsDLRLanguage(string language) {
return Array.IndexOf(s_languageIds, language.ToLower()) > -1;
}
internal static bool IsDLRLanguageExtension(string extension) {
return Array.IndexOf(s_fileExtensions, extension.ToLower()) > -1;
}
internal static ScriptEngine GetScriptEngineByExtension(string extension) {
return s_scriptEnvironment.GetEngineByFileExtension(extension);
}
internal static ScriptEngine GetScriptEngineByName(string language) {
return s_scriptEnvironment.GetEngine(language);
}
internal static BuildResult GetBuildResult(string virtualPath, IBuildProvider buildProvider) {
// If any script files in App_Scripts changed, they need to be reloaded
ReloadChangedScriptFiles();
virtualPath = VirtualPathUtility.ToAbsolute(virtualPath);
string cacheKey = virtualPath.ToLowerInvariant();
// Look up the cache before and after taking the lock
BuildResult result = (BuildResult)HttpRuntime.Cache[cacheKey];
if (result != null)
return result;
ScriptEngine scriptEngine = buildProvider.GetScriptEngine();
lock (typeof(EngineHelper)) {
result = (BuildResult)HttpRuntime.Cache[cacheKey];
if (result != null)
return result;
DateTime utcStart = DateTime.UtcNow;
CompiledCode compiledCode = null;
string scriptCode = buildProvider.GetScriptCode();
if (scriptCode != null) {
// We pass the physical path for debugging purpose
string physicalPath = HostingEnvironment.MapPath(virtualPath);
ScriptSource source = scriptEngine.CreateScriptSourceFromString(scriptCode, physicalPath, SourceCodeKind.File);
try {
compiledCode = source.Compile();
} catch (SyntaxErrorException e) {
EngineHelper.ThrowSyntaxErrorException(e);
}
}
// Note that we cache the result even if there is no script, to avoid having to check
// again later.
result = buildProvider.CreateBuildResult(compiledCode, virtualPath);
CacheDependency cacheDependency = HostingEnvironment.VirtualPathProvider.GetCacheDependency(
virtualPath, new Util.SingleObjectCollection(virtualPath), utcStart);
// Cache the result with a 5 minute sliding expiration
HttpRuntime.Cache.Insert(cacheKey, result, cacheDependency,
Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));
}
return result;
}
internal static void ExecuteCode(ScriptScope scope, CompiledCode compiledCode, string virtualPath) {
try {
compiledCode.Execute(scope);
} catch (SyntaxErrorException e) {
EngineHelper.ThrowSyntaxErrorException(e);
} catch (Exception e) {
if (!EngineHelper.ProcessRuntimeException(compiledCode.Engine, e, virtualPath))
throw;
}
}
internal static CompiledCode CompileExpression(string expr,
ScriptEngine scriptEngine, string scriptVirtualPath, int lineOffset) {
try {
return scriptEngine.CreateScriptSourceFromString(expr, SourceCodeKind.Expression).Compile();
} catch (SyntaxErrorException e) {
ThrowSyntaxErrorException(e, scriptVirtualPath, lineOffset + e.Line);
}
return null;
}
internal static CompiledCode CompileCodeDom(System.CodeDom.CodeMemberMethod code,
ScriptEngine scriptEngine) {
try {
return scriptEngine.CreateScriptSource(code).Compile();
} catch (SyntaxErrorException e) {
ThrowSyntaxErrorException(e);
}
return null;
}
internal static object EvaluateCompiledCode(CompiledCode compiledExpression, ScriptScope scope,
string defaultVirtualPath, int lineOffset) {
try {
return compiledExpression.Execute(scope);
} catch (Exception e) {
if (!ProcessRuntimeException(compiledExpression.Engine, e, defaultVirtualPath, lineOffset))
throw;
}
return null;
}
internal static void ExecuteCompiledCode(CompiledCode compiledExpression, ScriptScope module) {
try {
compiledExpression.Execute(module);
} catch (Exception e) {
if (!ProcessRuntimeException(compiledExpression.Engine, e, null))
throw;
}
}
// Call a method
internal static object CallMethod(ScriptEngine engine, DynamicFunction f, string defaultVirtualPath,
params object[] args) {
try {
return f.Invoke(engine, args);
} catch (Exception e) {
if (!ProcessRuntimeException(engine, e, defaultVirtualPath))
throw;
}
return null;
}
internal static bool ProcessRuntimeException(ScriptEngine engine, Exception e, string virtualPath) {
return ProcessRuntimeException(engine, e, virtualPath, 0 /*lineOffset*/);
}
internal static bool ProcessRuntimeException(ScriptEngine engine, Exception e, string defaultVirtualPath, int lineOffset) {
var frames = engine.GetService<ExceptionOperations>().GetStackFrames(e);
if (frames.Count == 0)
return false;
DynamicStackFrame frame = frames[0];
int line = frame.GetFileLineNumber();
// Get the physical path of the file where the exception occured, and attempt to get a
// virtual path from it
string physicalPath = frame.GetFileName();
string virtualPath = Misc.GetVirtualPathFromPhysicalPath(physicalPath);
// If we couldn't get one, use the passed in one, and adjust the line number
if (virtualPath == null) {
virtualPath = defaultVirtualPath;
line += lineOffset;
}
Misc.ThrowException(e.Message, e, virtualPath, line);
return true;
}
internal static void ThrowSyntaxErrorException(Microsoft.Scripting.SyntaxErrorException e) {
ThrowSyntaxErrorException(e, null, 1);
}
internal static void ThrowSyntaxErrorException(Microsoft.Scripting.SyntaxErrorException e,
string defaultVirtualPath, int defaultLine) {
// Try to get a virtual path
string virtualPath = Misc.GetVirtualPathFromPhysicalPath(e.GetSymbolDocumentName());
int line;
// If we couldn't get one, use the passed in path
if (virtualPath == null) {
virtualPath = defaultVirtualPath;
line = defaultLine;
} else {
line = e.Line;
}
Misc.ThrowException(null /*message*/, e, virtualPath, line);
}
private static void OnAppScriptFileChanged(string path) {
// Remember the fact that something in App_Script changed
s_appScriptDirChanged = true;
}
private static void ReloadChangedScriptFiles() {
// Nothing to do if no files changed
if (!s_appScriptDirChanged)
return;
// TODO: a new ScriptRuntime should be created instead
foreach (string path in Directory.GetFiles(s_scriptFolder)) {
string ext = Path.GetExtension(path);
if (IsDLRLanguageExtension(ext)) {
try {
s_scriptEnvironment.ExecuteFile(path);
} catch (SyntaxErrorException e) {
EngineHelper.ThrowSyntaxErrorException(e);
}
}
}
// Clear out the flag to mark that all the changes were processed
s_appScriptDirChanged = false;
}
}
// The base class of what we cache when we build a python file
internal class BuildResult {
private CompiledCode _compiledCode;
private string _scriptVirtualPath;
public BuildResult(CompiledCode compiledCode, string scriptVirtualPath) {
_scriptVirtualPath = scriptVirtualPath;
_compiledCode = compiledCode;
}
public CompiledCode CompiledCode { get { return _compiledCode; } }
public string ScriptVirtualPath { get { return _scriptVirtualPath; } }
}
abstract class TypeWithEventsBuildResult : BuildResult {
private bool _initMethodsCalled;
internal TypeWithEventsBuildResult(CompiledCode compiledCode, string scriptVirtualPath)
: base(compiledCode, scriptVirtualPath) { }
internal void InitMethods(Type type, ScriptScope moduleGlobals) {
if (!_initMethodsCalled) {
lock (this) {
if (!_initMethodsCalled) {
InitMethodsInternal(type, moduleGlobals);
_initMethodsCalled = true;
}
}
}
}
private void InitMethodsInternal(Type type, ScriptScope moduleGlobals) {
// If CompiledCode is null, there was no script to compile
if (CompiledCode == null)
return;
foreach (KeyValuePair<string, object> pair in moduleGlobals.GetItems()) {
// Wrap it as a dynamic object. It may not be something callable, and if it's not,
// it will fail when we try to call it.
DynamicFunction f = new DynamicFunction(pair.Value);
ProcessEventHandler(pair.Key, type, f);
}
}
internal abstract bool ProcessEventHandler(string handlerName, Type type, DynamicFunction f);
}
}
| |
// 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.Data.Common;
using System.Runtime.InteropServices;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.Data.SqlTypes
{
/// <summary>
/// Represents an 8-bit unsigned integer to be stored in
/// or retrieved from a database.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[XmlSchemaProvider("GetXsdType")]
public struct SqlByte : INullable, IComparable, IXmlSerializable
{
private bool _fNotNull; // false if null
private byte _value;
private static readonly int s_iBitNotByteMax = ~0xff;
// constructor
// construct a Null
private SqlByte(bool fNull)
{
_fNotNull = false;
_value = 0;
}
public SqlByte(byte value)
{
_value = value;
_fNotNull = true;
}
// INullable
public bool IsNull
{
get { return !_fNotNull; }
}
// property: Value
public byte Value
{
get
{
if (_fNotNull)
return _value;
else
throw new SqlNullValueException();
}
}
// Implicit conversion from byte to SqlByte
public static implicit operator SqlByte(byte x)
{
return new SqlByte(x);
}
// Explicit conversion from SqlByte to byte. Throw exception if x is Null.
public static explicit operator byte (SqlByte x)
{
return x.Value;
}
public override string ToString()
{
return IsNull ? SQLResource.NullString : _value.ToString((IFormatProvider)null);
}
public static SqlByte Parse(string s)
{
if (s == SQLResource.NullString)
return SqlByte.Null;
else
return new SqlByte(byte.Parse(s, null));
}
// Unary operators
public static SqlByte operator ~(SqlByte x)
{
return x.IsNull ? Null : new SqlByte(unchecked((byte)~x._value));
}
// Binary operators
// Arithmetic operators
public static SqlByte operator +(SqlByte x, SqlByte y)
{
if (x.IsNull || y.IsNull)
return Null;
int iResult = x._value + y._value;
if ((iResult & s_iBitNotByteMax) != 0)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlByte((byte)iResult);
}
public static SqlByte operator -(SqlByte x, SqlByte y)
{
if (x.IsNull || y.IsNull)
return Null;
int iResult = x._value - y._value;
if ((iResult & s_iBitNotByteMax) != 0)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlByte((byte)iResult);
}
public static SqlByte operator *(SqlByte x, SqlByte y)
{
if (x.IsNull || y.IsNull)
return Null;
int iResult = x._value * y._value;
if ((iResult & s_iBitNotByteMax) != 0)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlByte((byte)iResult);
}
public static SqlByte operator /(SqlByte x, SqlByte y)
{
if (x.IsNull || y.IsNull)
return Null;
if (y._value != 0)
{
return new SqlByte((byte)(x._value / y._value));
}
else
throw new DivideByZeroException(SQLResource.DivideByZeroMessage);
}
public static SqlByte operator %(SqlByte x, SqlByte y)
{
if (x.IsNull || y.IsNull)
return Null;
if (y._value != 0)
{
return new SqlByte((byte)(x._value % y._value));
}
else
throw new DivideByZeroException(SQLResource.DivideByZeroMessage);
}
// Bitwise operators
public static SqlByte operator &(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlByte((byte)(x._value & y._value));
}
public static SqlByte operator |(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlByte((byte)(x._value | y._value));
}
public static SqlByte operator ^(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlByte((byte)(x._value ^ y._value));
}
// Implicit conversions
// Implicit conversion from SqlBoolean to SqlByte
public static explicit operator SqlByte(SqlBoolean x)
{
return x.IsNull ? Null : new SqlByte(x.ByteValue);
}
// Explicit conversions
// Explicit conversion from SqlMoney to SqlByte
public static explicit operator SqlByte(SqlMoney x)
{
return x.IsNull ? Null : new SqlByte(checked((byte)x.ToInt32()));
}
// Explicit conversion from SqlInt16 to SqlByte
public static explicit operator SqlByte(SqlInt16 x)
{
if (x.IsNull)
return Null;
if (x.Value > byte.MaxValue || x.Value < byte.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
return x.IsNull ? Null : new SqlByte((byte)(x.Value));
}
// Explicit conversion from SqlInt32 to SqlByte
public static explicit operator SqlByte(SqlInt32 x)
{
if (x.IsNull)
return Null;
if (x.Value > byte.MaxValue || x.Value < byte.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
return x.IsNull ? Null : new SqlByte((byte)(x.Value));
}
// Explicit conversion from SqlInt64 to SqlByte
public static explicit operator SqlByte(SqlInt64 x)
{
if (x.IsNull)
return Null;
if (x.Value > byte.MaxValue || x.Value < byte.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
return x.IsNull ? Null : new SqlByte((byte)(x.Value));
}
// Explicit conversion from SqlSingle to SqlByte
public static explicit operator SqlByte(SqlSingle x)
{
if (x.IsNull)
return Null;
if (x.Value > byte.MaxValue || x.Value < byte.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
return x.IsNull ? Null : new SqlByte((byte)(x.Value));
}
// Explicit conversion from SqlDouble to SqlByte
public static explicit operator SqlByte(SqlDouble x)
{
if (x.IsNull)
return Null;
if (x.Value > byte.MaxValue || x.Value < byte.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
return x.IsNull ? Null : new SqlByte((byte)(x.Value));
}
// Explicit conversion from SqlDecimal to SqlByte
public static explicit operator SqlByte(SqlDecimal x)
{
return (SqlByte)(SqlInt32)x;
}
// Implicit conversion from SqlString to SqlByte
// Throws FormatException or OverflowException if necessary.
public static explicit operator SqlByte(SqlString x)
{
return x.IsNull ? Null : new SqlByte(byte.Parse(x.Value, null));
}
// Overloading comparison operators
public static SqlBoolean operator ==(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value == y._value);
}
public static SqlBoolean operator !=(SqlByte x, SqlByte y)
{
return !(x == y);
}
public static SqlBoolean operator <(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value < y._value);
}
public static SqlBoolean operator >(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value > y._value);
}
public static SqlBoolean operator <=(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value <= y._value);
}
public static SqlBoolean operator >=(SqlByte x, SqlByte y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value >= y._value);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator ~
public static SqlByte OnesComplement(SqlByte x)
{
return ~x;
}
// Alternative method for operator +
public static SqlByte Add(SqlByte x, SqlByte y)
{
return x + y;
}
// Alternative method for operator -
public static SqlByte Subtract(SqlByte x, SqlByte y)
{
return x - y;
}
// Alternative method for operator *
public static SqlByte Multiply(SqlByte x, SqlByte y)
{
return x * y;
}
// Alternative method for operator /
public static SqlByte Divide(SqlByte x, SqlByte y)
{
return x / y;
}
// Alternative method for operator %
public static SqlByte Mod(SqlByte x, SqlByte y)
{
return x % y;
}
public static SqlByte Modulus(SqlByte x, SqlByte y)
{
return x % y;
}
// Alternative method for operator &
public static SqlByte BitwiseAnd(SqlByte x, SqlByte y)
{
return x & y;
}
// Alternative method for operator |
public static SqlByte BitwiseOr(SqlByte x, SqlByte y)
{
return x | y;
}
// Alternative method for operator ^
public static SqlByte Xor(SqlByte x, SqlByte y)
{
return x ^ y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlByte x, SqlByte y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlByte x, SqlByte y)
{
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlByte x, SqlByte y)
{
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlByte x, SqlByte y)
{
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlByte x, SqlByte y)
{
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlByte x, SqlByte y)
{
return (x >= y);
}
// Alternative method for conversions.
public SqlBoolean ToSqlBoolean()
{
return (SqlBoolean)this;
}
public SqlDouble ToSqlDouble()
{
return this;
}
public SqlInt16 ToSqlInt16()
{
return this;
}
public SqlInt32 ToSqlInt32()
{
return this;
}
public SqlInt64 ToSqlInt64()
{
return this;
}
public SqlMoney ToSqlMoney()
{
return this;
}
public SqlDecimal ToSqlDecimal()
{
return this;
}
public SqlSingle ToSqlSingle()
{
return this;
}
public SqlString ToSqlString()
{
return (SqlString)this;
}
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
public int CompareTo(object value)
{
if (value is SqlByte)
{
SqlByte i = (SqlByte)value;
return CompareTo(i);
}
throw ADP.WrongType(value.GetType(), typeof(SqlByte));
}
public int CompareTo(SqlByte value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
if (this < value) return -1;
if (this > value) return 1;
return 0;
}
// Compares this instance with a specified object
public override bool Equals(object value)
{
if (!(value is SqlByte))
{
return false;
}
SqlByte i = (SqlByte)value;
if (i.IsNull || IsNull)
return (i.IsNull && IsNull);
else
return (this == i).Value;
}
// For hashing purpose
public override int GetHashCode()
{
return IsNull ? 0 : Value.GetHashCode();
}
XmlSchema IXmlSerializable.GetSchema() { return null; }
void IXmlSerializable.ReadXml(XmlReader reader)
{
string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
reader.ReadElementString();
_fNotNull = false;
}
else
{
_value = XmlConvert.ToByte(reader.ReadElementString());
_fNotNull = true;
}
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (IsNull)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
writer.WriteString(XmlConvert.ToString(_value));
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("unsignedByte", XmlSchema.Namespace);
}
public static readonly SqlByte Null = new SqlByte(true);
public static readonly SqlByte Zero = new SqlByte(0);
public static readonly SqlByte MinValue = new SqlByte(byte.MinValue);
public static readonly SqlByte MaxValue = new SqlByte(byte.MaxValue);
} // SqlByte
} // namespace System
| |
using System;
using System.Threading.Tasks;
using System.Linq;
using NUnit.Framework;
using TimeAndDate.Services.Tests;
using TimeAndDate.Services;
using TimeAndDate.Services.DataTypes.DST;
using TimeAndDate.Services.DataTypes;
namespace TimeAndDate.Services.Tests.IntegrationTests
{
[TestFixture()]
public class DSTServiceTests
{
[Test()]
public void Calling_DstService_Should_ReturnAllDst ()
{
// Arrage
var expectedReturnedCount = 121;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
var result = service.GetDaylightSavingTime ();
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.AreEqual (expectedReturnedCount, result.Count);
HasValidSampleCountry (sampleCountry);
}
[Test()]
public void Calling_DstService_WithYear_Should_ReturnAllDst ()
{
// Arrage
var year = 2014;
var expectedReturnedCount = 132;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
var result = service.GetDaylightSavingTime (year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.AreEqual (expectedReturnedCount, result.Count);
HasValidSampleCountry (sampleCountry);
}
[Test()]
public void Calling_DstService_WithCountry_Should_ReturnAllDst ()
{
// Arrage
var countryCode = "no";
var country = "Norway";
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
var result = service.GetDaylightSavingTime (countryCode);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsFalse (service.IncludeOnlyDstCountries);
Assert.AreEqual (country, sampleCountry.Region.Country.Name);
Assert.IsTrue (result.Count == 1);
HasValidSampleCountry (sampleCountry);
}
[Test()]
public void Calling_DstService_WithCountry_And_WithYear_Should_ReturnAllDst ()
{
// Arrage
var countryCode = "no";
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
var result = service.GetDaylightSavingTime (countryCode, year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsFalse (service.IncludeOnlyDstCountries);
Assert.IsTrue (result.Count == 1);
HasValidSampleCountry (sampleCountry);
}
[Test()]
public void Calling_DstService_WithoutPlacesForEveryCountry_Should_ReturnAllDstWithoutPlaces ()
{
// Arrage
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
service.IncludePlacesForEveryCountry = false;
var result = service.GetDaylightSavingTime (year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsFalse (service.IncludePlacesForEveryCountry);
Assert.IsTrue (result.All (x => x.Region.Locations.ToList().Count == 0));
HasValidSampleCountry (sampleCountry);
}
[Test()]
public void Calling_DstService_WithPlacesForEveryCountry_Should_ReturnAnyDstWithPlaces ()
{
// Arrage
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
var result = service.GetDaylightSavingTime (year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsTrue (service.IncludePlacesForEveryCountry);
Assert.IsTrue (result.Any (x => x.Region.Locations.ToList().Count > 0));
HasValidSampleCountry (sampleCountry);
}
[Test()]
public void Calling_DstService_WithoutTimeChanges_Should_NotReturnAnyTimeChanges ()
{
// Arrage
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
service.IncludeTimeChanges = false;
var result = service.GetDaylightSavingTime (year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsFalse (service.IncludeTimeChanges);
Assert.IsTrue (result.All (x => x.TimeChanges.ToList().Count == 0));
HasValidSampleCountry (sampleCountry);
}
[Test()]
public void Calling_DstService_WithTimeChanges_Should_ReturnAnyTimeChanges ()
{
// Arrage
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
service.IncludeTimeChanges = true;
var result = service.GetDaylightSavingTime (year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsTrue (service.IncludeTimeChanges);
Assert.IsTrue (result.Any (x => x.TimeChanges.ToList().Count > 0));
HasValidSampleCountry (sampleCountry);
}
[Test()]
public void Calling_DstService_WithOnlyDstCountries_Should_ReturnOnlyDstCountries ()
{
// Arrage
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
service.IncludeOnlyDstCountries = true;
var result = service.GetDaylightSavingTime (year);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsTrue (service.IncludeOnlyDstCountries);
Assert.AreEqual(132, result.Count);
HasValidSampleCountry (sampleCountry);
}
[Test()]
public void Calling_DstService_WithoutOnlyDstCountries_Should_ReturnAllCountries ()
{
// Arrage
var year = 2014;
// Act
var service = new DSTService (Config.AccessKey, Config.SecretKey);
service.IncludeOnlyDstCountries = false;
var result = service.GetDaylightSavingTime (year);
var noDstAllYear = result.Where (x => x.Special == DSTSpecialType.NoDaylightSavingTime);
var sampleCountry = result.SingleOrDefault (x => x.Region.Country.Name == "Norway");
// Assert
Assert.IsFalse (service.IncludeOnlyDstCountries);
Assert.AreEqual(348, result.Count);
Assert.Greater (noDstAllYear.Count(), 0);
HasValidSampleCountry (sampleCountry);
}
public void HasValidSampleCountry (DST norway)
{
Assert.AreEqual ("Oslo", norway.Region.BiggestPlace);
Assert.AreEqual ("no", norway.Region.Country.Id);
Assert.Greater (norway.DstEnd.Year, 1);
Assert.Greater (norway.DstStart.Year, 1);
Assert.AreEqual ("CEST", norway.DstTimezone.Abbrevation);
Assert.AreEqual (3600, norway.DstTimezone.BasicOffset);
Assert.AreEqual (3600, norway.DstTimezone.DSTOffset);
Assert.AreEqual (7200, norway.DstTimezone.TotalOffset);
Assert.AreEqual ("Central European Summer Time", norway.DstTimezone.Name);
Assert.AreEqual (2, norway.DstTimezone.Offset.Hours);
Assert.AreEqual (0, norway.DstTimezone.Offset.Minutes);
Assert.AreEqual ("CET", norway.StandardTimezone.Abbrevation);
Assert.AreEqual (3600, norway.StandardTimezone.BasicOffset);
Assert.AreEqual (0, norway.StandardTimezone.DSTOffset);
Assert.AreEqual (3600, norway.StandardTimezone.TotalOffset);
Assert.AreEqual ("Central European Time", norway.StandardTimezone.Name);
Assert.AreEqual (1, norway.StandardTimezone.Offset.Hours);
Assert.AreEqual (0, norway.StandardTimezone.Offset.Minutes);
Assert.IsNotNull (norway.Region.Description);
Assert.IsNotEmpty (norway.Region.Description);
}
}
}
| |
/*
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 java.io;
using java.lang;
using java.lang.reflect;
using org.junit;
using stab.query;
using cnatural.helpers;
namespace stab.reflection.test {
public class TypeBuilderTest {
[Test]
public void SimpleClassTest() {
// public class SimpleClass {
// public SimpleClass() {
// }
// }
var typeSystem = new Library(new String[0]);
var typeBuilder = typeSystem.defineType("stab/SimpleClass");
typeBuilder.setPublic(true);
typeBuilder.setBaseType(typeSystem.getType("java/lang/Object"));
createDefaultConstructor(typeBuilder);
var bytecode = typeBuilder.createType(typeSystem);
saveBytecode("SimpleClass", bytecode);
var loader = new DynamicClassLoader();
Class<?> c = loader.defineClass("stab.SimpleClass", bytecode);
loader.linkClass(c);
var cstr = c.getConstructor();
cstr.newInstance();
}
[Test]
public void classWithFieldTest() {
// public class ClassWithField {
// public int field;
// public ClassWithField() {
// field = 123;
// }
// }
var typeSystem = new Library(new String[0]);
var typeBuilder = typeSystem.defineType("stab/ClassWithField");
typeBuilder.setPublic(true);
typeBuilder.setBaseType(typeSystem.getType("java/lang/Object"));
var field = typeBuilder.defineField("field", typeSystem.IntType);
field.setPublic(true);
var methodBuilder = typeBuilder.defineMethod("<init>");
methodBuilder.setPublic(true);
methodBuilder.setReturnType(typeSystem.VoidType);
var generator = methodBuilder.getCodeGenerator();
generator.beginScope();
generator.emit(Opcode.Aload, generator.getLocal("this"));
generator.emit(Opcode.Invokespecial, typeBuilder.BaseType.getMethod("<init>", Query.empty<TypeInfo>()));
generator.emit(Opcode.Aload, generator.getLocal("this"));
generator.emit(Opcode.Ldc, (Object)123);
generator.emit(Opcode.Putfield, field);
generator.emit(Opcode.Return);
generator.endScope();
var bytecode = typeBuilder.createType(typeSystem);
saveBytecode("ClassWithField", bytecode);
var loader = new DynamicClassLoader();
var c = loader.defineClass("stab.ClassWithField", bytecode);
loader.linkClass(c);
var cstr = c.getConstructor();
var f = c.getField("field");
var instance = cstr.newInstance();
int value = f.getInt(instance);
Assert.assertEquals(123, value);
}
[Test]
public void classWithStaticFieldTest() {
// public class ClassWithStaticField {
// public static int FIELD = 123;
// public ClassWithStaticField() {
// }
// }
var typeSystem = new Library(new String[0]);
var typeBuilder = typeSystem.defineType("stab/ClassWithStaticField");
typeBuilder.setPublic(true);
typeBuilder.setBaseType(typeSystem.getType("java/lang/Object"));
var field = typeBuilder.defineField("FIELD", typeSystem.IntType);
field.setPublic(true);
field.setStatic(true);
field.setValue(new Integer(123));
createDefaultConstructor(typeBuilder);
var bytecode = typeBuilder.createType(typeSystem);
saveBytecode("ClassWithStaticField", bytecode);
var loader = new DynamicClassLoader();
var c = loader.defineClass("stab.ClassWithStaticField", bytecode);
loader.linkClass(c);
var f = c.getField("FIELD");
int value = f.getInt(null);
Assert.assertEquals(123, value);
}
[Test]
public void staticInnerClassTest() {
// public class StaticInnerClass {
// public static class Nested {
// public Nested() {
// }
// }
// public StaticInnerClass() {
// }
// }
var typeSystem = new Library(new String[0]);
var typeBuilder = typeSystem.defineType("stab/StaticInnerClass");
typeBuilder.setPublic(true);
typeBuilder.setBaseType(typeSystem.getType("java/lang/Object"));
createDefaultConstructor(typeBuilder);
var nestedType = typeBuilder.defineNestedType("Nested");
nestedType.setPublic(true);
nestedType.setNestedPublic(true);
nestedType.setBaseType(typeSystem.getType("java/lang/Object"));
createDefaultConstructor(nestedType);
var bytecode = typeBuilder.createType(typeSystem);
saveBytecode("StaticInnerClass", bytecode);
var innerBytecode = nestedType.createType(typeSystem);
saveBytecode("StaticInnerClass$Nested", innerBytecode);
var loader = new DynamicClassLoader();
var c = loader.defineClass("stab.StaticInnerClass", bytecode);
var nc = loader.defineClass("stab.StaticInnerClass$Nested", innerBytecode);
loader.linkClass(c);
loader.linkClass(nc);
var cstr = c.getConstructor();
cstr.newInstance();
var ncstr = nc.getConstructor();
ncstr.newInstance();
}
[Test]
public void genericClassTest() {
// public class GenericClass<T> {
// public T field;
// public GenericClass(T t) {
// this.field = t;
// }
// }
var typeSystem = new Library(new String[0]);
var typeBuilder = typeSystem.defineType("stab/GenericClass");
typeBuilder.setPublic(true);
typeBuilder.setBaseType(typeSystem.getType("java/lang/Object"));
var t = typeBuilder.addGenericArgument("T");
var field = typeBuilder.defineField("field", t);
field.setPublic(true);
var methodBuilder = typeBuilder.defineMethod("<init>");
methodBuilder.setPublic(true);
methodBuilder.setReturnType(typeSystem.VoidType);
methodBuilder.addParameter(t).setName("t");
var generator = methodBuilder.getCodeGenerator();
generator.beginScope();
generator.emit(Opcode.Aload, generator.getLocal("this"));
generator.emit(Opcode.Invokespecial, typeBuilder.BaseType.getMethod("<init>", Query.empty<TypeInfo>()));
generator.emit(Opcode.Aload, generator.getLocal("this"));
generator.emit(Opcode.Aload, generator.getLocal("t"));
generator.emit(Opcode.Putfield, field);
generator.emit(Opcode.Return);
generator.endScope();
var bytecode = typeBuilder.createType(typeSystem);
saveBytecode("GenericClass", bytecode);
var loader = new DynamicClassLoader();
var c = loader.defineClass("stab.GenericClass", bytecode);
loader.linkClass(c);
var cstr = c.getConstructor(typeof(Object));
var f = c.getField("field");
var instance = cstr.newInstance("TEST");
Assert.assertEquals("TEST", f.get(instance));
}
private void createDefaultConstructor(TypeBuilder typeBuilder) {
var methodBuilder = typeBuilder.defineMethod("<init>");
methodBuilder.setPublic(true);
methodBuilder.setReturnType(typeBuilder.Library.VoidType);
var generator = methodBuilder.getCodeGenerator();
generator.beginScope();
generator.emit(Opcode.Aload, generator.getLocal("this"));
generator.emit(Opcode.Invokespecial, typeBuilder.BaseType.getMethod("<init>", Query.empty<TypeInfo>()));
generator.emit(Opcode.Return);
generator.endScope();
}
private void saveBytecode(String className, byte[] bytecode) {
var generatedPath = PathHelper.combine(System.getProperty("user.dir"), "Tests/resources/TypeBuilderTest/stab");
var generatedDir = new File(generatedPath);
if (!generatedDir.exists()) {
generatedDir.mkdir();
}
var stream = new FileOutputStream(PathHelper.combine(generatedPath, className + ".class"));
stream.write(bytecode);
stream.close();
}
private class DynamicClassLoader : ClassLoader {
public Class<?> defineClass(String name, byte[] code) {
return defineClass(name, code, 0, sizeof(code));
}
public void linkClass(Class<?> c) {
resolveClass(c);
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmPOSsetup
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmPOSsetup() : base()
{
Load += frmPOSsetup_Load1;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.TextBox _txtInteger_0;
public System.Windows.Forms.TextBox _txtInteger_9;
public System.Windows.Forms.CheckBox chkCustBal;
public System.Windows.Forms.CheckBox chkConCashup;
public System.Windows.Forms.TextBox _txtPrice_0;
public System.Windows.Forms.CheckBox chkCheckCash;
public System.Windows.Forms.CheckBox chkPrintinvoice;
public System.Windows.Forms.CheckBox chkFinalizeCash;
public System.Windows.Forms.CheckBox chkDisplaySelling;
public System.Windows.Forms.CheckBox chkLearningPOS;
public System.Windows.Forms.CheckBox chkCurrency;
public System.Windows.Forms.CheckBox chkSerialTracking;
public System.Windows.Forms.CheckBox chkPrintA4;
public System.Windows.Forms.CheckBox chkSerialNumber;
public System.Windows.Forms.CheckBox chkOrderNumber;
public System.Windows.Forms.CheckBox chkCardNumber;
public System.Windows.Forms.CheckBox chkLogoffAuto;
public System.Windows.Forms.CheckBox chkReceiptBarcode;
public System.Windows.Forms.CheckBox chkBypassTender;
public System.Windows.Forms.CheckBox chkSecurityPopup;
public System.Windows.Forms.TextBox _txtFields_5;
public System.Windows.Forms.RadioButton _optPrint_2;
public System.Windows.Forms.RadioButton _optPrint_1;
public System.Windows.Forms.RadioButton _optPrint_0;
public System.Windows.Forms.GroupBox Frame1;
public System.Windows.Forms.CheckBox chkSearchAuto;
public System.Windows.Forms.TextBox _txtFields_9;
public System.Windows.Forms.CheckBox chkDividingLine;
public System.Windows.Forms.CheckBox chkOpenTill;
public System.Windows.Forms.CheckBox chkQuickCashup;
public System.Windows.Forms.CheckBox chkBlindCashup;
public System.Windows.Forms.RadioButton _optDeposits_2;
public System.Windows.Forms.RadioButton _optDeposits_1;
public System.Windows.Forms.RadioButton _optDeposits_0;
public System.Windows.Forms.GroupBox frmDeposits;
public System.Windows.Forms.CheckBox chkSets;
public System.Windows.Forms.CheckBox chkShrink;
public System.Windows.Forms.CheckBox chkSuppress;
public System.Windows.Forms.TextBox _txtFields_0;
public System.Windows.Forms.TextBox _txtFields_1;
public System.Windows.Forms.TextBox _txtFields_2;
public System.Windows.Forms.TextBox _txtFields_3;
public System.Windows.Forms.TextBox _txtFields_4;
public System.Windows.Forms.TextBox _txtInteger_5;
public System.Windows.Forms.TextBox _txtInteger_6;
public System.Windows.Forms.TextBox _txtInteger_7;
public System.Windows.Forms.TextBox _txtInteger_8;
public System.Windows.Forms.Button cmdCancel;
public System.Windows.Forms.Button cmdClose;
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.Label _lblLabels_10;
public System.Windows.Forms.Label _lblLabels_9;
public Microsoft.VisualBasic.PowerPacks.LineShape Line1;
public System.Windows.Forms.Label _lbl_0;
public System.Windows.Forms.Label _lblLabels_0;
public System.Windows.Forms.Label _lblLabels_1;
public System.Windows.Forms.Label _lblLabels_2;
public System.Windows.Forms.Label _lblLabels_3;
public System.Windows.Forms.Label _lblLabels_4;
public System.Windows.Forms.Label _lblLabels_5;
public System.Windows.Forms.Label _lblLabels_6;
public System.Windows.Forms.Label _lblLabels_7;
public System.Windows.Forms.Label _lblLabels_8;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2;
public System.Windows.Forms.Label _lbl_5;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_0;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_1;
public System.Windows.Forms.Label _lbl_1;
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents optDeposits As Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray
//Public WithEvents optPrint As Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray
//Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
//Public WithEvents txtInteger As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
//Public WithEvents txtPrice As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
public RectangleShapeArray Shape1;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this.Line1 = new Microsoft.VisualBasic.PowerPacks.LineShape();
this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._Shape1_0 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._Shape1_1 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._txtInteger_0 = new System.Windows.Forms.TextBox();
this._txtInteger_9 = new System.Windows.Forms.TextBox();
this.chkCustBal = new System.Windows.Forms.CheckBox();
this.chkConCashup = new System.Windows.Forms.CheckBox();
this._txtPrice_0 = new System.Windows.Forms.TextBox();
this.chkCheckCash = new System.Windows.Forms.CheckBox();
this.chkPrintinvoice = new System.Windows.Forms.CheckBox();
this.chkFinalizeCash = new System.Windows.Forms.CheckBox();
this.chkDisplaySelling = new System.Windows.Forms.CheckBox();
this.chkLearningPOS = new System.Windows.Forms.CheckBox();
this.chkCurrency = new System.Windows.Forms.CheckBox();
this.chkSerialTracking = new System.Windows.Forms.CheckBox();
this.chkPrintA4 = new System.Windows.Forms.CheckBox();
this.chkSerialNumber = new System.Windows.Forms.CheckBox();
this.chkOrderNumber = new System.Windows.Forms.CheckBox();
this.chkCardNumber = new System.Windows.Forms.CheckBox();
this.chkLogoffAuto = new System.Windows.Forms.CheckBox();
this.chkReceiptBarcode = new System.Windows.Forms.CheckBox();
this.chkBypassTender = new System.Windows.Forms.CheckBox();
this.chkSecurityPopup = new System.Windows.Forms.CheckBox();
this._txtFields_5 = new System.Windows.Forms.TextBox();
this.Frame1 = new System.Windows.Forms.GroupBox();
this._optPrint_2 = new System.Windows.Forms.RadioButton();
this._optPrint_1 = new System.Windows.Forms.RadioButton();
this._optPrint_0 = new System.Windows.Forms.RadioButton();
this.chkSearchAuto = new System.Windows.Forms.CheckBox();
this._txtFields_9 = new System.Windows.Forms.TextBox();
this.chkDividingLine = new System.Windows.Forms.CheckBox();
this.chkOpenTill = new System.Windows.Forms.CheckBox();
this.chkQuickCashup = new System.Windows.Forms.CheckBox();
this.chkBlindCashup = new System.Windows.Forms.CheckBox();
this.frmDeposits = new System.Windows.Forms.GroupBox();
this._optDeposits_2 = new System.Windows.Forms.RadioButton();
this._optDeposits_1 = new System.Windows.Forms.RadioButton();
this._optDeposits_0 = new System.Windows.Forms.RadioButton();
this.chkSets = new System.Windows.Forms.CheckBox();
this.chkShrink = new System.Windows.Forms.CheckBox();
this.chkSuppress = new System.Windows.Forms.CheckBox();
this._txtFields_0 = new System.Windows.Forms.TextBox();
this._txtFields_1 = new System.Windows.Forms.TextBox();
this._txtFields_2 = new System.Windows.Forms.TextBox();
this._txtFields_3 = new System.Windows.Forms.TextBox();
this._txtFields_4 = new System.Windows.Forms.TextBox();
this._txtInteger_5 = new System.Windows.Forms.TextBox();
this._txtInteger_6 = new System.Windows.Forms.TextBox();
this._txtInteger_7 = new System.Windows.Forms.TextBox();
this._txtInteger_8 = new System.Windows.Forms.TextBox();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdClose = new System.Windows.Forms.Button();
this._lblLabels_10 = new System.Windows.Forms.Label();
this._lblLabels_9 = new System.Windows.Forms.Label();
this._lbl_0 = new System.Windows.Forms.Label();
this._lblLabels_0 = new System.Windows.Forms.Label();
this._lblLabels_1 = new System.Windows.Forms.Label();
this._lblLabels_2 = new System.Windows.Forms.Label();
this._lblLabels_3 = new System.Windows.Forms.Label();
this._lblLabels_4 = new System.Windows.Forms.Label();
this._lblLabels_5 = new System.Windows.Forms.Label();
this._lblLabels_6 = new System.Windows.Forms.Label();
this._lblLabels_7 = new System.Windows.Forms.Label();
this._lblLabels_8 = new System.Windows.Forms.Label();
this._lbl_5 = new System.Windows.Forms.Label();
this._lbl_1 = new System.Windows.Forms.Label();
this.Frame1.SuspendLayout();
this.frmDeposits.SuspendLayout();
this.picButtons.SuspendLayout();
this.SuspendLayout();
//
//ShapeContainer1
//
this.ShapeContainer1.Location = new System.Drawing.Point(0, 0);
this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0);
this.ShapeContainer1.Name = "ShapeContainer1";
this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] {
this.Line1,
this._Shape1_2,
this._Shape1_0,
this._Shape1_1
});
this.ShapeContainer1.Size = new System.Drawing.Size(483, 670);
this.ShapeContainer1.TabIndex = 64;
this.ShapeContainer1.TabStop = false;
//
//Line1
//
this.Line1.BorderColor = System.Drawing.SystemColors.WindowText;
this.Line1.Name = "Line1";
this.Line1.X1 = 200;
this.Line1.X2 = 200;
this.Line1.Y1 = 324;
this.Line1.Y2 = 656;
//
//_Shape1_2
//
this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_2.FillColor = System.Drawing.Color.Black;
this._Shape1_2.Location = new System.Drawing.Point(12, 56);
this._Shape1_2.Name = "_Shape1_2";
this._Shape1_2.Size = new System.Drawing.Size(459, 113);
//
//_Shape1_0
//
this._Shape1_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Shape1_0.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_0.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_0.FillColor = System.Drawing.Color.Black;
this._Shape1_0.Location = new System.Drawing.Point(12, 184);
this._Shape1_0.Name = "_Shape1_0";
this._Shape1_0.Size = new System.Drawing.Size(459, 118);
//
//_Shape1_1
//
this._Shape1_1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Shape1_1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_1.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_1.FillColor = System.Drawing.Color.Black;
this._Shape1_1.Location = new System.Drawing.Point(12, 318);
this._Shape1_1.Name = "_Shape1_1";
this._Shape1_1.Size = new System.Drawing.Size(461, 345);
//
//_txtInteger_0
//
this._txtInteger_0.AcceptsReturn = true;
this._txtInteger_0.BackColor = System.Drawing.SystemColors.Window;
this._txtInteger_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtInteger_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtInteger_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtInteger_0.Location = new System.Drawing.Point(424, 631);
this._txtInteger_0.MaxLength = 2;
this._txtInteger_0.Name = "_txtInteger_0";
this._txtInteger_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtInteger_0.Size = new System.Drawing.Size(41, 19);
this._txtInteger_0.TabIndex = 63;
this._txtInteger_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//_txtInteger_9
//
this._txtInteger_9.AcceptsReturn = true;
this._txtInteger_9.BackColor = System.Drawing.SystemColors.Window;
this._txtInteger_9.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtInteger_9.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtInteger_9.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtInteger_9.Location = new System.Drawing.Point(422, 277);
this._txtInteger_9.MaxLength = 0;
this._txtInteger_9.Name = "_txtInteger_9";
this._txtInteger_9.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtInteger_9.Size = new System.Drawing.Size(42, 19);
this._txtInteger_9.TabIndex = 61;
this._txtInteger_9.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//chkCustBal
//
this.chkCustBal.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkCustBal.Cursor = System.Windows.Forms.Cursors.Default;
this.chkCustBal.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkCustBal.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkCustBal.Location = new System.Drawing.Point(22, 469);
this.chkCustBal.Name = "chkCustBal";
this.chkCustBal.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkCustBal.Size = new System.Drawing.Size(170, 19);
this.chkCustBal.TabIndex = 59;
this.chkCustBal.Text = "Print Customer Balances";
this.chkCustBal.UseVisualStyleBackColor = false;
//
//chkConCashup
//
this.chkConCashup.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkConCashup.Cursor = System.Windows.Forms.Cursors.Default;
this.chkConCashup.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkConCashup.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkConCashup.Location = new System.Drawing.Point(22, 449);
this.chkConCashup.Name = "chkConCashup";
this.chkConCashup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkConCashup.Size = new System.Drawing.Size(170, 19);
this.chkConCashup.TabIndex = 58;
this.chkConCashup.Text = "Activate Consolidate Cashup";
this.chkConCashup.UseVisualStyleBackColor = false;
//
//_txtPrice_0
//
this._txtPrice_0.AcceptsReturn = true;
this._txtPrice_0.BackColor = System.Drawing.SystemColors.Window;
this._txtPrice_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtPrice_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtPrice_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtPrice_0.Location = new System.Drawing.Point(376, 604);
this._txtPrice_0.MaxLength = 0;
this._txtPrice_0.Name = "_txtPrice_0";
this._txtPrice_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtPrice_0.Size = new System.Drawing.Size(88, 19);
this._txtPrice_0.TabIndex = 57;
this._txtPrice_0.Text = "0.00";
this._txtPrice_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//chkCheckCash
//
this.chkCheckCash.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkCheckCash.Cursor = System.Windows.Forms.Cursors.Default;
this.chkCheckCash.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkCheckCash.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkCheckCash.Location = new System.Drawing.Point(208, 606);
this.chkCheckCash.Name = "chkCheckCash";
this.chkCheckCash.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkCheckCash.Size = new System.Drawing.Size(177, 25);
this.chkCheckCash.TabIndex = 56;
this.chkCheckCash.Text = "Remove Excess Cash from Till";
this.chkCheckCash.UseVisualStyleBackColor = false;
//
//chkPrintinvoice
//
this.chkPrintinvoice.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkPrintinvoice.Cursor = System.Windows.Forms.Cursors.Default;
this.chkPrintinvoice.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkPrintinvoice.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkPrintinvoice.Location = new System.Drawing.Point(22, 432);
this.chkPrintinvoice.Name = "chkPrintinvoice";
this.chkPrintinvoice.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkPrintinvoice.Size = new System.Drawing.Size(173, 15);
this.chkPrintinvoice.TabIndex = 55;
this.chkPrintinvoice.Text = "Do Not Print VAT On Invoice";
this.chkPrintinvoice.UseVisualStyleBackColor = false;
//
//chkFinalizeCash
//
this.chkFinalizeCash.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkFinalizeCash.Cursor = System.Windows.Forms.Cursors.Default;
this.chkFinalizeCash.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkFinalizeCash.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkFinalizeCash.Location = new System.Drawing.Point(208, 590);
this.chkFinalizeCash.Name = "chkFinalizeCash";
this.chkFinalizeCash.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkFinalizeCash.Size = new System.Drawing.Size(215, 17);
this.chkFinalizeCash.TabIndex = 54;
this.chkFinalizeCash.Text = "Cash Sales have to be finalized (Touch)";
this.chkFinalizeCash.UseVisualStyleBackColor = false;
//
//chkDisplaySelling
//
this.chkDisplaySelling.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkDisplaySelling.Cursor = System.Windows.Forms.Cursors.Default;
this.chkDisplaySelling.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkDisplaySelling.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkDisplaySelling.Location = new System.Drawing.Point(208, 570);
this.chkDisplaySelling.Name = "chkDisplaySelling";
this.chkDisplaySelling.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkDisplaySelling.Size = new System.Drawing.Size(179, 19);
this.chkDisplaySelling.TabIndex = 53;
this.chkDisplaySelling.Text = "Display Selling Price";
this.chkDisplaySelling.UseVisualStyleBackColor = false;
//
//chkLearningPOS
//
this.chkLearningPOS.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkLearningPOS.Cursor = System.Windows.Forms.Cursors.Default;
this.chkLearningPOS.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkLearningPOS.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkLearningPOS.Location = new System.Drawing.Point(208, 551);
this.chkLearningPOS.Name = "chkLearningPOS";
this.chkLearningPOS.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkLearningPOS.Size = new System.Drawing.Size(179, 19);
this.chkLearningPOS.TabIndex = 52;
this.chkLearningPOS.Text = "POS Learning Mode";
this.chkLearningPOS.UseVisualStyleBackColor = false;
//
//chkCurrency
//
this.chkCurrency.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkCurrency.Cursor = System.Windows.Forms.Cursors.Default;
this.chkCurrency.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkCurrency.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkCurrency.Location = new System.Drawing.Point(-184, 578);
this.chkCurrency.Name = "chkCurrency";
this.chkCurrency.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkCurrency.Size = new System.Drawing.Size(187, 19);
this.chkCurrency.TabIndex = 51;
this.chkCurrency.Text = "Enable International Currency";
this.chkCurrency.UseVisualStyleBackColor = false;
this.chkCurrency.Visible = false;
//
//chkSerialTracking
//
this.chkSerialTracking.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkSerialTracking.Cursor = System.Windows.Forms.Cursors.Default;
this.chkSerialTracking.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkSerialTracking.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkSerialTracking.Location = new System.Drawing.Point(-176, 464);
this.chkSerialTracking.Name = "chkSerialTracking";
this.chkSerialTracking.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkSerialTracking.Size = new System.Drawing.Size(186, 17);
this.chkSerialTracking.TabIndex = 50;
this.chkSerialTracking.Text = "Enable Serial Tracking in Sales";
this.chkSerialTracking.UseVisualStyleBackColor = false;
this.chkSerialTracking.Visible = false;
//
//chkPrintA4
//
this.chkPrintA4.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkPrintA4.Cursor = System.Windows.Forms.Cursors.Default;
this.chkPrintA4.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkPrintA4.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkPrintA4.Location = new System.Drawing.Point(208, 534);
this.chkPrintA4.Name = "chkPrintA4";
this.chkPrintA4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkPrintA4.Size = new System.Drawing.Size(258, 17);
this.chkPrintA4.TabIndex = 49;
this.chkPrintA4.Text = "Print A4 Invoice with Exclusive Total";
this.chkPrintA4.UseVisualStyleBackColor = false;
//
//chkSerialNumber
//
this.chkSerialNumber.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkSerialNumber.Cursor = System.Windows.Forms.Cursors.Default;
this.chkSerialNumber.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkSerialNumber.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkSerialNumber.Location = new System.Drawing.Point(22, 522);
this.chkSerialNumber.Name = "chkSerialNumber";
this.chkSerialNumber.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkSerialNumber.Size = new System.Drawing.Size(161, 19);
this.chkSerialNumber.TabIndex = 48;
this.chkSerialNumber.Text = "Serial Reference Number";
this.chkSerialNumber.UseVisualStyleBackColor = false;
//
//chkOrderNumber
//
this.chkOrderNumber.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkOrderNumber.Cursor = System.Windows.Forms.Cursors.Default;
this.chkOrderNumber.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkOrderNumber.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkOrderNumber.Location = new System.Drawing.Point(22, 504);
this.chkOrderNumber.Name = "chkOrderNumber";
this.chkOrderNumber.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkOrderNumber.Size = new System.Drawing.Size(161, 19);
this.chkOrderNumber.TabIndex = 47;
this.chkOrderNumber.Text = "Order Number Reference";
this.chkOrderNumber.UseVisualStyleBackColor = false;
//
//chkCardNumber
//
this.chkCardNumber.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkCardNumber.Cursor = System.Windows.Forms.Cursors.Default;
this.chkCardNumber.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkCardNumber.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkCardNumber.Location = new System.Drawing.Point(22, 486);
this.chkCardNumber.Name = "chkCardNumber";
this.chkCardNumber.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkCardNumber.Size = new System.Drawing.Size(169, 19);
this.chkCardNumber.TabIndex = 46;
this.chkCardNumber.Text = "Card Number Reference";
this.chkCardNumber.UseVisualStyleBackColor = false;
//
//chkLogoffAuto
//
this.chkLogoffAuto.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkLogoffAuto.Cursor = System.Windows.Forms.Cursors.Default;
this.chkLogoffAuto.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkLogoffAuto.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkLogoffAuto.Location = new System.Drawing.Point(208, 520);
this.chkLogoffAuto.Name = "chkLogoffAuto";
this.chkLogoffAuto.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkLogoffAuto.Size = new System.Drawing.Size(258, 13);
this.chkLogoffAuto.TabIndex = 45;
this.chkLogoffAuto.Text = "Automatically Logoff Cashier";
this.chkLogoffAuto.UseVisualStyleBackColor = false;
//
//chkReceiptBarcode
//
this.chkReceiptBarcode.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkReceiptBarcode.Cursor = System.Windows.Forms.Cursors.Default;
this.chkReceiptBarcode.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkReceiptBarcode.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkReceiptBarcode.Location = new System.Drawing.Point(208, 502);
this.chkReceiptBarcode.Name = "chkReceiptBarcode";
this.chkReceiptBarcode.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkReceiptBarcode.Size = new System.Drawing.Size(258, 13);
this.chkReceiptBarcode.TabIndex = 44;
this.chkReceiptBarcode.Text = "Print Barcodes on receipts";
this.chkReceiptBarcode.UseVisualStyleBackColor = false;
//
//chkBypassTender
//
this.chkBypassTender.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkBypassTender.Cursor = System.Windows.Forms.Cursors.Default;
this.chkBypassTender.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkBypassTender.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkBypassTender.Location = new System.Drawing.Point(208, 484);
this.chkBypassTender.Name = "chkBypassTender";
this.chkBypassTender.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkBypassTender.Size = new System.Drawing.Size(258, 13);
this.chkBypassTender.TabIndex = 43;
this.chkBypassTender.Text = "Bypass Cashout Tender";
this.chkBypassTender.UseVisualStyleBackColor = false;
//
//chkSecurityPopup
//
this.chkSecurityPopup.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkSecurityPopup.Cursor = System.Windows.Forms.Cursors.Default;
this.chkSecurityPopup.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkSecurityPopup.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkSecurityPopup.Location = new System.Drawing.Point(208, 466);
this.chkSecurityPopup.Name = "chkSecurityPopup";
this.chkSecurityPopup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkSecurityPopup.Size = new System.Drawing.Size(258, 13);
this.chkSecurityPopup.TabIndex = 42;
this.chkSecurityPopup.Text = "Bypass Security Popup";
this.chkSecurityPopup.UseVisualStyleBackColor = false;
//
//_txtFields_5
//
this._txtFields_5.AcceptsReturn = true;
this._txtFields_5.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_5.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_5.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_5.Location = new System.Drawing.Point(160, 240);
this._txtFields_5.MaxLength = 0;
this._txtFields_5.Name = "_txtFields_5";
this._txtFields_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_5.Size = new System.Drawing.Size(39, 19);
this._txtFields_5.TabIndex = 41;
this._txtFields_5.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtFields_5.Visible = false;
//
//Frame1
//
this.Frame1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.Frame1.Controls.Add(this._optPrint_2);
this.Frame1.Controls.Add(this._optPrint_1);
this.Frame1.Controls.Add(this._optPrint_0);
this.Frame1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.Frame1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Frame1.Location = new System.Drawing.Point(22, 188);
this.Frame1.Name = "Frame1";
this.Frame1.Padding = new System.Windows.Forms.Padding(0);
this.Frame1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Frame1.Size = new System.Drawing.Size(191, 79);
this.Frame1.TabIndex = 7;
this.Frame1.TabStop = false;
this.Frame1.Text = "Print POS Transaction";
//
//_optPrint_2
//
this._optPrint_2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._optPrint_2.Cursor = System.Windows.Forms.Cursors.Default;
this._optPrint_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._optPrint_2.Location = new System.Drawing.Point(15, 36);
this._optPrint_2.Name = "_optPrint_2";
this._optPrint_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optPrint_2.Size = new System.Drawing.Size(112, 16);
this._optPrint_2.TabIndex = 9;
this._optPrint_2.TabStop = true;
this._optPrint_2.Text = "No";
this._optPrint_2.UseVisualStyleBackColor = false;
//
//_optPrint_1
//
this._optPrint_1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._optPrint_1.Cursor = System.Windows.Forms.Cursors.Default;
this._optPrint_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._optPrint_1.Location = new System.Drawing.Point(15, 18);
this._optPrint_1.Name = "_optPrint_1";
this._optPrint_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optPrint_1.Size = new System.Drawing.Size(112, 16);
this._optPrint_1.TabIndex = 8;
this._optPrint_1.TabStop = true;
this._optPrint_1.Text = "Yes";
this._optPrint_1.UseVisualStyleBackColor = false;
//
//_optPrint_0
//
this._optPrint_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._optPrint_0.Cursor = System.Windows.Forms.Cursors.Default;
this._optPrint_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._optPrint_0.Location = new System.Drawing.Point(15, 54);
this._optPrint_0.Name = "_optPrint_0";
this._optPrint_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optPrint_0.Size = new System.Drawing.Size(112, 16);
this._optPrint_0.TabIndex = 10;
this._optPrint_0.TabStop = true;
this._optPrint_0.Text = "Ask";
this._optPrint_0.UseVisualStyleBackColor = false;
//
//chkSearchAuto
//
this.chkSearchAuto.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkSearchAuto.Cursor = System.Windows.Forms.Cursors.Default;
this.chkSearchAuto.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkSearchAuto.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkSearchAuto.Location = new System.Drawing.Point(208, 448);
this.chkSearchAuto.Name = "chkSearchAuto";
this.chkSearchAuto.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkSearchAuto.Size = new System.Drawing.Size(256, 13);
this.chkSearchAuto.TabIndex = 23;
this.chkSearchAuto.Text = "Automatically search for stock items";
this.chkSearchAuto.UseVisualStyleBackColor = false;
//
//_txtFields_9
//
this._txtFields_9.AcceptsReturn = true;
this._txtFields_9.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_9.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_9.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_9.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_9.Location = new System.Drawing.Point(402, 426);
this._txtFields_9.MaxLength = 0;
this._txtFields_9.Name = "_txtFields_9";
this._txtFields_9.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_9.Size = new System.Drawing.Size(43, 19);
this._txtFields_9.TabIndex = 38;
this._txtFields_9.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtFields_9.Visible = false;
//
//chkDividingLine
//
this.chkDividingLine.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkDividingLine.Cursor = System.Windows.Forms.Cursors.Default;
this.chkDividingLine.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkDividingLine.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkDividingLine.Location = new System.Drawing.Point(208, 432);
this.chkDividingLine.Name = "chkDividingLine";
this.chkDividingLine.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkDividingLine.Size = new System.Drawing.Size(258, 13);
this.chkDividingLine.TabIndex = 22;
this.chkDividingLine.Text = "Print Dividing line on Receipt";
this.chkDividingLine.UseVisualStyleBackColor = false;
//
//chkOpenTill
//
this.chkOpenTill.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkOpenTill.Cursor = System.Windows.Forms.Cursors.Default;
this.chkOpenTill.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkOpenTill.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkOpenTill.Location = new System.Drawing.Point(208, 414);
this.chkOpenTill.Name = "chkOpenTill";
this.chkOpenTill.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkOpenTill.Size = new System.Drawing.Size(258, 13);
this.chkOpenTill.TabIndex = 21;
this.chkOpenTill.Text = "Only Open Till for Cash Transaction";
this.chkOpenTill.UseVisualStyleBackColor = false;
//
//chkQuickCashup
//
this.chkQuickCashup.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkQuickCashup.Cursor = System.Windows.Forms.Cursors.Default;
this.chkQuickCashup.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkQuickCashup.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkQuickCashup.Location = new System.Drawing.Point(208, 396);
this.chkQuickCashup.Name = "chkQuickCashup";
this.chkQuickCashup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkQuickCashup.Size = new System.Drawing.Size(258, 13);
this.chkQuickCashup.TabIndex = 40;
this.chkQuickCashup.Text = "Quick Cashup";
this.chkQuickCashup.UseVisualStyleBackColor = false;
//
//chkBlindCashup
//
this.chkBlindCashup.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkBlindCashup.Cursor = System.Windows.Forms.Cursors.Default;
this.chkBlindCashup.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkBlindCashup.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkBlindCashup.Location = new System.Drawing.Point(208, 378);
this.chkBlindCashup.Name = "chkBlindCashup";
this.chkBlindCashup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkBlindCashup.Size = new System.Drawing.Size(258, 13);
this.chkBlindCashup.TabIndex = 39;
this.chkBlindCashup.Text = "Blind Cashup";
this.chkBlindCashup.UseVisualStyleBackColor = false;
//
//frmDeposits
//
this.frmDeposits.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.frmDeposits.Controls.Add(this._optDeposits_2);
this.frmDeposits.Controls.Add(this._optDeposits_1);
this.frmDeposits.Controls.Add(this._optDeposits_0);
this.frmDeposits.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.frmDeposits.ForeColor = System.Drawing.SystemColors.ControlText;
this.frmDeposits.Location = new System.Drawing.Point(22, 344);
this.frmDeposits.Name = "frmDeposits";
this.frmDeposits.Padding = new System.Windows.Forms.Padding(0);
this.frmDeposits.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.frmDeposits.Size = new System.Drawing.Size(166, 82);
this.frmDeposits.TabIndex = 16;
this.frmDeposits.TabStop = false;
this.frmDeposits.Text = "Deposits";
//
//_optDeposits_2
//
this._optDeposits_2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._optDeposits_2.Cursor = System.Windows.Forms.Cursors.Default;
this._optDeposits_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._optDeposits_2.Location = new System.Drawing.Point(8, 54);
this._optDeposits_2.Name = "_optDeposits_2";
this._optDeposits_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optDeposits_2.Size = new System.Drawing.Size(145, 13);
this._optDeposits_2.TabIndex = 19;
this._optDeposits_2.TabStop = true;
this._optDeposits_2.Text = "Automatically Determined";
this._optDeposits_2.UseVisualStyleBackColor = false;
//
//_optDeposits_1
//
this._optDeposits_1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._optDeposits_1.Cursor = System.Windows.Forms.Cursors.Default;
this._optDeposits_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._optDeposits_1.Location = new System.Drawing.Point(8, 36);
this._optDeposits_1.Name = "_optDeposits_1";
this._optDeposits_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optDeposits_1.Size = new System.Drawing.Size(145, 13);
this._optDeposits_1.TabIndex = 18;
this._optDeposits_1.TabStop = true;
this._optDeposits_1.Text = "Pricing Group Two";
this._optDeposits_1.UseVisualStyleBackColor = false;
//
//_optDeposits_0
//
this._optDeposits_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._optDeposits_0.Cursor = System.Windows.Forms.Cursors.Default;
this._optDeposits_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._optDeposits_0.Location = new System.Drawing.Point(8, 16);
this._optDeposits_0.Name = "_optDeposits_0";
this._optDeposits_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optDeposits_0.Size = new System.Drawing.Size(145, 13);
this._optDeposits_0.TabIndex = 17;
this._optDeposits_0.TabStop = true;
this._optDeposits_0.Text = "Pricing Group One";
this._optDeposits_0.UseVisualStyleBackColor = false;
//
//chkSets
//
this.chkSets.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkSets.Cursor = System.Windows.Forms.Cursors.Default;
this.chkSets.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkSets.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkSets.Location = new System.Drawing.Point(208, 324);
this.chkSets.Name = "chkSets";
this.chkSets.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkSets.Size = new System.Drawing.Size(250, 13);
this.chkSets.TabIndex = 20;
this.chkSets.Text = "Automatically Build Sets";
this.chkSets.UseVisualStyleBackColor = false;
//
//chkShrink
//
this.chkShrink.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkShrink.Cursor = System.Windows.Forms.Cursors.Default;
this.chkShrink.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkShrink.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkShrink.Location = new System.Drawing.Point(208, 342);
this.chkShrink.Name = "chkShrink";
this.chkShrink.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkShrink.Size = new System.Drawing.Size(256, 13);
this.chkShrink.TabIndex = 36;
this.chkShrink.Text = "Automatically Build Shrinks";
this.chkShrink.UseVisualStyleBackColor = false;
//
//chkSuppress
//
this.chkSuppress.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkSuppress.Cursor = System.Windows.Forms.Cursors.Default;
this.chkSuppress.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkSuppress.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkSuppress.Location = new System.Drawing.Point(208, 360);
this.chkSuppress.Name = "chkSuppress";
this.chkSuppress.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkSuppress.Size = new System.Drawing.Size(258, 13);
this.chkSuppress.TabIndex = 37;
this.chkSuppress.Text = "Switch on Suppress After Cashup";
this.chkSuppress.UseVisualStyleBackColor = false;
//
//_txtFields_0
//
this._txtFields_0.AcceptsReturn = true;
this._txtFields_0.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_0.Location = new System.Drawing.Point(240, 60);
this._txtFields_0.MaxLength = 0;
this._txtFields_0.Name = "_txtFields_0";
this._txtFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_0.Size = new System.Drawing.Size(225, 19);
this._txtFields_0.TabIndex = 1;
//
//_txtFields_1
//
this._txtFields_1.AcceptsReturn = true;
this._txtFields_1.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_1.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_1.Location = new System.Drawing.Point(240, 81);
this._txtFields_1.MaxLength = 0;
this._txtFields_1.Name = "_txtFields_1";
this._txtFields_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_1.Size = new System.Drawing.Size(225, 19);
this._txtFields_1.TabIndex = 2;
//
//_txtFields_2
//
this._txtFields_2.AcceptsReturn = true;
this._txtFields_2.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_2.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_2.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_2.Location = new System.Drawing.Point(240, 103);
this._txtFields_2.MaxLength = 0;
this._txtFields_2.Name = "_txtFields_2";
this._txtFields_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_2.Size = new System.Drawing.Size(225, 19);
this._txtFields_2.TabIndex = 3;
//
//_txtFields_3
//
this._txtFields_3.AcceptsReturn = true;
this._txtFields_3.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_3.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_3.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_3.Location = new System.Drawing.Point(240, 124);
this._txtFields_3.MaxLength = 0;
this._txtFields_3.Name = "_txtFields_3";
this._txtFields_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_3.Size = new System.Drawing.Size(225, 19);
this._txtFields_3.TabIndex = 4;
//
//_txtFields_4
//
this._txtFields_4.AcceptsReturn = true;
this._txtFields_4.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_4.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_4.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_4.Location = new System.Drawing.Point(240, 145);
this._txtFields_4.MaxLength = 0;
this._txtFields_4.Name = "_txtFields_4";
this._txtFields_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_4.Size = new System.Drawing.Size(225, 19);
this._txtFields_4.TabIndex = 5;
//
//_txtInteger_5
//
this._txtInteger_5.AcceptsReturn = true;
this._txtInteger_5.BackColor = System.Drawing.SystemColors.Window;
this._txtInteger_5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtInteger_5.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtInteger_5.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtInteger_5.Location = new System.Drawing.Point(422, 188);
this._txtInteger_5.MaxLength = 0;
this._txtInteger_5.Name = "_txtInteger_5";
this._txtInteger_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtInteger_5.Size = new System.Drawing.Size(42, 19);
this._txtInteger_5.TabIndex = 11;
this._txtInteger_5.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//_txtInteger_6
//
this._txtInteger_6.AcceptsReturn = true;
this._txtInteger_6.BackColor = System.Drawing.SystemColors.Window;
this._txtInteger_6.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtInteger_6.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtInteger_6.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtInteger_6.Location = new System.Drawing.Point(422, 210);
this._txtInteger_6.MaxLength = 0;
this._txtInteger_6.Name = "_txtInteger_6";
this._txtInteger_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtInteger_6.Size = new System.Drawing.Size(42, 19);
this._txtInteger_6.TabIndex = 12;
this._txtInteger_6.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//_txtInteger_7
//
this._txtInteger_7.AcceptsReturn = true;
this._txtInteger_7.BackColor = System.Drawing.SystemColors.Window;
this._txtInteger_7.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtInteger_7.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtInteger_7.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtInteger_7.Location = new System.Drawing.Point(422, 232);
this._txtInteger_7.MaxLength = 0;
this._txtInteger_7.Name = "_txtInteger_7";
this._txtInteger_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtInteger_7.Size = new System.Drawing.Size(42, 19);
this._txtInteger_7.TabIndex = 13;
this._txtInteger_7.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//_txtInteger_8
//
this._txtInteger_8.AcceptsReturn = true;
this._txtInteger_8.BackColor = System.Drawing.SystemColors.Window;
this._txtInteger_8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtInteger_8.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtInteger_8.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtInteger_8.Location = new System.Drawing.Point(422, 254);
this._txtInteger_8.MaxLength = 0;
this._txtInteger_8.Name = "_txtInteger_8";
this._txtInteger_8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtInteger_8.Size = new System.Drawing.Size(42, 19);
this._txtInteger_8.TabIndex = 14;
this._txtInteger_8.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//picButtons
//
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Controls.Add(this.cmdCancel);
this.picButtons.Controls.Add(this.cmdClose);
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.Name = "picButtons";
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Size = new System.Drawing.Size(483, 39);
this.picButtons.TabIndex = 26;
//
//cmdCancel
//
this.cmdCancel.BackColor = System.Drawing.SystemColors.Control;
this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdCancel.Location = new System.Drawing.Point(12, 2);
this.cmdCancel.Name = "cmdCancel";
this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdCancel.Size = new System.Drawing.Size(73, 29);
this.cmdCancel.TabIndex = 25;
this.cmdCancel.TabStop = false;
this.cmdCancel.Text = "&Undo";
this.cmdCancel.UseVisualStyleBackColor = false;
//
//cmdClose
//
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Location = new System.Drawing.Point(396, 2);
this.cmdClose.Name = "cmdClose";
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.TabIndex = 24;
this.cmdClose.TabStop = false;
this.cmdClose.Text = "E&xit";
this.cmdClose.UseVisualStyleBackColor = false;
//
//_lblLabels_10
//
this._lblLabels_10.AutoSize = true;
this._lblLabels_10.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_10.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_10.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_10.Location = new System.Drawing.Point(208, 632);
this._lblLabels_10.Name = "_lblLabels_10";
this._lblLabels_10.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_10.Size = new System.Drawing.Size(221, 13);
this._lblLabels_10.TabIndex = 62;
this._lblLabels_10.Text = "Cent Rounding: default=5 Cent, max=50 Cent";
//
//_lblLabels_9
//
this._lblLabels_9.AutoSize = true;
this._lblLabels_9.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_9.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_9.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_9.Location = new System.Drawing.Point(317, 277);
this._lblLabels_9.Name = "_lblLabels_9";
this._lblLabels_9.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_9.Size = new System.Drawing.Size(106, 13);
this._lblLabels_9.TabIndex = 60;
this._lblLabels_9.Text = "No of Payouts Prints:";
this._lblLabels_9.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lbl_0
//
this._lbl_0.AutoSize = true;
this._lbl_0.BackColor = System.Drawing.Color.Transparent;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_0.Location = new System.Drawing.Point(12, 170);
this._lbl_0.Name = "_lbl_0";
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.Size = new System.Drawing.Size(120, 14);
this._lbl_0.TabIndex = 6;
this._lbl_0.Text = "&2. Transaction Prints";
//
//_lblLabels_0
//
this._lblLabels_0.AutoSize = true;
this._lblLabels_0.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_0.Location = new System.Drawing.Point(20, 64);
this._lblLabels_0.Name = "_lblLabels_0";
this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_0.Size = new System.Drawing.Size(135, 13);
this._lblLabels_0.TabIndex = 27;
this._lblLabels_0.Text = "First Receipt Heading Line:";
this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_1
//
this._lblLabels_1.AutoSize = true;
this._lblLabels_1.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_1.Location = new System.Drawing.Point(28, 84);
this._lblLabels_1.Name = "_lblLabels_1";
this._lblLabels_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_1.Size = new System.Drawing.Size(153, 13);
this._lblLabels_1.TabIndex = 28;
this._lblLabels_1.Text = "Second Receipt Heading Line:";
this._lblLabels_1.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_2
//
this._lblLabels_2.AutoSize = true;
this._lblLabels_2.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_2.Location = new System.Drawing.Point(18, 106);
this._lblLabels_2.Name = "_lblLabels_2";
this._lblLabels_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_2.Size = new System.Drawing.Size(140, 13);
this._lblLabels_2.TabIndex = 29;
this._lblLabels_2.Text = "Third Receipt Heading Line:";
this._lblLabels_2.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_3
//
this._lblLabels_3.AutoSize = true;
this._lblLabels_3.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_3.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_3.Location = new System.Drawing.Point(20, 128);
this._lblLabels_3.Name = "_lblLabels_3";
this._lblLabels_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_3.Size = new System.Drawing.Size(80, 13);
this._lblLabels_3.TabIndex = 30;
this._lblLabels_3.Text = "Receipt Footer:";
this._lblLabels_3.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_4
//
this._lblLabels_4.AutoSize = true;
this._lblLabels_4.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_4.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_4.Location = new System.Drawing.Point(26, 148);
this._lblLabels_4.Name = "_lblLabels_4";
this._lblLabels_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_4.Size = new System.Drawing.Size(71, 13);
this._lblLabels_4.TabIndex = 31;
this._lblLabels_4.Text = "VAT Number:";
this._lblLabels_4.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_5
//
this._lblLabels_5.AutoSize = true;
this._lblLabels_5.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_5.Location = new System.Drawing.Point(217, 190);
this._lblLabels_5.Name = "_lblLabels_5";
this._lblLabels_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_5.Size = new System.Drawing.Size(152, 13);
this._lblLabels_5.TabIndex = 32;
this._lblLabels_5.Text = "No of Account Payment Prints:";
this._lblLabels_5.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_6
//
this._lblLabels_6.AutoSize = true;
this._lblLabels_6.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_6.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_6.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_6.Location = new System.Drawing.Point(223, 211);
this._lblLabels_6.Name = "_lblLabels_6";
this._lblLabels_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_6.Size = new System.Drawing.Size(132, 13);
this._lblLabels_6.TabIndex = 33;
this._lblLabels_6.Text = "No of Account Sale Prints:";
this._lblLabels_6.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_7
//
this._lblLabels_7.AutoSize = true;
this._lblLabels_7.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_7.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_7.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_7.Location = new System.Drawing.Point(219, 232);
this._lblLabels_7.Name = "_lblLabels_7";
this._lblLabels_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_7.Size = new System.Drawing.Size(138, 13);
this._lblLabels_7.TabIndex = 34;
this._lblLabels_7.Text = "Cash Before Delivery Prints:";
this._lblLabels_7.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_8
//
this._lblLabels_8.AutoSize = true;
this._lblLabels_8.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_8.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_8.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_8.Location = new System.Drawing.Point(222, 254);
this._lblLabels_8.Name = "_lblLabels_8";
this._lblLabels_8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_8.Size = new System.Drawing.Size(129, 13);
this._lblLabels_8.TabIndex = 35;
this._lblLabels_8.Text = "No of Consignment Prints:";
this._lblLabels_8.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lbl_5
//
this._lbl_5.AutoSize = true;
this._lbl_5.BackColor = System.Drawing.Color.Transparent;
this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_5.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_5.Location = new System.Drawing.Point(15, 42);
this._lbl_5.Name = "_lbl_5";
this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_5.Size = new System.Drawing.Size(100, 14);
this._lbl_5.TabIndex = 0;
this._lbl_5.Text = "&1. Receipt Details";
//
//_lbl_1
//
this._lbl_1.AutoSize = true;
this._lbl_1.BackColor = System.Drawing.Color.Transparent;
this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_1.Location = new System.Drawing.Point(12, 304);
this._lbl_1.Name = "_lbl_1";
this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_1.Size = new System.Drawing.Size(118, 14);
this._lbl_1.TabIndex = 15;
this._lbl_1.Text = "&3. Other Parameters";
//
//frmPOSsetup
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224)));
this.ClientSize = new System.Drawing.Size(483, 670);
this.ControlBox = false;
this.Controls.Add(this._txtInteger_0);
this.Controls.Add(this._txtInteger_9);
this.Controls.Add(this.chkCustBal);
this.Controls.Add(this.chkConCashup);
this.Controls.Add(this._txtPrice_0);
this.Controls.Add(this.chkCheckCash);
this.Controls.Add(this.chkPrintinvoice);
this.Controls.Add(this.chkFinalizeCash);
this.Controls.Add(this.chkDisplaySelling);
this.Controls.Add(this.chkLearningPOS);
this.Controls.Add(this.chkCurrency);
this.Controls.Add(this.chkSerialTracking);
this.Controls.Add(this.chkPrintA4);
this.Controls.Add(this.chkSerialNumber);
this.Controls.Add(this.chkOrderNumber);
this.Controls.Add(this.chkCardNumber);
this.Controls.Add(this.chkLogoffAuto);
this.Controls.Add(this.chkReceiptBarcode);
this.Controls.Add(this.chkBypassTender);
this.Controls.Add(this.chkSecurityPopup);
this.Controls.Add(this._txtFields_5);
this.Controls.Add(this.Frame1);
this.Controls.Add(this.chkSearchAuto);
this.Controls.Add(this._txtFields_9);
this.Controls.Add(this.chkDividingLine);
this.Controls.Add(this.chkOpenTill);
this.Controls.Add(this.chkQuickCashup);
this.Controls.Add(this.chkBlindCashup);
this.Controls.Add(this.frmDeposits);
this.Controls.Add(this.chkSets);
this.Controls.Add(this.chkShrink);
this.Controls.Add(this.chkSuppress);
this.Controls.Add(this._txtFields_0);
this.Controls.Add(this._txtFields_1);
this.Controls.Add(this._txtFields_2);
this.Controls.Add(this._txtFields_3);
this.Controls.Add(this._txtFields_4);
this.Controls.Add(this._txtInteger_5);
this.Controls.Add(this._txtInteger_6);
this.Controls.Add(this._txtInteger_7);
this.Controls.Add(this._txtInteger_8);
this.Controls.Add(this.picButtons);
this.Controls.Add(this._lblLabels_10);
this.Controls.Add(this._lblLabels_9);
this.Controls.Add(this._lbl_0);
this.Controls.Add(this._lblLabels_0);
this.Controls.Add(this._lblLabels_1);
this.Controls.Add(this._lblLabels_2);
this.Controls.Add(this._lblLabels_3);
this.Controls.Add(this._lblLabels_4);
this.Controls.Add(this._lblLabels_5);
this.Controls.Add(this._lblLabels_6);
this.Controls.Add(this._lblLabels_7);
this.Controls.Add(this._lblLabels_8);
this.Controls.Add(this._lbl_5);
this.Controls.Add(this._lbl_1);
this.Controls.Add(this.ShapeContainer1);
this.Cursor = System.Windows.Forms.Cursors.Default;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.KeyPreview = true;
this.Location = new System.Drawing.Point(73, 22);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmPOSsetup";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Point Of Sale Parameters";
this.Frame1.ResumeLayout(false);
this.frmDeposits.ResumeLayout(false);
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
namespace FakeItEasy
{
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
#if FEATURE_NETCORE_REFLECTION
using System.Reflection;
#endif
using System.Threading;
/// <summary>
/// Provides validation extensions for <see cref="IArgumentConstraintManager{T}"/>.
/// </summary>
public static class ArgumentConstraintManagerExtensions
{
/// <summary>
/// Constrains an argument so that it must be null (Nothing in VB).
/// </summary>
/// <typeparam name="T">The type of the argument.</typeparam>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <returns>A dummy argument value.</returns>
public static T IsNull<T>(this IArgumentConstraintManager<T> manager) where T : class
{
Guard.AgainstNull(manager, nameof(manager));
return manager.Matches(x => x is null, x => x.Write("NULL"));
}
/// <summary>
/// Constrains an argument so that it must be null (Nothing in VB).
/// </summary>
/// <typeparam name="T">The type of the argument.</typeparam>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <returns>A dummy argument value.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is by design to support the fluent API.")]
public static T? IsNull<T>(this IArgumentConstraintManager<T?> manager) where T : struct
{
Guard.AgainstNull(manager, nameof(manager));
return manager.Matches(x => x is null, x => x.Write("NULL"));
}
/// <summary>
/// Constrains an argument so that it must not be null (Nothing in VB).
/// </summary>
/// <typeparam name="T">The type of the argument.</typeparam>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <returns>A dummy argument value.</returns>
public static T IsNotNull<T>(this INegatableArgumentConstraintManager<T> manager) where T : class
{
Guard.AgainstNull(manager, nameof(manager));
return manager.Matches(x => x is object, x => x.Write("NOT NULL"));
}
/// <summary>
/// Constrains an argument so that it must not be null (Nothing in VB).
/// </summary>
/// <typeparam name="T">The type of the argument.</typeparam>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <returns>A dummy argument value.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is by design to support the fluent API.")]
public static T? IsNotNull<T>(this INegatableArgumentConstraintManager<T?> manager) where T : struct
{
Guard.AgainstNull(manager, nameof(manager));
return manager.Matches(x => x is object, x => x.Write("NOT NULL"));
}
/// <summary>
/// Constrains the string argument to contain the specified text.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The string the argument string should contain.</param>
/// <returns>A dummy argument value.</returns>
public static string Contains(this IArgumentConstraintManager<string> manager, string value)
{
Guard.AgainstNull(manager, nameof(manager));
Guard.AgainstNull(value, nameof(value));
#if FEATURE_STRING_CONTAINS_COMPARISONTYPE
return manager.NullCheckedMatches(x => x.Contains(value, StringComparison.CurrentCulture), x => x.Write("string that contains ").WriteArgumentValue(value));
#else
return manager.NullCheckedMatches(x => x.Contains(value), x => x.Write("string that contains ").WriteArgumentValue(value));
#endif
}
/// <summary>
/// Constrains the sequence so that it must contain the specified value.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The value the collection should contain.</param>
/// <typeparam name="T">The type of sequence.</typeparam>
/// <returns>A dummy argument value.</returns>
public static T Contains<T>(this IArgumentConstraintManager<T> manager, object? value) where T : IEnumerable
{
Guard.AgainstNull(manager, nameof(manager));
return manager.NullCheckedMatches(
x => x.Cast<object>().Contains(value),
x => x.Write("sequence that contains the value ").WriteArgumentValue(value));
}
/// <summary>
/// Constrains the string so that it must start with the specified value.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The value the string should start with.</param>
/// <returns>A dummy argument value.</returns>
public static string StartsWith(this IArgumentConstraintManager<string> manager, string value)
{
Guard.AgainstNull(manager, nameof(manager));
Guard.AgainstNull(value, nameof(value));
return manager.NullCheckedMatches(x => x.StartsWith(value, StringComparison.Ordinal), x => x.Write("string that starts with ").WriteArgumentValue(value));
}
/// <summary>
/// Constrains the string so that it must end with the specified value.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The value the string should end with.</param>
/// <returns>A dummy argument value.</returns>
public static string EndsWith(this IArgumentConstraintManager<string> manager, string value)
{
Guard.AgainstNull(manager, nameof(manager));
Guard.AgainstNull(value, nameof(value));
return manager.NullCheckedMatches(x => x.EndsWith(value, StringComparison.Ordinal), x => x.Write("string that ends with ").WriteArgumentValue(value));
}
/// <summary>
/// Constrains the string so that it must be null or empty.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <returns>A dummy argument value.</returns>
public static string IsNullOrEmpty(this IArgumentConstraintManager<string> manager)
{
Guard.AgainstNull(manager, nameof(manager));
return manager.Matches(x => string.IsNullOrEmpty(x), "NULL or string.Empty");
}
/// <summary>
/// Constrains argument value so that it must be greater than the specified value.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The value the string should start with.</param>
/// <typeparam name="T">The type of argument to constrain.</typeparam>
/// <returns>A dummy argument value.</returns>
public static T IsGreaterThan<T>(this IArgumentConstraintManager<T> manager, T value) where T : IComparable
{
Guard.AgainstNull(manager, nameof(manager));
return manager.Matches(x => x.CompareTo(value) > 0, x => x.Write("greater than ").WriteArgumentValue(value));
}
/// <summary>
/// The tested argument collection should contain the same elements as the
/// specified collection, in the same order.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="values">The sequence to test against.</param>
/// <typeparam name="T">The type of argument to constrain.</typeparam>
/// <returns>A dummy argument value.</returns>
public static T IsSameSequenceAs<T>(this IArgumentConstraintManager<T> manager, IEnumerable values) where T : IEnumerable
{
Guard.AgainstNull(manager, nameof(manager));
Guard.AgainstNull(values, nameof(values));
var list = values.AsList();
return manager.NullCheckedMatches(
x => x.Cast<object>().SequenceEqual(list),
x => x.WriteArgumentValues(list));
}
/// <summary>
/// The tested argument collection should contain the same elements as the
/// specified collection, in the same order.
/// </summary>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="values">The sequence to test against.</param>
/// <typeparam name="T">The type of argument to constrain.</typeparam>
/// <returns>A dummy argument value.</returns>
public static T IsSameSequenceAs<T>(this IArgumentConstraintManager<T> manager, params object?[] values) where T : IEnumerable
{
Guard.AgainstNull(manager, nameof(manager));
Guard.AgainstNull(values, nameof(values));
return manager.IsSameSequenceAs((IEnumerable)values);
}
/// <summary>
/// Tests that the IEnumerable contains no items.
/// </summary>
/// <typeparam name="T">The type of argument.</typeparam>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <returns>A dummy argument value.</returns>
public static T IsEmpty<T>(this IArgumentConstraintManager<T> manager) where T : IEnumerable
{
Guard.AgainstNull(manager, nameof(manager));
return manager.NullCheckedMatches(
x => !x.Cast<object>().Any(),
x => x.Write("empty collection"));
}
/// <summary>
/// Tests that the passed in argument is equal to the specified value.
/// </summary>
/// <typeparam name="T">The type of the argument.</typeparam>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The value to compare to.</param>
/// <returns>A dummy argument value.</returns>
public static T IsEqualTo<T>(this IArgumentConstraintManager<T> manager, T value)
{
Guard.AgainstNull(manager, nameof(manager));
return manager.Matches(
x => object.Equals(value, x),
x => x.Write("equal to ").WriteArgumentValue(value));
}
/// <summary>
/// Tests that the passed in argument is the same instance (reference) as the specified value.
/// </summary>
/// <typeparam name="T">The type of the argument.</typeparam>
/// <param name="manager">The constraint manager to match the constraint.</param>
/// <param name="value">The reference to compare to.</param>
/// <returns>A dummy argument value.</returns>
public static T IsSameAs<T>(this IArgumentConstraintManager<T> manager, T value)
{
Guard.AgainstNull(manager, nameof(manager));
return manager.Matches(
x => object.ReferenceEquals(value, x),
x => x.Write("same as ").WriteArgumentValue(value));
}
/// <summary>
/// Constrains the argument to be of the specified type.
/// </summary>
/// <typeparam name="T">The type of argument in the method signature.</typeparam>
/// <param name="manager">The constraint manager.</param>
/// <param name="type">The type to constrain the argument with.</param>
/// <returns>A dummy value.</returns>
public static T IsInstanceOf<T>(this IArgumentConstraintManager<T> manager, Type type)
{
Guard.AgainstNull(manager, nameof(manager));
Guard.AgainstNull(type, nameof(type));
return manager.Matches(x => x is object && type.IsAssignableFrom(x.GetType()), description => description.Write("Instance of ").Write(type.ToString()));
}
/// <summary>
/// Constrains the argument with a predicate.
/// </summary>
/// <param name="manager">
/// The constraint manager.
/// </param>
/// <param name="predicate">
/// The predicate that should constrain the argument.
/// </param>
/// <param name="description">
/// A human readable description of the constraint.
/// </param>
/// <typeparam name="T">
/// The type of argument in the method signature.
/// </typeparam>
/// <returns>
/// A dummy argument value.
/// </returns>
public static T Matches<T>(this IArgumentConstraintManager<T> manager, Func<T, bool> predicate, string description)
{
Guard.AgainstNull(manager, nameof(manager));
Guard.AgainstNull(predicate, nameof(predicate));
Guard.AgainstNull(description, nameof(description));
return manager.Matches(predicate, x => x.Write(description));
}
/// <summary>
/// Constrains the argument with a predicate.
/// </summary>
/// <param name="manager">
/// The constraint manager.
/// </param>
/// <param name="predicate">
/// The predicate that should constrain the argument.
/// </param>
/// <param name="descriptionFormat">
/// A human readable description of the constraint format string.
/// </param>
/// <param name="args">
/// Arguments for the format string.
/// </param>
/// <typeparam name="T">
/// The type of argument in the method signature.
/// </typeparam>
/// <returns>
/// A dummy argument value.
/// </returns>
public static T Matches<T>(this IArgumentConstraintManager<T> manager, Func<T, bool> predicate, string descriptionFormat, params object?[] args)
{
Guard.AgainstNull(manager, nameof(manager));
Guard.AgainstNull(predicate, nameof(predicate));
Guard.AgainstNull(descriptionFormat, nameof(descriptionFormat));
Guard.AgainstNull(args, nameof(args));
return manager.Matches(predicate, x => x.Write(descriptionFormat, args));
}
/// <summary>
/// Constrains the argument with a predicate.
/// </summary>
/// <param name="manager">
/// The constraint manager.
/// </param>
/// <param name="predicate">
/// The predicate that should constrain the argument.
/// </param>
/// <typeparam name="T">
/// The type of argument in the method signature.
/// </typeparam>
/// <returns>
/// A dummy argument value.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Appropriate for Linq expressions.")]
public static T Matches<T>(this IArgumentConstraintManager<T> manager, Expression<Func<T, bool>> predicate)
{
Guard.AgainstNull(manager, nameof(manager));
Guard.AgainstNull(predicate, nameof(predicate));
return manager.Matches(predicate.Compile(), predicate.ToString());
}
/// <summary>
/// Constrains the argument to be not null (Nothing in VB) and to match
/// the specified predicate.
/// </summary>
/// <typeparam name="T">The type of the argument to constrain.</typeparam>
/// <param name="manager">The constraint manager.</param>
/// <param name="predicate">The predicate that constrains non null values.</param>
/// <param name="descriptionWriter">An action that writes a description of the constraint
/// to the output.</param>
/// <returns>A dummy argument value.</returns>
public static T NullCheckedMatches<T>(this IArgumentConstraintManager<T> manager, Func<T, bool> predicate, Action<IOutputWriter> descriptionWriter)
{
Guard.AgainstNull(manager, nameof(manager));
Guard.AgainstNull(predicate, nameof(predicate));
Guard.AgainstNull(descriptionWriter, nameof(descriptionWriter));
return manager.Matches(
x => x is object && predicate(x),
descriptionWriter);
}
/// <summary>
/// Constrains the <see cref="CancellationToken"/> argument to be canceled (<c>IsCancellationRequested</c> is true).
/// </summary>
/// <param name="manager">The constraint manager.</param>
/// <returns>A dummy argument value.</returns>
public static CancellationToken IsCanceled(this IArgumentConstraintManager<CancellationToken> manager)
{
Guard.AgainstNull(manager, nameof(manager));
return manager.Matches(
token => token.IsCancellationRequested,
x => x.Write("canceled cancellation token"));
}
/// <summary>
/// Constrains the <see cref="CancellationToken"/> argument to be not canceled (<c>IsCancellationRequested</c> is false).
/// </summary>
/// <param name="manager">The constraint manager.</param>
/// <returns>A dummy argument value.</returns>
public static CancellationToken IsNotCanceled(this INegatableArgumentConstraintManager<CancellationToken> manager)
{
Guard.AgainstNull(manager, nameof(manager));
return manager.Matches(
token => !token.IsCancellationRequested,
x => x.Write("non-canceled cancellation token"));
}
}
}
| |
// 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.Metadata.ManagedReference
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Reflection;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Plugins;
internal abstract class CacheBase
{
private static readonly int CleanupIntervalInDays = 5; // 5 days and clean up
private static readonly int CleanupMaxCount = 100; // 100 items before clean up
private static readonly int CleanupTo = 10; // clean up and keep latest 10 items
private Dictionary<string, BuildInfo> _configs = new Dictionary<string, BuildInfo>();
private readonly string _path;
public static readonly string AssemblyName;
static CacheBase()
{
AssemblyName = Assembly.GetExecutingAssembly().GetName().ToString();
}
public CacheBase(string path)
{
_path = path;
_configs = ReadCacheFile(path);
}
public BuildInfo GetValidConfig(IEnumerable<string> inputProjects)
{
var key = StringExtension.GetNormalizedFullPathKey(inputProjects);
return GetConfig(key);
}
public void SaveToCache(IEnumerable<string> inputProjects, IDictionary<string, List<string>> containedFiles, DateTime triggeredTime, string outputFolder, IList<string> fileRelativePaths, bool shouldSkipMarkup, IDictionary<string, string> msbuildProperties)
{
var key = StringExtension.GetNormalizedFullPathKey(inputProjects);
DateTime completeTime = DateTime.UtcNow;
BuildInfo info = new BuildInfo
{
InputFilesKey = key,
ContainedFiles = containedFiles,
TriggeredUtcTime = triggeredTime,
CompleteUtcTime = completeTime,
OutputFolder = StringExtension.ToNormalizedFullPath(Path.Combine(EnvironmentContext.OutputDirectory, outputFolder)),
RelatvieOutputFiles = StringExtension.GetNormalizedPathList(fileRelativePaths),
BuildAssembly = AssemblyName,
ShouldSkipMarkup = shouldSkipMarkup,
MSBuildProperties = msbuildProperties,
};
this.SaveConfig(key, info);
}
#region Virtual Methods
protected virtual BuildInfo GetConfig(string key)
{
BuildInfo buildInfo = this.ReadConfig(key);
if (buildInfo != null)
{
var checksum = buildInfo.CheckSum;
try
{
var resultCorrupted = GetMd5(buildInfo.OutputFolder, buildInfo.RelatvieOutputFiles) != checksum;
if (!resultCorrupted && checksum != null)
{
return buildInfo;
}
else
{
Logger.Log(LogLevel.Warning, $"Cache for {key} in {_path} is corrupted");
}
}
catch (Exception e)
{
Logger.Log(LogLevel.Warning, $"Cache for {key} in {_path} is not valid: {e.Message}");
}
}
return null;
}
protected virtual BuildInfo ReadConfig(string key)
{
BuildInfo info;
if (_configs.TryGetValue(key, out info)) return info;
return null;
}
protected virtual void SaveConfig(string key, BuildInfo config)
{
config.CheckSum = GetMd5(config.OutputFolder, config.RelatvieOutputFiles);
_configs[key] = config;
CleanupConfig();
JsonUtility.Serialize(_path, _configs);
}
protected virtual void CleanupConfig()
{
// Copy oldkeys to a new list
var oldKeys = _configs.Where(s => s.Value.TriggeredUtcTime.CompareTo(DateTime.UtcNow.AddDays(-CleanupIntervalInDays)) < 1).ToList();
foreach (var key in oldKeys)
{
_configs.Remove(key.Key);
}
if (_configs.Count > CleanupMaxCount)
{
var cleanUpTo = Math.Min(CleanupMaxCount, CleanupTo);
// Cleanup the old ones
_configs = _configs.OrderByDescending(s => s.Value.TriggeredUtcTime).Take(cleanUpTo).ToDictionary(s => s.Key, s => s.Value);
}
}
#endregion
#region Private Methodes
private static Dictionary<string, BuildInfo> ReadCacheFile(string path)
{
try
{
if (File.Exists(path))
{
return JsonUtility.Deserialize<Dictionary<string, BuildInfo>>(path);
}
}
catch
{
}
return new Dictionary<string, BuildInfo>();
}
private static string GetMd5(string rootFolder, IEnumerable<string> relativeFilePath)
{
if (relativeFilePath == null) return null;
var files = (from p in relativeFilePath select Path.Combine(rootFolder, p)).ToList();
MD5 md5 = MD5.Create();
using (FileCollectionStream reader = new FileCollectionStream(files))
{
var hash = md5.ComputeHash(reader);
return BitConverter.ToString(hash).Replace("-", "");
}
}
class FileCollectionStream : Stream
{
private IEnumerator<string> _fileEnumerator;
private FileStream _stream;
public FileCollectionStream(IEnumerable<string> files)
{
if (files == null) _fileEnumerator = null;
else _fileEnumerator = files.GetEnumerator();
}
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override long Length
{
get
{
throw new NotSupportedException();
}
}
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
public override void Flush()
{
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
if (_fileEnumerator == null) return 0;
if (_stream == null)
{
if (!TryGetNextFileStream(out _stream)) return 0;
}
int readed;
while (true)
{
readed = _stream.Read(buffer, offset, count);
if (readed == 0)
{
// Dispose current stream before fetching the next one
_stream.Dispose();
if (!TryGetNextFileStream(out _stream)) return 0;
}
else
{
return readed;
}
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_fileEnumerator != null) _fileEnumerator.Dispose();
if (_stream != null) _stream.Dispose();
}
base.Dispose(disposing);
}
private bool TryGetNextFileStream(out FileStream stream)
{
var next = _fileEnumerator.MoveNext();
if (!next)
{
stream = null;
return false;
}
stream = new FileStream(_fileEnumerator.Current, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return true;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Decorator.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true),
NormalizedName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Email = table.Column<string>(nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
LockoutEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
NormalizedEmail = table.Column<string>(nullable: true),
NormalizedUserName = table.Column<string>(nullable: true),
PasswordHash = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
SecurityStamp = table.Column<string>(nullable: true),
TwoFactorEnabled = table.Column<bool>(nullable: false),
UserName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName");
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_UserId",
table: "AspNetUserRoles",
column: "UserId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| |
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 Service.Areas.HelpPage.ModelDescriptions;
using Service.Areas.HelpPage.Models;
namespace Service.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);
}
}
}
}
| |
/*
' Copyright (c) 2011 DotNetNuke Corporation
' All rights reserved.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
'
*/
using System;
using System.Collections.Generic;
//using System.Xml;
using System.Linq;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Data;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Entities.Users.Social;
using DotNetNuke.Security.Roles;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Journal;
using DotNetNuke.Services.Search.Controllers;
using DotNetNuke.Services.Search.Entities;
namespace DotNetNuke.Modules.Journal.Components {
/// -----------------------------------------------------------------------------
/// <summary>
/// The Controller class for Journal
/// </summary>
/// -----------------------------------------------------------------------------
//uncomment the interfaces to add the support.
public class FeatureController : ModuleSearchBase, IModuleSearchResultController
{
#region Optional Interfaces
/// -----------------------------------------------------------------------------
/// <summary>
/// ExportModule implements the IPortable ExportModule Interface
/// </summary>
/// <param name="moduleID">The Id of the module to be exported</param>
/// -----------------------------------------------------------------------------
public string ExportModule(int moduleID) {
//string strXML = "";
//List<JournalInfo> colJournals = GetJournals(ModuleID);
//if (colJournals.Count != 0)
//{
// strXML += "<Journals>";
// foreach (JournalInfo objJournal in colJournals)
// {
// strXML += "<Journal>";
// strXML += "<content>" + DotNetNuke.Common.Utilities.XmlUtils.XMLEncode(objJournal.Content) + "</content>";
// strXML += "</Journal>";
// }
// strXML += "</Journals>";
//}
//return strXML;
throw new NotImplementedException("The method or operation is not implemented.");
}
/// -----------------------------------------------------------------------------
/// <summary>
/// ImportModule implements the IPortable ImportModule Interface
/// </summary>
/// <param name="moduleID">The Id of the module to be imported</param>
/// <param name="content">The content to be imported</param>
/// <param name="version">The version of the module to be imported</param>
/// <param name="userId">The Id of the user performing the import</param>
/// -----------------------------------------------------------------------------
public void ImportModule(int moduleID, string content, string version, int userId) {
//XmlNode xmlJournals = DotNetNuke.Common.Globals.GetContent(Content, "Journals");
//foreach (XmlNode xmlJournal in xmlJournals.SelectNodes("Journal"))
//{
// JournalInfo objJournal = new JournalInfo();
// objJournal.ModuleId = ModuleID;
// objJournal.Content = xmlJournal.SelectSingleNode("content").InnerText;
// objJournal.CreatedByUser = UserID;
// AddJournal(objJournal);
//}
throw new NotImplementedException("The method or operation is not implemented.");
}
/// -----------------------------------------------------------------------------
/// <summary>
/// UpgradeModule implements the IUpgradeable Interface
/// </summary>
/// <param name="version">The current version of the module</param>
/// -----------------------------------------------------------------------------
public string UpgradeModule(string version) {
throw new NotImplementedException("The method or operation is not implemented.");
}
#endregion
#region Implement ModuleSearchBase
public override IList<SearchDocument> GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDateUtc)
{
var searchDocuments = new Dictionary<string, SearchDocument>();
var lastJournalId = Null.NullInteger;
try
{
while (true)
{
using (var reader = DataProvider.Instance()
.ExecuteReader("Journal_GetSearchItems", moduleInfo.PortalID,
moduleInfo.TabModuleID, beginDateUtc, lastJournalId, Constants.SearchBatchSize))
{
var journalIds = new Dictionary<int, int>();
while (reader.Read())
{
var journalId = Convert.ToInt32(reader["JournalId"]);
//var journalTypeId = reader["JournalTypeId"].ToString();
var userId = Convert.ToInt32(reader["UserId"]);
var dateUpdated = Convert.ToDateTime(reader["DateUpdated"]);
var profileId = reader["ProfileId"].ToString();
var groupId = reader["GroupId"].ToString();
var title = reader["Title"].ToString();
var summary = reader["Summary"].ToString();
var securityKey = reader["SecurityKey"].ToString();
var tabId = reader["TabId"].ToString();
var tabModuleId = reader["ModuleId"].ToString();
var key = string.Format("JI_{0}", journalId);
if (searchDocuments.ContainsKey(key))
{
searchDocuments[key].UniqueKey +=
string.Format(",{0}", securityKey);
}
else
{
var searchDocument = new SearchDocument
{
UniqueKey = string.Format("JI_{0}_{1}", journalId, securityKey),
Body = summary,
ModifiedTimeUtc = dateUpdated,
Title = title,
AuthorUserId = userId,
Keywords = new Dictionary<string, string>
{
{"TabId", tabId},
{"TabModuleId", tabModuleId},
{"ProfileId", profileId},
{"GroupId", groupId}
}
};
searchDocuments.Add(key, searchDocument);
}
if (journalId > lastJournalId)
{
lastJournalId = journalId;
}
if (!journalIds.ContainsKey(journalId))
{
journalIds.Add(journalId, userId);
}
}
if (journalIds.Count == 0)
{
break;
}
//index comments for this journal
AddCommentItems(journalIds, searchDocuments);
}
}
}
catch (Exception ex)
{
Exceptions.LogException(ex);
}
return searchDocuments.Values.ToList();
}
#endregion
#region Implement IModuleSearchController
public bool HasViewPermission(SearchResult searchResult)
{
var securityKeys = searchResult.UniqueKey.Split('_')[2].Split(',');
var userInfo = UserController.Instance.GetCurrentUserInfo();
var selfKey = string.Format("U{0}", userInfo.UserID);
if (securityKeys.Contains("E") || securityKeys.Contains(selfKey))
{
return true;
}
//do not show items in private group
if (securityKeys.Any(s => s.StartsWith("R")))
{
var groupId = Convert.ToInt32(securityKeys.First(s => s.StartsWith("R")).Substring(1));
var role = RoleController.Instance.GetRoleById(searchResult.PortalId, groupId);
if (role != null && !role.IsPublic && !userInfo.IsInRole(role.RoleName))
{
return false;
}
}
if (securityKeys.Contains("C"))
{
return userInfo.UserID > 0;
}
if (securityKeys.Any(s => s.StartsWith("F")))
{
var targetUser = UserController.GetUserById(searchResult.PortalId, searchResult.AuthorUserId);
return targetUser != null && targetUser.Social.Friend != null && targetUser.Social.Friend.Status == RelationshipStatus.Accepted;
}
return false;
}
public string GetDocUrl(SearchResult searchResult)
{
string url;
var portalSettings = PortalController.Instance.GetCurrentPortalSettings();
var journalId = Convert.ToInt32(searchResult.UniqueKey.Split('_')[1]);
var groupId = Convert.ToInt32(searchResult.Keywords["GroupId"]);
var tabId = Convert.ToInt32(searchResult.Keywords["TabId"]);
//var tabModuleId = Convert.ToInt32(searchResult.Keywords["TabModuleId"]);
var profileId = Convert.ToInt32(searchResult.Keywords["ProfileId"]);
if (groupId > 0 && tabId > 0)
{
url = Globals.NavigateURL(tabId, string.Empty, "GroupId=" + groupId, "jid=" + journalId);
}
else if (tabId == portalSettings.UserTabId)
{
url = Globals.NavigateURL(portalSettings.UserTabId, string.Empty, string.Format("userId={0}", profileId), "jid=" + journalId);
}
else
{
url = Globals.NavigateURL(tabId, string.Empty, "jid=" + journalId);
}
return url;
}
#endregion
#region Private Methods
private void AddCommentItems(Dictionary<int, int> journalIds, IDictionary<string, SearchDocument> searchDocuments)
{
var comments = JournalController.Instance.GetCommentsByJournalIds(journalIds.Keys.ToList());
foreach (var commentInfo in comments)
{
var journalResult = searchDocuments[string.Format("JI_{0}", commentInfo.JournalId)];
if (journalResult != null)
{
journalResult.Body += string.Format(" {0}", commentInfo.Comment);
if (commentInfo.DateCreated > journalResult.ModifiedTimeUtc)
{
journalResult.ModifiedTimeUtc = commentInfo.DateUpdated;
}
}
}
}
#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 Airguitar.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;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Lucene.Net.Support;
using Microsoft.ServiceFabric.Data;
using Microsoft.ServiceFabric.Data.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Lucene.Net.Store
{
/// <summary> A memory-resident <see cref="Directory"/> implementation. Locking
/// implementation is by default the <see cref="SingleInstanceLockFactory"/>
/// but can be changed with <see cref="Directory.SetLockFactory"/>.
/// </summary>
[Serializable]
public class ReliableRAMDirectory: Lucene.Net.Store.Directory
{
private const long serialVersionUID = 1L;
internal protected long internalSizeInBytes = 0;
public static IReliableDictionary<string, ReliableRAMFile> fileMap
{
get
{
return StateManager.GetOrAddAsync<IReliableDictionary<string, ReliableRAMFile>>("TheIndices").Result;
}
}
public static IReliableStateManager StateManager
{
get;
set;
}
public static void UpdateFile(ReliableRAMFile file)
{
var existing = GetFile(file.MapName);
using (var tx = StateManager.CreateTransaction())
{
fileMap.TryUpdateAsync(tx, file.MapName, file, existing);
tx.CommitAsync().GetAwaiter().GetResult();
}
}
// *****
// Lock acquisition sequence: RAMDirectory, then RAMFile
// *****
/// <summary>Constructs an empty <see cref="Directory"/>. </summary>
public ReliableRAMDirectory()
{
SetLockFactory(new SingleInstanceLockFactory());
}
/// <summary> Creates a new <c>RAMDirectory</c> instance from a different
/// <c>Directory</c> implementation. This can be used to load
/// a disk-based index into memory.
/// <p/>
/// This should be used only with indices that can fit into memory.
/// <p/>
/// Note that the resulting <c>RAMDirectory</c> instance is fully
/// independent from the original <c>Directory</c> (it is a
/// complete copy). Any subsequent changes to the
/// original <c>Directory</c> will not be visible in the
/// <c>RAMDirectory</c> instance.
///
/// </summary>
/// <param name="dir">a <c>Directory</c> value
/// </param>
/// <exception cref="System.IO.IOException">if an error occurs
/// </exception>
public ReliableRAMDirectory(Directory dir):this(dir, false)
{
}
private ReliableRAMDirectory(Directory dir, bool closeDir)
: this()
{
Directory.Copy(dir, this, closeDir);
}
//https://issues.apache.org/jira/browse/LUCENENET-174
[System.Runtime.Serialization.OnDeserialized]
void OnDeserialized(System.Runtime.Serialization.StreamingContext context)
{
if (interalLockFactory == null)
{
SetLockFactory(new SingleInstanceLockFactory());
}
}
public override System.String[] ListAll()
{
lock (this)
{
EnsureOpen();
List<string> keys = new List<string>();
foreach (var kv in fileMap.ToList())
keys.Add(kv.Key);
System.Collections.Generic.ISet<string> fileNames =
Lucene.Net.Support.Compatibility.SetFactory.CreateHashSet(keys);
System.String[] result = new System.String[fileNames.Count];
int i = 0;
foreach(string filename in fileNames)
{
result[i++] = filename;
}
return result;
}
}
/// <summary>Returns true iff the named file exists in this directory. </summary>
public override bool FileExists(System.String name)
{
EnsureOpen();
using (var tx = StateManager.CreateTransaction())
{
var ret = fileMap.ContainsKeyAsync(tx, name).Result;
tx.CommitAsync().GetAwaiter().GetResult();
return ret;
}
}
static ReliableRAMFile GetFile(string name)
{
ReliableRAMFile file;
using (var tx = StateManager.CreateTransaction())
{
file = fileMap.TryGetValueAsync(tx, name).GetAwaiter().GetResult().Value;
tx.CommitAsync().GetAwaiter().GetResult();
}
if(file != null)
file.MapName = name;
return file;
}
/// <summary>Returns the time the named file was last modified.</summary>
/// <throws> IOException if the file does not exist </throws>
public override long FileModified(System.String name)
{
EnsureOpen();
ReliableRAMFile file = GetFile(name);
if (file == null)
{
throw new System.IO.FileNotFoundException(name);
}
// RAMOutputStream.Flush() was changed to use DateTime.UtcNow.
// Convert it back to local time before returning (previous behavior)
return new DateTime(file.LastModified*TimeSpan.TicksPerMillisecond, DateTimeKind.Utc).ToLocalTime().Ticks/
TimeSpan.TicksPerMillisecond;
}
/// <summary>Set the modified time of an existing file to now.</summary>
/// <throws> IOException if the file does not exist </throws>
public override void TouchFile(System.String name)
{
EnsureOpen();
ReliableRAMFile file = GetFile(name);
if (file == null)
{
throw new System.IO.FileNotFoundException(name);
}
long ts2, ts1 = System.DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;
do
{
try
{
System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * 0 + 100 * 1));
}
catch (System.Threading.ThreadInterruptedException ie)
{
// In 3.0 we will change this to throw
// InterruptedException instead
ThreadClass.Current().Interrupt();
throw new System.SystemException(ie.Message, ie);
}
ts2 = System.DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;
}
while (ts1 == ts2);
file.LastModified = ts2;
}
/// <summary>Returns the length in bytes of a file in the directory.</summary>
/// <throws> IOException if the file does not exist </throws>
public override long FileLength(System.String name)
{
EnsureOpen();
var file = GetFile(name);
if (file == null)
{
throw new System.IO.FileNotFoundException(name);
}
return file.Length;
}
/// <summary>Return total size in bytes of all files in this
/// directory. This is currently quantized to
/// RAMOutputStream.BUFFER_SIZE.
/// </summary>
public long SizeInBytes()
{
lock(this)
{
return internalSizeInBytes;
}
}
/// <summary>Removes an existing file in the directory.</summary>
/// <throws> IOException if the file does not exist </throws>
public override void DeleteFile(System.String name)
{
lock(this)
{
EnsureOpen();
ReliableRAMFile file = GetFile(name);
if (file == null)
{
throw new System.IO.FileNotFoundException(name);
}
using (var tx = StateManager.CreateTransaction())
{
fileMap.TryRemoveAsync(tx, name).GetAwaiter().GetResult();
tx.CommitAsync().GetAwaiter().GetResult();
}
file.directory = null;
internalSizeInBytes -= file.sizeInBytes;
}
}
/// <summary>Creates a new, empty file in the directory with the given name. Returns a stream writing this file. </summary>
public override IndexOutput CreateOutput(System.String name)
{
EnsureOpen();
ReliableRAMFile file = new ReliableRAMFile(this, name);
ReliableRAMFile existing = GetFile(name);
using (var tx = StateManager.CreateTransaction())
{
if (existing != null)
{
internalSizeInBytes -= existing.sizeInBytes;
existing.directory = null;
fileMap.TryUpdateAsync(tx, name, file, existing).GetAwaiter().GetResult();
}
else
{
fileMap.TryAddAsync(tx, name, file).GetAwaiter().GetResult();
}
tx.CommitAsync().GetAwaiter().GetResult();
}
return new ReliableRAMOutputStream(file);
}
/// <summary>Returns a stream reading an existing file. </summary>
public override IndexInput OpenInput(System.String name)
{
EnsureOpen();
ReliableRAMFile file = GetFile(name);
if (file == null)
{
throw new System.IO.FileNotFoundException(name);
}
return new ReliableRAMInputStream(file);
}
/// <summary>Closes the store to future operations, releasing associated memory. </summary>
protected override async void Dispose(bool disposing)
{
isOpen = false;
await fileMap.ClearAsync();
}
//public HashMap<string, RAMFile> fileMap_ForNUnit
//{
// get { return fileMap; }
//}
//public long sizeInBytes_ForNUnitTest
//{
// get { return sizeInBytes; }
// set { sizeInBytes = value; }
//}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Publishing;
using Umbraco.Core.Services;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.TestHelpers.Entities;
using umbraco.editorControls.tinyMCE3;
using umbraco.interfaces;
namespace Umbraco.Tests.Services
{
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)]
[TestFixture, RequiresSTA]
public class ThreadSafetyServiceTest : BaseDatabaseFactoryTest
{
private PerThreadPetaPocoUnitOfWorkProvider _uowProvider;
private PerThreadDatabaseFactory _dbFactory;
[SetUp]
public override void Initialize()
{
base.Initialize();
//we need to use our own custom IDatabaseFactory for the DatabaseContext because we MUST ensure that
//a Database instance is created per thread, whereas the default implementation which will work in an HttpContext
//threading environment, or a single apartment threading environment will not work for this test because
//it is multi-threaded.
_dbFactory = new PerThreadDatabaseFactory();
//overwrite the local object
ApplicationContext.DatabaseContext = new DatabaseContext(_dbFactory);
//disable cache
var cacheHelper = CacheHelper.CreateDisabledCacheHelper();
//here we are going to override the ServiceContext because normally with our test cases we use a
//global Database object but this is NOT how it should work in the web world or in any multi threaded scenario.
//we need a new Database object for each thread.
_uowProvider = new PerThreadPetaPocoUnitOfWorkProvider(_dbFactory);
ApplicationContext.Services = new ServiceContext(_uowProvider, new FileUnitOfWorkProvider(), new PublishingStrategy(), cacheHelper);
CreateTestData();
}
[TearDown]
public override void TearDown()
{
_error = null;
//dispose!
_dbFactory.Dispose();
_uowProvider.Dispose();
base.TearDown();
}
/// <summary>
/// Used to track exceptions during multi-threaded tests, volatile so that it is not locked in CPU registers.
/// </summary>
private volatile Exception _error = null;
private const int MaxThreadCount = 20;
[Test]
public void Ensure_All_Threads_Execute_Successfully_Content_Service()
{
//we will mimick the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton
var contentService = (ContentService)ServiceContext.ContentService;
var threads = new List<Thread>();
Debug.WriteLine("Starting test...");
for (var i = 0; i < MaxThreadCount; i++)
{
var t = new Thread(() =>
{
try
{
Debug.WriteLine("Created content on thread: " + Thread.CurrentThread.ManagedThreadId);
//create 2 content items
string name1 = "test" + Guid.NewGuid();
var content1 = contentService.CreateContent(name1, -1, "umbTextpage", 0);
Debug.WriteLine("Saving content1 on thread: " + Thread.CurrentThread.ManagedThreadId);
contentService.Save(content1);
Thread.Sleep(100); //quick pause for maximum overlap!
string name2 = "test" + Guid.NewGuid();
var content2 = contentService.CreateContent(name2, -1, "umbTextpage", 0);
Debug.WriteLine("Saving content2 on thread: " + Thread.CurrentThread.ManagedThreadId);
contentService.Save(content2);
}
catch(Exception e)
{
_error = e;
}
});
threads.Add(t);
}
//start all threads
threads.ForEach(x => x.Start());
//wait for all to complete
threads.ForEach(x => x.Join());
//kill them all
threads.ForEach(x => x.Abort());
if (_error == null)
{
//now look up all items, there should be 40!
var items = contentService.GetRootContent();
Assert.AreEqual(40, items.Count());
}
else
{
throw new Exception("Error!", _error);
}
}
[Test]
public void Ensure_All_Threads_Execute_Successfully_Media_Service()
{
//we will mimick the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton
var mediaService = (MediaService)ServiceContext.MediaService;
var threads = new List<Thread>();
Debug.WriteLine("Starting test...");
for (var i = 0; i < MaxThreadCount; i++)
{
var t = new Thread(() =>
{
try
{
Debug.WriteLine("Created content on thread: " + Thread.CurrentThread.ManagedThreadId);
//create 2 content items
string name1 = "test" + Guid.NewGuid();
var folder1 = mediaService.CreateMedia(name1, -1, Constants.Conventions.MediaTypes.Folder, 0);
Debug.WriteLine("Saving folder1 on thread: " + Thread.CurrentThread.ManagedThreadId);
mediaService.Save(folder1, 0);
Thread.Sleep(100); //quick pause for maximum overlap!
string name = "test" + Guid.NewGuid();
var folder2 = mediaService.CreateMedia(name, -1, Constants.Conventions.MediaTypes.Folder, 0);
Debug.WriteLine("Saving folder2 on thread: " + Thread.CurrentThread.ManagedThreadId);
mediaService.Save(folder2, 0);
}
catch (Exception e)
{
_error = e;
}
});
threads.Add(t);
}
//start all threads
threads.ForEach(x => x.Start());
//wait for all to complete
threads.ForEach(x => x.Join());
//kill them all
threads.ForEach(x => x.Abort());
if (_error == null)
{
//now look up all items, there should be 40!
var items = mediaService.GetRootMedia();
Assert.AreEqual(40, items.Count());
}
else
{
Assert.Fail("ERROR! " + _error);
}
}
public void CreateTestData()
{
//Create and Save ContentType "umbTextpage" -> 1045
ContentType contentType = MockedContentTypes.CreateSimpleContentType("umbTextpage", "Textpage");
contentType.Key = new Guid("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522");
ServiceContext.ContentTypeService.Save(contentType);
}
/// <summary>
/// Creates a Database object per thread, this mimics the web context which is per HttpContext and is required for the multi-threaded test
/// </summary>
internal class PerThreadDatabaseFactory : DisposableObject, IDatabaseFactory
{
private readonly ConcurrentDictionary<int, UmbracoDatabase> _databases = new ConcurrentDictionary<int, UmbracoDatabase>();
public UmbracoDatabase CreateDatabase()
{
var db = _databases.GetOrAdd(Thread.CurrentThread.ManagedThreadId, i => new UmbracoDatabase(Umbraco.Core.Configuration.GlobalSettings.UmbracoConnectionName));
return db;
}
protected override void DisposeResources()
{
//dispose the databases
_databases.ForEach(x => x.Value.Dispose());
}
}
/// <summary>
/// Creates a UOW with a Database object per thread
/// </summary>
internal class PerThreadPetaPocoUnitOfWorkProvider : DisposableObject, IDatabaseUnitOfWorkProvider
{
private readonly PerThreadDatabaseFactory _dbFactory;
public PerThreadPetaPocoUnitOfWorkProvider(PerThreadDatabaseFactory dbFactory)
{
_dbFactory = dbFactory;
}
public IDatabaseUnitOfWork GetUnitOfWork()
{
//Create or get a database instance for this thread.
var db = _dbFactory.CreateDatabase();
return new PetaPocoUnitOfWork(db);
}
protected override void DisposeResources()
{
//dispose the databases
_dbFactory.Dispose();
}
}
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection.Emit;
using System.Reflection;
using Glass.Mapper.Configuration;
namespace Glass.Mapper
{
/// <summary>
/// Class Utilities
/// </summary>
public class Utilities
{
private static readonly ConcurrentDictionary<Type, ActivationManager.CompiledActivator<object>> Activators =
new ConcurrentDictionary<Type, ActivationManager.CompiledActivator<object>>();
public static object GetDefault(Type type)
{
if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
/// <summary>
/// Returns a delegate method that will load a class based on its constuctor
/// </summary>
/// <param name="type">The type.</param>
/// <returns>IDictionary{ConstructorInfoDelegate}.</returns>
/// <exception cref="MapperException">Only supports constructors with a maximum of 10 parameters</exception>
public static IDictionary<ConstructorInfo, Delegate> CreateConstructorDelegates(Type type)
{
var constructors = type.GetConstructors();
var dic = new Dictionary<ConstructorInfo, Delegate>();
foreach (var constructor in constructors)
{
var parameters = constructor.GetParameters();
var types = parameters.Select(x => x.ParameterType).ToArray();
var dynMethod = new DynamicMethod("DM$OBJ_FACTORY_" + type.Name, type, types, type);
ILGenerator ilGen = dynMethod.GetILGenerator();
for (int i = 0; i < parameters.Count(); i++)
{
ilGen.Emit(OpCodes.Ldarg, i);
}
ilGen.Emit(OpCodes.Newobj, constructor);
ilGen.Emit(OpCodes.Ret);
Type genericType;
switch (parameters.Count())
{
case 0:
genericType = typeof(Func<>);
break;
case 1:
genericType = typeof(Func<,>);
break;
case 2:
genericType = typeof(Func<,,>);
break;
case 3:
genericType = typeof(Func<,,,>);
break;
case 4:
genericType = typeof(Func<,,,,>);
break;
case 5:
genericType = typeof(Func<,,,,,>);
break;
case 6:
genericType = typeof(Func<,,,,,,>);
break;
case 7:
genericType = typeof(Func<,,,,,,,>);
break;
case 8:
genericType = typeof(Func<,,,,,,,,>);
break;
case 9:
genericType = typeof(Func<,,,,,,,,>);
break;
case 10:
genericType = typeof(Func<,,,,,,,,,>);
break;
default:
throw new MapperException("Only supports constructors with a maximum of 10 parameters for type {0}".Formatted(type.FullName));
}
var delegateType =
genericType.MakeGenericType(parameters.Select(x => x.ParameterType).Concat(new[] { type }).ToArray());
if (!types.Any())
types = Type.EmptyTypes;
dic[constructor] = dynMethod.CreateDelegate(delegateType);
}
return dic;
}
/// <summary>
/// The flags
/// </summary>
public static BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy |
BindingFlags.Instance;
/// <summary>
/// Gets a property based on the type and name
/// </summary>
/// <param name="type">The type.</param>
/// <param name="name">The name.</param>
/// <returns>PropertyInfo.</returns>
public static PropertyInfo GetProperty(Type type, string name)
{
PropertyInfo property = null;
try
{
property = type.GetProperty(name, Flags);
}
catch (AmbiguousMatchException ex)
{
//this is probably caused by an item having two indexers e.g SearchResultItem;
}
if (property == null)
{
var interfaces = type.GetInterfaces();
foreach (var inter in interfaces)
{
try
{
property = inter.GetProperty(name);
if (property != null)
return property;
}
catch (AmbiguousMatchException ex)
{
//this is probably caused by an item having two indexers e.g SearchResultItem;
}
}
}
return property;
}
/// <summary>
/// Gets all properties on a type
/// </summary>
/// <param name="type">The type.</param>
/// <returns>IEnumerable{PropertyInfo}.</returns>
public static IEnumerable<PropertyInfo> GetAllProperties(Type type)
{
List<Type> typeList = new List<Type>();
typeList.Add(type);
if (type.IsInterface)
{
typeList.AddRange(type.GetInterfaces());
}
List<PropertyInfo> propertyList = new List<PropertyInfo>();
foreach (Type interfaceType in typeList)
{
foreach (PropertyInfo property in interfaceType.GetProperties(Flags))
{
var finalProperty = GetProperty(property.DeclaringType, property.Name);
propertyList.Add(finalProperty);
}
}
return propertyList;
}
public static NameValueCollection GetPropertiesCollection(object target, bool lowerCaseName = false,
bool underscoreForHyphens = true)
{
NameValueCollection nameValues = new NameValueCollection();
if (target != null)
{
var type = target.GetType();
var properties = GetAllProperties(type);
foreach (var propertyInfo in properties)
{
var value = propertyInfo.GetValue(target, null);
var key = lowerCaseName ? propertyInfo.Name.ToLower() : propertyInfo.Name;
if (underscoreForHyphens)
{
key = key.Replace("_", "-");
}
nameValues.Add(key, value == null ? string.Empty : value.ToString());
}
}
return nameValues;
}
/// <summary>
/// Creates the type of the generic.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="arguments">The arguments.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>System.Object.</returns>
public static object CreateGenericType(Type type, Type[] arguments, params object[] parameters)
{
Type genericType = type.MakeGenericType(arguments);
object obj;
if (parameters != null && parameters.Any())
{
var paramTypes = parameters.Select(p => p.GetType()).ToArray();
obj = GetActivator(genericType, paramTypes)(parameters);
}
else
obj = GetActivator(genericType)();
return obj;
}
public static ActivationManager.CompiledActivator<object> GetActivator(Type type,
Type[] arguments,
params object[] parameters)
{
Type genericType = type.MakeGenericType(arguments);
var paramTypes = parameters.Select(p => p.GetType()).ToArray();
return GetActivator(genericType, paramTypes);
}
/// <summary>
/// Gets the generic argument.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>Type.</returns>
/// <exception cref="Glass.Mapper.MapperException">
/// Type {0} has more than one generic argument.Formatted(type.FullName)
/// or
/// The type {0} does not contain any generic arguments.Formatted(type.FullName)
/// </exception>
public static Type GetGenericArgument(Type type)
{
Type[] types = type.GetGenericArguments();
var count = types.Count();
if (count == 1)
return types[0];
else if(count > 1)
throw new MapperException("Type {0} has more than one generic argument".Formatted(type.FullName));
else
throw new MapperException("The type {0} does not contain any generic arguments".Formatted(type.FullName));
}
public static string GetPropertyName(Expression expression)
{
string name = String.Empty;
switch (expression.NodeType)
{
case ExpressionType.Convert:
Expression operand = (expression as UnaryExpression).Operand;
name = operand.CastTo<MemberExpression>().Member.Name;
break;
case ExpressionType.Call:
name = expression.CastTo<MethodCallExpression>().Method.Name;
break;
case ExpressionType.MemberAccess:
name = expression.CastTo<MemberExpression>().Member.Name;
break;
case ExpressionType.TypeAs:
var unaryExp = expression.CastTo<UnaryExpression>();
name = GetPropertyName(unaryExp.Operand);
break;
}
return name;
}
/// <summary>
/// Returns a PropertyInfo based on a link expression, it will pull the first property name from the linq express.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="expression">The expression.</param>
/// <returns>PropertyInfo.</returns>
public static PropertyInfo GetPropertyInfo(Type type, Expression expression)
{
string name = GetPropertyName(expression);
if (name.IsNullOrEmpty())
throw new MapperException("Unable to get property name from lambda expression");
PropertyInfo info = type.GetProperty(name);
//if we don't find the property straight away then it is probably an interface
//and we need to check all inherited interfaces.
if (info == null)
{
info = GetAllProperties(type).FirstOrDefault(x => x.Name == name);
}
return info;
}
/// <summary>
/// Creates an action delegate that can be used to set a property's value
/// </summary>
/// <remarks>
/// This compiles down to 'native' IL for maximum performance
/// </remarks>
/// <param name="property">The property to create a setter for</param>
/// <returns>An action delegate</returns>
public static Func<PropertyInfo, Action<object, object>> SetPropertyAction = (PropertyInfo property) =>
{
PropertyInfo propertyInfo = property;
Type type = property.DeclaringType;
if (propertyInfo.CanWrite)
{
if (type == null)
{
throw new InvalidOperationException(
"PropertyInfo 'property' must have a valid (non-null) DeclaringType.");
}
Type propertyType = propertyInfo.PropertyType;
ParameterExpression instanceParameter = Expression.Parameter(typeof(object), "instance");
ParameterExpression valueParameter = Expression.Parameter(typeof(object), "value");
Expression<Action<object, object>> lambda = Expression.Lambda<Action<object, object>>(
Expression.Assign(
Expression.Property(Expression.Convert(instanceParameter, type), propertyInfo),
Expression.Convert(valueParameter, propertyType)),
instanceParameter,
valueParameter
);
return lambda.Compile();
}
else
{
return (object instance, object value) =>
{
//does nothing
};
}
};
/// <summary>
/// Creates a function delegate that can be used to get a property's value
/// </summary>
/// <remarks>
/// This compiles down to 'native' IL for maximum performance
/// </remarks>
/// <param name="property">The property to create a getter for</param>
/// <returns>A function delegate</returns>
public static Func<PropertyInfo, Func<object, object>> GetPropertyFunc = (PropertyInfo property) =>
{
PropertyInfo propertyInfo = property;
Type type = property.DeclaringType;
if (type == null)
{
throw new InvalidOperationException(
"PropertyInfo 'property' must have a valid (non-null) DeclaringType.");
}
if (propertyInfo.CanWrite)
{
ParameterExpression instanceParameter = Expression.Parameter(typeof(object), "instance");
Expression<Func<object, object>> lambda = Expression.Lambda<Func<object, object>>(
Expression.Convert(
Expression.Property(
Expression.Convert(instanceParameter, type),
propertyInfo),
typeof(object)),
instanceParameter
);
return lambda.Compile();
}
else
{
return (object instance) => { return null; };
}
};
/// <summary>
/// Gets the activator.
/// </summary>
/// <param name="forType">For type.</param>
/// <param name="parameterTypes">The parameter types.</param>
/// <returns></returns>
protected static ActivationManager.CompiledActivator<object> GetActivator(Type forType,
Type [] parameterTypes = null)
{
return Activators.GetOrAdd(forType, type => ActivationManager.GetActivator<object>(type, parameterTypes));
}
public static AbstractPropertyConfiguration GetGlassProperty<T, K>(
Expression<Func<T, object>> field,
Context context,
T model) where K : AbstractTypeConfiguration, new()
{
MemberExpression memberExpression;
var finalTarget = GetTargetObjectOfLamba(field, model, out memberExpression);
if (context == null)
throw new NullReferenceException("Context cannot be null");
var config = context.GetTypeConfiguration<K>(finalTarget);
//lambda expression does not always return expected memberinfo when inheriting
//c.f. http://stackoverflow.com/questions/6658669/lambda-expression-not-returning-expected-memberinfo
var prop = config.Type.GetProperty(memberExpression.Member.Name);
//interfaces don't deal with inherited properties well
if (prop == null && config.Type.IsInterface)
{
Func<Type, PropertyInfo> interfaceCheck = null;
interfaceCheck = (inter) =>
{
var interfaces = inter.GetInterfaces();
var properties =
interfaces.Select(x => x.GetProperty(memberExpression.Member.Name)).Where(
x => x != null);
if (properties.Any()) return properties.First();
else
return interfaces.Select(x => interfaceCheck(x)).FirstOrDefault(x => x != null);
};
prop = interfaceCheck(config.Type);
}
if (prop != null && prop.DeclaringType != prop.ReflectedType)
{
//properties mapped in data handlers are based on declaring type when field is inherited, make sure we match
prop = prop.DeclaringType.GetProperty(prop.Name);
}
if (prop == null)
throw new MapperException(
"Page editting error. Could not find property {0} on type {1}".Formatted(
memberExpression.Member.Name, config.Type.FullName));
//ME - changed this to work by name because properties on interfaces do not show up as declared types.
var dataHandler = config.Properties.FirstOrDefault(x => x.PropertyInfo.Name == prop.Name);
if (dataHandler == null)
{
throw new MapperException(
"Page editing error. Could not find data handler for property {2} {0}.{1}".Formatted(
prop.DeclaringType, prop.Name, prop.MemberType));
}
return dataHandler;
}
public static K GetTypeConfig<T, K>(Expression<Func<T, object>> field, Context context, T model)
where K : AbstractTypeConfiguration, new()
{
MemberExpression memberExpression;
var finalTarget = GetTargetObjectOfLamba(field, model, out memberExpression);
if (context == null)
throw new NullReferenceException("Context cannot be null");
var config = context.GetTypeConfiguration<K>(finalTarget);
return config;
}
public static object GetTargetObjectOfLamba<T>(Expression<Func<T, object>> field, T model,
out MemberExpression memberExpression)
{
if (field.Parameters.Count > 1)
throw new MapperException("To many parameters in linq expression {0}".Formatted(field.Body));
if (field.Body is UnaryExpression)
{
memberExpression = ((UnaryExpression)field.Body).Operand as MemberExpression;
}
else if (!(field.Body is MemberExpression))
{
throw new MapperException("Expression doesn't evaluate to a member {0}".Formatted(field.Body));
}
else
{
memberExpression = (MemberExpression)field.Body;
}
//we have to deconstruct the lambda expression to find the
//correct model object
//For example if we have the lambda expression x =>x.Children.First().Content
//we have to evaluate what the first Child object is, then evaluate the field to edit from there.
//this contains the expression that will evaluate to the object containing the property
var objectExpression = memberExpression.Expression;
var finalTarget =
Expression.Lambda(objectExpression, field.Parameters).Compile().DynamicInvoke(model);
return finalTarget;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Data.Core;
using Avalonia.Utilities;
#nullable enable
// Don't need to override GetHashCode as the ISyntax objects will not be stored in a hash; the
// only reason they have overridden Equals methods is for unit testing.
#pragma warning disable 659
namespace Avalonia.Markup.Parsers
{
internal static class SelectorGrammar
{
private enum State
{
Start,
Middle,
Colon,
Class,
Name,
CanHaveType,
Traversal,
TypeName,
Property,
Template,
End,
}
public static IEnumerable<ISyntax> Parse(string s)
{
var r = new CharacterReader(s.AsSpan());
return Parse(ref r, null);
}
private static IEnumerable<ISyntax> Parse(ref CharacterReader r, char? end)
{
var state = State.Start;
var selector = new List<ISyntax>();
while (!r.End && state != State.End)
{
ISyntax? syntax = null;
switch (state)
{
case State.Start:
state = ParseStart(ref r);
break;
case State.Middle:
(state, syntax) = ParseMiddle(ref r, end);
break;
case State.CanHaveType:
state = ParseCanHaveType(ref r);
break;
case State.Colon:
(state, syntax) = ParseColon(ref r);
break;
case State.Class:
(state, syntax) = ParseClass(ref r);
break;
case State.Traversal:
(state, syntax) = ParseTraversal(ref r);
break;
case State.TypeName:
(state, syntax) = ParseTypeName(ref r);
break;
case State.Property:
(state, syntax) = ParseProperty(ref r);
break;
case State.Template:
(state, syntax) = ParseTemplate(ref r);
break;
case State.Name:
(state, syntax) = ParseName(ref r);
break;
}
if (syntax != null)
{
selector.Add(syntax);
}
}
if (state != State.Start && state != State.Middle && state != State.End && state != State.CanHaveType)
{
throw new ExpressionParseException(r.Position, "Unexpected end of selector");
}
return selector;
}
private static State ParseStart(ref CharacterReader r)
{
r.SkipWhitespace();
if (r.End)
{
return State.End;
}
if (r.TakeIf(':'))
{
return State.Colon;
}
else if (r.TakeIf('.'))
{
return State.Class;
}
else if (r.TakeIf('#'))
{
return State.Name;
}
return State.TypeName;
}
private static (State, ISyntax?) ParseMiddle(ref CharacterReader r, char? end)
{
if (r.TakeIf(':'))
{
return (State.Colon, null);
}
else if (r.TakeIf('.'))
{
return (State.Class, null);
}
else if (r.TakeIf(char.IsWhiteSpace) || r.Peek == '>')
{
return (State.Traversal, null);
}
else if (r.TakeIf('/'))
{
return (State.Template, null);
}
else if (r.TakeIf('#'))
{
return (State.Name, null);
}
else if (r.TakeIf(','))
{
return (State.Start, new CommaSyntax());
}
else if (end.HasValue && !r.End && r.Peek == end.Value)
{
return (State.End, null);
}
return (State.TypeName, null);
}
private static State ParseCanHaveType(ref CharacterReader r)
{
if (r.TakeIf('['))
{
return State.Property;
}
return State.Middle;
}
private static (State, ISyntax) ParseColon(ref CharacterReader r)
{
var identifier = r.ParseStyleClass();
if (identifier.IsEmpty)
{
throw new ExpressionParseException(r.Position, "Expected class name, is, nth-child or nth-last-child selector after ':'.");
}
const string IsKeyword = "is";
const string NotKeyword = "not";
const string NthChildKeyword = "nth-child";
const string NthLastChildKeyword = "nth-last-child";
if (identifier.SequenceEqual(IsKeyword.AsSpan()) && r.TakeIf('('))
{
var syntax = ParseType(ref r, new IsSyntax());
Expect(ref r, ')');
return (State.CanHaveType, syntax);
}
if (identifier.SequenceEqual(NotKeyword.AsSpan()) && r.TakeIf('('))
{
var argument = Parse(ref r, ')');
Expect(ref r, ')');
var syntax = new NotSyntax { Argument = argument };
return (State.Middle, syntax);
}
if (identifier.SequenceEqual(NthChildKeyword.AsSpan()) && r.TakeIf('('))
{
var (step, offset) = ParseNthChildArguments(ref r);
var syntax = new NthChildSyntax { Step = step, Offset = offset };
return (State.Middle, syntax);
}
if (identifier.SequenceEqual(NthLastChildKeyword.AsSpan()) && r.TakeIf('('))
{
var (step, offset) = ParseNthChildArguments(ref r);
var syntax = new NthLastChildSyntax { Step = step, Offset = offset };
return (State.Middle, syntax);
}
else
{
return (
State.CanHaveType,
new ClassSyntax
{
Class = ":" + identifier.ToString()
});
}
}
private static (State, ISyntax?) ParseTraversal(ref CharacterReader r)
{
r.SkipWhitespace();
if (r.TakeIf('>'))
{
r.SkipWhitespace();
return (State.Middle, new ChildSyntax());
}
else if (r.TakeIf('/'))
{
return (State.Template, null);
}
else if (!r.End)
{
return (State.Middle, new DescendantSyntax());
}
else
{
return (State.End, null);
}
}
private static (State, ISyntax) ParseClass(ref CharacterReader r)
{
var @class = r.ParseStyleClass();
if (@class.IsEmpty)
{
throw new ExpressionParseException(r.Position, $"Expected a class name after '.'.");
}
return (State.CanHaveType, new ClassSyntax { Class = @class.ToString() });
}
private static (State, ISyntax) ParseTemplate(ref CharacterReader r)
{
var template = r.ParseIdentifier();
const string TemplateKeyword = "template";
if (!template.SequenceEqual(TemplateKeyword.AsSpan()))
{
throw new ExpressionParseException(r.Position, $"Expected 'template', got '{template.ToString()}'");
}
else if (!r.TakeIf('/'))
{
throw new ExpressionParseException(r.Position, "Expected '/'");
}
return (State.Start, new TemplateSyntax());
}
private static (State, ISyntax) ParseName(ref CharacterReader r)
{
var name = r.ParseIdentifier();
if (name.IsEmpty)
{
throw new ExpressionParseException(r.Position, $"Expected a name after '#'.");
}
return (State.CanHaveType, new NameSyntax { Name = name.ToString() });
}
private static (State, ISyntax) ParseTypeName(ref CharacterReader r)
{
return (State.CanHaveType, ParseType(ref r, new OfTypeSyntax()));
}
private static (State, ISyntax) ParseProperty(ref CharacterReader r)
{
var property = r.ParseIdentifier();
if (!r.TakeIf('='))
{
throw new ExpressionParseException(r.Position, $"Expected '=', got '{r.Peek}'");
}
var value = r.TakeUntil(']');
r.Take();
return (State.CanHaveType, new PropertySyntax { Property = property.ToString(), Value = value.ToString() });
}
private static TSyntax ParseType<TSyntax>(ref CharacterReader r, TSyntax syntax)
where TSyntax : ITypeSyntax
{
ReadOnlySpan<char> ns = default;
ReadOnlySpan<char> type;
var namespaceOrTypeName = r.ParseIdentifier();
if (namespaceOrTypeName.IsEmpty)
{
throw new ExpressionParseException(r.Position, $"Expected an identifier, got '{r.Peek}");
}
if (!r.End && r.TakeIf('|'))
{
ns = namespaceOrTypeName;
if (r.End)
{
throw new ExpressionParseException(r.Position, $"Unexpected end of selector.");
}
type = r.ParseIdentifier();
}
else
{
type = namespaceOrTypeName;
}
syntax.Xmlns = ns.ToString();
syntax.TypeName = type.ToString();
return syntax;
}
private static (int step, int offset) ParseNthChildArguments(ref CharacterReader r)
{
int step = 0;
int offset = 0;
if (r.Peek == 'o')
{
var constArg = r.TakeUntil(')').ToString().Trim();
if (constArg.Equals("odd", StringComparison.Ordinal))
{
step = 2;
offset = 1;
}
else
{
throw new ExpressionParseException(r.Position, $"Expected nth-child(odd). Actual '{constArg}'.");
}
}
else if (r.Peek == 'e')
{
var constArg = r.TakeUntil(')').ToString().Trim();
if (constArg.Equals("even", StringComparison.Ordinal))
{
step = 2;
offset = 0;
}
else
{
throw new ExpressionParseException(r.Position, $"Expected nth-child(even). Actual '{constArg}'.");
}
}
else
{
r.SkipWhitespace();
var stepOrOffset = 0;
var stepOrOffsetStr = r.TakeWhile(c => char.IsDigit(c) || c == '-' || c == '+').ToString();
if (stepOrOffsetStr.Length == 0
|| (stepOrOffsetStr.Length == 1
&& stepOrOffsetStr[0] == '+'))
{
stepOrOffset = 1;
}
else if (stepOrOffsetStr.Length == 1
&& stepOrOffsetStr[0] == '-')
{
stepOrOffset = -1;
}
else if (!int.TryParse(stepOrOffsetStr.ToString(), out stepOrOffset))
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child step or offset value. Integer was expected.");
}
r.SkipWhitespace();
if (r.Peek == ')')
{
step = 0;
offset = stepOrOffset;
}
else
{
step = stepOrOffset;
if (r.Peek != 'n')
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child step value, \"xn+y\" pattern was expected.");
}
r.Skip(1); // skip 'n'
r.SkipWhitespace();
if (r.Peek != ')')
{
int sign;
var nextChar = r.Take();
if (nextChar == '+')
{
sign = 1;
}
else if (nextChar == '-')
{
sign = -1;
}
else
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child sign. '+' or '-' was expected.");
}
r.SkipWhitespace();
if (sign != 0
&& !int.TryParse(r.TakeUntil(')').ToString(), out offset))
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child offset value. Integer was expected.");
}
offset *= sign;
}
}
}
Expect(ref r, ')');
return (step, offset);
}
private static void Expect(ref CharacterReader r, char c)
{
if (r.End)
{
throw new ExpressionParseException(r.Position, $"Expected '{c}', got end of selector.");
}
else if (!r.TakeIf(')'))
{
throw new ExpressionParseException(r.Position, $"Expected '{c}', got '{r.Peek}'.");
}
}
public interface ISyntax
{
}
public interface ITypeSyntax
{
string TypeName { get; set; }
string Xmlns { get; set; }
}
public class OfTypeSyntax : ISyntax, ITypeSyntax
{
public string TypeName { get; set; } = string.Empty;
public string Xmlns { get; set; } = string.Empty;
public override bool Equals(object? obj)
{
var other = obj as OfTypeSyntax;
return other != null && other.TypeName == TypeName && other.Xmlns == Xmlns;
}
}
public class IsSyntax : ISyntax, ITypeSyntax
{
public string TypeName { get; set; } = string.Empty;
public string Xmlns { get; set; } = string.Empty;
public override bool Equals(object? obj)
{
var other = obj as IsSyntax;
return other != null && other.TypeName == TypeName && other.Xmlns == Xmlns;
}
}
public class ClassSyntax : ISyntax
{
public string Class { get; set; } = string.Empty;
public override bool Equals(object? obj)
{
return obj is ClassSyntax && ((ClassSyntax)obj).Class == Class;
}
}
public class NameSyntax : ISyntax
{
public string Name { get; set; } = string.Empty;
public override bool Equals(object? obj)
{
return obj is NameSyntax && ((NameSyntax)obj).Name == Name;
}
}
public class PropertySyntax : ISyntax
{
public string Property { get; set; } = string.Empty;
public string Value { get; set; } = string.Empty;
public override bool Equals(object? obj)
{
return obj is PropertySyntax &&
((PropertySyntax)obj).Property == Property &&
((PropertySyntax)obj).Value == Value;
}
}
public class ChildSyntax : ISyntax
{
public override bool Equals(object? obj)
{
return obj is ChildSyntax;
}
}
public class DescendantSyntax : ISyntax
{
public override bool Equals(object? obj)
{
return obj is DescendantSyntax;
}
}
public class TemplateSyntax : ISyntax
{
public override bool Equals(object? obj)
{
return obj is TemplateSyntax;
}
}
public class NotSyntax : ISyntax
{
public IEnumerable<ISyntax> Argument { get; set; } = Enumerable.Empty<ISyntax>();
public override bool Equals(object? obj)
{
return (obj is NotSyntax not) && Argument.SequenceEqual(not.Argument);
}
}
public class NthChildSyntax : ISyntax
{
public int Offset { get; set; }
public int Step { get; set; }
public override bool Equals(object? obj)
{
return (obj is NthChildSyntax nth) && nth.Offset == Offset && nth.Step == Step;
}
}
public class NthLastChildSyntax : ISyntax
{
public int Offset { get; set; }
public int Step { get; set; }
public override bool Equals(object? obj)
{
return (obj is NthLastChildSyntax nth) && nth.Offset == Offset && nth.Step == Step;
}
}
public class CommaSyntax : ISyntax
{
public override bool Equals(object? obj)
{
return obj is CommaSyntax or;
}
}
}
}
| |
using System;
using BigMath;
using NUnit.Framework;
using Raksha.Crypto;
using Raksha.Crypto.Digests;
using Raksha.Crypto.Encodings;
using Raksha.Crypto.Engines;
using Raksha.Crypto.Generators;
using Raksha.Crypto.Parameters;
using Raksha.Math;
using Raksha.Security;
using Raksha.Utilities.Encoders;
using Raksha.Tests.Utilities;
namespace Raksha.Tests.Crypto
{
[TestFixture]
public class RsaBlindedTest
: SimpleTest
{
static BigInteger mod = new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16);
static BigInteger pubExp = new BigInteger("11", 16);
static BigInteger privExp = new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16);
static BigInteger p = new BigInteger("f75e80839b9b9379f1cf1128f321639757dba514642c206bbbd99f9a4846208b3e93fbbe5e0527cc59b1d4b929d9555853004c7c8b30ee6a213c3d1bb7415d03", 16);
static BigInteger q = new BigInteger("b892d9ebdbfc37e397256dd8a5d3123534d1f03726284743ddc6be3a709edb696fc40c7d902ed804c6eee730eee3d5b20bf6bd8d87a296813c87d3b3cc9d7947", 16);
static BigInteger pExp = new BigInteger("1d1a2d3ca8e52068b3094d501c9a842fec37f54db16e9a67070a8b3f53cc03d4257ad252a1a640eadd603724d7bf3737914b544ae332eedf4f34436cac25ceb5", 16);
static BigInteger qExp = new BigInteger("6c929e4e81672fef49d9c825163fec97c4b7ba7acb26c0824638ac22605d7201c94625770984f78a56e6e25904fe7db407099cad9b14588841b94f5ab498dded", 16);
static BigInteger crtCoef = new BigInteger("dae7651ee69ad1d081ec5e7188ae126f6004ff39556bde90e0b870962fa7b926d070686d8244fe5a9aa709a95686a104614834b0ada4b10f53197a5cb4c97339", 16);
static string input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
//
// to check that we handling byte extension by big number correctly.
//
static string edgeInput = "ff6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
static byte[] oversizedSig = Hex.Decode("01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff004e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e");
static byte[] dudBlock = Hex.Decode("000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff004e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e");
static byte[] truncatedDataBlock = Hex.Decode("0001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff004e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e");
static byte[] incorrectPadding = Hex.Decode("0001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e");
static byte[] missingDataBlock = Hex.Decode("0001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
public override string Name
{
get { return "RSABlinded"; }
}
private void doTestStrictPkcs1Length(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
{
IAsymmetricBlockCipher eng = new RsaBlindedEngine();
eng.Init(true, privParameters);
byte[] data = null;
try
{
data = eng.ProcessBlock(oversizedSig, 0, oversizedSig.Length);
}
catch (Exception e)
{
Fail("RSA: failed - exception " + e.ToString(), e);
}
eng = new Pkcs1Encoding(eng);
eng.Init(false, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
Fail("oversized signature block not recognised");
}
catch (InvalidCipherTextException e)
{
if (!e.Message.Equals("block incorrect size"))
{
Fail("RSA: failed - exception " + e.ToString(), e);
}
}
// Create the encoding with StrictLengthEnabled=false (done thru environment in Java version)
Pkcs1Encoding.StrictLengthEnabled = false;
eng = new Pkcs1Encoding(new RsaBlindedEngine());
eng.Init(false, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (InvalidCipherTextException e)
{
Fail("RSA: failed - exception " + e.ToString(), e);
}
Pkcs1Encoding.StrictLengthEnabled = true;
}
private void doTestTruncatedPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
{
checkForPkcs1Exception(pubParameters, privParameters, truncatedDataBlock, "block truncated");
}
private void doTestDudPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
{
checkForPkcs1Exception(pubParameters, privParameters, dudBlock, "unknown block type");
}
private void doTestWrongPaddingPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
{
checkForPkcs1Exception(pubParameters, privParameters, incorrectPadding, "block padding incorrect");
}
private void doTestMissingDataPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
{
checkForPkcs1Exception(pubParameters, privParameters, missingDataBlock, "no data in block");
}
private void checkForPkcs1Exception(RsaKeyParameters pubParameters, RsaKeyParameters privParameters, byte[] inputData, string expectedMessage)
{
IAsymmetricBlockCipher eng = new RsaBlindedEngine();
eng.Init(true, privParameters);
byte[] data = null;
try
{
data = eng.ProcessBlock(inputData, 0, inputData.Length);
}
catch (Exception e)
{
Fail("RSA: failed - exception " + e.ToString(), e);
}
eng = new Pkcs1Encoding(eng);
eng.Init(false, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
Fail("missing data block not recognised");
}
catch (InvalidCipherTextException e)
{
if (!e.Message.Equals(expectedMessage))
{
Fail("RSA: failed - exception " + e.ToString(), e);
}
}
}
private void doTestOaep(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
{
//
// OAEP - public encrypt, private decrypt
//
IAsymmetricBlockCipher eng = new OaepEncoding(new RsaBlindedEngine());
byte[] data = Hex.Decode(input);
eng.Init(true, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
eng.Init(false, privParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
if (!input.Equals(Hex.ToHexString(data)))
{
Fail("failed OAEP Test");
}
}
public override void PerformTest()
{
RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp);
RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(mod, pubExp, privExp, p, q, pExp, qExp, crtCoef);
byte[] data = Hex.Decode(edgeInput);
//
// RAW
//
IAsymmetricBlockCipher eng = new RsaBlindedEngine();
eng.Init(true, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("RSA: failed - exception " + e.ToString(), e);
}
eng.Init(false, privParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
if (!edgeInput.Equals(Hex.ToHexString(data)))
{
Fail("failed RAW edge Test");
}
data = Hex.Decode(input);
eng.Init(true, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
eng.Init(false, privParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
if (!input.Equals(Hex.ToHexString(data)))
{
Fail("failed RAW Test");
}
//
// PKCS1 - public encrypt, private decrypt
//
eng = new Pkcs1Encoding(eng);
eng.Init(true, pubParameters);
if (eng.GetOutputBlockSize() != ((Pkcs1Encoding)eng).GetUnderlyingCipher().GetOutputBlockSize())
{
Fail("PKCS1 output block size incorrect");
}
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
eng.Init(false, privParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
if (!input.Equals(Hex.ToHexString(data)))
{
Fail("failed PKCS1 public/private Test");
}
//
// PKCS1 - private encrypt, public decrypt
//
eng = new Pkcs1Encoding(((Pkcs1Encoding)eng).GetUnderlyingCipher());
eng.Init(true, privParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
eng.Init(false, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
if (!input.Equals(Hex.ToHexString(data)))
{
Fail("failed PKCS1 private/public Test");
}
//
// key generation test
//
RsaKeyPairGenerator pGen = new RsaKeyPairGenerator();
RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25);
pGen.Init(genParam);
AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();
eng = new RsaBlindedEngine();
if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 768)
{
Fail("failed key generation (768) length test");
}
eng.Init(true, pair.Public);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
eng.Init(false, pair.Private);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
if (!input.Equals(Hex.ToHexString(data)))
{
Fail("failed key generation (768) Test");
}
genParam = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25);
pGen.Init(genParam);
pair = pGen.GenerateKeyPair();
eng.Init(true, pair.Public);
if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 1024)
{
Fail("failed key generation (1024) length test");
}
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
eng.Init(false, pair.Private);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
if (!input.Equals(Hex.ToHexString(data)))
{
Fail("failed key generation (1024) test");
}
doTestOaep(pubParameters, privParameters);
doTestStrictPkcs1Length(pubParameters, privParameters);
doTestDudPkcs1Block(pubParameters, privParameters);
doTestMissingDataPkcs1Block(pubParameters, privParameters);
doTestTruncatedPkcs1Block(pubParameters, privParameters);
doTestWrongPaddingPkcs1Block(pubParameters, privParameters);
try
{
new RsaBlindedEngine().ProcessBlock(new byte[]{ 1 }, 0, 1);
Fail("failed initialisation check");
}
catch (InvalidOperationException)
{
// expected
}
}
public static void Main(
string[] args)
{
ITest test = new RsaBlindedTest();
ITestResult result = test.Perform();
Console.WriteLine(result);
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.AppService;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Navigation;
using Autofac;
using Microsoft.WindowsAzure.MobileServices;
using UrbanSketchers.Core;
using UrbanSketchers.Interfaces;
using UrbanSketchers.Support;
using UWP.Support;
using Xamarin.Forms;
using Frame = Windows.UI.Xaml.Controls.Frame;
namespace UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public sealed partial class App
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
InitializeComponent();
Suspending += OnSuspending;
FilePickerService.Current = new UWPFilePickerService();
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (Debugger.IsAttached)
DebugSettings.EnableFrameRateCounter = true;
#endif
var rootFrame = CreateRootFrame(e);
if (rootFrame.Content == null)
rootFrame.Navigate(typeof(MainPage), e.Arguments);
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Background activated
/// </summary>
/// <param name="args">the background activated event arguments</param>
protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
{
if (args.TaskInstance.TriggerDetails is AppServiceTriggerDetails details)
details.AppServiceConnection.RequestReceived += AppServiceConnection_RequestReceived;
}
private async void AppServiceConnection_RequestReceived(AppServiceConnection sender,
AppServiceRequestReceivedEventArgs args)
{
var deferral = args.GetDeferral();
var request = args.Request;
var message = request.Message;
if (message.TryGetValue("Method", out var value))
{
var method = value.ToString();
if (method.Equals("upload", StringComparison.OrdinalIgnoreCase))
await UploadAsync(request, message);
else
await SendFailureResponseAsync(request, "The only valid Method is 'Upload'");
}
else
{
await SendFailureResponseAsync(request, "The Message must contain a Method, FileToken and Title");
}
deferral.Complete();
}
private static async Task SendFailureResponseAsync(AppServiceRequest request, string message)
{
var response = new ValueSet
{
["ErrorMessage"] = message,
["Succeeded"] = false
};
await request.SendResponseAsync(response);
}
////async Task UploadAsync(StorageFile fileToUpload)
////{
//// using (var connection = new AppServiceConnection
//// {
//// AppServiceName = "Upload.1",
//// PackageFamilyName = "MichaelS.Scherotter.UrbanSketches_9eg5g21zq32qm"
//// })
//// {
//// var status = await connection.OpenAsync();
//// if (status == AppServiceConnectionStatus.Success)
//// {
//// var message = new ValueSet
//// {
//// ["Method"] = "Upload",
//// ["Title"] = "A sketch",
//// ["Address"] = "Optional address",
//// ["CreationDate"] = DateTime.UtcNow,
//// ["Description"] = "Optional description",
//// ["FileToken"] = SharedStorageAccessManager.AddFile(fileToUpload),
//// ["Latitude"] = 40.0,
//// ["Longitude"] = 100.3
//// };
//// var response = await connection.SendMessageAsync(message);
//// bool succeeded = (bool) response.Message["Success"];
//// }
//// }
////}
/// <summary>
/// Upload
/// </summary>
/// <param name="request"></param>
/// <param name="message"></param>
/// <returns></returns>
private static async Task UploadAsync(AppServiceRequest request, ValueSet message)
{
var sketch = Container.Current.Resolve<ISketch>();
StorageFile file = null;
if (message.TryGetValue("FileToken", out var fileToken))
file = await SharedStorageAccessManager.RedeemTokenForFileAsync(fileToken.ToString());
if (file == null)
{
await SendFailureResponseAsync(request, "The Message must contain a FileToken");
}
else
{
var imageProperties = await file.Properties.GetImagePropertiesAsync();
if (message.TryGetValue("Title", out var title))
sketch.Title = title.ToString();
else
sketch.Title = imageProperties.Title;
if (string.IsNullOrWhiteSpace(sketch.Title))
{
await SendFailureResponseAsync(request,
"Message must have a Title property or the image must have a Title EXIF property.");
return;
}
if (message.TryGetValue("CreationDate", out var dateCreated))
sketch.CreationDate = (DateTime) dateCreated;
else
sketch.CreationDate = imageProperties.DateTaken.ToUniversalTime().DateTime;
if (message.TryGetValue("Address", out var address))
sketch.Address = address.ToString();
if (message.TryGetValue("Latitude", out var latitude))
sketch.Latitude = (double) latitude;
else if (imageProperties.Latitude.HasValue)
sketch.Latitude = imageProperties.Latitude.Value;
if (message.TryGetValue("Longitude", out var longitude))
sketch.Longitude = (double) longitude;
else if (imageProperties.Longitude.HasValue)
sketch.Longitude = imageProperties.Longitude.Value;
if (message.TryGetValue("Description", out var description))
sketch.Description = description.ToString();
using (var stream = await file.OpenStreamForReadAsync())
{
try
{
sketch.ImageUrl =
await Container.Current.Resolve<ISketchManager>().UploadAsync(file.Name, stream);
await Container.Current.Resolve<ISketchManager>().SaveAsync(sketch);
}
catch (Exception e)
{
await SendFailureResponseAsync(request, e.Message);
return;
}
}
var response = new ValueSet
{
["Succeeded"] = true
};
await request.SendResponseAsync(response);
}
}
/// <summary>
/// Activated
/// </summary>
/// <param name="args">the activated event arguments</param>
protected override void OnActivated(IActivatedEventArgs args)
{
base.OnActivated(args);
switch (args.Kind)
{
case ActivationKind.Protocol:
if (args is ProtocolActivatedEventArgs protocolArgs)
if (protocolArgs.Uri.ToString().StartsWith("urbansketchesauth:"))
Container.Current.Resolve<ISketchManager>().CurrentClient.ResumeWithURL(protocolArgs.Uri);
break;
}
}
private Frame CreateRootFrame(LaunchActivatedEventArgs e)
{
var rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e != null)
{
Forms.Init(e);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
return rootFrame;
}
/// <summary>
/// Share target activated
/// </summary>
/// <param name="args">the share target activated event arguments</param>
protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
var frame = CreateRootFrame(null);
frame.Navigate(typeof(ShareTargetPage), args.ShareOperation);
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
private void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| |
// <copyright file=ColorUtils company=Hydra>
// Copyright (c) 2015 All Rights Reserved
// </copyright>
// <author>Christopher Cameron</author>
using System;
using UnityEngine;
namespace Hydra.HydraCommon.Utils
{
/// <summary>
/// ColorUtils provides utility methods for working with colors.
/// </summary>
public static class ColorUtils
{
public static readonly Color hydraPrimary = RGB(17, 154, 144);
public static readonly Color hydraSecondary = RGB(34, 199, 187);
public enum Gamut
{
RGB,
HSL
}
public enum BlendMode
{
None,
Replace,
Normal,
Darken,
Multiply,
ColorBurn,
LinearBurn,
DarkerColor,
Lighten,
Screen,
ColorDodge,
Add,
LighterColor,
Overlay,
SoftLight,
HardLight,
PinLight,
HardMix,
Difference,
Exclusion,
Subtract,
Divide,
Hue,
Saturation,
Color,
Luminosity
}
/// <summary>
/// Returns a color based on the given rgb 0-255 values.
/// </summary>
/// <param name="red">Red.</param>
/// <param name="green">Green.</param>
/// <param name="blue">Blue.</param>
public static Color RGB(int red, int green, int blue)
{
return new Color(red / 255.0f, green / 255.0f, blue / 255.0f);
}
/// <summary>
/// Returns a linear color at the delta between the two input colors.
/// </summary>
/// <param name="colorA">Color a.</param>
/// <param name="colorB">Color b.</param>
/// <param name="delta">Delta.</param>
public static Color Lerp(Color colorA, Color colorB, float delta)
{
return new Color(Mathf.Lerp(colorA.r, colorB.r, delta), Mathf.Lerp(colorA.g, colorB.g, delta),
Mathf.Lerp(colorA.b, colorB.b, delta), Mathf.Lerp(colorA.a, colorB.a, delta));
}
/// <summary>
/// Converts RGB color values to HSL.
/// </summary>
/// <returns>The HSL value.</returns>
/// <param name="red">Red.</param>
/// <param name="green">Green.</param>
/// <param name="blue">Blue.</param>
/// <param name="alpha">Alpha.</param>
public static Vector4 RgbToHsl(float red, float green, float blue, float alpha)
{
float max = HydraMathUtils.Max(red, green, blue);
float min = HydraMathUtils.Min(red, green, blue);
float hue = (max + min) / 2.0f;
float saturation;
float lightness = hue;
if (HydraMathUtils.Approximately(max, min))
{
// achromatic
hue = 0.0f;
saturation = 0.0f;
}
else
{
float delta = max - min;
saturation = (lightness > 0.5f) ? delta / (2.0f - max - min) : delta / (max + min);
if (red >= green && red >= blue)
hue = (green - blue) / delta + (green < blue ? 6.0f : 0.0f);
else if (green >= red && green >= blue)
hue = (blue - red) / delta + 2.0f;
else
hue = (red - green) / delta + 4.0f;
hue /= 6.0f;
}
return new Vector4(hue, saturation, lightness, alpha);
}
/// <summary>
/// Converts RGB color values to HSL.
/// </summary>
/// <returns>The HSL value.</returns>
/// <param name="red">Red.</param>
/// <param name="green">Green.</param>
/// <param name="blue">Blue.</param>
public static Vector4 RgbToHsl(float red, float green, float blue)
{
return RgbToHsl(red, green, blue, 1.0f);
}
/// <summary>
/// Converts RGB color values to HSL.
/// </summary>
/// <returns>The HSL value.</returns>
/// <param name="color">Color.</param>
public static Vector4 RgbToHsl(Color color)
{
return RgbToHsl(color.r, color.g, color.b, color.a);
}
/// <summary>
/// Converts RGB color values to a Vector3. Color(0.5, 0.5, 0.5) is Vector3(0, 0, 0).
/// </summary>
/// <returns>The vector.</returns>
/// <param name="color">Color.</param>
public static Vector3 RgbToVector(Color color)
{
return new Vector3((color.r - 0.5f) * 2.0f, (color.g - 0.5f) * 2.0f, (color.b - 0.5f) * 2.0f);
}
/// <summary>
/// Converts HSL color values to RGB.
/// </summary>
/// <returns>The RGB value.</returns>
/// <param name="hue">Hue.</param>
/// <param name="saturation">Saturation.</param>
/// <param name="lightness">Lightness.</param>
/// <param name="alpha">Alpha.</param>
public static Color HslToRgb(float hue, float saturation, float lightness, float alpha)
{
// Achromatic
if (HydraMathUtils.Approximately(saturation, 0.0f))
return new Color(lightness, lightness, lightness, alpha);
float q = (lightness < 0.5f) ? lightness * (1.0f + saturation) : lightness + saturation - lightness * saturation;
float p = 2.0f * lightness - q;
float r = HueToChannel(p, q, hue + 1.0f / 3.0f);
float g = HueToChannel(p, q, hue);
float b = HueToChannel(p, q, hue - 1.0f / 3.0f);
return new Color(r, g, b, alpha);
}
/// <summary>
/// Converts HSL color values to RGB.
/// </summary>
/// <returns>The RGB value.</returns>
/// <param name="hue">Hue.</param>
/// <param name="saturation">Saturation.</param>
/// <param name="lightness">Lightness.</param>
public static Color HslToRgb(float hue, float saturation, float lightness)
{
return HslToRgb(hue, saturation, lightness, 1.0f);
}
/// <summary>
/// Converts HSL color values to RGB.
/// </summary>
/// <returns>The RGB value.</returns>
/// <param name="hsl">Hsl.</param>
public static Color HslToRgb(Vector4 hsl)
{
return HslToRgb(hsl.x, hsl.y, hsl.z, hsl.w);
}
/// <summary>
/// Converts a hue to a single RGB channel.
/// </summary>
/// <returns>The RGB channel value.</returns>
/// <param name="p">P.</param>
/// <param name="q">Q.</param>
/// <param name="t">T.</param>
public static float HueToChannel(float p, float q, float t)
{
if (t < 0)
t += 1;
if (t > 1)
t -= 1;
if (t < 1.0f / 6.0f)
return p + (q - p) * 6 * t;
if (t < 1.0f / 2.0f)
return q;
if (t < 2.0f / 3.0f)
return p + (q - p) * (2.0f / 3.0f - t) * 6.0f;
return p;
}
/// <summary>
/// Invert the specified input.
/// </summary>
/// <param name="input">Input.</param>
public static Color Invert(Color input)
{
return new Color(1.0f - input.r, 1.0f - input.g, 1.0f - input.b, 1.0f - input.a);
}
/// <summary>
/// Blend the specified Colors using the given BlendMode.
/// </summary>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
/// <param name="mode">Mode.</param>
public static Color Blend(Color baseLayer, Color topLayer, BlendMode mode)
{
switch (mode)
{
case BlendMode.None:
return baseLayer;
case BlendMode.Replace:
return topLayer;
case BlendMode.Normal:
return BlendNormal(baseLayer, topLayer);
case BlendMode.Darken:
return BlendDarken(baseLayer, topLayer);
case BlendMode.Multiply:
return BlendMultiply(baseLayer, topLayer);
case BlendMode.ColorBurn:
return BlendColorBurn(baseLayer, topLayer);
case BlendMode.LinearBurn:
return BlendLinearBurn(baseLayer, topLayer);
case BlendMode.DarkerColor:
return BlendDarkerColor(baseLayer, topLayer);
case BlendMode.Lighten:
return BlendLighten(baseLayer, topLayer);
case BlendMode.Screen:
return BlendScreen(baseLayer, topLayer);
case BlendMode.ColorDodge:
return BlendColorDodge(baseLayer, topLayer);
case BlendMode.Add:
return BlendAdd(baseLayer, topLayer);
case BlendMode.LighterColor:
return BlendLighterColor(baseLayer, topLayer);
case BlendMode.Overlay:
return BlendOverlay(baseLayer, topLayer);
case BlendMode.SoftLight:
return BlendSoftLight(baseLayer, topLayer);
case BlendMode.HardLight:
return BlendHardLight(baseLayer, topLayer);
case BlendMode.PinLight:
return BlendPinLight(baseLayer, topLayer);
case BlendMode.HardMix:
return BlendHardMix(baseLayer, topLayer);
case BlendMode.Difference:
return BlendDifference(baseLayer, topLayer);
case BlendMode.Exclusion:
return BlendExclusion(baseLayer, topLayer);
case BlendMode.Subtract:
return BlendSubtract(baseLayer, topLayer);
case BlendMode.Divide:
return BlendDivide(baseLayer, topLayer);
case BlendMode.Hue:
return BlendHue(baseLayer, topLayer);
case BlendMode.Saturation:
return BlendSaturation(baseLayer, topLayer);
case BlendMode.Color:
return BlendColor(baseLayer, topLayer);
case BlendMode.Luminosity:
return BlendLuminosity(baseLayer, topLayer);
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Blends the two colors together.
/// </summary>
/// <returns>The blended color.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendNormal(Color baseLayer, Color topLayer)
{
if (HydraMathUtils.Approximately(topLayer.a, 0.0f))
return baseLayer;
if (HydraMathUtils.Approximately(baseLayer.a, 0.0f))
return topLayer;
float alpha = 1.0f - (1.0f - topLayer.a) * (1.0f - baseLayer.a);
return new Color(topLayer.r * topLayer.a / alpha + baseLayer.r * baseLayer.a * (1.0f - topLayer.a) / alpha,
topLayer.g * topLayer.a / alpha + baseLayer.g * baseLayer.a * (1.0f - topLayer.a) / alpha,
topLayer.b * topLayer.a / alpha + baseLayer.b * baseLayer.a * (1.0f - topLayer.a) / alpha, alpha);
}
/// <summary>
/// Returns the smallest value in each channel.
/// </summary>
/// <returns>The smallest channels.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendDarken(Color baseLayer, Color topLayer)
{
return new Color(HydraMathUtils.Min(baseLayer.r, topLayer.r), HydraMathUtils.Min(baseLayer.g, topLayer.g),
HydraMathUtils.Min(baseLayer.b, topLayer.b), HydraMathUtils.Min(baseLayer.a, topLayer.a));
}
/// <summary>
/// Multiplies the two colors.
/// </summary>
/// <returns>The multiplied color.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendMultiply(Color baseLayer, Color topLayer)
{
return baseLayer * topLayer;
}
/// <summary>
/// Divides the inverted bottom layer by the top layer, and then inverts the result.
/// </summary>
/// <returns>The color burn.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendColorBurn(Color baseLayer, Color topLayer)
{
Color divide = BlendDivide(Invert(baseLayer), topLayer);
return Invert(divide);
}
/// <summary>
/// Sums the value in the two layers and subtracts 1.
/// </summary>
/// <returns>The linear burn.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendLinearBurn(Color baseLayer, Color topLayer)
{
return new Color((baseLayer.r + topLayer.r) - 1.0f, (baseLayer.g + topLayer.g) - 1.0f,
(baseLayer.b + topLayer.b) - 1.0f, (baseLayer.a + topLayer.a) - 1.0f);
}
/// <summary>
/// Returns the darker color.
/// </summary>
/// <returns>The darker color.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendDarkerColor(Color baseLayer, Color topLayer)
{
return (RgbToHsl(baseLayer).z < RgbToHsl(topLayer).z) ? baseLayer : topLayer;
}
/// <summary>
/// Returns the largest value in each channel.
/// </summary>
/// <returns>The largest channels.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendLighten(Color baseLayer, Color topLayer)
{
return new Color(HydraMathUtils.Max(baseLayer.r, topLayer.r), HydraMathUtils.Max(baseLayer.g, topLayer.g),
HydraMathUtils.Max(baseLayer.b, topLayer.b), HydraMathUtils.Max(baseLayer.a, topLayer.a));
}
/// <summary>
/// Inverts both layers, multiplies them, and then inverts the result.
/// </summary>
/// <returns>The screen blend.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendScreen(Color baseLayer, Color topLayer)
{
Color multiple = BlendMultiply(Invert(baseLayer), Invert(topLayer));
return Invert(multiple);
}
/// <summary>
/// Divides the bottom layer by the inverted top layer.
/// </summary>
/// <returns>The color dodge blend.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendColorDodge(Color baseLayer, Color topLayer)
{
return BlendDivide(baseLayer, Invert(topLayer));
}
/// <summary>
/// Returns the sums of the color channels.
/// </summary>
/// <returns>The added layers.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendAdd(Color baseLayer, Color topLayer)
{
return new Color(HydraMathUtils.Min(baseLayer.r + topLayer.r, 1.0f),
HydraMathUtils.Min(baseLayer.g + topLayer.g, 1.0f), HydraMathUtils.Min(baseLayer.b + topLayer.b, 1.0f),
HydraMathUtils.Min(baseLayer.a + topLayer.a, 1.0f));
}
/// <summary>
/// Returns the lighter color.
/// </summary>
/// <returns>The lighter color.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendLighterColor(Color baseLayer, Color topLayer)
{
return (RgbToHsl(baseLayer).z > RgbToHsl(topLayer).z) ? baseLayer : topLayer;
}
/// <summary>
/// Overlay combines Multiply and Screen blend modes.
/// </summary>
/// <returns>The overlay.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendOverlay(Color baseLayer, Color topLayer)
{
return new Color(OverlayChannel(baseLayer.r, topLayer.r), OverlayChannel(baseLayer.g, topLayer.g),
OverlayChannel(baseLayer.b, topLayer.b), OverlayChannel(baseLayer.a, topLayer.a));
}
/// <summary>
/// The parts of the top layer where base layer is light become lighter,
/// the parts where the base layer is dark become darker.
/// </summary>
/// <returns>The channel.</returns>
/// <param name="baseChannel">Base channel.</param>
/// <param name="topChannel">Top channel.</param>
public static float OverlayChannel(float baseChannel, float topChannel)
{
float output = 2.0f * baseChannel * topChannel;
if (baseChannel >= 0.5f)
output = 1.0f - 2.0f * (1.0f - baseChannel) * (1.0f - topChannel);
return HydraMathUtils.Clamp(output, 0.0f, 1.0f);
}
/// <summary>
/// A softer version of Hard Light. Applying pure black or white does not result in pure black or white.
/// </summary>
/// <returns>The blend.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendSoftLight(Color baseLayer, Color topLayer)
{
return new Color(SoftLightChannel(baseLayer.r, topLayer.r), SoftLightChannel(baseLayer.g, topLayer.g),
SoftLightChannel(baseLayer.b, topLayer.b), SoftLightChannel(baseLayer.a, topLayer.a));
}
/// <summary>
/// Applies soft light blending to a single channel.
/// </summary>
/// <returns>The light channel.</returns>
/// <param name="baseChannel">Base channel.</param>
/// <param name="topChannel">Top channel.</param>
public static float SoftLightChannel(float baseChannel, float topChannel)
{
return (1.0f - 2.0f * topChannel) * baseChannel * baseChannel + 2.0f * topChannel * baseChannel;
}
/// <summary>
/// Combines Multiply and Screen blend modes. Equivalent to Overlay,
/// but with the bottom and top images swapped.
/// </summary>
/// <returns>The blend.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendHardLight(Color baseLayer, Color topLayer)
{
return BlendOverlay(topLayer, baseLayer);
}
/// <summary>
/// Replaces colors depending on the lightness of the topLayer. If the topLayer is
/// more than 50% lightness and the baseLayer is darker than the topLayer, then the
/// baseLayer is returned. If the topLayer is less than 50% lightness
/// and the baseLayer is lighter than the topLayer, then the baseLayer is returned.
/// </summary>
/// <returns>The pin light.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendPinLight(Color baseLayer, Color topLayer)
{
Vector4 baseHsl = RgbToHsl(baseLayer);
Vector4 topHsl = HslToRgb(topLayer);
if (topHsl.z >= 0.5f && baseHsl.z <= topHsl.z)
return baseLayer;
if (topHsl.z <= 0.5f && baseHsl.z >= topHsl.z)
return baseLayer;
return topLayer;
}
/// <summary>
/// Returns a hard mix blend of the colors.
/// </summary>
/// <returns>The hard mix.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendHardMix(Color baseLayer, Color topLayer)
{
return new Color(HardMixChannel(baseLayer.r, topLayer.r), HardMixChannel(baseLayer.g, topLayer.g),
HardMixChannel(baseLayer.b, topLayer.b), HardMixChannel(baseLayer.a, topLayer.a));
}
/// <summary>
/// Applies hard mix blending to a single channel.
/// </summary>
/// <returns>The mix channel.</returns>
/// <param name="baseChannel">Base channel.</param>
/// <param name="topChannel">Top channel.</param>
public static float HardMixChannel(float baseChannel, float topChannel)
{
if (baseChannel + topChannel < 1.0f)
return 0.0f;
if (baseChannel + topChannel > 1.0f)
return 1.0f;
return (baseChannel >= topChannel) ? 1.0f : 0.0f;
}
/// <summary>
/// Takes the magnitude of each channel once subtracted.
/// </summary>
/// <returns>The difference.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendDifference(Color baseLayer, Color topLayer)
{
return new Color(HydraMathUtils.Abs(baseLayer.r - topLayer.r), HydraMathUtils.Abs(baseLayer.g - topLayer.g),
HydraMathUtils.Abs(baseLayer.b - topLayer.b), HydraMathUtils.Abs(baseLayer.a - topLayer.a));
}
/// <summary>
/// Exclusion blending mode inverts base layer according to the brightness values in the top layer.
/// </summary>
/// <returns>The blend.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendExclusion(Color baseLayer, Color topLayer)
{
return new Color(ExclusionChannel(baseLayer.r, topLayer.r), ExclusionChannel(baseLayer.g, topLayer.g),
ExclusionChannel(baseLayer.b, topLayer.b), ExclusionChannel(baseLayer.a, topLayer.a));
}
/// <summary>
/// Applies exclusion blending to a single channel.
/// </summary>
/// <returns>The channel.</returns>
/// <param name="baseChannel">Base channel.</param>
/// <param name="topChannel">Top channel.</param>
public static float ExclusionChannel(float baseChannel, float topChannel)
{
return baseChannel * (1.0f - topChannel) + topChannel * (1.0f - baseChannel);
}
/// <summary>
/// Returns the top layer subtracted from the base layer.
/// </summary>
/// <returns>The blend.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendSubtract(Color baseLayer, Color topLayer)
{
return new Color(HydraMathUtils.Max(baseLayer.r - topLayer.r, 0.0f),
HydraMathUtils.Max(baseLayer.g - topLayer.g, 0.0f), HydraMathUtils.Max(baseLayer.b - topLayer.b, 0.0f),
HydraMathUtils.Max(baseLayer.a - topLayer.a, 0.0f));
}
/// <summary>
/// Divides the channels.
/// </summary>
/// <returns>The blend.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendDivide(Color baseLayer, Color topLayer)
{
return new Color(HydraMathUtils.Min(baseLayer.r / topLayer.r, 1.0f),
HydraMathUtils.Min(baseLayer.g / topLayer.g, 1.0f), HydraMathUtils.Min(baseLayer.b / topLayer.b, 1.0f),
HydraMathUtils.Min(baseLayer.a / topLayer.a, 1.0f));
}
/// <summary>
/// Preserves the saturation and lightness of the bottom layer, while adopting the hue of the top layer.
/// </summary>
/// <returns>The hue.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendHue(Color baseLayer, Color topLayer)
{
Vector4 baseHsl = RgbToHsl(baseLayer);
Vector4 topHsl = RgbToHsl(topLayer);
return HslToRgb(new Vector4(topHsl.x, baseHsl.y, baseHsl.z, baseHsl.w));
}
/// <summary>
/// Preserves the hue and lightness of the bottom layer, while adopting the saturation of the top layer.
/// </summary>
/// <returns>The saturation.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendSaturation(Color baseLayer, Color topLayer)
{
Vector4 baseHsl = RgbToHsl(baseLayer);
Vector4 topHsl = RgbToHsl(topLayer);
return HslToRgb(new Vector4(baseHsl.x, topHsl.y, baseHsl.z, baseHsl.w));
}
/// <summary>
/// Preserves the lightness of the bottom layer, while adopting the hue and saturation of the top layer.
/// </summary>
/// <returns>The color.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendColor(Color baseLayer, Color topLayer)
{
Vector4 baseHsl = RgbToHsl(baseLayer);
Vector4 topHsl = RgbToHsl(topLayer);
return HslToRgb(new Vector4(topHsl.x, topHsl.y, baseHsl.z, baseHsl.w));
}
/// <summary>
/// Preserves the hue and saturation of the bottom layer, while adopting the lightness of the top layer.
/// </summary>
/// <returns>The luminosity.</returns>
/// <param name="baseLayer">Base layer.</param>
/// <param name="topLayer">Top layer.</param>
public static Color BlendLuminosity(Color baseLayer, Color topLayer)
{
Vector4 baseHsl = RgbToHsl(baseLayer);
Vector4 topHsl = RgbToHsl(topLayer);
return HslToRgb(new Vector4(baseHsl.x, baseHsl.y, topHsl.z, baseHsl.w));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using FluentAssertions;
using NetFusion.Rest.Client;
using NetFusion.Rest.Resources;
using NetFusion.Rest.Server.Hal;
using Xunit;
namespace WebTests.Rest.ClientRequests
{
/// <summary>
/// These tests validate the property serialization of resources using the new System.Text.Json serializer.
/// Resources are returned from WebApi controller methods. These tests validate that resource wrapped
/// models are correctly returned to the client. Calling clients invoking actions on resources only
/// submit back the model and not the resource.
/// </summary>
public class ResourceSerializationTests
{
private static JsonSerializerOptions SerializerOptions => new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
/// <summary>
/// A WebApi can return a single resource wrapping a model and containing
/// links pertaining to the model.
/// </summary>
[Fact]
public void SingleResource()
{
var resource = TestModel.AsResource();
resource.Links = TestLinks;
var json = JsonSerializer.Serialize(resource, SerializerOptions);
// Deserialize json back into object to determine JSON contained
// expected serialized data:
var result = JsonSerializer.Deserialize<HalResource<Sensor>>(json, SerializerOptions);
result.Should().NotBeNull();
result.Model.Should().BeEquivalentTo(TestModel);
result.Links.Should().NotBeNull();
result.Links.Should().BeEquivalentTo(TestLinks);
}
/// <summary>
/// A WebApi can return a single resource containing a child related embedded resource.
/// </summary>
[Fact]
public void SingleEmbeddedResource()
{
var resource = TestModel.AsResource();
resource.Links = TestLinks;
var stats = new Stats
{
DateStarted = DateTime.Now,
NumberReads = 499
};
var embeddedResource = stats.AsResource();
embeddedResource.Links = new Dictionary<string, Link>
{
{ "reset", new Link { Href = "http://sensor/stats/reset"}}
};
resource.EmbedModel(embeddedResource, "stats");
var json = JsonSerializer.Serialize(resource, SerializerOptions);
// Deserialize json back into object to determine JSON contained
// expected serialized data:
var result = JsonSerializer.Deserialize<HalResource<Sensor>>(json, SerializerOptions);
result.Embedded.Should().NotBeNull();
result.Embedded.Should().ContainKey("stats");
// Validate the embedded resource:
var embeddedResult = result.GetEmbeddedResource<Stats>("stats");
embeddedResult.Should().NotBeNull();
embeddedResult.Model.Should().BeEquivalentTo(stats);
embeddedResult.Links.Should().BeEquivalentTo(embeddedResource.Links);
}
/// <summary>
/// A WebApi can return a resource containing an embedded collection of
/// related resources.
/// </summary>
[Fact]
public void CollectionOfEmbeddedResources()
{
var resource = TestModel.AsResource();
resource.Links = TestLinks;
var stats = new[]
{
new Stats { DateStarted = DateTime.Now, NumberReads = 444 },
new Stats { DateStarted = DateTime.Now, NumberReads = 555 }
};
var embeddedResources = stats.AsResources();
// Add some links to embedded resource:
foreach (var embeddedResource in embeddedResources)
{
embeddedResource.Links = new Dictionary<string, Link>
{
{ "reset", new Link { Href = "http://sensor/stats/reset"}}
};
}
resource.EmbedModel(embeddedResources, "stats");
var json = JsonSerializer.Serialize(resource, SerializerOptions);
// Deserialize json back into object to determine JSON contained
// expected serialized data:
var result = JsonSerializer.Deserialize<HalResource<Sensor>>(json, SerializerOptions);
result.Embedded.Should().NotBeNull();
result.Embedded.Should().ContainKey("stats");
// Validate the embedded resource:
var embeddedResults = result.GetEmbeddedResources<Stats>("stats").ToArray();
embeddedResults.Should().HaveCount(2);
embeddedResults[0].Model.Should().BeEquivalentTo(embeddedResources[0].Model);
embeddedResults[0].Links.Should().BeEquivalentTo(embeddedResources[0].Links);
embeddedResults[1].Model.Should().BeEquivalentTo(embeddedResources[1].Model);
embeddedResults[1].Links.Should().BeEquivalentTo(embeddedResources[1].Links);
}
/// <summary>
/// The server can also embedded a model if there is no resource related information.
/// </summary>
[Fact]
public void SingleEmbeddedModel()
{
var resource = TestModel.AsResource();
resource.Links = TestLinks;
var stats = new Stats
{
DateStarted = DateTime.Now,
NumberReads = 499
};
resource.EmbedModel(stats, "model");
var json = JsonSerializer.Serialize(resource, SerializerOptions);
// Deserialize json back into object to determine JSON contained
// expected serialized data:
var result = JsonSerializer.Deserialize<HalResource<Sensor>>(json, SerializerOptions);
// Validate the embedded resource:
var embeddedModel = result.GetEmbeddedModel<Stats>("model");
embeddedModel.Should().BeEquivalentTo(stats);
}
/// <summary>
/// The server can also embedded a collection of models if there is no resource related information.
/// </summary>
[Fact]
public void CollectionOfEmbeddedModels()
{
var resource = TestModel.AsResource();
resource.Links = TestLinks;
var stats = new[]
{
new Stats { DateStarted = DateTime.Now, NumberReads = 294 },
new Stats { DateStarted = DateTime.Now, NumberReads = 555 }
};
resource.EmbedModel(stats, "models");
var json = JsonSerializer.Serialize(resource, SerializerOptions);
// Deserialize json back into object to determine JSON contained
// expected serialized data:
var result = JsonSerializer.Deserialize<HalResource<Sensor>>(json, SerializerOptions);
// Validate the embedded resource:
var embeddedModels = result.GetEmbeddedModels<Stats>("models").ToArray();
embeddedModels.Should().HaveCount(2);
embeddedModels[0].Should().BeEquivalentTo(stats[0]);
embeddedModels[1].Should().BeEquivalentTo(stats[1]);
}
private static Sensor TestModel => new Sensor
{
SensorId = "S435345",
Name = "Sensor-One",
Values = new []{ 10, 40, 60 }
};
private static IDictionary<string, Link> TestLinks => new Dictionary<string, Link>
{
{ "status", new Link { Href = "http://sensor/status"} },
{ "version", new Link { Href = "http://sensor/version"} }
};
}
public class Sensor
{
public string SensorId { get; set; }
public string Name { get; set; }
public int[] Values { get; set; }
}
public class Stats
{
public DateTime DateStarted { get; set; }
public int NumberReads { get; set; }
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Client.Linden
{
public class LLStandaloneLoginModule : ISharedRegionModule, ILoginServiceToRegionsConnector
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected List<Scene> m_scenes = new List<Scene>();
protected Scene m_firstScene;
protected bool m_enabled = false; // Module is only enabled if running in standalone mode
protected bool authenticate;
protected string welcomeMessage;
public bool RegionLoginsEnabled
{
get
{
if (m_firstScene != null)
{
return m_firstScene.SceneGridService.RegionLoginsEnabled;
}
else
{
return false;
}
}
}
protected LLStandaloneLoginService m_loginService;
#region IRegionModule Members
public void Initialise(IConfigSource source)
{
IConfig startupConfig = source.Configs["Startup"];
if (startupConfig != null)
{
m_enabled = !startupConfig.GetBoolean("gridmode", false);
}
if (m_enabled)
{
authenticate = true;
welcomeMessage = "Welcome to OpenSim";
IConfig standaloneConfig = source.Configs["StandAlone"];
if (standaloneConfig != null)
{
authenticate = standaloneConfig.GetBoolean("accounts_authenticate", true);
welcomeMessage = standaloneConfig.GetString("welcome_message");
}
}
}
public void AddRegion(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (m_enabled)
{
RemoveScene(scene);
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void RegionLoaded(Scene scene)
{
if (m_firstScene == null)
{
m_firstScene = scene;
if (m_enabled)
{
//TODO: fix casting.
LibraryRootFolder rootFolder
= m_firstScene.CommsManager.UserProfileCacheService.LibraryRoot as LibraryRootFolder;
IHttpServer httpServer = MainServer.Instance;
//TODO: fix the casting of the user service, maybe by registering the userManagerBase with scenes, or refactoring so we just need a IUserService reference
m_loginService
= new LLStandaloneLoginService(
(UserManagerBase)m_firstScene.CommsManager.UserAdminService, welcomeMessage,
m_firstScene.InventoryService, m_firstScene.CommsManager.NetworkServersInfo, authenticate,
rootFolder, this);
httpServer.AddXmlRPCHandler("login_to_simulator", m_loginService.XmlRpcLoginMethod);
// provides the web form login
httpServer.AddHTTPHandler("login", m_loginService.ProcessHTMLLogin);
// Provides the LLSD login
httpServer.SetDefaultLLSDHandler(m_loginService.LLSDLoginMethod);
}
}
if (m_enabled)
{
AddScene(scene);
}
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LLStandaloneLoginModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
protected void AddScene(Scene scene)
{
lock (m_scenes)
{
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
}
}
}
protected void RemoveScene(Scene scene)
{
lock (m_scenes)
{
if (m_scenes.Contains(scene))
{
m_scenes.Remove(scene);
}
}
}
public bool NewUserConnection(ulong regionHandle, AgentCircuitData agent, out string reason)
{
Scene scene;
if (TryGetRegion(regionHandle, out scene))
{
return scene.NewUserConnection(agent, out reason);
}
reason = "Region not found.";
return false;
}
public void LogOffUserFromGrid(ulong regionHandle, UUID AvatarID, UUID RegionSecret, string message)
{
Scene scene;
if (TryGetRegion(regionHandle, out scene))
{
scene.HandleLogOffUserFromGrid(AvatarID, RegionSecret, message);
}
}
public RegionInfo RequestNeighbourInfo(ulong regionhandle)
{
Scene scene;
if (TryGetRegion(regionhandle, out scene))
{
return scene.RegionInfo;
}
return null;
}
public RegionInfo RequestClosestRegion(string region)
{
Scene scene;
if (TryGetRegion(region, out scene))
{
return scene.RegionInfo;
}
else if (m_scenes.Count > 0)
{
return m_scenes[0].RegionInfo;
}
return null;
}
public RegionInfo RequestNeighbourInfo(UUID regionID)
{
Scene scene;
if (TryGetRegion(regionID, out scene))
{
return scene.RegionInfo;
}
return null;
}
protected bool TryGetRegion(ulong regionHandle, out Scene scene)
{
lock (m_scenes)
{
foreach (Scene nextScene in m_scenes)
{
if (nextScene.RegionInfo.RegionHandle == regionHandle)
{
scene = nextScene;
return true;
}
}
}
scene = null;
return false;
}
protected bool TryGetRegion(UUID regionID, out Scene scene)
{
lock (m_scenes)
{
foreach (Scene nextScene in m_scenes)
{
if (nextScene.RegionInfo.RegionID == regionID)
{
scene = nextScene;
return true;
}
}
}
scene = null;
return false;
}
protected bool TryGetRegion(string regionName, out Scene scene)
{
lock (m_scenes)
{
foreach (Scene nextScene in m_scenes)
{
if (nextScene.RegionInfo.RegionName.Equals(regionName, StringComparison.InvariantCultureIgnoreCase))
{
scene = nextScene;
return true;
}
}
}
scene = null;
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace BTDB.KVDBLayer.BTreeMem;
class BTreeLeafComp : IBTreeLeafNode, IBTreeNode
{
internal readonly long TransactionId;
byte[]? _keyBytes;
struct Member
{
internal ushort KeyOffset;
internal ushort KeyLength;
internal byte[] Value;
}
Member[] _keyValues;
internal const long MaxTotalLen = ushort.MaxValue;
internal const int MaxMembers = 30;
BTreeLeafComp(long transactionId, int length)
{
TransactionId = transactionId;
_keyValues = new Member[length];
}
internal BTreeLeafComp(long transactionId, BTreeLeafMember[] newKeyValues)
{
Debug.Assert(newKeyValues.Length > 0 && newKeyValues.Length <= MaxMembers);
TransactionId = transactionId;
_keyBytes = new byte[newKeyValues.Sum(m => m.Key.Length)];
_keyValues = new Member[newKeyValues.Length];
ushort ofs = 0;
for (var i = 0; i < newKeyValues.Length; i++)
{
_keyValues[i] = new Member
{
KeyOffset = ofs,
KeyLength = (ushort)newKeyValues[i].Key.Length,
Value = newKeyValues[i].Value
};
Array.Copy(newKeyValues[i].Key, 0, _keyBytes, ofs, _keyValues[i].KeyLength);
ofs += _keyValues[i].KeyLength;
}
}
BTreeLeafComp(long transactionId, byte[] newKeyBytes, Member[] newKeyValues)
{
TransactionId = transactionId;
_keyBytes = newKeyBytes;
_keyValues = newKeyValues;
}
internal static IBTreeNode CreateFirst(ref CreateOrUpdateCtx ctx)
{
Debug.Assert(ctx.Key.Length <= MaxTotalLen);
var result = new BTreeLeafComp(ctx.TransactionId, 1);
result._keyBytes = ctx.Key.ToArray();
result._keyValues[0] = new Member
{
KeyOffset = 0,
KeyLength = (ushort)result._keyBytes.Length,
Value = ctx.Value.ToArray()
};
return result;
}
int Find(in ReadOnlySpan<byte> key)
{
var left = 0;
var keyValues = _keyValues;
var right = keyValues.Length;
var keyBytes = _keyBytes;
while (left < right)
{
var middle = (left + right) / 2;
int currentKeyOfs = keyValues[middle].KeyOffset;
int currentKeyLen = keyValues[middle].KeyLength;
var result = key.SequenceCompareTo(keyBytes.AsSpan(currentKeyOfs, currentKeyLen));
if (result == 0)
{
return middle * 2 + 1;
}
if (result < 0)
{
right = middle;
}
else
{
left = middle + 1;
}
}
return left * 2;
}
public void CreateOrUpdate(ref CreateOrUpdateCtx ctx)
{
var index = Find(ctx.Key);
if ((index & 1) == 1)
{
index = (int)((uint)index / 2);
ctx.Created = false;
ctx.KeyIndex = index;
var m = _keyValues[index];
m.Value = ctx.Value.ToArray();
var leaf = this;
if (ctx.TransactionId != TransactionId)
{
leaf = new BTreeLeafComp(ctx.TransactionId, _keyValues.Length);
Array.Copy(_keyValues, leaf._keyValues, _keyValues.Length);
leaf._keyBytes = _keyBytes;
ctx.Node1 = leaf;
ctx.Update = true;
}
leaf._keyValues[index] = m;
ctx.Stack.Add(new NodeIdxPair { Node = leaf, Idx = index });
return;
}
if ((long)_keyBytes!.Length + ctx.Key.Length > MaxTotalLen)
{
var currentKeyValues = new BTreeLeafMember[_keyValues.Length];
for (var i = 0; i < currentKeyValues.Length; i++)
{
var member = _keyValues[i];
currentKeyValues[i] = new BTreeLeafMember
{
Key = _keyBytes.AsSpan(member.KeyOffset, member.KeyLength).ToArray(),
Value = member.Value
};
}
new BTreeLeaf(ctx.TransactionId - 1, currentKeyValues).CreateOrUpdate(ref ctx);
return;
}
index = index / 2;
ctx.Created = true;
ctx.KeyIndex = index;
var newKey = ctx.Key;
if (_keyValues.Length < MaxMembers)
{
var newKeyValues = new Member[_keyValues.Length + 1];
var newKeyBytes = new byte[_keyBytes.Length + newKey.Length];
Array.Copy(_keyValues, 0, newKeyValues, 0, index);
var ofs = (ushort)(index == 0 ? 0 : newKeyValues[index - 1].KeyOffset + newKeyValues[index - 1].KeyLength);
newKeyValues[index] = new Member
{
KeyOffset = ofs,
KeyLength = (ushort)newKey.Length,
Value = ctx.Value.ToArray()
};
Array.Copy(_keyBytes, 0, newKeyBytes, 0, ofs);
newKey.CopyTo(newKeyBytes.AsSpan(ofs));
Array.Copy(_keyBytes, ofs, newKeyBytes, ofs + newKey.Length, _keyBytes.Length - ofs);
Array.Copy(_keyValues, index, newKeyValues, index + 1, _keyValues.Length - index);
RecalculateOffsets(newKeyValues);
var leaf = this;
if (ctx.TransactionId != TransactionId)
{
leaf = new BTreeLeafComp(ctx.TransactionId, newKeyBytes, newKeyValues);
ctx.Node1 = leaf;
ctx.Update = true;
}
else
{
_keyValues = newKeyValues;
_keyBytes = newKeyBytes;
}
ctx.Stack.Add(new NodeIdxPair { Node = leaf, Idx = index });
return;
}
ctx.Split = true;
var keyCountLeft = (_keyValues.Length + 1) / 2;
var keyCountRight = _keyValues.Length + 1 - keyCountLeft;
var leftNode = new BTreeLeafComp(ctx.TransactionId, keyCountLeft);
var rightNode = new BTreeLeafComp(ctx.TransactionId, keyCountRight);
ctx.Node1 = leftNode;
ctx.Node2 = rightNode;
if (index < keyCountLeft)
{
Array.Copy(_keyValues, 0, leftNode._keyValues, 0, index);
var ofs = (ushort)(index == 0 ? 0 : _keyValues[index - 1].KeyOffset + _keyValues[index - 1].KeyLength);
leftNode._keyValues[index] = new Member
{
KeyOffset = ofs,
KeyLength = (ushort)newKey.Length,
Value = ctx.Value.ToArray()
};
Array.Copy(_keyValues, index, leftNode._keyValues, index + 1, keyCountLeft - index - 1);
Array.Copy(_keyValues, keyCountLeft - 1, rightNode._keyValues, 0, keyCountRight);
var leftKeyBytesLen = _keyValues[keyCountLeft - 1].KeyOffset + newKey.Length;
var newKeyBytes = new byte[leftKeyBytesLen];
Array.Copy(_keyBytes, 0, newKeyBytes, 0, ofs);
newKey.CopyTo(newKeyBytes.AsSpan(ofs));
Array.Copy(_keyBytes, ofs, newKeyBytes, ofs + newKey.Length, leftKeyBytesLen - (ofs + newKey.Length));
leftNode._keyBytes = newKeyBytes;
newKeyBytes = new byte[_keyBytes.Length + newKey.Length - leftKeyBytesLen];
Array.Copy(_keyBytes, leftKeyBytesLen - newKey.Length, newKeyBytes, 0, newKeyBytes.Length);
rightNode._keyBytes = newKeyBytes;
ctx.Stack.Add(new NodeIdxPair { Node = leftNode, Idx = index });
ctx.SplitInRight = false;
RecalculateOffsets(leftNode._keyValues);
}
else
{
Array.Copy(_keyValues, 0, leftNode._keyValues, 0, keyCountLeft);
var leftKeyBytesLen = _keyValues[keyCountLeft].KeyOffset;
var newKeyBytes = new byte[leftKeyBytesLen];
Array.Copy(_keyBytes, 0, newKeyBytes, 0, leftKeyBytesLen);
leftNode._keyBytes = newKeyBytes;
newKeyBytes = new byte[_keyBytes.Length + newKey.Length - leftKeyBytesLen];
var ofs = (index == _keyValues.Length ? _keyBytes.Length : _keyValues[index].KeyOffset) - leftKeyBytesLen;
Array.Copy(_keyBytes, leftKeyBytesLen, newKeyBytes, 0, ofs);
newKey.CopyTo(newKeyBytes.AsSpan(ofs));
Array.Copy(_keyBytes, ofs + leftKeyBytesLen, newKeyBytes, ofs + newKey.Length, _keyBytes.Length - ofs - leftKeyBytesLen);
rightNode._keyBytes = newKeyBytes;
Array.Copy(_keyValues, keyCountLeft, rightNode._keyValues, 0, index - keyCountLeft);
rightNode._keyValues[index - keyCountLeft] = new Member
{
KeyOffset = 0,
KeyLength = (ushort)newKey.Length,
Value = ctx.Value.ToArray(),
};
Array.Copy(_keyValues, index, rightNode._keyValues, index - keyCountLeft + 1, keyCountLeft + keyCountRight - 1 - index);
ctx.Stack.Add(new NodeIdxPair { Node = rightNode, Idx = index - keyCountLeft });
ctx.SplitInRight = true;
}
RecalculateOffsets(rightNode._keyValues);
}
public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, in ReadOnlySpan<byte> key)
{
var idx = Find(key);
FindResult result;
if ((idx & 1) == 1)
{
result = FindResult.Exact;
idx = (int)((uint)idx / 2);
}
else
{
result = FindResult.Previous;
idx = (int)((uint)idx / 2) - 1;
}
stack.Add(new NodeIdxPair { Node = this, Idx = idx });
keyIndex = idx;
return result;
}
public long CalcKeyCount()
{
return _keyValues.Length;
}
public byte[] GetLeftMostKey()
{
Debug.Assert(_keyValues[0].KeyOffset == 0);
return _keyBytes.AsSpan(0, _keyValues[0].KeyLength).ToArray();
}
public void FillStackByIndex(List<NodeIdxPair> stack, long keyIndex)
{
stack.Add(new NodeIdxPair { Node = this, Idx = (int)keyIndex });
}
public long FindLastWithPrefix(in ReadOnlySpan<byte> prefix)
{
var left = 0;
var keyValues = _keyValues;
var right = keyValues.Length - 1;
var keyBytes = _keyBytes;
int result;
int currentKeyOfs;
int currentKeyLen;
while (left < right)
{
var middle = (left + right) / 2;
currentKeyOfs = keyValues[middle].KeyOffset;
currentKeyLen = keyValues[middle].KeyLength;
result = prefix.SequenceCompareTo(keyBytes.AsSpan(currentKeyOfs, Math.Min(currentKeyLen, prefix.Length)));
if (result < 0)
{
right = middle;
}
else
{
left = middle + 1;
}
}
currentKeyOfs = keyValues[left].KeyOffset;
currentKeyLen = keyValues[left].KeyLength;
result = prefix.SequenceCompareTo(keyBytes.AsSpan(currentKeyOfs, Math.Min(currentKeyLen, prefix.Length)));
if (result < 0) left--;
return left;
}
public bool NextIdxValid(int idx)
{
return idx + 1 < _keyValues.Length;
}
public void FillStackByLeftMost(List<NodeIdxPair> stack, int idx)
{
// Nothing to do
}
public void FillStackByRightMost(List<NodeIdxPair> stack, int i)
{
// Nothing to do
}
public int GetLastChildrenIdx()
{
return _keyValues.Length - 1;
}
public IBTreeNode EraseRange(long transactionId, long firstKeyIndex, long lastKeyIndex)
{
var newKeyValues = new Member[_keyValues.Length + firstKeyIndex - lastKeyIndex - 1];
var newKeyBytes = new byte[_keyBytes!.Length + _keyValues[firstKeyIndex].KeyOffset - _keyValues[lastKeyIndex].KeyOffset - _keyValues[lastKeyIndex].KeyLength];
Array.Copy(_keyValues, 0, newKeyValues, 0, (int)firstKeyIndex);
Array.Copy(_keyValues, (int)lastKeyIndex + 1, newKeyValues, (int)firstKeyIndex, newKeyValues.Length - (int)firstKeyIndex);
Array.Copy(_keyBytes, 0, newKeyBytes, 0, _keyValues[firstKeyIndex].KeyOffset);
Array.Copy(_keyBytes, _keyValues[lastKeyIndex].KeyOffset + _keyValues[lastKeyIndex].KeyLength, newKeyBytes, _keyValues[firstKeyIndex].KeyOffset, newKeyBytes.Length - _keyValues[firstKeyIndex].KeyOffset);
RecalculateOffsets(newKeyValues);
if (TransactionId == transactionId)
{
_keyValues = newKeyValues;
_keyBytes = newKeyBytes;
return this;
}
return new BTreeLeafComp(transactionId, newKeyBytes, newKeyValues);
}
public IBTreeNode EraseOne(long transactionId, long keyIndex)
{
var newKeyValues = new Member[_keyValues.Length - 1];
var newKeyBytes = new byte[_keyBytes!.Length - _keyValues[keyIndex].KeyLength];
Array.Copy(_keyValues, 0, newKeyValues, 0, (int)keyIndex);
Array.Copy(_keyValues, (int)keyIndex + 1, newKeyValues, (int)keyIndex, newKeyValues.Length - (int)keyIndex);
Array.Copy(_keyBytes, 0, newKeyBytes, 0, _keyValues[keyIndex].KeyOffset);
Array.Copy(_keyBytes, _keyValues[keyIndex].KeyOffset + _keyValues[keyIndex].KeyLength, newKeyBytes, _keyValues[keyIndex].KeyOffset, newKeyBytes.Length - _keyValues[keyIndex].KeyOffset);
RecalculateOffsets(newKeyValues);
if (TransactionId == transactionId)
{
_keyValues = newKeyValues;
_keyBytes = newKeyBytes;
return this;
}
return new BTreeLeafComp(transactionId, newKeyBytes, newKeyValues);
}
static void RecalculateOffsets(Member[] keyValues)
{
ushort ofs = 0;
for (var i = 0; i < keyValues.Length; i++)
{
keyValues[i].KeyOffset = ofs;
ofs += keyValues[i].KeyLength;
}
}
public ReadOnlySpan<byte> GetKey(int idx)
{
return _keyBytes.AsSpan(_keyValues[idx].KeyOffset, _keyValues[idx].KeyLength);
}
public ReadOnlySpan<byte> GetMemberValue(int idx)
{
return _keyValues[idx].Value;
}
public void SetMemberValue(int idx, in ReadOnlySpan<byte> value)
{
_keyValues[idx].Value = value.ToArray();
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
**
**
** Purpose: Culture-specific collection of resources.
**
**
===========================================================*/
namespace System.Resources {
using System;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
// A ResourceSet stores all the resources defined in one particular CultureInfo.
//
// The method used to load resources is straightforward - this class
// enumerates over an IResourceReader, loading every name and value, and
// stores them in a hash table. Custom IResourceReaders can be used.
//
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ResourceSet : IDisposable, IEnumerable
{
[NonSerialized] protected IResourceReader Reader;
#if FEATURE_CORECLR
internal Hashtable Table;
#else
protected Hashtable Table;
#endif
private Hashtable _caseInsensitiveTable; // For case-insensitive lookups.
#if LOOSELY_LINKED_RESOURCE_REFERENCE
[OptionalField]
private Assembly _assembly; // For LooselyLinkedResourceReferences
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
protected ResourceSet()
{
// To not inconvenience people subclassing us, we should allocate a new
// hashtable here just so that Table is set to something.
CommonInit();
}
// For RuntimeResourceSet, ignore the Table parameter - it's a wasted
// allocation.
internal ResourceSet(bool junk)
{
}
// Creates a ResourceSet using the system default ResourceReader
// implementation. Use this constructor to open & read from a file
// on disk.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public ResourceSet(String fileName)
{
Reader = new ResourceReader(fileName);
CommonInit();
ReadResources();
}
#if LOOSELY_LINKED_RESOURCE_REFERENCE
public ResourceSet(String fileName, Assembly assembly)
{
Reader = new ResourceReader(fileName);
CommonInit();
_assembly = assembly;
ReadResources();
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
// Creates a ResourceSet using the system default ResourceReader
// implementation. Use this constructor to read from an open stream
// of data.
//
[System.Security.SecurityCritical] // auto-generated_required
public ResourceSet(Stream stream)
{
Reader = new ResourceReader(stream);
CommonInit();
ReadResources();
}
#if LOOSELY_LINKED_RESOURCE_REFERENCE
[System.Security.SecurityCritical] // auto_generated_required
public ResourceSet(Stream stream, Assembly assembly)
{
Reader = new ResourceReader(stream);
CommonInit();
_assembly = assembly;
ReadResources();
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
public ResourceSet(IResourceReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
Contract.EndContractBlock();
Reader = reader;
CommonInit();
ReadResources();
}
#if LOOSELY_LINKED_RESOURCE_REFERENCE
public ResourceSet(IResourceReader reader, Assembly assembly)
{
if (reader == null)
throw new ArgumentNullException("reader");
Contract.EndContractBlock();
Reader = reader;
CommonInit();
_assembly = assembly;
ReadResources();
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
private void CommonInit()
{
Table = new Hashtable();
}
// Closes and releases any resources used by this ResourceSet, if any.
// All calls to methods on the ResourceSet after a call to close may
// fail. Close is guaranteed to be safely callable multiple times on a
// particular ResourceSet, and all subclasses must support these semantics.
public virtual void Close()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing) {
// Close the Reader in a thread-safe way.
IResourceReader copyOfReader = Reader;
Reader = null;
if (copyOfReader != null)
copyOfReader.Close();
}
Reader = null;
_caseInsensitiveTable = null;
Table = null;
}
public void Dispose()
{
Dispose(true);
}
#if LOOSELY_LINKED_RESOURCE_REFERENCE
// Optional - used for resolving assembly manifest resource references.
// This can safely be null.
[ComVisible(false)]
public Assembly Assembly {
get { return _assembly; }
/*protected*/ set { _assembly = value; }
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
// Returns the preferred IResourceReader class for this kind of ResourceSet.
// Subclasses of ResourceSet using their own Readers &; should override
// GetDefaultReader and GetDefaultWriter.
public virtual Type GetDefaultReader()
{
return typeof(ResourceReader);
}
#if !FEATURE_CORECLR
// Returns the preferred IResourceWriter class for this kind of ResourceSet.
// Subclasses of ResourceSet using their own Readers &; should override
// GetDefaultReader and GetDefaultWriter.
public virtual Type GetDefaultWriter()
{
return typeof(ResourceWriter);
}
#endif // !FEATURE_CORECLR
[ComVisible(false)]
public virtual IDictionaryEnumerator GetEnumerator()
{
return GetEnumeratorHelper();
}
/// <internalonly/>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumeratorHelper();
}
private IDictionaryEnumerator GetEnumeratorHelper()
{
Hashtable copyOfTable = Table; // Avoid a race with Dispose
if (copyOfTable == null)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
return copyOfTable.GetEnumerator();
}
// Look up a string value for a resource given its name.
//
public virtual String GetString(String name)
{
Object obj = GetObjectInternal(name);
try {
return (String)obj;
}
catch (InvalidCastException) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name));
}
}
public virtual String GetString(String name, bool ignoreCase)
{
Object obj;
String s;
// Case-sensitive lookup
obj = GetObjectInternal(name);
try {
s = (String)obj;
}
catch (InvalidCastException) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name));
}
// case-sensitive lookup succeeded
if (s != null || !ignoreCase) {
return s;
}
// Try doing a case-insensitive lookup
obj = GetCaseInsensitiveObjectInternal(name);
try {
return (String)obj;
}
catch (InvalidCastException) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name));
}
}
// Look up an object value for a resource given its name.
//
public virtual Object GetObject(String name)
{
return GetObjectInternal(name);
}
public virtual Object GetObject(String name, bool ignoreCase)
{
Object obj = GetObjectInternal(name);
if (obj != null || !ignoreCase)
return obj;
return GetCaseInsensitiveObjectInternal(name);
}
protected virtual void ReadResources()
{
IDictionaryEnumerator en = Reader.GetEnumerator();
while (en.MoveNext()) {
Object value = en.Value;
#if LOOSELY_LINKED_RESOURCE_REFERENCE
if (Assembly != null && value is LooselyLinkedResourceReference) {
LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value;
value = assRef.Resolve(Assembly);
}
#endif //LOOSELYLINKEDRESOURCEREFERENCE
Table.Add(en.Key, value);
}
// While technically possible to close the Reader here, don't close it
// to help with some WinRes lifetime issues.
}
private Object GetObjectInternal(String name)
{
if (name == null)
throw new ArgumentNullException("name");
Contract.EndContractBlock();
Hashtable copyOfTable = Table; // Avoid a race with Dispose
if (copyOfTable == null)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
return copyOfTable[name];
}
private Object GetCaseInsensitiveObjectInternal(String name)
{
Hashtable copyOfTable = Table; // Avoid a race with Dispose
if (copyOfTable == null)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
Hashtable caseTable = _caseInsensitiveTable; // Avoid a race condition with Close
if (caseTable == null)
{
caseTable = new Hashtable(StringComparer.OrdinalIgnoreCase);
#if _DEBUG
//Console.WriteLine("ResourceSet::GetObject loading up case-insensitive data");
BCLDebug.Perf(false, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing "+name+" correctly in your source");
#endif
IDictionaryEnumerator en = copyOfTable.GetEnumerator();
while (en.MoveNext())
{
caseTable.Add(en.Key, en.Value);
}
_caseInsensitiveTable = caseTable;
}
return caseTable[name];
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Configuration;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace QuickSharpApiClient
{
public enum MethodType
{
Get,
Post,
Put,
Delete
}
public enum HttpContentType
{
Json,
Xml,
Text
}
public enum Credentials
{
None = 0,
Default = 1,
Basic = 2,
OAuth = 3
}
public class ApiClient
{
private IDictionary<string, string> _headers = new Dictionary<string, string>();
private IDictionary<HttpContentType, string> _contentTypes = new Dictionary<HttpContentType, string>
{
{ HttpContentType.Json, "application/json" },
{ HttpContentType.Xml, "application/xml" },
{ HttpContentType.Text, "application/text" }
};
public bool UseDefaultCredentials { get; set; }
public Credentials UseCredentials { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string AccessToken { get; set; }
public int MaxResponseContentBufferSize { get; set; }
public string ApiUrl { get; private set; }
public HttpContentType DefaultContentType { get; set; }
public MethodType Method { get; private set; }
public string ContentType
{
get
{
string contentType;
_contentTypes.TryGetValue(DefaultContentType, out contentType);
return contentType;
}
}
public void AddHeader(string key, string value)
{
_headers.Add(key, value);
}
public ApiClient(string uri, MethodType method)
{
MaxResponseContentBufferSize = 256000;
DefaultContentType = HttpContentType.Json;
Method = method;
ApiUrl = uri;
this.AddHeader("User-Agent", "Mozilla /5.0 (Compatible MSIE 9.0;Windows NT 6.1;WOW64; Trident/5.0)");
}
public Task<string> SendAsync(string contentRequest = "")
{
try
{
var uri = new Uri(ApiUrl);
var httpContentRequest = new StringContent(contentRequest, System.Text.Encoding.UTF8, ContentType);
AllowUnsafeHeaderParsing(true);
var response = SendAsync(uri, httpContentRequest, Method);
AllowUnsafeHeaderParsing(false);
var resultAsync = response.Result.Content.ReadAsStringAsync();
return resultAsync;
}
catch (HttpRequestException hre)
{
throw hre;
}
catch (Exception ex)
{
// For debugging
throw ex;
}
}
public TResponse SendAsync<TRequest, TResponse>(TRequest request)
{
var contentRequest = ConvertToJson(request);
var response = SendAsync(contentRequest);
return ConvertFromJson<TResponse>(response.Result);
}
public TResponse SendAsync<TResponse>()
{
var response = SendAsync();
return ConvertFromJson<TResponse>(response.Result);
}
private async Task<HttpResponseMessage> SendAsync(Uri uri, HttpContent content, MethodType method)
{
if(UseDefaultCredentials)
{
UseCredentials = Credentials.Default;
}
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = UseCredentials == Credentials.Default
};
var client = new HttpClient(handler, true) { MaxResponseContentBufferSize = 256000 };
if (UseCredentials == Credentials.Basic)
{
if ((string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password)))
{
throw new InvalidOperationException("Basic Authentication required.");
}
var byteArray = Encoding.ASCII.GetBytes(string.Concat(UserName, ":", Password));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
else if (UseCredentials == Credentials.OAuth)
{
if (string.IsNullOrWhiteSpace(AccessToken))
{
throw new InvalidOperationException("Access token required.");
}
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
}
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ContentType));
foreach (var header in _headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
Task<HttpResponseMessage> message = null;
switch (Method)
{
case MethodType.Get:
message = client.GetAsync(uri);
break;
case MethodType.Post:
message = client.PostAsync(uri, content);
break;
case MethodType.Put:
message = client.PutAsync(uri, content);
break;
case MethodType.Delete:
message = client.DeleteAsync(uri);
break;
}
return await message;
}
public static string ConvertToJson<TRequest>(TRequest request)
{
var serializer = new JavaScriptSerializer();
var result = serializer.Serialize(request);
return result;
}
public static TResponse ConvertFromJson<TResponse>(string request)
{
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<TResponse>(request);
return result;
}
// Enable/disable useUnsafeHeaderParsing.
private static bool AllowUnsafeHeaderParsing(bool enable)
{
//Get the assembly that contains the internal class
var assembly = Assembly.GetAssembly(typeof(SettingsSection));
if (assembly != null)
{
//Use the assembly in order to get the internal type for the internal class
Type settingsSectionType = assembly.GetType("System.Net.Configuration.SettingsSectionInternal");
if (settingsSectionType != null)
{
//Use the internal static property to get an instance of the internal settings class.
//If the static instance isn't created already invoking the property will create it for us.
object anInstance = settingsSectionType.InvokeMember("Section",
BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });
if (anInstance != null)
{
//Locate the private bool field that tells the framework if unsafe header parsing is allowed
FieldInfo aUseUnsafeHeaderParsing = settingsSectionType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance);
if (aUseUnsafeHeaderParsing != null)
{
aUseUnsafeHeaderParsing.SetValue(anInstance, enable);
return true;
}
}
}
}
return false;
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Linq;
using Encog.MathUtil.Error;
using Encog.ML.Data;
using Encog.Neural.Networks;
using Encog.Util;
namespace Encog.MathUtil.Matrices.Hessian
{
/// <summary>
/// Calculate the Hessian matrix using the finite difference method. This is a
/// very simple method of calculating the Hessian. The algorithm does not vary
/// greatly by number layers. This makes it very useful as a tool to check the
/// accuracy of other methods of determining the Hessian.
/// For more information on the Finite Difference Method see the following article.
/// http://en.wikipedia.org/wiki/Finite_difference_method
/// </summary>
public class HessianFD : BasicHessian
{
/// <summary>
/// The initial step size for dStep.
/// </summary>
public const double InitialStep = 0.001;
/// <summary>
/// The center of the point array.
/// </summary>
private int _center;
/// <summary>
/// The derivative coefficient, used for the finite difference method.
/// </summary>
private double[] _dCoeff;
/// <summary>
/// The derivative step size, used for the finite difference method.
/// </summary>
private double[] _dStep;
/// <summary>
/// The number of points actually used, which is (pointsPerSide*2)+1.
/// </summary>
private int _pointCount;
/// <summary>
/// The weight count.
/// </summary>
private int _weightCount;
/// <summary>
/// Construct the HessianFD.
/// </summary>
public HessianFD()
{
PointsPerSide = 5;
}
/// <summary>
/// The number of points requested per side. This determines the accuracy of the calculation.
/// </summary>
private int PointsPerSide { get; set; }
/// <inheritdoc />
public override void Init(BasicNetwork theNetwork, IMLDataSet theTraining)
{
base.Init(theNetwork, theTraining);
_weightCount = theNetwork.Structure.Flat.Weights.Length;
_center = PointsPerSide + 1;
_pointCount = (PointsPerSide*2) + 1;
_dCoeff = CreateCoefficients();
_dStep = new double[_weightCount];
for (int i = 0; i < _weightCount; i++)
{
_dStep[i] = InitialStep;
}
}
/// <inheritdoc />
public override void Compute()
{
_sse = 0;
for (int i = 0; i < _network.OutputCount; i++)
{
InternalCompute(i);
}
}
/// <inheritdoc />
private void InternalCompute(int outputNeuron)
{
int row = 0;
var error = new ErrorCalculation();
var derivative = new double[_weightCount];
// Loop over every training element
foreach (IMLDataPair pair in _training)
{
EngineArray.Fill(derivative, 0);
IMLData networkOutput = _network.Compute(pair.Input);
double e = pair.Ideal[outputNeuron] - networkOutput[outputNeuron];
error.UpdateError(networkOutput[outputNeuron], pair.Ideal[outputNeuron]);
int currentWeight = 0;
// loop over the output weights
int outputFeedCount = _network.GetLayerTotalNeuronCount(_network.LayerCount - 2);
for (int i = 0; i < _network.OutputCount; i++)
{
for (int j = 0; j < outputFeedCount; j++)
{
double jc;
if (i == outputNeuron)
{
jc = ComputeDerivative(pair.Input, outputNeuron,
currentWeight, _dStep,
networkOutput[outputNeuron], row);
}
else
{
jc = 0;
}
_gradients[currentWeight] += jc*e;
derivative[currentWeight] = jc;
currentWeight++;
}
}
// Loop over every weight in the neural network
while (currentWeight < _network.Flat.Weights.Length)
{
double jc = ComputeDerivative(
pair.Input, outputNeuron, currentWeight,
_dStep,
networkOutput[outputNeuron], row);
derivative[currentWeight] = jc;
_gradients[currentWeight] += jc*e;
currentWeight++;
}
row++;
UpdateHessian(derivative);
}
_sse += error.CalculateSSE();
}
/// <summary>
/// Computes the derivative of the output of the neural network with respect to a weight.
/// </summary>
/// <param name="inputData">The input data to the neural network.</param>
/// <param name="outputNeuron">The weight.</param>
/// <param name="weight">The step size.</param>
/// <param name="stepSize">The output from the neural network.</param>
/// <param name="networkOutput">The training row currently being processed.</param>
/// <param name="row"></param>
/// <returns>The derivative output.</returns>
private double ComputeDerivative(IMLData inputData, int outputNeuron, int weight, double[] stepSize,
double networkOutput, int row)
{
double temp = _network.Flat.Weights[weight];
var points = new double[_dCoeff.Length];
stepSize[row] = Math.Max(InitialStep*Math.Abs(temp), InitialStep);
points[_center] = networkOutput;
for (int i = 0; i < _dCoeff.Length; i++)
{
if (i == _center)
continue;
double newWeight = temp + ((i - _center))
*stepSize[row];
_network.Flat.Weights[weight] = newWeight;
IMLData output = _network.Compute(inputData);
points[i] = output[outputNeuron];
}
double result = _dCoeff.Select((t, i) => t*points[i]).Sum();
result /= Math.Pow(stepSize[row], 1);
_network.Flat.Weights[weight] = temp;
return result;
}
/// <summary>
/// Compute finite difference coefficients according to the method provided here:
/// http://en.wikipedia.org/wiki/Finite_difference_coefficients
/// </summary>
/// <returns>An array of the coefficients for FD.</returns>
public double[] CreateCoefficients()
{
var result = new double[_pointCount];
var delts = new Matrix(_pointCount, _pointCount);
double[][] t = delts.Data;
for (int j = 0; j < _pointCount; j++)
{
double delt = (j - _center);
double x = 1.0;
for (int k = 0; k < _pointCount; k++)
{
t[j][k] = x/EncogMath.Factorial(k);
x *= delt;
}
}
Matrix invMatrix = delts.Inverse();
double f = EncogMath.Factorial(_pointCount);
for (int k = 0; k < _pointCount; k++)
{
result[k] = (Math
.Round(invMatrix.Data[1][k]*f))/f;
}
return result;
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using DotNetOpenMail;
using DotNetOpenMail.SmtpAuth;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Data.SimpleDB;
namespace OpenSim.Region.CoreModules.Scripting.EmailModules
{
public class GetEmailModule : IGetEmailModule
{
//
// Log
//
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//
// Module vars
//
private IConfigSource m_Config;
private int m_MaxQueueSize = 50; // maximum size of an object mail queue
private Dictionary<UUID, List<Email>> m_MailQueues = new Dictionary<UUID, List<Email>>();
private Dictionary<UUID, DateTime> m_LastGetEmailCall = new Dictionary<UUID, DateTime>();
private TimeSpan m_QueueTimeout = new TimeSpan(2, 0, 0); // 2 hours without llGetNextEmail drops the queue
// Database support
private ConnectionFactory _connectionFactory;
private string _connectString = "";
private static long mTicksToEpoch = new DateTime(1970, 1, 1).Ticks;
// Scenes by Region Handle
private Dictionary<ulong, Scene> m_Scenes =
new Dictionary<ulong, Scene>();
private bool m_Enabled = false;
public void InsertEmail(UUID to, Email email)
{
// It's tempting to create the queue here. Don't; objects which have
// not yet called GetNextEmail should have no queue, and emails to them
// should be silently dropped.
lock (m_MailQueues)
{
if (m_MailQueues.ContainsKey(to))
{
if (m_MailQueues[to].Count >= m_MaxQueueSize)
{
// fail silently
return;
}
lock (m_MailQueues[to])
{
m_MailQueues[to].Add(email);
}
}
}
}
public void Initialise(Scene scene, IConfigSource config)
{
m_Config = config;
IConfig SMTPConfig;
//FIXME: RegionName is correct??
//m_RegionName = scene.RegionInfo.RegionName;
IConfig startupConfig = m_Config.Configs["Startup"];
m_Enabled = (startupConfig.GetString("getemailmodule", "DefaultGetEmailModule") == "DefaultGetEmailModule");
//Load SMTP SERVER config
try
{
if ((SMTPConfig = m_Config.Configs["SMTP"]) == null)
{
m_log.ErrorFormat("[InboundEmail]: SMTP not configured");
m_Enabled = false;
return;
}
if (!SMTPConfig.GetBoolean("inbound", true))
{
m_log.WarnFormat("[InboundEmail]: Inbound email module disabled in configuration");
m_Enabled = false;
return;
}
// Database support
_connectString = SMTPConfig.GetString("inbound_storage_connection", "");
if (_connectString == "")
{
m_log.ErrorFormat("[InboundEmail]: Could not find SMTP inbound_storage_connection.");
m_Enabled = false;
return;
}
_connectionFactory = new ConnectionFactory("MySQL", _connectString);
if (_connectionFactory == null)
{
m_log.ErrorFormat("[InboundEmail]: Inbound email module could not create MySQL connection.");
m_Enabled = false;
return;
}
}
catch (Exception e)
{
m_log.Error("[InboundEmail]: Inbound email not configured: " + e.Message);
m_log.Error(e.StackTrace);
m_Enabled = false;
return;
}
// It's a go!
if (m_Enabled)
{
lock (m_Scenes)
{
// Claim the interface slot
scene.RegisterModuleInterface<IGetEmailModule>(this);
// Add to scene list
if (m_Scenes.ContainsKey(scene.RegionInfo.RegionHandle))
{
m_Scenes[scene.RegionInfo.RegionHandle] = scene;
}
else
{
m_Scenes.Add(scene.RegionInfo.RegionHandle, scene);
}
}
m_log.Info("[InboundEmail]: Activated inbound email.");
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "DefaultGetEmailModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
/// <summary>
/// Delay function using thread in seconds
/// </summary>
/// <param name="seconds"></param>
private void DelayInSeconds(int delay)
{
delay = (int)((float)delay * 1000);
if (delay == 0)
return;
System.Threading.Thread.Sleep(delay);
}
public static uint DateTime2UnixTime(DateTime when)
{
long elapsed = DateTime.Now.Ticks - mTicksToEpoch;
return Convert.ToUInt32(elapsed / 10000000);
}
public static DateTime UnixTime2DateTime(uint when)
{
return new DateTime(mTicksToEpoch + when);
}
private bool IsLocal(UUID objectID)
{
UUID unused;
return (null != findPrim(objectID, out unused));
}
private SceneObjectPart findPrim(UUID objectID, out UUID regionUUID)
{
lock (m_Scenes)
{
foreach (Scene s in m_Scenes.Values)
{
SceneObjectPart part = s.GetSceneObjectPart(objectID);
if (part != null)
{
regionUUID = s.RegionInfo.RegionID;
return part;
}
}
}
regionUUID = UUID.Zero;
return null;
}
private void UpdateRegistration(ISimpleDB db, UUID uuid, UUID regionUUID)
{
string sql = "INSERT INTO emailregistrations (`uuid`, `time`, `region`) VALUES (?uuid, ?time, ?region)";
sql += " ON DUPLICATE KEY UPDATE `time`=?time";
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters["?uuid"] = uuid.ToString();
parameters["?region"] = regionUUID.ToString();
parameters["?time"] = DateTime2UnixTime(DateTime.UtcNow); // All storage dates are UTC
try
{
db.QueryNoResults(sql, parameters);
}
catch (Exception e)
{
m_log.Error("[InboundEmail]: Exception during database call to store message: "+e.Message);
m_log.Error(e.StackTrace);
}
}
private void DeleteMessage(ISimpleDB db, uint ID)
{
string sql = "DELETE FROM emailmessages WHERE `ID`=?id";
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters["?ID"] = ID.ToString();
try
{
db.QueryNoResults(sql, parameters);
}
catch (Exception e)
{
m_log.Error("[InboundEmail]: Exception during database call to delete delivered message: " + e.Message);
m_log.Error(e.StackTrace);
}
}
private uint QueryEmailCount(ISimpleDB db, UUID uuid)
{
try
{
string query
= "SELECT COUNT(*) FROM emailmessages WHERE uuid = ?uuid";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", uuid);
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
if (results.Count != 1)
return 0;
return Convert.ToUInt32(results[0]["COUNT(*)"]);
}
catch (Exception e)
{
m_log.Error("[InboundEmail]: Exception during database call to count messages: " + e.Message);
m_log.Error(e.StackTrace);
return 0;
}
}
private Email QueryNextEmail(ISimpleDB db, UUID uuid, string sender, string subject)
{
Email msg = new Email();
try
{
Dictionary<string, object> parms = new Dictionary<string, object>();
string query = "SELECT * FROM emailmessages WHERE uuid = ?uuid";
parms.Add("?uuid", uuid);
if (sender != "")
{
query += " AND from = ?from";
parms.Add("?from", sender);
}
if (subject != "")
{
query += " AND subject = ?subject";
parms.Add("?subject", subject);
}
query += " ORDER BY sent LIMIT 1";
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
if (results.Count != 1)
return null;
uint ID = Convert.ToUInt32(results[0]["ID"]);
uint unixtime = Convert.ToUInt32(results[0]["sent"]);
msg.time = unixtime.ToString(); // Note: email event is documented as string form of *UTC* unix time
msg.sender = results[0]["from"];
msg.subject = results[0]["subject"];
msg.message = results[0]["body"];
// This one has been handled, remove it from those queued in the DB.
DeleteMessage(db, ID);
}
catch (Exception e)
{
m_log.Error("[InboundEmail]: Exception during database call to store message: " + e.Message);
m_log.Error(e.StackTrace);
return null;
}
msg.numLeft = (int)QueryEmailCount(db, uuid);
return msg;
}
/// <summary>
///
/// </summary>
/// <param name="objectID"></param>
/// <param name="sender"></param>
/// <param name="subject"></param>
/// <returns></returns>
public Email GetNextEmail(UUID objectID, string sender, string subject)
{
try
{
using (ISimpleDB db = _connectionFactory.GetConnection())
{
UUID regionUUID;
SceneObjectPart part = findPrim(objectID, out regionUUID);
if (part != null)
{
UpdateRegistration(db, objectID, regionUUID);
return QueryNextEmail(db, objectID, sender, subject);
}
}
}
catch (Exception e)
{
m_log.Error("[InboundEmail]: Exception during database call to check messages: " + e.Message);
m_log.Error(e.StackTrace);
}
m_log.Error("[InboundEmail]: Next email not available. Part " + objectID.ToString() + " not found.");
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;
namespace ILRuntime.Runtime.Generated
{
unsafe class System_Type_Binding
{
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase method;
Type[] args;
Type type = typeof(System.Type);
args = new Type[]{};
method = type.GetMethod("GetMembers", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetMembers_0);
args = new Type[]{typeof(System.RuntimeTypeHandle)};
method = type.GetMethod("GetTypeFromHandle", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetTypeFromHandle_1);
args = new Type[]{typeof(System.String)};
method = type.GetMethod("GetField", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetField_2);
args = new Type[]{typeof(System.String)};
method = type.GetMethod("GetProperty", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetProperty_3);
args = new Type[]{};
method = type.GetMethod("get_IsGenericType", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, get_IsGenericType_4);
args = new Type[]{};
method = type.GetMethod("GetGenericTypeDefinition", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetGenericTypeDefinition_5);
args = new Type[]{typeof(System.Type)};
method = type.GetMethod("IsAssignableFrom", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, IsAssignableFrom_6);
args = new Type[]{};
method = type.GetMethod("get_IsArray", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, get_IsArray_7);
args = new Type[]{};
method = type.GetMethod("get_IsClass", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, get_IsClass_8);
args = new Type[]{typeof(System.Type), typeof(System.Type)};
method = type.GetMethod("op_Equality", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, op_Equality_9);
args = new Type[]{typeof(System.Reflection.BindingFlags)};
method = type.GetMethod("GetProperties", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetProperties_10);
args = new Type[]{typeof(System.Reflection.BindingFlags)};
method = type.GetMethod("GetFields", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetFields_11);
args = new Type[]{};
method = type.GetMethod("get_IsPrimitive", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, get_IsPrimitive_12);
args = new Type[]{typeof(System.Type)};
method = type.GetMethod("Equals", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, Equals_13);
args = new Type[]{typeof(System.String)};
method = type.GetMethod("GetType", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetType_14);
args = new Type[]{typeof(System.Type[])};
method = type.GetMethod("GetConstructor", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetConstructor_15);
args = new Type[]{typeof(System.String), typeof(System.Reflection.BindingFlags), typeof(System.Reflection.Binder), typeof(System.Object), typeof(System.Object[])};
method = type.GetMethod("InvokeMember", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, InvokeMember_16);
args = new Type[]{typeof(System.String)};
method = type.GetMethod("GetMethod", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetMethod_17);
args = new Type[]{};
method = type.GetMethod("get_BaseType", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, get_BaseType_18);
args = new Type[]{typeof(System.Type), typeof(System.Type)};
method = type.GetMethod("op_Inequality", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, op_Inequality_19);
args = new Type[]{typeof(System.String), typeof(System.Reflection.BindingFlags)};
method = type.GetMethod("GetField", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetField_20);
args = new Type[]{typeof(System.String), typeof(System.Reflection.BindingFlags)};
method = type.GetMethod("GetProperty", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetProperty_21);
args = new Type[]{typeof(System.Reflection.BindingFlags)};
method = type.GetMethod("GetMethods", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetMethods_22);
args = new Type[]{};
method = type.GetMethod("get_FullName", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, get_FullName_23);
args = new Type[]{typeof(System.Reflection.BindingFlags)};
method = type.GetMethod("GetMembers", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetMembers_24);
args = new Type[]{};
method = type.GetMethod("get_IsEnum", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, get_IsEnum_25);
args = new Type[]{};
method = type.GetMethod("GetElementType", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetElementType_26);
args = new Type[]{typeof(System.String)};
method = type.GetMethod("GetInterface", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetInterface_27);
args = new Type[]{};
method = type.GetMethod("GetGenericArguments", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetGenericArguments_28);
args = new Type[]{typeof(System.Reflection.BindingFlags), typeof(System.Reflection.Binder), typeof(System.Type[]), typeof(System.Reflection.ParameterModifier[])};
method = type.GetMethod("GetConstructor", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetConstructor_29);
app.RegisterCLRCreateArrayInstance(type, s => new System.Type[s]);
}
static StackObject* GetMembers_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetMembers();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* GetTypeFromHandle_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.RuntimeTypeHandle @handle = (System.RuntimeTypeHandle)typeof(System.RuntimeTypeHandle).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = System.Type.GetTypeFromHandle(@handle);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* GetField_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.String @name = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetField(@name);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* GetProperty_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.String @name = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetProperty(@name);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* get_IsGenericType_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.IsGenericType;
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method ? 1 : 0;
return __ret + 1;
}
static StackObject* GetGenericTypeDefinition_5(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetGenericTypeDefinition();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* IsAssignableFrom_6(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type @c = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.IsAssignableFrom(@c);
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method ? 1 : 0;
return __ret + 1;
}
static StackObject* get_IsArray_7(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.IsArray;
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method ? 1 : 0;
return __ret + 1;
}
static StackObject* get_IsClass_8(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.IsClass;
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method ? 1 : 0;
return __ret + 1;
}
static StackObject* op_Equality_9(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type @right = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type @left = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = left == right;
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method ? 1 : 0;
return __ret + 1;
}
static StackObject* GetProperties_10(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Reflection.BindingFlags @bindingAttr = (System.Reflection.BindingFlags)typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetProperties(@bindingAttr);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* GetFields_11(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Reflection.BindingFlags @bindingAttr = (System.Reflection.BindingFlags)typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetFields(@bindingAttr);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* get_IsPrimitive_12(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.IsPrimitive;
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method ? 1 : 0;
return __ret + 1;
}
static StackObject* Equals_13(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type @o = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.Equals(@o);
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method ? 1 : 0;
return __ret + 1;
}
static StackObject* GetType_14(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.String @typeName = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = System.Type.GetType(@typeName);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* GetConstructor_15(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type[] @types = (System.Type[])typeof(System.Type[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetConstructor(@types);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* InvokeMember_16(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 6);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Object[] @args = (System.Object[])typeof(System.Object[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Object @target = (System.Object)typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
System.Reflection.Binder @binder = (System.Reflection.Binder)typeof(System.Reflection.Binder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 4);
System.Reflection.BindingFlags @invokeAttr = (System.Reflection.BindingFlags)typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 5);
System.String @name = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 6);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.InvokeMember(@name, @invokeAttr, @binder, @target, @args);
object obj_result_of_this_method = result_of_this_method;
if(obj_result_of_this_method is CrossBindingAdaptorType)
{
return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance, true);
}
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method, true);
}
static StackObject* GetMethod_17(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.String @name = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetMethod(@name);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* get_BaseType_18(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.BaseType;
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* op_Inequality_19(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type @right = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type @left = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = left != right;
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method ? 1 : 0;
return __ret + 1;
}
static StackObject* GetField_20(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 3);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Reflection.BindingFlags @bindingAttr = (System.Reflection.BindingFlags)typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.String @name = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetField(@name, @bindingAttr);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* GetProperty_21(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 3);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Reflection.BindingFlags @bindingAttr = (System.Reflection.BindingFlags)typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.String @name = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetProperty(@name, @bindingAttr);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* GetMethods_22(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Reflection.BindingFlags @bindingAttr = (System.Reflection.BindingFlags)typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetMethods(@bindingAttr);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* get_FullName_23(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.FullName;
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* GetMembers_24(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Reflection.BindingFlags @bindingAttr = (System.Reflection.BindingFlags)typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetMembers(@bindingAttr);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* get_IsEnum_25(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.IsEnum;
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method ? 1 : 0;
return __ret + 1;
}
static StackObject* GetElementType_26(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetElementType();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* GetInterface_27(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.String @name = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetInterface(@name);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* GetGenericArguments_28(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetGenericArguments();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* GetConstructor_29(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 5);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Reflection.ParameterModifier[] @modifiers = (System.Reflection.ParameterModifier[])typeof(System.Reflection.ParameterModifier[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Type[] @types = (System.Type[])typeof(System.Type[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
System.Reflection.Binder @binder = (System.Reflection.Binder)typeof(System.Reflection.Binder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 4);
System.Reflection.BindingFlags @bindingAttr = (System.Reflection.BindingFlags)typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 5);
System.Type instance_of_this_method = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetConstructor(@bindingAttr, @binder, @types, @modifiers);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
}
}
| |
/* **********************************************************************************************************
* The MIT License (MIT) *
* *
* Copyright (c) 2016 Hypermediasystems Ges. f. Software mbH *
* Web: http://www.hypermediasystems.de *
* This file is part of hmssp *
* *
* 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.Dynamic;
using System.Reflection;
using Newtonsoft.Json;
namespace HMS.SP{
/// <summary>
/// <para>https://msdn.microsoft.com/en-us/library/office/dn499819.aspx#bk_Web</para>
/// </summary>
public class Web : SPBase,iSP{
[JsonProperty("__HMSError")]
public HMS.Util.__HMSError __HMSError_ { set; get; }
[JsonProperty("__status")]
public SP.__status __status_ { set; get; }
[JsonProperty("__deferred")]
public SP.__deferred __deferred_ { set; get; }
[JsonProperty("__metadata")]
public SP.__metadata __metadata_ { set; get; }
public Dictionary<string, string> __rest;
/// <summary>
/// <para>Specifies whether the current user can create declarative workflows. If not disabled on the Web application, the value is the same as the AllowCreateDeclarativeWorkflow property of the site collection. Default value: true.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("AllowCreateDeclarativeWorkflowForCurrentUser")]
public Boolean AllowCreateDeclarativeWorkflowForCurrentUser_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies whether the current user is allowed to use a designer application to customize this site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("AllowDesignerForCurrentUser")]
public Boolean AllowDesignerForCurrentUser_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies whether the current user is allowed to edit the master page.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("AllowMasterPageEditingForCurrentUser")]
public Boolean AllowMasterPageEditingForCurrentUser_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies whether the current user is allowed to revert the site to a default site template.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("AllowRevertFromTemplateForCurrentUser")]
public Boolean AllowRevertFromTemplateForCurrentUser_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies whether the site allows RSS feeds.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("AllowRssFeeds")]
public Boolean AllowRssFeeds_ { set; get; }
/// <summary>
/// <para>Specifies whether the current user can save declarative workflows as a template. If not disabled on the Web application, the value is the same as the AllowSaveDeclarativeWorkflowAsTemplate property of the site collection. Default value: true.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("AllowSaveDeclarativeWorkflowAsTemplateForCurrentUser")]
public Boolean AllowSaveDeclarativeWorkflowAsTemplateForCurrentUser_ { set; get; }
/// <summary>
/// <para>Specifies whether the current user can save or publish declarative workflows. If not disabled on the Web application, the value is the same as the AllowSavePublishDeclarativeWorkflowAsTemplate property of the site collection. When enabled, can only be set by a site collection administrator. Default value: true.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("AllowSavePublishDeclarativeWorkflowForCurrentUser")]
public Boolean AllowSavePublishDeclarativeWorkflowForCurrentUser_ { set; get; }
/// <summary>
/// <para>Gets a collection of metadata for the Web site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("AllProperties")]
public SP.PropertyValues AllProperties_ { set; get; }
/// <summary>
/// <para>The instance Id of the App Instance that this web represents. </para>
/// <para>R/W: R</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("AppInstanceId")]
public Guid AppInstanceId_ { set; get; }
/// <summary>
/// <para>Gets or sets the group of users who have been given contribute permissions to the Web site.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("AssociatedMemberGroup")]
public SP.Group AssociatedMemberGroup_ { set; get; }
/// <summary>
/// <para>Gets or sets the associated owner group of the Web site.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("AssociatedOwnerGroup")]
public SP.Group AssociatedOwnerGroup_ { set; get; }
/// <summary>
/// <para>Gets or sets the associated visitor group of the Web site.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("AssociatedVisitorGroup")]
public SP.Group AssociatedVisitorGroup_ { set; get; }
/// <summary>
/// <para>Gets the collection of all content types that apply to the current scope, including those of the current Web site, as well as any parent Web sites.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("AvailableContentTypes")]
public SP.ContentTypeCollection AvailableContentTypes_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the collection of all fields available for the current scope, including those of the current site, as well as any parent sites.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("AvailableFields")]
public SP.FieldCollection AvailableFields_ { set; get; }
/// <summary>
/// <para>Gets either the identifier (ID) of the site definition configuration that was used to create the site, or the ID of the site definition configuration from which the site template used to create the site was derived.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("Configuration")]
public Int16 Configuration_ { set; get; }
/// <summary>
/// <para>Gets the collection of content types for the Web site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("ContentTypes")]
public SP.ContentTypeCollection ContentTypes_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies when the site was created.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("Created")]
public DateTime Created_ { set; get; }
/// <summary>
/// <para>Gets the current user of the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("CurrentUser")]
public SP.User CurrentUser_ { set; get; }
/// <summary>
/// <para>Gets or sets the URL for a custom master page file to apply to the website.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("CustomMasterUrl")]
public String CustomMasterUrl_ { set; get; }
/// <summary>
/// <para>Gets or sets the description for the site.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("Description")]
public String Description_ { set; get; }
/// <summary>
/// <para>Gets or sets the description for the site.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("DescriptionResource")]
public SP.__deferred DescriptionResource_ { set; get; }
/// <summary>
/// <para>Gets the URL where the current user can download SharePoint Designer.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("DesignerDownloadUrlForCurrentUser")]
public String DesignerDownloadUrlForCurrentUser_ { set; get; }
/// <summary>
/// <para>Determines if the Document Library Callout's WAC previewers are enabled or not.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("DocumentLibraryCalloutOfficeWebAppPreviewersDisabled")]
public Boolean DocumentLibraryCalloutOfficeWebAppPreviewersDisabled_ { set; get; }
/// <summary>
/// <para>Represents the intersection of permissions of the app principal and the user principal. In the app-only case, this property returns only the permissions of the app principal.To check only user permissions (ignoring app permissions), use the GetUserEffectivePermissions method.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("EffectiveBasePermissions")]
public SP.BasePermissions EffectiveBasePermissions_ { set; get; }
/// <summary>
/// <para>Gets or sets a Boolean value that specifies whether the Web site should use Minimal Download Strategy.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("EnableMinimalDownload")]
public Boolean EnableMinimalDownload_ { set; get; }
/// <summary>
/// <para>Gets the collection of event receiver definitions that are currently available on the website.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("EventReceivers")]
public SP.EventReceiverCollection EventReceivers_ { set; get; }
// undefined class SP.EventReceiverCollection : Object { }
/// <summary>
/// <para>Gets a value that specifies the collection of features that are currently activated in the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("Features")]
public SP.FeatureCollection Features_ { set; get; }
/// <summary>
/// <para>Gets the collection of field objects that represents all the fields in the Web site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("Fields")]
public SP.FieldCollection Fields_ { set; get; }
/// <summary>
/// <para>Gets the collection of all first-level folders in the Web site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("Folders")]
public SP.FolderCollection Folders_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the site identifier for the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("Id")]
public Guid Id_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the LCID for the language that is used on the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("Language")]
public Int32 Language_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies when an item was last modified in the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("LastItemModifiedDate")]
public DateTime LastItemModifiedDate_ { set; get; }
/// <summary>
/// <para>Gets the collection of all lists that are contained in the Web site available to the current user based on the permissions of the current user.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("Lists")]
public SP.ListCollection Lists_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the collection of list definitions and list templates available for creating lists on the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("ListTemplates")]
public SP.ListTemplateCollection ListTemplates_ { set; get; }
/// <summary>
/// <para>Gets or sets the URL of the master page that is used for the website.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("MasterUrl")]
public String MasterUrl_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the navigation structure on the site, including the Quick Launch area and the top navigation bar.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("Navigation")]
public SP.Navigation Navigation_ { set; get; }
/// <summary>
/// <para>Gets the parent website of the specified website.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("ParentWeb")]
public SP.Web ParentWeb_ { set; get; }
/// <summary>
/// <para>Gets the collection of push notification subscribers over the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("PushNotificationSubscribers")]
public SP.PushNotificationSubscriberCollection PushNotificationSubscribers_ { set; get; }
/// <summary>
/// <para>Gets or sets a value that specifies whether the Quick Launch area is enabled on the site.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("QuickLaunchEnabled")]
public Boolean QuickLaunchEnabled_ { set; get; }
/// <summary>
/// <para>Specifies the collection of recycle bin items of the recycle bin of the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("RecycleBin")]
public SP.RecycleBin RecycleBin_ { set; get; }
// undefined class SP.RecycleBin : Object { }
/// <summary>
/// <para>Gets or sets a value that determines whether the recycle bin is enabled for the website.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("RecycleBinEnabled")]
public Boolean RecycleBinEnabled_ { set; get; }
/// <summary>
/// <para>Gets the regional settings that are currently implemented on the website.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("RegionalSettings")]
public SP.RegionalSettings RegionalSettings_ { set; get; }
/// <summary>
/// <para>Gets the collection of role definitions for the Web site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("RoleDefinitions")]
public SP.RoleDefinitionCollection RoleDefinitions_ { set; get; }
/// <summary>
/// <para>Gets the root folder for the Web site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("RootFolder")]
public SP.Folder RootFolder_ { set; get; }
/// <summary>
/// <para>Gets or sets a Boolean value that specifies whether the Web site can be saved as a site template.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("SaveSiteAsTemplateEnabled")]
public Boolean SaveSiteAsTemplateEnabled_ { set; get; }
/// <summary>
/// <para>Gets or sets the server-relative URL for the Web site.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("ServerRelativeUrl")]
public String ServerRelativeUrl_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies whether the current user is able to view the file system structure of this site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("ShowUrlStructureForCurrentUser")]
public Boolean ShowUrlStructureForCurrentUser_ { set; get; }
/// <summary>
/// <para>Gets the collection of groups for the site collection.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("SiteGroups")]
public SP.GroupCollection SiteGroups_ { set; get; }
/// <summary>
/// <para>Gets the UserInfo list of the site collection that contains the Web site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("SiteUserInfoList")]
public SP.List SiteUserInfoList_ { set; get; }
/// <summary>
/// <para>Gets the collection of all users that belong to the site collection.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("SiteUsers")]
public SP.UserCollection SiteUsers_ { set; get; }
/// <summary>
/// <para>Specifies the language code identifiers (LCIDs) of the languages that are enabled for the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("SupportedUILanguageIds")]
public Int32[] SupportedUILanguageIds_ { set; get; }
/// <summary>
/// <para>Gets or sets a value that specifies whether the RSS feeds are enabled on the site.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("SyndicationEnabled")]
public Boolean SyndicationEnabled_ { set; get; }
/// <summary>
/// <para>The theming information for this site. This includes information like colors, fonts, border radii sizes etc.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("ThemeInfo")]
public SP.ThemeInfo ThemeInfo_ { set; get; }
/// <summary>
/// <para>Gets or sets the title for the Web site.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("Title")]
public String Title_ { set; get; }
/// <summary>
/// <para>Gets or sets the title for the Web site.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("TitleResource")]
public SP.__deferred TitleResource_ { set; get; }
/// <summary>
/// <para>Gets or sets value that specifies whether the tree view is enabled on the site.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("TreeViewEnabled")]
public Boolean TreeViewEnabled_ { set; get; }
/// <summary>
/// <para>Gets or sets the user interface (UI) version of the Web site.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("UIVersion")]
public Int32 UIVersion_ { set; get; }
/// <summary>
/// <para>Gets or sets a value that specifies whether the settings UI for visual upgrade is shown or hidden.</para>
/// <para>R/W: RW</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("UIVersionConfigurationEnabled")]
public Boolean UIVersionConfigurationEnabled_ { set; get; }
/// <summary>
/// <para>Gets the absolute URL for the website.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("Url")]
public String Url_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the collection of user custom actions for the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("UserCustomActions")]
public SP.UserCustomActionCollection UserCustomActions_ { set; get; }
/// <summary>
/// <para>Represents key properties of the subsites of a site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("WebInfos")]
public SP.WebInformation WebInfos_ { set; get; }
/// <summary>
/// <para>Gets a Web site collection object that represents all Web sites immediately beneath the Web site, excluding children of those Web sites.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("Webs")]
public SP.WebCollection Webs_ { set; get; }
/// <summary>
/// <para>Gets the name of the site definition or site template that was used to create the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:Yes</para>
/// </summary>
[JsonProperty("WebTemplate")]
public String WebTemplate_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the collection of all workflow associations for the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("WorkflowAssociations")]
public SP.WorkflowAssociationCollection WorkflowAssociations_ { set; get; }
// undefined class SP.WorkflowAssociationCollection : Object { }
/// <summary>
/// <para>Gets a value that specifies the collection of workflow templates associated with the site.</para>
/// <para>R/W: R</para>
/// <para>Returned with resource:No</para>
/// </summary>
[JsonProperty("WorkflowTemplates")]
public SP.WorkflowTemplateCollection WorkflowTemplates_ { set; get; }
// undefined class SP.WorkflowTemplateCollection : Object { }
/// <summary>
/// <para> Endpoints </para>
/// </summary>
static string[] endpoints = {
"http://<site url>/_api/web",
};
public Web(ExpandoObject expObj)
{
try
{
var use_EO = ((dynamic)expObj).entry.content.properties;
HMS.SP.SPUtil.expando2obj(use_EO, this, typeof(Web));
}
catch (Exception ex)
{
}
}
// used by Newtonsoft.JSON
public Web()
{
}
public Web(string json)
{
if( json == String.Empty )
return;
dynamic jobject = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
dynamic refObj = jobject;
if (jobject.d != null)
refObj = jobject.d;
string errInfo = "";
if (refObj.results != null)
{
if (refObj.results.Count > 1)
errInfo = "Result is Collection, only 1. entry displayed.";
refObj = refObj.results[0];
}
List<string> usedFields = new List<string>();
usedFields.Add("__HMSError");
HMS.SP.SPUtil.dyn_ValueSet("__HMSError", refObj, this);
usedFields.Add("__deferred");
this.__deferred_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.__deferred));
usedFields.Add("__metadata");
this.__metadata_ = new SP.__metadata(HMS.SP.SPUtil.dyn_toString(refObj.__metadata));
usedFields.Add("AllowCreateDeclarativeWorkflowForCurrentUser");
HMS.SP.SPUtil.dyn_ValueSet("AllowCreateDeclarativeWorkflowForCurrentUser", refObj, this);
usedFields.Add("AllowDesignerForCurrentUser");
HMS.SP.SPUtil.dyn_ValueSet("AllowDesignerForCurrentUser", refObj, this);
usedFields.Add("AllowMasterPageEditingForCurrentUser");
HMS.SP.SPUtil.dyn_ValueSet("AllowMasterPageEditingForCurrentUser", refObj, this);
usedFields.Add("AllowRevertFromTemplateForCurrentUser");
HMS.SP.SPUtil.dyn_ValueSet("AllowRevertFromTemplateForCurrentUser", refObj, this);
usedFields.Add("AllowRssFeeds");
HMS.SP.SPUtil.dyn_ValueSet("AllowRssFeeds", refObj, this);
usedFields.Add("AllowSaveDeclarativeWorkflowAsTemplateForCurrentUser");
HMS.SP.SPUtil.dyn_ValueSet("AllowSaveDeclarativeWorkflowAsTemplateForCurrentUser", refObj, this);
usedFields.Add("AllowSavePublishDeclarativeWorkflowForCurrentUser");
HMS.SP.SPUtil.dyn_ValueSet("AllowSavePublishDeclarativeWorkflowForCurrentUser", refObj, this);
usedFields.Add("AllProperties");
this.AllProperties_ = new SP.PropertyValues(HMS.SP.SPUtil.dyn_toString(refObj.AllProperties));
usedFields.Add("AppInstanceId");
HMS.SP.SPUtil.dyn_ValueSet("AppInstanceId", refObj, this);
usedFields.Add("AssociatedMemberGroup");
this.AssociatedMemberGroup_ = new SP.Group(HMS.SP.SPUtil.dyn_toString(refObj.AssociatedMemberGroup));
usedFields.Add("AssociatedOwnerGroup");
this.AssociatedOwnerGroup_ = new SP.Group(HMS.SP.SPUtil.dyn_toString(refObj.AssociatedOwnerGroup));
usedFields.Add("AssociatedVisitorGroup");
this.AssociatedVisitorGroup_ = new SP.Group(HMS.SP.SPUtil.dyn_toString(refObj.AssociatedVisitorGroup));
usedFields.Add("AvailableContentTypes");
this.AvailableContentTypes_ = new SP.ContentTypeCollection(HMS.SP.SPUtil.dyn_toString(refObj.AvailableContentTypes));
usedFields.Add("AvailableFields");
this.AvailableFields_ = new SP.FieldCollection(HMS.SP.SPUtil.dyn_toString(refObj.AvailableFields));
usedFields.Add("Configuration");
HMS.SP.SPUtil.dyn_ValueSet("Configuration", refObj, this);
usedFields.Add("ContentTypes");
this.ContentTypes_ = new SP.ContentTypeCollection(HMS.SP.SPUtil.dyn_toString(refObj.ContentTypes));
usedFields.Add("Created");
HMS.SP.SPUtil.dyn_ValueSet("Created", refObj, this);
usedFields.Add("CurrentUser");
this.CurrentUser_ = new SP.User(HMS.SP.SPUtil.dyn_toString(refObj.CurrentUser));
usedFields.Add("CustomMasterUrl");
HMS.SP.SPUtil.dyn_ValueSet("CustomMasterUrl", refObj, this);
usedFields.Add("Description");
HMS.SP.SPUtil.dyn_ValueSet("Description", refObj, this);
usedFields.Add("DescriptionResource");
this.DescriptionResource_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.DescriptionResource));
usedFields.Add("DesignerDownloadUrlForCurrentUser");
HMS.SP.SPUtil.dyn_ValueSet("DesignerDownloadUrlForCurrentUser", refObj, this);
usedFields.Add("DocumentLibraryCalloutOfficeWebAppPreviewersDisabled");
HMS.SP.SPUtil.dyn_ValueSet("DocumentLibraryCalloutOfficeWebAppPreviewersDisabled", refObj, this);
usedFields.Add("EffectiveBasePermissions");
this.EffectiveBasePermissions_ = new SP.BasePermissions(HMS.SP.SPUtil.dyn_toString(refObj.EffectiveBasePermissions));
usedFields.Add("EnableMinimalDownload");
HMS.SP.SPUtil.dyn_ValueSet("EnableMinimalDownload", refObj, this);
usedFields.Add("EventReceivers");
this.EventReceivers_ = new SP.EventReceiverCollection(HMS.SP.SPUtil.dyn_toString(refObj.EventReceivers));
usedFields.Add("Features");
this.Features_ = new SP.FeatureCollection(HMS.SP.SPUtil.dyn_toString(refObj.Features));
usedFields.Add("Fields");
this.Fields_ = new SP.FieldCollection(HMS.SP.SPUtil.dyn_toString(refObj.Fields));
usedFields.Add("Folders");
this.Folders_ = new SP.FolderCollection(HMS.SP.SPUtil.dyn_toString(refObj.Folders));
usedFields.Add("Id");
HMS.SP.SPUtil.dyn_ValueSet("Id", refObj, this);
usedFields.Add("Language");
HMS.SP.SPUtil.dyn_ValueSet("Language", refObj, this);
usedFields.Add("LastItemModifiedDate");
HMS.SP.SPUtil.dyn_ValueSet("LastItemModifiedDate", refObj, this);
usedFields.Add("Lists");
this.Lists_ = new SP.ListCollection(HMS.SP.SPUtil.dyn_toString(refObj.Lists));
usedFields.Add("ListTemplates");
this.ListTemplates_ = new SP.ListTemplateCollection(HMS.SP.SPUtil.dyn_toString(refObj.ListTemplates));
usedFields.Add("MasterUrl");
HMS.SP.SPUtil.dyn_ValueSet("MasterUrl", refObj, this);
usedFields.Add("Navigation");
this.Navigation_ = new SP.Navigation(HMS.SP.SPUtil.dyn_toString(refObj.Navigation));
usedFields.Add("ParentWeb");
this.ParentWeb_ = new SP.Web(HMS.SP.SPUtil.dyn_toString(refObj.ParentWeb));
usedFields.Add("PushNotificationSubscribers");
this.PushNotificationSubscribers_ = new SP.PushNotificationSubscriberCollection(HMS.SP.SPUtil.dyn_toString(refObj.PushNotificationSubscribers));
usedFields.Add("QuickLaunchEnabled");
HMS.SP.SPUtil.dyn_ValueSet("QuickLaunchEnabled", refObj, this);
usedFields.Add("RecycleBin");
this.RecycleBin_ = new SP.RecycleBin(HMS.SP.SPUtil.dyn_toString(refObj.RecycleBin));
usedFields.Add("RecycleBinEnabled");
HMS.SP.SPUtil.dyn_ValueSet("RecycleBinEnabled", refObj, this);
usedFields.Add("RegionalSettings");
this.RegionalSettings_ = new SP.RegionalSettings(HMS.SP.SPUtil.dyn_toString(refObj.RegionalSettings));
usedFields.Add("RoleDefinitions");
this.RoleDefinitions_ = new SP.RoleDefinitionCollection(HMS.SP.SPUtil.dyn_toString(refObj.RoleDefinitions));
usedFields.Add("RootFolder");
this.RootFolder_ = new SP.Folder(HMS.SP.SPUtil.dyn_toString(refObj.RootFolder));
usedFields.Add("SaveSiteAsTemplateEnabled");
HMS.SP.SPUtil.dyn_ValueSet("SaveSiteAsTemplateEnabled", refObj, this);
usedFields.Add("ServerRelativeUrl");
HMS.SP.SPUtil.dyn_ValueSet("ServerRelativeUrl", refObj, this);
usedFields.Add("ShowUrlStructureForCurrentUser");
HMS.SP.SPUtil.dyn_ValueSet("ShowUrlStructureForCurrentUser", refObj, this);
usedFields.Add("SiteGroups");
this.SiteGroups_ = new SP.GroupCollection(HMS.SP.SPUtil.dyn_toString(refObj.SiteGroups));
usedFields.Add("SiteUserInfoList");
this.SiteUserInfoList_ = new SP.List(HMS.SP.SPUtil.dyn_toString(refObj.SiteUserInfoList));
usedFields.Add("SiteUsers");
this.SiteUsers_ = new SP.UserCollection(HMS.SP.SPUtil.dyn_toString(refObj.SiteUsers));
usedFields.Add("SupportedUILanguageIds");
HMS.SP.SPUtil.dyn_ValueSet("SupportedUILanguageIds", refObj, this);
usedFields.Add("SyndicationEnabled");
HMS.SP.SPUtil.dyn_ValueSet("SyndicationEnabled", refObj, this);
usedFields.Add("ThemeInfo");
this.ThemeInfo_ = new SP.ThemeInfo(HMS.SP.SPUtil.dyn_toString(refObj.ThemeInfo));
usedFields.Add("Title");
HMS.SP.SPUtil.dyn_ValueSet("Title", refObj, this);
usedFields.Add("TitleResource");
this.TitleResource_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.TitleResource));
usedFields.Add("TreeViewEnabled");
HMS.SP.SPUtil.dyn_ValueSet("TreeViewEnabled", refObj, this);
usedFields.Add("UIVersion");
HMS.SP.SPUtil.dyn_ValueSet("UIVersion", refObj, this);
usedFields.Add("UIVersionConfigurationEnabled");
HMS.SP.SPUtil.dyn_ValueSet("UIVersionConfigurationEnabled", refObj, this);
usedFields.Add("Url");
HMS.SP.SPUtil.dyn_ValueSet("Url", refObj, this);
usedFields.Add("UserCustomActions");
this.UserCustomActions_ = new SP.UserCustomActionCollection(HMS.SP.SPUtil.dyn_toString(refObj.UserCustomActions));
usedFields.Add("WebInfos");
this.WebInfos_ = new SP.WebInformation(HMS.SP.SPUtil.dyn_toString(refObj.WebInfos));
usedFields.Add("Webs");
this.Webs_ = new SP.WebCollection(HMS.SP.SPUtil.dyn_toString(refObj.Webs));
usedFields.Add("WebTemplate");
HMS.SP.SPUtil.dyn_ValueSet("WebTemplate", refObj, this);
usedFields.Add("WorkflowAssociations");
this.WorkflowAssociations_ = new SP.WorkflowAssociationCollection(HMS.SP.SPUtil.dyn_toString(refObj.WorkflowAssociations));
usedFields.Add("WorkflowTemplates");
this.WorkflowTemplates_ = new SP.WorkflowTemplateCollection(HMS.SP.SPUtil.dyn_toString(refObj.WorkflowTemplates));
this.__rest = new Dictionary<string, string>();
var dyn = ((Newtonsoft.Json.Linq.JContainer)refObj).First;
while (dyn != null)
{
string Name = ((Newtonsoft.Json.Linq.JProperty)dyn).Name;
string Value = ((Newtonsoft.Json.Linq.JProperty)dyn).Value.ToString();
if ( !usedFields.Contains( Name ))
this.__rest.Add( Name, Value);
dyn = dyn.Next;
}
if( errInfo != "")
this.__HMSError_.info = errInfo;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing;
namespace WinHtmlEditor
{
/// <summary>
/// Specifies the display options for the ToolStripColorPicker such as
/// image, text and underline.
/// </summary>
public enum ToolStripColorPickerDisplayType
{
// <summary>
/// Specifies that only a normal image is to be rendered for this ToolStripColorPicker
/// </summary>
NormalImage,
/// <summary>
/// Specifies that both image and text are to be rendered for this ToolStripColorPicker
/// </summary>
NormalImageAndText,
/// <summary>
/// Specifies that both color under-line and image are to be rendered for this ToolStripColorPicker
/// </summary>
UnderLineAndImage,
/// <summary>
/// Specifies that both color under-line and text are to be rendered for this ToolStripColorPicker
/// </summary>
UnderLineAndText,
/// <summary>
/// Specifies that both color under-line, text and image are to be rendered for this ToolStripColorPicker
/// </summary>
UnderLineTextAndImage,
/// <summary>
/// Specifies that only a color under-line is to be rendered for this ToolStripColorPicker
/// </summary>
UnderLineOnly,
/// <summary>
/// Specified that neither image, text nor under-line is to be rendered for this ToolStripColorPicker
/// </summary>
None,
/// <summary>
/// Specifies that only text is to be rendered for this ToolStripColorPicker
/// </summary>
Text
}
/// <summary>
/// Represents a ToolStripButtonItem that contains Color Picker control.
/// </summary>
[DefaultEvent("SelectedColorChanged"), DefaultProperty("Color"),
Description("ToolStripItem that allows selecting a color from a color picker control."),
ToolboxItem(false),
ToolboxBitmap(typeof(ToolStripColorPicker), "ToolStripColorPicker")]
public class ToolStripColorPicker : ToolStripSplitButton
{
#region Events
/// <summary>
/// Occurs when the value of the Color property changes.
/// </summary>
[Category("Behavior"), Description("Occurs when the value of the Color property changes.")]
public event EventHandler SelectedColorChanged;
/// <summary>
/// Occurs when the button portion of the color is clicked.
/// </summary>
[Category("Behavior"), Description("Occurs when the button portion of the color is clicked.")]
public event EventHandler ButtonPortionClicked;
#endregion
#region Properties
private ToolStripColorPickerDisplayType _buttonDisplayStyle = ToolStripColorPickerDisplayType.UnderLineAndImage;
/// <summary>
/// Gets or sets the ToolStripColorPickerDisplayType in order to
/// specified the display style of the button - image, text, underline etc.
/// </summary>
[Category("Appearance"), Description("Specifies whether to display the image, text and underline on the button.")
, DefaultValue(typeof(ToolStripColorPickerDisplayType), "ToolStripColorPickerDisplayType.UnderLineAndImage")]
public ToolStripColorPickerDisplayType ButtonDisplayStyle
{
get { return _buttonDisplayStyle; }
set
{
_buttonDisplayStyle = value;
UpdateDisplayStyle();
}
}
/// <summary>
/// Overrides, Gets or sets the ToolStripItem.DisplayStyle property, use
/// the ButtonDisplayStyle instead.
/// </summary>
[Browsable(false)]
public override ToolStripItemDisplayStyle DisplayStyle
{
get { return base.DisplayStyle; }
set { base.DisplayStyle = value; }
}
/// <summary>
/// Gets or sets the color assign to the color picker control.
/// </summary>
[Category("Data"),
Description("Gets or sets the color assign to the color picker control."),
DefaultValue(typeof(Color), "Color.Black")]
public Color Color
{
get { return _colorPicker.Color; }
set
{
_colorPicker.Color = value;
Refresh();
OnSelectedColorChanged(EventArgs.Empty);
}
}
private bool _addColorNameToToolTip = true;
/// <summary>
/// Gets or sets value indicating whether to render the color name to the tool tip text.
/// </summary>
[DefaultValue(true),
Category("Behavior"), Description("Value indicating whether to render the color name to the tool tip text.")]
public bool AddColorNameToToolTip
{
get { return _addColorNameToToolTip; }
set { _addColorNameToToolTip = value; }
}
private string _originalToolTipText = "";
/// <summary>
/// Gets or sets the text that appears as a tooltip in the button.
/// the color name will be rendered to the tooltip if the AddColorNameToolTip property set to true.
/// </summary>
[Category("Behavior"), Description("The text that appears as a tooltip (the color name will be render automatically if defined to do so.")]
new public string ToolTipText
{
get { return _originalToolTipText; }
set
{
_originalToolTipText = value;
if (_addColorNameToToolTip)
{
base.ToolTipText = _originalToolTipText +
" (" + _colorPicker.ColorName + ")";
}
else
{
base.ToolTipText = value;
}
}
}
#endregion
#region Private Members
/// <summary>
/// The color picker control that opens when clicking on the button
/// </summary>
private OfficeColorPicker _colorPicker = new OfficeColorPicker();
/// <summary>
/// Default color rectangle (under line)
/// </summary>
private Rectangle _colorRectangle = new Rectangle(2, 17, 14, 4);
/// <summary>
/// The underline picture rectangle - stretch to 14X14
/// </summary>
private Rectangle _pictureRectangle = new Rectangle(2, 2, 14, 14);
// Settings for the button painting
private bool _showColorUnderLine = true;
private bool _showUnderLineImage = true;
private bool _showUnderLineText = false;
private System.ComponentModel.IContainer components = null;
#endregion
#region Ctor
/// <summary>
/// Initializes a new instance of the ToolStripColorPicker that holds
/// OfficeColorPicker control inside a ToolStripItem to add to ToolStrip containers.
/// </summary>
public ToolStripColorPicker()
: base()
{
InitControl();
}
/// <summary>
/// Initializes a new instance of the ToolStripColorPicker that holds
/// OfficeColorPicker control inside a ToolStripItem to add to ToolStrip containers.
/// </summary>
/// <param name="startingColor">The color to assign to the color picker control</param>
public ToolStripColorPicker(Color startingColor)
: base()
{
Color = startingColor;
InitControl();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
if (!_colorPicker.IsDisposed)
_colorPicker.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Inits
/// <summary>
/// Set starting properties for the control and register the needed events.
/// </summary>
private void InitControl()
{
_colorPicker.SelectedColorChanged += new EventHandler(HandleSelectedColorChanged);
this.AutoSize = false;
this.Width = 30;
this.DropDownItems.Add("test");
}
/// <summary>
/// Set the painting properties by the _buttonDisplayStyle property.
/// </summary>
private void UpdateDisplayStyle()
{
switch (_buttonDisplayStyle)
{
case ToolStripColorPickerDisplayType.NormalImage:
DisplayStyle = ToolStripItemDisplayStyle.Image;
_showColorUnderLine = false;
_showUnderLineImage = false;
_showUnderLineText = false;
break;
case ToolStripColorPickerDisplayType.NormalImageAndText:
DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
_showColorUnderLine = false;
_showUnderLineImage = false;
_showUnderLineText = false;
break;
case ToolStripColorPickerDisplayType.UnderLineAndImage:
DisplayStyle = ToolStripItemDisplayStyle.None;
_showColorUnderLine = true;
_showUnderLineImage = true;
_showUnderLineText = false;
break;
case ToolStripColorPickerDisplayType.UnderLineAndText:
DisplayStyle = ToolStripItemDisplayStyle.None;
_showColorUnderLine = true;
_showUnderLineImage = false;
_showUnderLineText = true;
break;
case ToolStripColorPickerDisplayType.UnderLineTextAndImage:
DisplayStyle = ToolStripItemDisplayStyle.None;
_showColorUnderLine = true;
_showUnderLineImage = true;
_showUnderLineText = true;
break;
case ToolStripColorPickerDisplayType.UnderLineOnly:
DisplayStyle = ToolStripItemDisplayStyle.None;
_showColorUnderLine = true;
_showUnderLineImage = false;
_showUnderLineText = false;
break;
case ToolStripColorPickerDisplayType.None:
DisplayStyle = ToolStripItemDisplayStyle.None;
_showColorUnderLine = false;
_showUnderLineImage = false;
_showUnderLineText = false;
break;
case ToolStripColorPickerDisplayType.Text:
DisplayStyle = ToolStripItemDisplayStyle.Text;
_showColorUnderLine = false;
_showUnderLineImage = false;
_showUnderLineText = false;
break;
default:
break;
}
Refresh();
}
#endregion
#region Overrides (event handlers)
protected override void OnButtonClick(EventArgs e)
{
base.OnButtonClick(e);
OnButtonPortionClicked(e);
}
protected override void OnDropDownOpened(EventArgs e)
{
Point startPoint = GetOpenPoint();
_colorPicker.Show(startPoint);
}
/// <summary>
/// Gets the button position by the parent ToolStrip
/// </summary>
/// <returns></returns>
private Point GetOpenPoint()
{
if (this.Owner == null) return new Point(5, 5);
int x = 0;
foreach (ToolStripItem item in this.Parent.Items)
{
if (item == this) break;
if (item.Visible)
x += item.Width;
}
return this.Owner.PointToScreen(new Point(x, -4));
}
/// <summary>
/// Fires the SelectedColorChanged event.
/// </summary>
/// <param name="e"></param>
public void OnSelectedColorChanged(EventArgs e)
{
if (SelectedColorChanged != null)
SelectedColorChanged(this, e);
}
/// <summary>
/// Fires the ButtonPortionClicked event.
/// </summary>
/// <param name="e"></param>
public void OnButtonPortionClicked(EventArgs e)
{
if (ButtonPortionClicked != null)
ButtonPortionClicked(this, e);
}
/// <summary>
/// Repaint the button with the new color
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void HandleSelectedColorChanged(object sender, EventArgs e)
{
Refresh();
OnSelectedColorChanged(EventArgs.Empty);
}
/// <summary>
/// Repaint the parent tool strip and the button tool tip
/// </summary>
private void Refresh()
{
// Call the tool tip set property to add color name to tool tip
ToolTipText = _originalToolTipText;
// Refresh the toolstrip that holds this button.
if (this.Owner != null)
this.Owner.Refresh();
}
#endregion
#region Painting the Button
/// <summary>
/// Paints the underline rectangle.
/// </summary>
/// <param name="g"></param>
/// <param name="bounds"></param>
private void PaintUnderLine(Graphics g)
{
Color lineColor = Color;
if (!Enabled)
lineColor = Color.Gray;
// Paint the line down on the button
using (Brush brush = new SolidBrush(lineColor))
{
_colorRectangle = new Rectangle(2, this.Height - 6,
this.Width - 16, 4);
g.FillRectangle(brush, _colorRectangle);
}
}
/// <summary>
/// Paints the under line image
/// </summary>
/// <param name="g"></param>
/// <param name="bounds"></param>
/// <returns></returns>
private Size PaintUnderLineImage(Graphics g)
{
Bitmap bmp = this.Image as Bitmap;
// Paints the image, if exists
if (bmp != null)
{
bmp.MakeTransparent(this.ImageTransparentColor);
g.DrawImage(bmp, _pictureRectangle,
0, 0, bmp.Width, bmp.Height,
GraphicsUnit.Pixel,
Enabled ? null : CustomColors.GrayScaleAttributes
);
return bmp.Size;
}
else
{
return new Size(0, 0);
}
}
/// <summary>
/// Paints the underline text
/// </summary>
/// <param name="g"></param>
/// <param name="imageSize"></param>
/// <param name="bounds"></param>
private void PaintUnderLineText(Graphics g, Size imageSize)
{
Color textColor = ForeColor;
if (!Enabled)
textColor = Color.Gray;
using (Brush brush = new SolidBrush(textColor))
{
int x = imageSize.Width + 2;
int y = 2;
Rectangle stringRec = new Rectangle(x, y, this.Width - x, this.Height - y);
g.DrawString(Text, this.Font, brush, stringRec);
}
}
/// <summary>
/// Overrides, Paint the image in the specified scale and the color line if defined.
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
if (_showColorUnderLine)
{
base.OnPaint(e);
Size imageSize = new Size(0, 0);
PaintUnderLine(e.Graphics);
if (this.Image != null && _showUnderLineImage)
{
imageSize = PaintUnderLineImage(e.Graphics);
}
if (_showUnderLineText)
{
PaintUnderLineText(e.Graphics, imageSize);
}
}
else
{
base.OnPaint(e);
}
}
#endregion
}
}
| |
//
// MessageBar.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Hyena.Gui;
using Hyena.Gui.Theming;
namespace Hyena.Widgets
{
public class MessageBar : Alignment
{
private HBox box;
private HBox button_box;
private AnimatedImage image;
private WrapLabel label;
private Button close_button;
private Window win;
private Theme theme;
public event EventHandler CloseClicked {
add { close_button.Clicked += value; }
remove { close_button.Clicked -= value; }
}
public MessageBar () : base (0.0f, 0.5f, 1.0f, 0.0f)
{
win = new Window (WindowType.Popup);
win.Name = "gtk-tooltips";
win.EnsureStyle ();
win.StyleSet += delegate {
Style = win.Style;
};
HBox shell_box = new HBox ();
shell_box.Spacing = 10;
box = new HBox ();
box.Spacing = 10;
image = new AnimatedImage ();
try {
image.Pixbuf = Gtk.IconTheme.Default.LoadIcon ("process-working", 22, IconLookupFlags.NoSvg);
image.FrameHeight = 22;
image.FrameWidth = 22;
Spinning = false;
image.Load ();
} catch {
}
label = new WrapLabel ();
label.Show ();
box.PackStart (image, false, false, 0);
box.PackStart (label, true, true, 0);
box.Show ();
button_box = new HBox ();
button_box.Spacing = 3;
close_button = new Button (new Image (Stock.Close, IconSize.Menu));
close_button.Relief = ReliefStyle.None;
close_button.Clicked += delegate { Hide (); };
close_button.ShowAll ();
close_button.Hide ();
shell_box.PackStart (box, true, true, 0);
shell_box.PackStart (button_box, false, false, 0);
shell_box.PackStart (close_button, false, false, 0);
shell_box.Show ();
Add (shell_box);
EnsureStyle ();
BorderWidth = 3;
}
protected MessageBar (IntPtr raw) : base (raw)
{
}
protected override void OnShown ()
{
base.OnShown ();
image.Show ();
}
protected override void OnHidden ()
{
base.OnHidden ();
image.Hide ();
}
protected override void OnRealized ()
{
base.OnRealized ();
theme = Hyena.Gui.Theming.ThemeEngine.CreateTheme (this);
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
base.OnSizeAllocated (allocation);
QueueDraw ();
}
protected override bool OnExposeEvent (Gdk.EventExpose evnt)
{
if (!IsDrawable) {
return false;
}
Cairo.Context cr = Gdk.CairoHelper.Create (evnt.Window);
try {
Gdk.Color color = Style.Background (StateType.Normal);
theme.DrawFrame (cr, Allocation, CairoExtensions.GdkColorToCairoColor (color));
return base.OnExposeEvent (evnt);
} finally {
CairoExtensions.DisposeContext (cr);
}
}
private bool changing_style = false;
protected override void OnStyleSet (Gtk.Style previousStyle)
{
if (changing_style) {
return;
}
changing_style = true;
Style = win.Style;
label.Style = Style;
changing_style = false;
}
public void RemoveButton (Button button)
{
button_box.Remove (button);
}
public void ClearButtons ()
{
foreach (Widget child in button_box.Children) {
button_box.Remove (child);
}
}
public void AddButton (Button button)
{
button_box.Show ();
button.Show ();
button_box.PackStart (button, false, false, 0);
}
public bool ShowCloseButton {
set {
close_button.Visible = value;
QueueDraw ();
}
}
public string Message {
set {
label.Markup = value;
QueueDraw ();
}
}
public Gdk.Pixbuf Pixbuf {
set {
image.InactivePixbuf = value;
QueueDraw ();
}
}
public bool Spinning {
get { return image.Active; }
set { image.Active = value; }
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.IO;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Text;
using Microsoft.Win32;
using System.Collections.Generic;
namespace Tests
{
public class TestDriver
{
const string ReferenceDirRoot = @"Microsoft.Research\Imported\ReferenceAssemblies\";
const string ContractReferenceDirRoot = @"Microsoft.Research\Contracts\bin\Debug\";
const string FoxtrotExe = @"Foxtrot\Driver\bin\debug\foxtrot.exe";
const string ToolsRoot = @"Microsoft.Research\Imported\Tools\";
internal static string Rewrite(string absoluteSourceDir, string absoluteBinary, Options options)
{
var referencedir = options.MakeAbsolute(Path.Combine(ReferenceDirRoot, options.BuildFramework));
var contractreferencedir = options.MakeAbsolute(Path.Combine(ContractReferenceDirRoot, options.ContractFramework));
var absoluteSourcedir = Path.GetDirectoryName(absoluteBinary);
var absoluteSource = absoluteBinary;
var libPathsString = FormLibPaths(absoluteSourceDir, contractreferencedir, options);
var targetName = options.TestName + ".rw" + Path.GetExtension(absoluteBinary);
var binDir = options.UseBinDir ? Path.Combine(Path.Combine(absoluteSourcedir, "bin"), options.BuildFramework) : absoluteSourcedir;
var targetfile = Path.Combine(binDir, targetName);
Console.WriteLine("Rewriting '{0}' to '{1}'", absoluteBinary, targetfile);
if (!Directory.Exists(binDir))
{
Directory.CreateDirectory(binDir);
}
var exitCode = RunProcess(binDir, options.MakeAbsolute(FoxtrotExe),
String.Format("/out:{0} -nobox -libpaths:{3} -libpaths:{4} {5} {1} {2}", targetfile, options.FoxtrotOptions, absoluteSource, referencedir, contractreferencedir, libPathsString),
options.TestName);
if (exitCode != 0)
{
return null;
}
else
{
if (options.UseBinDir)
{
File.Copy(targetfile, Path.Combine(absoluteSourcedir, targetName), true);
return Path.Combine(absoluteSourcedir, targetName);
}
}
return targetfile;
}
internal static int PEVerify(string assemblyFile, Options options)
{
var peVerifyPath = options.MakeAbsolute(Path.Combine(ToolsRoot, String.Format(@"{0}\peverify.exe", options.BuildFramework)));
assemblyFile = options.MakeAbsolute(assemblyFile);
var path = Path.GetDirectoryName(assemblyFile);
var file = Path.GetFileName(assemblyFile);
if (file == "mscorlib.dll") return -1; // peverify returns 0 for mscorlib without verifying.
var exitCode = RunProcess(path, peVerifyPath, "/unique \"" + file + "\"", "repro");
return exitCode;
}
internal static string RewriteAndVerify(string sourceDir, string binary, Options options)
{
if (!Path.IsPathRooted(sourceDir)) { sourceDir = options.MakeAbsolute(sourceDir); }
if (!Path.IsPathRooted(binary)) { binary = options.MakeAbsolute(binary); }
string target = Rewrite(sourceDir, binary, options);
if (target != null)
{
PEVerify(target, options);
}
return target;
}
private static int RunProcess(string cwd, string tool, string arguments, string writeBatchFile = null)
{
ProcessStartInfo i = new ProcessStartInfo(tool, arguments);
Console.WriteLine("Running '{0}'", i.FileName);
Console.WriteLine(" {0}", i.Arguments);
i.RedirectStandardOutput = true;
i.RedirectStandardError = true;
i.UseShellExecute = false;
i.CreateNoWindow = true;
i.WorkingDirectory = cwd;
i.ErrorDialog = false;
if (writeBatchFile != null)
{
var file = new StreamWriter(Path.Combine(cwd, writeBatchFile + ".bat"));
file.WriteLine("{0} {1} %1 %2 %3 %4 %5", i.FileName, i.Arguments);
file.Close();
}
using (Process p = Process.Start(i))
{
p.OutputDataReceived += new DataReceivedEventHandler(OutputDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(ErrorDataReceived);
p.BeginOutputReadLine();
p.BeginErrorReadLine();
Assert.IsTrue(p.WaitForExit(200000), String.Format("{0} timed out", i.FileName));
if (p.ExitCode != 0)
{
Assert.AreEqual(0, p.ExitCode, "{0} returned an errorcode of {1}.", i.FileName, p.ExitCode);
}
return p.ExitCode;
}
}
public static int Run(string targetExe)
{
return RunProcess(Environment.CurrentDirectory, targetExe, "");
}
static string FormLibPaths(string absoluteSourceDir, string contractReferenceDir, Options options)
{
var oldcwd = Environment.CurrentDirectory;
try
{
Environment.CurrentDirectory = absoluteSourceDir;
StringBuilder sb = null;
if (options.UseContractReferenceAssemblies)
{
sb = new StringBuilder("/libpaths:").Append(contractReferenceDir);
}
if (options.LibPaths == null) return "";
foreach (var path in options.LibPaths)
{
if (sb == null)
{
sb = new StringBuilder("/libpaths:");
}
else
{
sb.Append(';');
}
sb.Append(options.MakeAbsolute(Path.Combine(path, options.ContractFramework)));
}
if (sb == null) return "";
return sb.ToString();
}
finally
{
Environment.CurrentDirectory = oldcwd;
}
}
internal static string Build(Options options, out string absoluteSourceDir)
{
var sourceFile = options.MakeAbsolute(options.SourceFile);
var compilerpath = options.MakeAbsolute(Path.Combine(ToolsRoot, String.Format(@"{0}\{1}", options.BuildFramework, options.Compiler)));
var contractreferencedir = options.MakeAbsolute(Path.Combine(ContractReferenceDirRoot, options.BuildFramework));
var sourcedir = absoluteSourceDir = Path.GetDirectoryName(sourceFile);
var outputdir = Path.Combine(Path.Combine(sourcedir, "bin"), options.BuildFramework);
var extension = options.UseExe ? ".exe" : ".dll";
var targetKind = options.UseExe ? "exe" : "library";
var targetfile = Path.Combine(outputdir, Path.GetFileNameWithoutExtension(sourceFile) + extension);
// add Microsoft.Contracts reference if needed
if (!options.BuildFramework.Contains("v4."))
{
options.References.Add("Microsoft.Contracts.dll");
}
var oldCwd = Environment.CurrentDirectory;
try
{
Environment.CurrentDirectory = sourcedir;
var resolvedReferences = ResolveReferences(options);
var referenceString = ReferenceOptions(resolvedReferences);
if (!Directory.Exists(outputdir))
{
Directory.CreateDirectory(outputdir);
}
var exitCode = RunProcess(sourcedir, compilerpath, String.Format("/debug /t:{4} /out:{0} {3} {2} {1}", targetfile, sourceFile, referenceString, options.CompilerOptions, targetKind));
if (exitCode != 0)
{
return null;
}
CopyReferenceAssemblies(resolvedReferences, outputdir);
return targetfile;
}
finally
{
Environment.CurrentDirectory = oldCwd;
}
}
static void ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("{0}", e.Data);
}
static void OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("{0}", e.Data);
}
private static void CopyReferenceAssemblies(List<string> resolvedReferences, string outputdir)
{
foreach (var r in resolvedReferences)
{
try
{
File.Copy(r, Path.Combine(outputdir, Path.GetFileName(r)), true);
}
catch { }
}
}
private static List<string> ResolveReferences(Options options)
{
var result = new List<string>();
foreach (var r in options.References)
{
foreach (var root in options.LibPaths)
{
var dir = options.MakeAbsolute(Path.Combine(root, options.BuildFramework));
var path = Path.Combine(dir, r);
if (File.Exists(path))
{
result.Add(path);
break;
}
}
foreach (var root in new[] { ReferenceDirRoot, ContractReferenceDirRoot })
{
var dir = options.MakeAbsolute(Path.Combine(root, options.BuildFramework));
var path = Path.Combine(dir, r);
if (File.Exists(path))
{
result.Add(path);
break;
}
}
}
return result;
}
private static string ReferenceOptions(List<string> references)
{
var sb = new StringBuilder();
foreach (var r in references)
{
sb.Append(String.Format(@"/r:{0} ", r));
}
return sb.ToString();
}
internal static void BuildRewriteRun(Options options)
{
string absoluteSourceDir;
var target = Build(options, out absoluteSourceDir);
if (target != null)
{
var rwtarget = RewriteAndVerify(absoluteSourceDir, target, options);
if (rwtarget != null)
{
Run(rwtarget);
}
}
}
}
class Options
{
const string RelativeRoot = @"..\..\..\..\..\..";
const string TestHarnessDirectory = @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug";
public readonly string RootDirectory;
public readonly string SourceFile;
private readonly string compilerCode;
private readonly string compilerOptions;
public string FoxtrotOptions;
private List<string> libPaths;
public readonly List<string> References;
public readonly bool UseContractReferenceAssemblies = true;
public string BuildFramework = @".NETFramework\v4.0";
public string ContractFramework = @".NETFramework\v4.0";
public bool UseBinDir = true;
public bool UseExe = true;
private int instance;
public List<string> LibPaths
{
get
{
if (libPaths == null) { libPaths = new List<string>(); }
return libPaths;
}
}
public string TestName
{
get
{
if (SourceFile != null) { return Path.GetFileNameWithoutExtension(SourceFile) + instance; }
else return instance.ToString();
}
}
public string Compiler
{
get
{
switch (compilerCode)
{
case "VB": return "vbc.exe";
default: return "csc.exe";
}
}
}
bool IsV4 { get { return this.BuildFramework.Contains("v4"); } }
bool IsSilverlight { get { return this.BuildFramework.Contains("Silverlight"); } }
string Moniker
{
get
{
if (IsSilverlight)
{
if (IsV4)
{
return "SILVERLIGHT_4_0";
}
else
{
return "SILVERLIGHT_3_0";
}
}
else
{
if (IsV4)
{
return "NETFRAMEWORK_4_0";
}
else
{
return "NETFRAMEWORK_3_5";
}
}
}
}
private string DefaultCompilerOptions
{
get
{
switch (compilerCode)
{
case "VB":
return String.Format("/define:\"DEBUG=-1,{0},CONTRACTS_FULL\",_MyType=\\\"Console\\\" " +
"/imports:Microsoft.VisualBasic,System,System.Collections,System.Collections.Generic,System.Data,System.Diagnostics,System.Linq,System.Xml.Linq " +
"/optioncompare:Binary /optionexplicit+ /optionstrict+ /optioninfer+ ",
Moniker);
default:
return String.Format("/d:CONTRACTS_FULL;DEBUG;{0} {1}", Moniker, MakeAbsolute(@"Foxtrot\Tests\Sources\TestHarness.cs"));
}
}
}
public string CompilerOptions
{
get
{
return DefaultCompilerOptions + " " + compilerOptions;
}
}
private Options(int instance)
{
RootDirectory = Path.GetFullPath(RelativeRoot);
this.instance = instance;
}
public Options(string testName, int instance, string foxtrotOptions)
: this(instance)
{
this.SourceFile = testName;
FoxtrotOptions = foxtrotOptions;
}
public Options(int instance, System.Data.DataRow dataRow)
: this(instance)
{
SourceFile = LoadString(dataRow, "Name");
FoxtrotOptions = LoadString(dataRow, "FoxtrotOptions");
UseContractReferenceAssemblies = LoadBool("ContractReferenceAssemblies", dataRow, false);
compilerOptions = LoadString(dataRow, "CompilerOptions");
References = LoadList(dataRow, "References", "System.dll", "ClousotTestHarness.dll");
libPaths = LoadList(dataRow, "LibPaths", MakeAbsolute(TestHarnessDirectory));
compilerCode = LoadString("Compiler", dataRow, "CS");
UseBinDir = LoadBool("BinDir", dataRow, false);
}
private static string LoadString(System.Data.DataRow dataRow, string name)
{
if (!ColumnExists(dataRow, name)) return "";
return (string)dataRow[name];
}
private static List<string> LoadList(System.Data.DataRow dataRow, string name, params string[] initial)
{
if (!ColumnExists(dataRow, name)) return new List<string>();
string listdata = dataRow[name] as string;
var result = new List<string>(initial);
if (!string.IsNullOrEmpty(listdata))
{
result.AddRange(listdata.Split(';'));
}
return result;
}
private static bool ColumnExists(System.Data.DataRow dataRow, string name)
{
return dataRow.Table.Columns.IndexOf(name) >= 0;
}
private bool LoadBool(string name, System.Data.DataRow dataRow, bool defaultValue)
{
if (!ColumnExists(dataRow, name)) return defaultValue;
var booloption = dataRow[name] as string;
if (!string.IsNullOrEmpty(booloption))
{
bool result;
if (bool.TryParse(booloption, out result))
{
return result;
}
}
return defaultValue;
}
private string LoadString(string name, System.Data.DataRow dataRow, string defaultValue)
{
if (!ColumnExists(dataRow, name)) return defaultValue;
var option = dataRow[name] as string;
if (!string.IsNullOrEmpty(option))
{
return option;
}
return defaultValue;
}
public string MakeAbsolute(string relativeToRoot)
{
return Path.GetFullPath(Path.Combine(this.RootDirectory, relativeToRoot));
}
internal void Delete(string fileName)
{
var absolute = MakeAbsolute(fileName);
if (File.Exists(absolute))
{
File.Delete(absolute);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace DataStoreService.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// DataflowBlockOptions.cs
//
//
// DataflowBlockOptions types for configuring dataflow blocks
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace System.Threading.Tasks.Dataflow
{
/// <summary>
/// Provides options used to configure the processing performed by dataflow blocks.
/// </summary>
/// <remarks>
/// <see cref="DataflowBlockOptions"/> is mutable and can be configured through its properties.
/// When specific configuration options are not set, the following defaults are used:
/// <list type="table">
/// <listheader>
/// <term>Options</term>
/// <description>Default</description>
/// </listheader>
/// <item>
/// <term>TaskScheduler</term>
/// <description><see cref="System.Threading.Tasks.TaskScheduler.Default"/></description>
/// </item>
/// <item>
/// <term>MaxMessagesPerTask</term>
/// <description>DataflowBlockOptions.Unbounded (-1)</description>
/// </item>
/// <item>
/// <term>CancellationToken</term>
/// <description><see cref="System.Threading.CancellationToken.None"/></description>
/// </item>
/// <item>
/// <term>BoundedCapacity</term>
/// <description>DataflowBlockOptions.Unbounded (-1)</description>
/// </item>
/// <item>
/// <term>NameFormat</term>
/// <description>"{0} Id={1}"</description>
/// </item>
/// <item>
/// <term>EnsureOrdered</term>
/// <description>true</description>
/// </item>
/// </list>
/// Dataflow blocks capture the state of the options at their construction. Subsequent changes
/// to the provided <see cref="DataflowBlockOptions"/> instance should not affect the behavior
/// of a dataflow block.
/// </remarks>
[DebuggerDisplay("TaskScheduler = {TaskScheduler}, MaxMessagesPerTask = {MaxMessagesPerTask}, BoundedCapacity = {BoundedCapacity}")]
public class DataflowBlockOptions
{
/// <summary>
/// A constant used to specify an unlimited quantity for <see cref="DataflowBlockOptions"/> members
/// that provide an upper bound. This field is constant.
/// </summary>
public const Int32 Unbounded = -1;
/// <summary>The scheduler to use for scheduling tasks to process messages.</summary>
private TaskScheduler _taskScheduler = TaskScheduler.Default;
/// <summary>The cancellation token to monitor for cancellation requests.</summary>
private CancellationToken _cancellationToken = CancellationToken.None;
/// <summary>The maximum number of messages that may be processed per task.</summary>
private Int32 _maxMessagesPerTask = Unbounded;
/// <summary>The maximum number of messages that may be buffered by the block.</summary>
private Int32 _boundedCapacity = Unbounded;
/// <summary>The name format to use for creating a name for a block.</summary>
private string _nameFormat = "{0} Id={1}"; // see NameFormat property for a description of format items
/// <summary>Whether to force ordered processing of messages.</summary>
private bool _ensureOrdered = true;
/// <summary>A default instance of <see cref="DataflowBlockOptions"/>.</summary>
/// <remarks>
/// Do not change the values of this instance. It is shared by all of our blocks when no options are provided by the user.
/// </remarks>
internal static readonly DataflowBlockOptions Default = new DataflowBlockOptions();
/// <summary>Returns this <see cref="DataflowBlockOptions"/> instance if it's the default instance or else a cloned instance.</summary>
/// <returns>An instance of the options that may be cached by the block.</returns>
internal DataflowBlockOptions DefaultOrClone()
{
return (this == Default) ?
this :
new DataflowBlockOptions
{
TaskScheduler = this.TaskScheduler,
CancellationToken = this.CancellationToken,
MaxMessagesPerTask = this.MaxMessagesPerTask,
BoundedCapacity = this.BoundedCapacity,
NameFormat = this.NameFormat,
EnsureOrdered = this.EnsureOrdered
};
}
/// <summary>Initializes the <see cref="DataflowBlockOptions"/>.</summary>
public DataflowBlockOptions() { }
/// <summary>Gets or sets the <see cref="System.Threading.Tasks.TaskScheduler"/> to use for scheduling tasks.</summary>
public TaskScheduler TaskScheduler
{
get { return _taskScheduler; }
set
{
Debug.Assert(this != Default, "Default instance is supposed to be immutable.");
if (value == null) throw new ArgumentNullException("value");
_taskScheduler = value;
}
}
/// <summary>Gets or sets the <see cref="System.Threading.CancellationToken"/> to monitor for cancellation requests.</summary>
public CancellationToken CancellationToken
{
get { return _cancellationToken; }
set
{
Debug.Assert(this != Default, "Default instance is supposed to be immutable.");
_cancellationToken = value;
}
}
/// <summary>Gets or sets the maximum number of messages that may be processed per task.</summary>
public Int32 MaxMessagesPerTask
{
get { return _maxMessagesPerTask; }
set
{
Debug.Assert(this != Default, "Default instance is supposed to be immutable.");
if (value < 1 && value != Unbounded) throw new ArgumentOutOfRangeException("value");
_maxMessagesPerTask = value;
}
}
/// <summary>Gets a MaxMessagesPerTask value that may be used for comparison purposes.</summary>
/// <returns>The maximum value, usable for comparison purposes.</returns>
/// <remarks>Unlike MaxMessagesPerTask, this property will always return a positive value.</remarks>
internal Int32 ActualMaxMessagesPerTask
{
get { return (_maxMessagesPerTask == Unbounded) ? Int32.MaxValue : _maxMessagesPerTask; }
}
/// <summary>Gets or sets the maximum number of messages that may be buffered by the block.</summary>
public Int32 BoundedCapacity
{
get { return _boundedCapacity; }
set
{
Debug.Assert(this != Default, "Default instance is supposed to be immutable.");
if (value < 1 && value != Unbounded) throw new ArgumentOutOfRangeException("value");
_boundedCapacity = value;
}
}
/// <summary>
/// Gets or sets the format string to use when a block is queried for its name.
/// </summary>
/// <remarks>
/// The name format may contain up to two format items. {0} will be substituted
/// with the block's name. {1} will be substituted with the block's Id, as is
/// returned from the block's Completion.Id property.
/// </remarks>
public string NameFormat
{
get { return _nameFormat; }
set
{
Debug.Assert(this != Default, "Default instance is supposed to be immutable.");
if (value == null) throw new ArgumentNullException("value");
_nameFormat = value;
}
}
/// <summary>Gets or sets whether ordered processing should be enforced on a block's handling of messages.</summary>
/// <remarks>
/// By default, dataflow blocks enforce ordering on the processing of messages. This means that a
/// block like <see cref="TransformBlock{TInput, TOutput}"/> will ensure that messages are output in the same
/// order they were input, even if parallelism is employed by the block and the processing of a message N finishes
/// after the processing of a subsequent message N+1 (the block will reorder the results to maintain the input
/// ordering prior to making those results available to a consumer). Some blocks may allow this to be relaxed,
/// however. Setting <see cref="EnsureOrdered"/> to false tells a block that it may relax this ordering if
/// it's able to do so. This can be beneficial if the immediacy of a processed result being made available
/// is more important than the input-to-output ordering being maintained.
/// </remarks>
public bool EnsureOrdered
{
get { return _ensureOrdered; }
set { _ensureOrdered = value; }
}
}
/// <summary>
/// Provides options used to configure the processing performed by dataflow blocks that
/// process each message through the invocation of a user-provided delegate, blocks such
/// as <see cref="ActionBlock{T}"/> and <see cref="TransformBlock{TInput,TOutput}"/>.
/// </summary>
/// <remarks>
/// <see cref="ExecutionDataflowBlockOptions"/> is mutable and can be configured through its properties.
/// When specific configuration options are not set, the following defaults are used:
/// <list type="table">
/// <listheader>
/// <term>Options</term>
/// <description>Default</description>
/// </listheader>
/// <item>
/// <term>TaskScheduler</term>
/// <description><see cref="System.Threading.Tasks.TaskScheduler.Default"/></description>
/// </item>
/// <item>
/// <term>CancellationToken</term>
/// <description><see cref="System.Threading.CancellationToken.None"/></description>
/// </item>
/// <item>
/// <term>MaxMessagesPerTask</term>
/// <description>DataflowBlockOptions.Unbounded (-1)</description>
/// </item>
/// <item>
/// <term>BoundedCapacity</term>
/// <description>DataflowBlockOptions.Unbounded (-1)</description>
/// </item>
/// <item>
/// <term>NameFormat</term>
/// <description>"{0} Id={1}"</description>
/// </item>
/// <item>
/// <term>EnsureOrdered</term>
/// <description>true</description>
/// </item>
/// <item>
/// <term>MaxDegreeOfParallelism</term>
/// <description>1</description>
/// </item>
/// <item>
/// <term>SingleProducerConstrained</term>
/// <description>false</description>
/// </item>
/// </list>
/// Dataflow block captures the state of the options at their construction. Subsequent changes
/// to the provided <see cref="ExecutionDataflowBlockOptions"/> instance should not affect the behavior
/// of a dataflow block.
/// </remarks>
[DebuggerDisplay("TaskScheduler = {TaskScheduler}, MaxMessagesPerTask = {MaxMessagesPerTask}, BoundedCapacity = {BoundedCapacity}, MaxDegreeOfParallelism = {MaxDegreeOfParallelism}")]
public class ExecutionDataflowBlockOptions : DataflowBlockOptions
{
/// <summary>A default instance of <see cref="DataflowBlockOptions"/>.</summary>
/// <remarks>
/// Do not change the values of this instance. It is shared by all of our blocks when no options are provided by the user.
/// </remarks>
internal new static readonly ExecutionDataflowBlockOptions Default = new ExecutionDataflowBlockOptions();
/// <summary>Returns this <see cref="ExecutionDataflowBlockOptions"/> instance if it's the default instance or else a cloned instance.</summary>
/// <returns>An instance of the options that may be cached by the block.</returns>
internal new ExecutionDataflowBlockOptions DefaultOrClone()
{
return (this == Default) ?
this :
new ExecutionDataflowBlockOptions
{
TaskScheduler = this.TaskScheduler,
CancellationToken = this.CancellationToken,
MaxMessagesPerTask = this.MaxMessagesPerTask,
BoundedCapacity = this.BoundedCapacity,
NameFormat = this.NameFormat,
EnsureOrdered = this.EnsureOrdered,
MaxDegreeOfParallelism = this.MaxDegreeOfParallelism,
SingleProducerConstrained = this.SingleProducerConstrained
};
}
/// <summary>The maximum number of tasks that may be used concurrently to process messages.</summary>
private Int32 _maxDegreeOfParallelism = 1;
/// <summary>Whether the code using this block will only ever have a single producer accessing the block at any given time.</summary>
private Boolean _singleProducerConstrained = false;
/// <summary>Initializes the <see cref="ExecutionDataflowBlockOptions"/>.</summary>
public ExecutionDataflowBlockOptions() { }
/// <summary>Gets the maximum number of messages that may be processed by the block concurrently.</summary>
public Int32 MaxDegreeOfParallelism
{
get { return _maxDegreeOfParallelism; }
set
{
Debug.Assert(this != Default, "Default instance is supposed to be immutable.");
if (value < 1 && value != Unbounded) throw new ArgumentOutOfRangeException("value");
_maxDegreeOfParallelism = value;
}
}
/// <summary>
/// Gets whether code using the dataflow block is constrained to one producer at a time.
/// </summary>
/// <remarks>
/// This property defaults to false, such that the block may be used by multiple
/// producers concurrently. This property should only be set to true if the code
/// using the block can guarantee that it will only ever be used by one producer
/// (e.g. a source linked to the block) at a time, meaning that methods like Post,
/// Complete, Fault, and OfferMessage will never be called concurrently. Some blocks
/// may choose to capitalize on the knowledge that there will only be one producer at a time
/// in order to provide better performance.
/// </remarks>
public Boolean SingleProducerConstrained
{
get { return _singleProducerConstrained; }
set
{
Debug.Assert(this != Default, "Default instance is supposed to be immutable.");
_singleProducerConstrained = value;
}
}
/// <summary>Gets a MaxDegreeOfParallelism value that may be used for comparison purposes.</summary>
/// <returns>The maximum value, usable for comparison purposes.</returns>
/// <remarks>Unlike MaxDegreeOfParallelism, this property will always return a positive value.</remarks>
internal Int32 ActualMaxDegreeOfParallelism
{
get { return (_maxDegreeOfParallelism == Unbounded) ? Int32.MaxValue : _maxDegreeOfParallelism; }
}
/// <summary>Gets whether these dataflow block options allow for parallel execution.</summary>
internal Boolean SupportsParallelExecution { get { return _maxDegreeOfParallelism == Unbounded || _maxDegreeOfParallelism > 1; } }
}
/// <summary>
/// Provides options used to configure the processing performed by dataflow blocks that
/// group together multiple messages, blocks such as <see cref="JoinBlock{T1,T2}"/> and
/// <see cref="BatchBlock{T}"/>.
/// </summary>
/// <remarks>
/// <see cref="GroupingDataflowBlockOptions"/> is mutable and can be configured through its properties.
/// When specific configuration options are not set, the following defaults are used:
/// <list type="table">
/// <listheader>
/// <term>Options</term>
/// <description>Default</description>
/// </listheader>
/// <item>
/// <term>TaskScheduler</term>
/// <description><see cref="System.Threading.Tasks.TaskScheduler.Default"/></description>
/// </item>
/// <item>
/// <term>CancellationToken</term>
/// <description><see cref="System.Threading.CancellationToken.None"/></description>
/// </item>
/// <item>
/// <term>MaxMessagesPerTask</term>
/// <description>DataflowBlockOptions.Unbounded (-1)</description>
/// </item>
/// <item>
/// <term>BoundedCapacity</term>
/// <description>DataflowBlockOptions.Unbounded (-1)</description>
/// </item>
/// <item>
/// <term>NameFormat</term>
/// <description>"{0} Id={1}"</description>
/// </item>
/// <item>
/// <term>EnsureOrdered</term>
/// <description>true</description>
/// </item>
/// <item>
/// <term>MaxNumberOfGroups</term>
/// <description>GroupingDataflowBlockOptions.Unbounded (-1)</description>
/// </item>
/// <item>
/// <term>Greedy</term>
/// <description>true</description>
/// </item>
/// </list>
/// Dataflow block capture the state of the options at their construction. Subsequent changes
/// to the provided <see cref="GroupingDataflowBlockOptions"/> instance should not affect the behavior
/// of a dataflow block.
/// </remarks>
[DebuggerDisplay("TaskScheduler = {TaskScheduler}, MaxMessagesPerTask = {MaxMessagesPerTask}, BoundedCapacity = {BoundedCapacity}, Greedy = {Greedy}, MaxNumberOfGroups = {MaxNumberOfGroups}")]
public class GroupingDataflowBlockOptions : DataflowBlockOptions
{
/// <summary>A default instance of <see cref="DataflowBlockOptions"/>.</summary>
/// <remarks>
/// Do not change the values of this instance. It is shared by all of our blocks when no options are provided by the user.
/// </remarks>
internal new static readonly GroupingDataflowBlockOptions Default = new GroupingDataflowBlockOptions();
/// <summary>Returns this <see cref="GroupingDataflowBlockOptions"/> instance if it's the default instance or else a cloned instance.</summary>
/// <returns>An instance of the options that may be cached by the block.</returns>
internal new GroupingDataflowBlockOptions DefaultOrClone()
{
return (this == Default) ?
this :
new GroupingDataflowBlockOptions
{
TaskScheduler = this.TaskScheduler,
CancellationToken = this.CancellationToken,
MaxMessagesPerTask = this.MaxMessagesPerTask,
BoundedCapacity = this.BoundedCapacity,
NameFormat = this.NameFormat,
EnsureOrdered = this.EnsureOrdered,
Greedy = this.Greedy,
MaxNumberOfGroups = this.MaxNumberOfGroups
};
}
/// <summary>Whether the block should greedily consume offered messages.</summary>
private Boolean _greedy = true;
/// <summary>The maximum number of groups that should be generated by the block.</summary>
private Int64 _maxNumberOfGroups = Unbounded;
/// <summary>Initializes the <see cref="GroupingDataflowBlockOptions"/>.</summary>
public GroupingDataflowBlockOptions() { }
/// <summary>Gets or sets the Boolean value to use to determine whether to greedily consume offered messages.</summary>
public Boolean Greedy
{
get { return _greedy; }
set
{
Debug.Assert(this != Default, "Default instance is supposed to be immutable.");
_greedy = value;
}
}
/// <summary>Gets or sets the maximum number of groups that should be generated by the block.</summary>
public Int64 MaxNumberOfGroups
{
get { return _maxNumberOfGroups; }
set
{
Debug.Assert(this != Default, "Default instance is supposed to be immutable.");
if (value <= 0 && value != Unbounded) throw new ArgumentOutOfRangeException("value");
_maxNumberOfGroups = value;
}
}
/// <summary>Gets a MaxNumberOfGroups value that may be used for comparison purposes.</summary>
/// <returns>The maximum value, usable for comparison purposes.</returns>
/// <remarks>Unlike MaxNumberOfGroups, this property will always return a positive value.</remarks>
internal Int64 ActualMaxNumberOfGroups
{
get { return (_maxNumberOfGroups == Unbounded) ? Int64.MaxValue : _maxNumberOfGroups; }
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmPriceList
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmPriceList() : base()
{
Load += frmPriceList_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.CheckBox chkChannel;
public System.Windows.Forms.ComboBox cmbDelivery;
public System.Windows.Forms.ComboBox cmbCOD;
public System.Windows.Forms.CheckBox _chkFields_12;
public System.Windows.Forms.TextBox _txtFields_0;
public System.Windows.Forms.Button cmdPrint;
public System.Windows.Forms.Button cmdAllocate;
public System.Windows.Forms.Button cmdCancel;
public System.Windows.Forms.Button cmdClose;
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.Label _lblLabels_0;
public System.Windows.Forms.Label _lblLabels_38;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2;
public System.Windows.Forms.Label _lbl_5;
//Public WithEvents chkFields As Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
public RectangleShapeArray Shape1;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this.chkChannel = new System.Windows.Forms.CheckBox();
this.cmbDelivery = new System.Windows.Forms.ComboBox();
this.cmbCOD = new System.Windows.Forms.ComboBox();
this._chkFields_12 = new System.Windows.Forms.CheckBox();
this._txtFields_0 = new System.Windows.Forms.TextBox();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdPrint = new System.Windows.Forms.Button();
this.cmdAllocate = new System.Windows.Forms.Button();
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdClose = new System.Windows.Forms.Button();
this._lblLabels_0 = new System.Windows.Forms.Label();
this._lblLabels_38 = new System.Windows.Forms.Label();
this._lbl_5 = new System.Windows.Forms.Label();
this.picButtons.SuspendLayout();
this.SuspendLayout();
//
//ShapeContainer1
//
this.ShapeContainer1.Location = new System.Drawing.Point(0, 0);
this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0);
this.ShapeContainer1.Name = "ShapeContainer1";
this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] { this._Shape1_2 });
this.ShapeContainer1.Size = new System.Drawing.Size(406, 158);
this.ShapeContainer1.TabIndex = 11;
this.ShapeContainer1.TabStop = false;
//
//_Shape1_2
//
this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_2.FillColor = System.Drawing.Color.Black;
this._Shape1_2.Location = new System.Drawing.Point(15, 60);
this._Shape1_2.Name = "_Shape1_2";
this._Shape1_2.Size = new System.Drawing.Size(379, 88);
//
//chkChannel
//
this.chkChannel.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.chkChannel.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.chkChannel.Cursor = System.Windows.Forms.Cursors.Default;
this.chkChannel.ForeColor = System.Drawing.SystemColors.ControlText;
this.chkChannel.Location = new System.Drawing.Point(210, 87);
this.chkChannel.Name = "chkChannel";
this.chkChannel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkChannel.Size = new System.Drawing.Size(136, 13);
this.chkChannel.TabIndex = 5;
this.chkChannel.Text = "Delivery Channel Name:";
this.chkChannel.UseVisualStyleBackColor = false;
//
//cmbDelivery
//
this.cmbDelivery.BackColor = System.Drawing.SystemColors.Window;
this.cmbDelivery.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbDelivery.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbDelivery.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbDelivery.Location = new System.Drawing.Point(210, 102);
this.cmbDelivery.Name = "cmbDelivery";
this.cmbDelivery.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbDelivery.Size = new System.Drawing.Size(178, 21);
this.cmbDelivery.TabIndex = 6;
//
//cmbCOD
//
this.cmbCOD.BackColor = System.Drawing.SystemColors.Window;
this.cmbCOD.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbCOD.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbCOD.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbCOD.Location = new System.Drawing.Point(21, 102);
this.cmbCOD.Name = "cmbCOD";
this.cmbCOD.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbCOD.Size = new System.Drawing.Size(178, 21);
this.cmbCOD.TabIndex = 4;
//
//_chkFields_12
//
this._chkFields_12.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._chkFields_12.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._chkFields_12.Cursor = System.Windows.Forms.Cursors.Default;
this._chkFields_12.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._chkFields_12.ForeColor = System.Drawing.SystemColors.WindowText;
this._chkFields_12.Location = new System.Drawing.Point(324, 126);
this._chkFields_12.Name = "_chkFields_12";
this._chkFields_12.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._chkFields_12.Size = new System.Drawing.Size(64, 19);
this._chkFields_12.TabIndex = 7;
this._chkFields_12.Text = "Disabled:";
this._chkFields_12.UseVisualStyleBackColor = false;
//
//_txtFields_0
//
this._txtFields_0.AcceptsReturn = true;
this._txtFields_0.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_0.Location = new System.Drawing.Point(102, 66);
this._txtFields_0.MaxLength = 0;
this._txtFields_0.Name = "_txtFields_0";
this._txtFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_0.Size = new System.Drawing.Size(285, 19);
this._txtFields_0.TabIndex = 2;
//
//picButtons
//
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Controls.Add(this.cmdPrint);
this.picButtons.Controls.Add(this.cmdAllocate);
this.picButtons.Controls.Add(this.cmdCancel);
this.picButtons.Controls.Add(this.cmdClose);
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.Name = "picButtons";
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Size = new System.Drawing.Size(406, 39);
this.picButtons.TabIndex = 10;
//
//cmdPrint
//
this.cmdPrint.BackColor = System.Drawing.SystemColors.Control;
this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPrint.Location = new System.Drawing.Point(243, 3);
this.cmdPrint.Name = "cmdPrint";
this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPrint.Size = new System.Drawing.Size(76, 28);
this.cmdPrint.TabIndex = 12;
this.cmdPrint.Text = "&Print";
this.cmdPrint.UseVisualStyleBackColor = false;
//
//cmdAllocate
//
this.cmdAllocate.BackColor = System.Drawing.SystemColors.Control;
this.cmdAllocate.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdAllocate.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdAllocate.Location = new System.Drawing.Point(150, 3);
this.cmdAllocate.Name = "cmdAllocate";
this.cmdAllocate.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdAllocate.Size = new System.Drawing.Size(79, 28);
this.cmdAllocate.TabIndex = 11;
this.cmdAllocate.Text = "&Allocate";
this.cmdAllocate.UseVisualStyleBackColor = false;
//
//cmdCancel
//
this.cmdCancel.BackColor = System.Drawing.SystemColors.Control;
this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdCancel.Location = new System.Drawing.Point(5, 3);
this.cmdCancel.Name = "cmdCancel";
this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdCancel.Size = new System.Drawing.Size(73, 29);
this.cmdCancel.TabIndex = 9;
this.cmdCancel.TabStop = false;
this.cmdCancel.Text = "&Undo";
this.cmdCancel.UseVisualStyleBackColor = false;
//
//cmdClose
//
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Location = new System.Drawing.Point(324, 3);
this.cmdClose.Name = "cmdClose";
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.TabIndex = 8;
this.cmdClose.TabStop = false;
this.cmdClose.Text = "E&xit";
this.cmdClose.UseVisualStyleBackColor = false;
//
//_lblLabels_0
//
this._lblLabels_0.AutoSize = true;
this._lblLabels_0.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_0.Location = new System.Drawing.Point(20, 87);
this._lblLabels_0.Name = "_lblLabels_0";
this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_0.Size = new System.Drawing.Size(106, 13);
this._lblLabels_0.TabIndex = 3;
this._lblLabels_0.Text = "COD Channel Name:";
this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_38
//
this._lblLabels_38.AutoSize = true;
this._lblLabels_38.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_38.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_38.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_38.Location = new System.Drawing.Point(20, 69);
this._lblLabels_38.Name = "_lblLabels_38";
this._lblLabels_38.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_38.Size = new System.Drawing.Size(84, 13);
this._lblLabels_38.TabIndex = 1;
this._lblLabels_38.Text = "Price List Name:";
this._lblLabels_38.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lbl_5
//
this._lbl_5.AutoSize = true;
this._lbl_5.BackColor = System.Drawing.Color.Transparent;
this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_5.Location = new System.Drawing.Point(15, 45);
this._lbl_5.Name = "_lbl_5";
this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_5.Size = new System.Drawing.Size(56, 13);
this._lbl_5.TabIndex = 0;
this._lbl_5.Text = "&1. General";
//
//frmPriceList
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224)));
this.ClientSize = new System.Drawing.Size(406, 158);
this.ControlBox = false;
this.Controls.Add(this.chkChannel);
this.Controls.Add(this.cmbDelivery);
this.Controls.Add(this.cmbCOD);
this.Controls.Add(this._chkFields_12);
this.Controls.Add(this._txtFields_0);
this.Controls.Add(this.picButtons);
this.Controls.Add(this._lblLabels_0);
this.Controls.Add(this._lblLabels_38);
this.Controls.Add(this._lbl_5);
this.Controls.Add(this.ShapeContainer1);
this.Cursor = System.Windows.Forms.Cursors.Default;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.KeyPreview = true;
this.Location = new System.Drawing.Point(73, 22);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmPriceList";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Edit Price List";
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
/*
* Copyright (c) Michel Bechelani. All rights reserved.
* see LICENSE
*/
using System;
using System.Collections;
using System.Text;
using Newtonsoft.Json;
namespace CloudNinja.Logging
{
public class KeyValueBuilder
{
bool appended;
StringBuilder builder;
string itemSeparator;
string keyValueSeparator;
public KeyValueBuilder()
{
this.appended = false;
this.builder = new StringBuilder();
this.itemSeparator = ", ";
this.keyValueSeparator = ": ";
}
public KeyValueBuilder(string keyValueSeparator, string itemSeparator)
{
this.appended = false;
this.builder = new StringBuilder();
this.itemSeparator = itemSeparator;
this.keyValueSeparator = keyValueSeparator;
}
public KeyValueBuilder Append(bool b)
{
this.builder.Append("{ ").Append(b).Append(" }");
return this;
}
public KeyValueBuilder Append(bool? b)
{
if (b.HasValue)
{
this.Append(b.Value);
}
else
{
this.builder.Append("{ ").Append("null").Append(" }");
}
return this;
}
public KeyValueBuilder Append(int n)
{
this.builder.Append("{ ").Append(n).Append(" }");
return this;
}
public KeyValueBuilder Append(int? n)
{
if (n.HasValue)
{
this.Append(n.Value);
}
else
{
this.builder.Append("{ ").Append("null").Append(" }");
}
return this;
}
public KeyValueBuilder Append(object o)
{
if (o == null)
{
this.builder.Append("null");
}
else if (o is int)
{
this.builder.Append((int)o);
}
else if (o is float)
{
this.builder.Append((float)o);
}
else if (o is string)
{
this.builder.Append(o as string);
}
else if (o is bool)
{
this.builder.Append((bool)o);
}
else
{
this.builder.Append(o.ToString());
}
return this;
}
public KeyValueBuilder Append(float f)
{
this.builder.Append("{ ").Append(f).Append(" }");
return this;
}
public KeyValueBuilder Append(float? f)
{
if (f.HasValue)
{
this.Append(f.Value);
}
else
{
this.builder.Append("{ ").Append("null").Append(" }");
}
return this;
}
public KeyValueBuilder Append(string s)
{
this.builder.Append(s);
return this;
}
public KeyValueBuilder Append(string key, IEnumerable enumerable)
{
if (this.appended)
{
this.builder.Append(this.itemSeparator);
}
this.builder.Append(key).Append(this.keyValueSeparator);
if (enumerable == null)
{
this.builder.Append("{ ").Append("null").Append(" }");
}
else
{
string serializedObject;
try
{
serializedObject = JsonConvert.SerializeObject(enumerable, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore });
}
catch
{
this.builder.Append("{ ").Append("[");
bool isFirst = true;
foreach (object o in enumerable)
{
if (!isFirst)
{
this.builder.Append(this.itemSeparator);
}
if (o is string)
{
this.builder.Append("\"");
this.builder.Append((o as string).EscapeCSharp());
this.builder.Append("\"");
}
else
{
this.Append(o);
}
isFirst = false;
}
this.builder.Append(" }").Append("]");
}
}
this.appended = true;
return this;
}
public KeyValueBuilder Append(string key, bool value)
{
if (this.appended)
{
this.builder.Append(this.itemSeparator);
}
this.builder.Append(key).Append(this.keyValueSeparator).Append(value);
this.appended = true;
return this;
}
public KeyValueBuilder Append(string key, bool? value)
{
if (this.appended)
{
this.builder.Append(this.itemSeparator);
}
this.builder.Append(key).Append(this.keyValueSeparator);
if (value.HasValue)
{
this.builder.Append(value);
}
else
{
this.builder.Append("null");
}
this.appended = true;
return this;
}
public KeyValueBuilder Append(string key, int value)
{
if (this.appended)
{
this.builder.Append(this.itemSeparator);
}
this.builder.Append(key).Append(this.keyValueSeparator).Append(value);
this.appended = true;
return this;
}
public KeyValueBuilder Append(string key, int? value)
{
if (this.appended)
{
this.builder.Append(this.itemSeparator);
}
this.builder.Append(key).Append(this.keyValueSeparator);
if (value.HasValue)
{
this.builder.Append(value);
}
else
{
this.builder.Append("null");
}
this.appended = true;
return this;
}
public KeyValueBuilder Append(string key, object o)
{
if (this.appended)
{
this.builder.Append(this.itemSeparator);
}
string serializedObject;
try
{
serializedObject = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore });
}
catch
{
serializedObject = o.ToString();
}
this.builder.Append(key).Append(this.keyValueSeparator).Append(serializedObject);
this.appended = true;
return this;
}
public KeyValueBuilder Append(string key, float value)
{
if (this.appended)
{
this.builder.Append(this.itemSeparator);
}
this.builder.Append(key).Append(this.keyValueSeparator).Append(value);
this.appended = true;
return this;
}
public KeyValueBuilder Append(string key, float? value)
{
if (this.appended)
{
this.builder.Append(this.itemSeparator);
}
this.builder.Append(key).Append(this.keyValueSeparator);
if (value.HasValue)
{
this.builder.Append(value);
}
else
{
this.builder.Append("null");
}
this.appended = true;
return this;
}
public KeyValueBuilder Append(string key, string value)
{
if (this.appended)
{
this.builder.Append(this.itemSeparator);
}
this.builder.Append(key).Append(this.keyValueSeparator).Append("\"").Append(value.EscapeCSharp()).Append("\"");
this.appended = true;
return this;
}
public override string ToString()
{
return this.builder.ToString();
}
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using Aurora.Framework;
using Aurora.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
/*****************************************************
*
* XMLRPCModule
*
* Module for accepting incoming communications from
* external XMLRPC client and calling a remote data
* procedure for a registered data channel/prim.
*
*
* 1. On module load, open a listener port
* 2. Attach an XMLRPC handler
* 3. When a request is received:
* 3.1 Parse into components: channel key, int, string
* 3.2 Look up registered channel listeners
* 3.3 Call the channel (prim) remote data method
* 3.4 Capture the response (llRemoteDataReply)
* 3.5 Return response to client caller
* 3.6 If no response from llRemoteDataReply within
* RemoteReplyScriptTimeout, generate script timeout fault
*
* Prims in script must:
* 1. Open a remote data channel
* 1.1 Generate a channel ID
* 1.2 Register primid,channelid pair with module
* 2. Implement the remote data procedure handler
*
* llOpenRemoteDataChannel
* llRemoteDataReply
* remote_data(integer type, key channel, key messageid, string sender, integer ival, string sval)
* llCloseRemoteDataChannel
*
* **************************************************/
namespace Aurora.Modules.Scripting
{
public class XMLRPCModule : ISharedRegionModule, IXMLRPC
{
private readonly object XMLRPCListLock = new object();
private readonly List<IScene> m_scenes = new List<IScene>();
private int RemoteReplyScriptTimeout = 9000;
private int RemoteReplyScriptWait = 300;
private bool m_httpServerStarted;
private string m_name = "XMLRPCModule";
// <channel id, RPCChannelInfo>
private Dictionary<UUID, RPCChannelInfo> m_openChannels;
private Dictionary<UUID, SendRemoteDataRequest> m_pendingSRDResponses;
private int m_remoteDataPort;
private Dictionary<UUID, RPCRequestInfo> m_rpcPending;
private Dictionary<UUID, RPCRequestInfo> m_rpcPendingResponses;
private IScriptModule m_scriptModule;
public bool IsSharedModule
{
get { return true; }
}
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
// We need to create these early because the scripts might be calling
// But since this gets called for every region, we need to make sure they
// get called only one time (or we lose any open channels)
if (null == m_openChannels)
{
m_openChannels = new Dictionary<UUID, RPCChannelInfo>();
m_rpcPending = new Dictionary<UUID, RPCRequestInfo>();
m_rpcPendingResponses = new Dictionary<UUID, RPCRequestInfo>();
m_pendingSRDResponses = new Dictionary<UUID, SendRemoteDataRequest>();
if (config.Configs["XMLRPC"] != null)
m_remoteDataPort = config.Configs["XMLRPC"].GetInt("XmlRpcPort", m_remoteDataPort);
}
}
public void AddRegion(IScene scene)
{
m_scenes.Add(scene);
scene.RegisterModuleInterface<IXMLRPC>(this);
}
public void RemoveRegion(IScene scene)
{
m_scenes.Remove(scene);
scene.UnregisterModuleInterface<IXMLRPC>(this);
}
public void RegionLoaded(IScene scene)
{
if (IsEnabled() && !m_httpServerStarted)
{
m_httpServerStarted = true;
// Start http server
// Attach xmlrpc handlers
MainConsole.Instance.Info("[XMLRPC MODULE]: " +
"Starting up XMLRPC Server on port " + m_remoteDataPort + " for llRemoteData commands.");
BaseHttpServer httpServer = new BaseHttpServer((uint) m_remoteDataPort, MainServer.Instance.HostName,
false);
httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData);
httpServer.Start();
}
m_scriptModule = scene.RequestModuleInterface<IScriptModule>();
}
public Type ReplaceableInterface
{
get { return null; }
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
#endregion
#region IXMLRPC Members
public int Port
{
get { return m_remoteDataPort; }
}
public bool IsEnabled()
{
return (m_remoteDataPort > 0);
}
/**********************************************
* OpenXMLRPCChannel
*
* Generate a UUID channel key and add it and
* the prim id to dictionary <channelUUID, primUUID>
*
* A custom channel key can be proposed.
* Otherwise, passing UUID.Zero will generate
* and return a random channel
*
* First check if there is a channel assigned for
* this itemID. If there is, then someone called
* llOpenRemoteDataChannel twice. Just return the
* original channel. Other option is to delete the
* current channel and assign a new one.
*
* ********************************************/
public UUID OpenXMLRPCChannel(UUID primID, UUID itemID, UUID channelID)
{
UUID newChannel = UUID.Zero;
// This should no longer happen, but the check is reasonable anyway
if (null == m_openChannels)
{
MainConsole.Instance.Warn("[XML RPC MODULE]: Attempt to open channel before initialization is complete");
return newChannel;
}
//Is a dupe?
#if (!ISWIN)
foreach (RPCChannelInfo ci in m_openChannels.Values)
{
if (ci.GetItemID().Equals(itemID))
{
// return the original channel ID for this item
newChannel = ci.GetChannelID();
break;
}
}
#else
foreach (RPCChannelInfo ci in m_openChannels.Values.Where(ci => ci.GetItemID().Equals(itemID)))
{
// return the original channel ID for this item
newChannel = ci.GetChannelID();
break;
}
#endif
if (newChannel == UUID.Zero)
{
newChannel = (channelID == UUID.Zero) ? UUID.Random() : channelID;
RPCChannelInfo rpcChanInfo = new RPCChannelInfo(primID, itemID, newChannel);
lock (XMLRPCListLock)
{
m_openChannels.Add(newChannel, rpcChanInfo);
}
}
//Make sure that the cmd handler thread is running
m_scriptModule.PokeThreads(itemID);
return newChannel;
}
// Delete channels based on itemID
// for when a script is deleted
public void DeleteChannels(UUID itemID)
{
if (m_openChannels != null)
{
ArrayList tmp = new ArrayList();
lock (XMLRPCListLock)
{
#if (!ISWIN)
foreach (RPCChannelInfo li in m_openChannels.Values)
{
if (li.GetItemID().Equals(itemID))
{
tmp.Add(itemID);
}
}
#else
foreach (RPCChannelInfo li in m_openChannels.Values.Where(li => li.GetItemID().Equals(itemID)))
{
tmp.Add(itemID);
}
#endif
IEnumerator tmpEnumerator = tmp.GetEnumerator();
while (tmpEnumerator.MoveNext())
m_openChannels.Remove((UUID) tmpEnumerator.Current);
}
}
//Make sure that the cmd handler thread is running
m_scriptModule.PokeThreads(itemID);
}
/**********************************************
* Remote Data Reply
*
* Response to RPC message
*
*********************************************/
public void RemoteDataReply(string channel, string message_id, string sdata, int idata)
{
UUID message_key = new UUID(message_id);
UUID channel_key = new UUID(channel);
RPCRequestInfo rpcInfo = null;
if (message_key == UUID.Zero)
{
#if (!ISWIN)
foreach (RPCRequestInfo oneRpcInfo in m_rpcPendingResponses.Values)
{
if (oneRpcInfo.GetChannelKey() == channel_key) rpcInfo = oneRpcInfo;
}
#else
foreach (RPCRequestInfo oneRpcInfo in m_rpcPendingResponses.Values.Where(oneRpcInfo => oneRpcInfo.GetChannelKey() == channel_key))
rpcInfo = oneRpcInfo;
#endif
}
else
{
m_rpcPendingResponses.TryGetValue(message_key, out rpcInfo);
}
if (rpcInfo != null)
{
rpcInfo.SetStrRetval(sdata);
rpcInfo.SetIntRetval(idata);
rpcInfo.SetProcessed(true);
m_rpcPendingResponses.Remove(message_key);
//Make sure that the cmd handler thread is running
m_scriptModule.PokeThreads(rpcInfo.GetItemID());
}
else
{
MainConsole.Instance.Warn("[XML RPC MODULE]: Channel or message_id not found");
}
}
/**********************************************
* CloseXMLRPCChannel
*
* Remove channel from dictionary
*
*********************************************/
public void CloseXMLRPCChannel(UUID channelKey)
{
if (m_openChannels.ContainsKey(channelKey))
m_openChannels.Remove(channelKey);
}
public bool hasRequests()
{
lock (XMLRPCListLock)
{
if (m_rpcPending != null)
if (m_rpcPending.Count > 0)
return true;
if (m_pendingSRDResponses != null)
if (m_pendingSRDResponses.Count > 0)
return true;
return false;
}
}
public IXmlRpcRequestInfo GetNextCompletedRequest()
{
if (m_rpcPending != null)
{
if (m_rpcPending.Count == 0)
return null;
lock (XMLRPCListLock)
{
#if (!ISWIN)
foreach (RPCRequestInfo luid in m_rpcPending.Values)
{
if (!luid.IsProcessed())
{
return luid;
}
}
#else
foreach (RPCRequestInfo luid in m_rpcPending.Values.Where(luid => !luid.IsProcessed()))
{
return luid;
}
#endif
}
}
return null;
}
public void RemoveCompletedRequest(UUID id)
{
lock (XMLRPCListLock)
{
RPCRequestInfo tmp;
if (m_rpcPending.TryGetValue(id, out tmp))
{
m_rpcPending.Remove(id);
m_rpcPendingResponses.Add(id, tmp);
}
else
{
MainConsole.Instance.Error("[XML RPC MODULE]: UNABLE TO REMOVE COMPLETED REQUEST");
}
}
}
public UUID SendRemoteData(UUID primID, UUID itemID, string channel, string dest, int idata, string sdata)
{
SendRemoteDataRequest req = new SendRemoteDataRequest(
primID, itemID, channel, dest, idata, sdata
);
m_pendingSRDResponses.Add(req.GetReqID(), req);
req.Process();
//Make sure that the cmd handler thread is running
m_scriptModule.PokeThreads(itemID);
return req.ReqID;
}
public IServiceRequest GetNextCompletedSRDRequest()
{
if (m_pendingSRDResponses != null)
{
if (m_pendingSRDResponses.Count == 0)
return null;
lock (XMLRPCListLock)
{
#if (!ISWIN)
foreach (SendRemoteDataRequest luid in m_pendingSRDResponses.Values)
{
if (luid.Finished)
{
return luid;
}
}
#else
foreach (SendRemoteDataRequest luid in m_pendingSRDResponses.Values.Where(luid => luid.Finished))
{
return luid;
}
#endif
}
}
return null;
}
public void RemoveCompletedSRDRequest(UUID id)
{
lock (XMLRPCListLock)
{
SendRemoteDataRequest tmpReq;
if (m_pendingSRDResponses.TryGetValue(id, out tmpReq))
{
m_pendingSRDResponses.Remove(id);
}
}
}
public void CancelSRDRequests(UUID itemID)
{
if (m_pendingSRDResponses != null)
{
lock (XMLRPCListLock)
{
#if (!ISWIN)
foreach (SendRemoteDataRequest li in m_pendingSRDResponses.Values)
{
if (li.ItemID.Equals(itemID))
{
m_pendingSRDResponses.Remove(li.GetReqID());
}
}
#else
foreach (SendRemoteDataRequest li in m_pendingSRDResponses.Values.Where(li => li.ItemID.Equals(itemID)))
{
m_pendingSRDResponses.Remove(li.GetReqID());
}
#endif
}
}
}
#endregion
public XmlRpcResponse XmlRpcRemoteData(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable) request.Params[0];
bool GoodXML = (requestData.Contains("Channel") && requestData.Contains("IntValue") &&
requestData.Contains("StringValue"));
if (GoodXML)
{
UUID channel = new UUID((string) requestData["Channel"]);
RPCChannelInfo rpcChanInfo;
if (m_openChannels.TryGetValue(channel, out rpcChanInfo))
{
string intVal = Convert.ToInt32(requestData["IntValue"]).ToString();
string strVal = (string) requestData["StringValue"];
RPCRequestInfo rpcInfo;
lock (XMLRPCListLock)
{
rpcInfo =
new RPCRequestInfo(rpcChanInfo.GetPrimID(), rpcChanInfo.GetItemID(), channel, strVal,
intVal);
m_rpcPending.Add(rpcInfo.GetMessageID(), rpcInfo);
}
int timeoutCtr = 0;
while (!rpcInfo.IsProcessed() && (timeoutCtr < RemoteReplyScriptTimeout))
{
Thread.Sleep(RemoteReplyScriptWait);
timeoutCtr += RemoteReplyScriptWait;
}
if (rpcInfo.IsProcessed())
{
Hashtable param = new Hashtable();
param["StringValue"] = rpcInfo.GetStrRetval();
param["IntValue"] = rpcInfo.GetIntRetval();
ArrayList parameters = new ArrayList {param};
response.Value = parameters;
rpcInfo = null;
}
else
{
response.SetFault(-1, "Script timeout");
rpcInfo = null;
}
}
else
{
response.SetFault(-1, "Invalid channel");
}
}
//Make sure that the cmd handler thread is running
m_scriptModule.PokeThreads(UUID.Zero);
return response;
}
}
public class RPCRequestInfo : IXmlRpcRequestInfo
{
private readonly UUID m_ChannelKey;
private readonly string m_IntVal;
private readonly UUID m_ItemID;
private readonly UUID m_MessageID;
private readonly UUID m_PrimID;
private readonly string m_StrVal;
private bool m_processed;
private int m_respInt;
private string m_respStr;
public RPCRequestInfo(UUID primID, UUID itemID, UUID channelKey, string strVal, string intVal)
{
m_PrimID = primID;
m_StrVal = strVal;
m_IntVal = intVal;
m_ItemID = itemID;
m_ChannelKey = channelKey;
m_MessageID = UUID.Random();
m_processed = false;
m_respStr = String.Empty;
m_respInt = 0;
}
#region IXmlRpcRequestInfo Members
public bool IsProcessed()
{
return m_processed;
}
public UUID GetChannelKey()
{
return m_ChannelKey;
}
public void SetProcessed(bool processed)
{
m_processed = processed;
}
public void SetStrRetval(string resp)
{
m_respStr = resp;
}
public string GetStrRetval()
{
return m_respStr;
}
public void SetIntRetval(int resp)
{
m_respInt = resp;
}
public int GetIntRetval()
{
return m_respInt;
}
public UUID GetPrimID()
{
return m_PrimID;
}
public UUID GetItemID()
{
return m_ItemID;
}
public string GetStrVal()
{
return m_StrVal;
}
public int GetIntValue()
{
return int.Parse(m_IntVal);
}
public UUID GetMessageID()
{
return m_MessageID;
}
#endregion
}
public class RPCChannelInfo
{
private readonly UUID m_ChannelKey;
private readonly UUID m_itemID;
private readonly UUID m_primID;
public RPCChannelInfo(UUID primID, UUID itemID, UUID channelID)
{
m_ChannelKey = channelID;
m_primID = primID;
m_itemID = itemID;
}
public UUID GetItemID()
{
return m_itemID;
}
public UUID GetChannelID()
{
return m_ChannelKey;
}
public UUID GetPrimID()
{
return m_primID;
}
}
public class SendRemoteDataRequest : ISendRemoteDataRequest
{
public string Channel { get; set; }
public string DestURL { get; set; }
public int Idata { get; set; }
public XmlRpcRequest Request { get; set; }
public int ResponseIdata { get; set; }
public string ResponseSdata { get; set; }
public string Sdata { get; set; }
private bool _finished;
private Thread httpThread;
public SendRemoteDataRequest(UUID primID, UUID itemID, string channel, string dest, int idata, string sdata)
{
this.Channel = channel;
DestURL = dest;
this.Idata = idata;
this.Sdata = sdata;
ItemID = itemID;
PrimID = primID;
ReqID = UUID.Random();
}
#region IServiceRequest Members
public bool Finished
{
get { return _finished; }
set { _finished = value; }
}
public UUID ItemID { get; set; }
public UUID PrimID { get; set; }
public UUID ReqID { get; set; }
public void Process()
{
httpThread = new Thread(SendRequest)
{Name = "HttpRequestThread", Priority = ThreadPriority.BelowNormal, IsBackground = true};
_finished = false;
httpThread.Start();
}
/*
* TODO: More work on the response codes. Right now
* returning 200 for success or 499 for exception
*/
public void SendRequest()
{
Culture.SetCurrentCulture();
Hashtable param = new Hashtable();
// Check if channel is an UUID
// if not, use as method name
UUID parseUID;
string mName = "llRemoteData";
if (!string.IsNullOrEmpty(Channel))
if (!UUID.TryParse(Channel, out parseUID))
mName = Channel;
else
param["Channel"] = Channel;
param["StringValue"] = Sdata;
param["IntValue"] = Convert.ToString(Idata);
ArrayList parameters = new ArrayList {param};
XmlRpcRequest req = new XmlRpcRequest(mName, parameters);
try
{
XmlRpcResponse resp = req.Send(DestURL, 30000);
if (resp != null)
{
Hashtable respParms;
if (resp.Value.GetType().Equals(typeof (Hashtable)))
{
respParms = (Hashtable) resp.Value;
}
else
{
ArrayList respData = (ArrayList) resp.Value;
respParms = (Hashtable) respData[0];
}
if (respParms != null)
{
if (respParms.Contains("StringValue"))
{
Sdata = (string) respParms["StringValue"];
}
if (respParms.Contains("IntValue"))
{
Idata = Convert.ToInt32(respParms["IntValue"]);
}
if (respParms.Contains("faultString"))
{
Sdata = (string) respParms["faultString"];
}
if (respParms.Contains("faultCode"))
{
Idata = Convert.ToInt32(respParms["faultCode"]);
}
}
}
}
catch (Exception we)
{
Sdata = we.Message;
MainConsole.Instance.Warn("[SendRemoteDataRequest]: Request failed");
MainConsole.Instance.Warn(we.StackTrace);
}
_finished = true;
}
public void Stop()
{
try
{
httpThread.Abort();
}
catch (Exception)
{
}
}
#endregion
public UUID GetReqID()
{
return ReqID;
}
}
}
| |
/*
Copyright (c) 2018, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
//#define AA_TIPS
using MatterHackers.Agg;
using MatterHackers.Agg.Image;
using MatterHackers.Agg.Transform;
using MatterHackers.Agg.VertexSource;
using MatterHackers.DataConverters2D;
using MatterHackers.RenderOpenGl.OpenGl;
using MatterHackers.VectorMath;
using System;
using Tesselate;
using MatterHackers.Agg.Platform;
using System.Collections.Generic;
namespace MatterHackers.RenderOpenGl
{
public class Graphics2DOpenGL : Graphics2D
{
// We can have a single static instance because all gl rendering is required to happen on the ui thread so there can
// be no runtime contention for this object (no thread contention).
private static AAGLTesselator triangleEdgeInfo = new AAGLTesselator();
/// <summary>
/// A texture per alpha value
/// </summary>
private static List<ImageBuffer> AATextureImages = null;
public bool DoEdgeAntiAliasing = true;
private static GLTesselator renderNowTesselator = new GLTesselator();
private int width;
private int height;
private RectangleDouble cachedClipRect;
public Graphics2DOpenGL()
{
}
public Graphics2DOpenGL(int width, int height)
{
this.width = width;
this.height = height;
cachedClipRect = new RectangleDouble(0, 0, width, height);
}
public override RectangleDouble GetClippingRect()
{
return cachedClipRect;
}
public override void SetClippingRect(RectangleDouble clippingRect)
{
cachedClipRect = clippingRect;
GL.Scissor((int)Math.Floor(Math.Max(clippingRect.Left, 0)), (int)Math.Floor(Math.Max(clippingRect.Bottom, 0)),
(int)Math.Ceiling(Math.Max(clippingRect.Width, 0)), (int)Math.Ceiling(Math.Max(clippingRect.Height, 0)));
GL.Enable(EnableCap.ScissorTest);
}
public override IScanlineCache ScanlineCache
{
get { return null; }
set { throw new Exception("There is no scanline cache on a GL surface."); }
}
public override int Width => width;
public override int Height => height;
public void PushOrthoProjection()
{
GL.Disable(EnableCap.CullFace);
GL.MatrixMode(MatrixMode.Projection);
GL.PushMatrix();
GL.LoadIdentity();
GL.Ortho(0, width, 0, height, 0, 1);
GL.MatrixMode(MatrixMode.Modelview);
GL.PushMatrix();
GL.LoadIdentity();
}
public void PopOrthoProjection()
{
GL.MatrixMode(MatrixMode.Projection);
GL.PopMatrix();
GL.MatrixMode(MatrixMode.Modelview);
GL.PopMatrix();
}
private void CheckLineImageCache()
{
if (AATextureImages == null)
{
AATextureImages = new List<ImageBuffer>();
for (int i = 0; i < 256; i++)
{
var texture = new ImageBuffer(1024, 4);
AATextureImages.Add(texture);
byte[] hardwarePixelBuffer = texture.GetBuffer();
for (int y = 0; y < 4; y++)
{
byte alpha = 0;
for (int x = 0; x < 1024; x++)
{
hardwarePixelBuffer[(y * 1024 + x) * 4 + 0] = 255;
hardwarePixelBuffer[(y * 1024 + x) * 4 + 1] = 255;
hardwarePixelBuffer[(y * 1024 + x) * 4 + 2] = 255;
hardwarePixelBuffer[(y * 1024 + x) * 4 + 3] = alpha;
alpha = (byte)i;
}
}
}
}
}
private void DrawAAShape(IVertexSource vertexSource, IColorType colorIn)
{
vertexSource.rewind(0);
Affine transform = GetTransform();
if (!transform.is_identity())
{
vertexSource = new VertexSourceApplyTransform(vertexSource, transform);
}
Color colorBytes = colorIn.ToColor();
// the alpha has come from the bound texture
GL.Color4(colorBytes.red, colorBytes.green, colorBytes.blue, (byte)255);
triangleEdgeInfo.Clear();
VertexSourceToTesselator.SendShapeToTesselator(triangleEdgeInfo, vertexSource);
// now render it
triangleEdgeInfo.RenderLastToGL();
}
/// <summary>
/// Draws a line with low poly rounded endcaps (only in GL implementation/only used by 2D GCode)
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="halfWidth"></param>
/// <param name="colorIn"></param>
public void DrawAALineRounded(Vector2 start, Vector2 end, double halfWidth, IColorType colorIn)
{
Color colorBytes = colorIn.ToColor();
GL.Color4(colorBytes.red, colorBytes.green, colorBytes.blue, colorBytes.alpha);
Affine transform = GetTransform();
if (!transform.is_identity())
{
transform.transform(ref start);
transform.transform(ref end);
}
//GL.Begin(BeginMode.Triangles);
Vector2 widthRightOffset = (end - start).GetPerpendicularRight().GetNormal() * halfWidth / 2;
// draw the main line part
triangleEdgeInfo.Draw1EdgeTriangle(start - widthRightOffset, end - widthRightOffset, end + widthRightOffset);
triangleEdgeInfo.Draw1EdgeTriangle(end + widthRightOffset, start + widthRightOffset, start - widthRightOffset);
// now draw the end rounds
int numSegments = 5;
Vector2 endCurveStart = end + widthRightOffset;
Vector2 startCurveStart = start + widthRightOffset;
for (int i = 0; i < numSegments + 1; i++)
{
Vector2 endCurveEnd = end + Vector2.Rotate(widthRightOffset, i * Math.PI / numSegments);
triangleEdgeInfo.Draw1EdgeTriangle(endCurveStart, endCurveEnd, end);
endCurveStart = endCurveEnd;
Vector2 startCurveEnd = start + Vector2.Rotate(widthRightOffset, -i * Math.PI / numSegments);
triangleEdgeInfo.Draw1EdgeTriangle(startCurveStart, startCurveEnd, start);
startCurveStart = startCurveEnd;
}
//GL.End();
}
/// <summary>
/// Draws a low poly circle (only in GL implementation/only used by 2D GCode)
/// </summary>
/// <param name="start"></param>
/// <param name="radius"></param>
/// <param name="colorIn"></param>
public void DrawAACircle(Vector2 start, double radius, IColorType colorIn)
{
Color colorBytes = colorIn.ToColor();
GL.Color4(colorBytes.red, colorBytes.green, colorBytes.blue, colorBytes.alpha);
Affine transform = GetTransform();
if (!transform.is_identity())
{
transform.transform(ref start);
}
// now draw the end rounds
int numSegments = 12;
double anglePerSegment = MathHelper.Tau / numSegments;
Vector2 currentOffset = new Vector2(0, radius);
Vector2 curveStart = start + currentOffset;
for (int i = 0; i < numSegments; i++)
{
currentOffset.Rotate(anglePerSegment);
Vector2 curveEnd = start + currentOffset;
triangleEdgeInfo.Draw1EdgeTriangle(curveStart, curveEnd, start);
curveStart = curveEnd;
}
}
public void PreRender(IColorType colorIn)
{
CheckLineImageCache();
PushOrthoProjection();
GL.Enable(EnableCap.Texture2D);
GL.BindTexture(TextureTarget.Texture2D, RenderOpenGl.ImageGlPlugin.GetImageGlPlugin(AATextureImages[colorIn.Alpha0To255], false).GLTextureHandle);
// the source is always all white so has no does not have its color changed by the alpha
GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha);
GL.Enable(EnableCap.Blend);
}
public override void Render(IVertexSource vertexSource, IColorType colorIn)
{
PreRender(colorIn);
if (DoEdgeAntiAliasing)
{
DrawAAShape(vertexSource, colorIn);
}
else
{
vertexSource.rewind(0);
Affine transform = GetTransform();
if (!transform.is_identity())
{
vertexSource = new VertexSourceApplyTransform(vertexSource, transform);
}
Color colorBytes = colorIn.ToColor();
GL.Color4(colorBytes.red, colorBytes.green, colorBytes.blue, colorBytes.alpha);
renderNowTesselator.Clear();
VertexSourceToTesselator.SendShapeToTesselator(renderNowTesselator, vertexSource);
}
PopOrthoProjection();
}
public override void Render(IImageByte source,
double x, double y,
double angleRadians,
double scaleX, double scaleY)
{
Affine transform = GetTransform();
if (!transform.is_identity())
{
// TODO: <BUG> make this do rotation and scaling
transform.transform(ref x, ref y);
scaleX *= transform.sx;
scaleY *= transform.sy;
}
// TODO: <BUG> make this do rotation and scaling
RectangleInt sourceBounds = source.GetBounds();
sourceBounds.Offset((int)x, (int)y);
RectangleInt destBounds = new RectangleInt((int)cachedClipRect.Left, (int)cachedClipRect.Bottom, (int)cachedClipRect.Right, (int)cachedClipRect.Top);
if (!RectangleInt.DoIntersect(sourceBounds, destBounds))
{
if (scaleX != 1 || scaleY != 1)// || angleDegrees != 0)
{
//throw new NotImplementedException();
}
//return;
}
ImageBuffer sourceAsImageBuffer = (ImageBuffer)source;
//ImageIO.SaveImageData($"c:\\temp\\gah-{DateTime.Now.Ticks}.png", sourceAsImageBuffer);
ImageGlPlugin glPlugin = ImageGlPlugin.GetImageGlPlugin(sourceAsImageBuffer, false);
// Prepare openGL for rendering
PushOrthoProjection();
GL.Disable(EnableCap.Lighting);
GL.Enable(EnableCap.Texture2D);
GL.Disable(EnableCap.DepthTest);
GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
GL.Translate(x, y, 0);
GL.Rotate(MathHelper.RadiansToDegrees(angleRadians), 0, 0, 1);
GL.Scale(scaleX, scaleY, 1);
Color color = Color.White;
GL.Color4((byte)color.Red0To255, (byte)color.Green0To255, (byte)color.Blue0To255, (byte)color.Alpha0To255);
glPlugin.DrawToGL();
//Restore openGL state
PopOrthoProjection();
}
public override void Render(IImageFloat imageSource,
double x, double y,
double angleDegrees,
double scaleX, double ScaleY)
{
throw new NotImplementedException();
}
public override void Rectangle(double left, double bottom, double right, double top, Color color, double strokeWidth)
{
#if true
// This only works for translation. If we have a rotation or scale in the transform this will have some problems.
Affine transform = GetTransform();
double fastLeft = left;
double fastBottom = bottom;
double fastRight = right;
double fastTop = top;
transform.transform(ref fastLeft, ref fastBottom);
transform.transform(ref fastRight, ref fastTop);
if (fastLeft == (int)fastLeft
&& fastBottom == (int)fastBottom
&& fastRight == (int)fastRight
&& fastTop == (int)fastTop
&& strokeWidth == 1)
{
// FillRectangle will do the translation so use the original variables
FillRectangle(left, bottom, right, bottom + 1, color);
FillRectangle(left, top, right, top - 1, color);
FillRectangle(left, bottom, left + 1, top, color);
FillRectangle(right - 1, bottom, right, top, color);
}
else
#endif
{
RoundedRect rect = new RoundedRect(left + .5, bottom + .5, right - .5, top - .5, 0);
Stroke rectOutline = new Stroke(rect, strokeWidth);
Render(rectOutline, color);
}
}
public override void FillRectangle(double left, double bottom, double right, double top, IColorType fillColor)
{
// This only works for translation. If we have a rotation or scale in the transform this will have some problems.
Affine transform = GetTransform();
double fastLeft = left;
double fastBottom = bottom;
double fastRight = right;
double fastTop = top;
transform.transform(ref fastLeft, ref fastBottom);
transform.transform(ref fastRight, ref fastTop);
if (Math.Abs(fastLeft - (int)fastLeft) < .01
&& Math.Abs(fastBottom - (int)fastBottom) < .01
&& Math.Abs(fastRight - (int)fastRight) < .01
&& Math.Abs(fastTop - (int)fastTop) < .01)
{
PushOrthoProjection();
GL.Disable(EnableCap.Texture2D);
GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
GL.Enable(EnableCap.Blend);
GL.Color4(fillColor.Red0To255, fillColor.Green0To255, fillColor.Blue0To255, fillColor.Alpha0To255);
GL.Begin(BeginMode.Triangles);
// triangle 1
{
GL.Vertex2(fastLeft, fastBottom);
GL.Vertex2(fastRight, fastBottom);
GL.Vertex2(fastRight, fastTop);
}
// triangle 2
{
GL.Vertex2(fastLeft, fastBottom);
GL.Vertex2(fastRight, fastTop);
GL.Vertex2(fastLeft, fastTop);
}
GL.End();
PopOrthoProjection();
}
else
{
RoundedRect rect = new RoundedRect(left, bottom, right, top, 0);
Render(rect, fillColor.ToColor());
}
}
public override void Line(double x1, double y1, double x2, double y2, Color color, double strokeWidth = 1)
{
RectangleDouble strokeBounds;
if (x1 == x2) // vertical line
{
strokeBounds = new RectangleDouble(x1 - strokeWidth / 2, y1, x1 + strokeWidth / 2, y2);
}
else // horizontal line
{
strokeBounds = new RectangleDouble(x1, y1 - strokeWidth / 2, x2, y1 + strokeWidth / 2);
}
// lets check for horizontal and vertical lines that are pixel aligned and render them as fills
bool canUseFill = (x1 == x2 || y1 == y2) // we are vertical or horizontal
&& Math.Abs(strokeBounds.Left - (int)strokeBounds.Left) < .01
&& Math.Abs(strokeBounds.Right - (int)strokeBounds.Right) < .01
&& Math.Abs(strokeBounds.Bottom - (int)strokeBounds.Bottom) < .01
&& Math.Abs(strokeBounds.Top - (int)strokeBounds.Top) < .01;
if (canUseFill)
{
// Draw as optimized vertical or horizontal line
FillRectangle(strokeBounds, color);
}
else
{
// Draw as a VertexSource - may yield incorrect lines in some cases
base.Line(x1, y1, x2, y2, color, strokeWidth);
}
}
public override void Clear(IColorType color)
{
Affine transform = GetTransform();
RoundedRect clearRect = new RoundedRect(new RectangleDouble(
cachedClipRect.Left - transform.tx, cachedClipRect.Bottom - transform.ty,
cachedClipRect.Right - transform.tx, cachedClipRect.Top - transform.ty), 0);
Render(clearRect, color.ToColor());
}
public void RenderTransformedPath(Matrix4X4 transform, IVertexSource path, Color color, bool doDepthTest)
{
CheckLineImageCache();
GL.Enable(EnableCap.Texture2D);
GL.BindTexture(TextureTarget.Texture2D, RenderOpenGl.ImageGlPlugin.GetImageGlPlugin(AATextureImages[color.Alpha0To255], false).GLTextureHandle);
// the source is always all white so has no does not have its color changed by the alpha
GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha);
GL.Enable(EnableCap.Blend);
GL.Disable(EnableCap.CullFace);
GL.MatrixMode(MatrixMode.Modelview);
GL.PushMatrix();
GL.MultMatrix(transform.GetAsFloatArray());
GL.Disable(EnableCap.Lighting);
if (doDepthTest)
{
GL.Enable(EnableCap.DepthTest);
}
else
{
GL.Disable(EnableCap.DepthTest);
}
this.affineTransformStack.Push(Affine.NewIdentity());
this.DrawAAShape(path, color);
this.affineTransformStack.Pop();
GL.PopMatrix();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Msagl.Core.GraphAlgorithms;
using Microsoft.Msagl.Core.Layout;
namespace Microsoft.Msagl.Layout.Layered {
/// <summary>
/// a class representing a graph where every edge goes down only one layer
/// </summary>
internal class ProperLayeredGraph {
/// <summary>
/// the underlying basic graph
/// </summary>
internal BasicGraph<Node, IntEdge> BaseGraph;
LayerEdge[] virtualNodesToInEdges;
LayerEdge[] virtualNodesToOutEdges;
int totalNumberOfNodes;
int firstVirtualNode;
private int FirstVirtualNode {
get {
return firstVirtualNode;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
internal ProperLayeredGraph(BasicGraph<Node, IntEdge> intGraph) {
Initialize(intGraph);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
internal void Initialize(BasicGraph<Node, IntEdge> intGraph)
{
BaseGraph = intGraph;
if (BaseGraph.Edges.Count > 0) {
var edgesGoingDown = from edge in BaseGraph.Edges
where edge.LayerEdges != null
select edge;
if(edgesGoingDown.Any() )
totalNumberOfNodes= (from edge in edgesGoingDown from layerEdge in edge.LayerEdges
select Math.Max(layerEdge.Source, layerEdge.Target) + 1).Max();
else totalNumberOfNodes = intGraph.NodeCount;
} else
totalNumberOfNodes = intGraph.NodeCount;
if (ExistVirtualNodes(BaseGraph.Edges)) {
firstVirtualNode = (from edge in BaseGraph.Edges
where edge.LayerEdges != null && edge.LayerEdges.Count > 1
let source = edge.Source
from layerEdge in edge.LayerEdges
let layerEdgeSource = layerEdge.Source
where layerEdge.Source != source
select layerEdgeSource).Min();
} else {
firstVirtualNode = BaseGraph.NodeCount;
totalNumberOfNodes = BaseGraph.NodeCount;
}
virtualNodesToInEdges = new LayerEdge[totalNumberOfNodes - FirstVirtualNode];
virtualNodesToOutEdges = new LayerEdge[totalNumberOfNodes - FirstVirtualNode];
foreach (IntEdge e in BaseGraph.Edges)
if (e.LayerSpan > 0)
foreach (LayerEdge le in e.LayerEdges) {
if (le.Target != e.Target)
virtualNodesToInEdges[le.Target - FirstVirtualNode] = le;
if (le.Source != e.Source)
virtualNodesToOutEdges[le.Source - FirstVirtualNode] = le;
}
}
static bool ExistVirtualNodes(ICollection<IntEdge> iCollection) {
foreach (var edge in iCollection)
if (edge.LayerEdges != null && edge.LayerEdges.Count > 1)
return true;
return false;
}
//internal ProperLayeredGraph(BasicGraph<IntEdge> intGraph, int[]layering) {
// this.baseGraph = intGraph;
// this.totalNumberOfNodes = intGraph.Nodes.Count + VirtualNodeCount(layering);
// virtualNodesToInEdges = new LayerEdge[totalNumberOfNodes - this.baseGraph.Nodes.Count];
// virtualNodesToOutEdges = new LayerEdge[totalNumberOfNodes - this.baseGraph.Nodes.Count];
// int currentVirtNode = intGraph.Nodes.Count;
// foreach (IntEdge e in baseGraph.Edges) {
// CreateLayerEdgesPath(e, layering, ref currentVirtNode);
// if (e.LayerSpan > 1)
// foreach (LayerEdge le in e.LayerEdges) {
// if (le.Target != e.Target)
// virtualNodesToInEdges[le.Target - NumOfOriginalNodes] = le;
// if (le.Source != e.Source)
// virtualNodesToOutEdges[le.Source - NumOfOriginalNodes] = le;
// }
// }
//}
/// <summary>
/// enumerates over the graph edges
/// </summary>
public IEnumerable<LayerEdge> Edges {
get {
foreach (IntEdge ie in BaseGraph.Edges) {
if (ie.LayerSpan > 0)
foreach (LayerEdge le in ie.LayerEdges)
yield return le;
}
}
}
/// <summary>
/// enumerates over edges of a node
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public IEnumerable<LayerEdge> InEdges(int node) {
if (node < BaseGraph.NodeCount)//original node
foreach (IntEdge e in BaseGraph.InEdges(node)) {
if (e.Source != e.Target && e.LayerEdges != null)
yield return LastEdge(e);
} else if (node >= firstVirtualNode)
yield return InEdgeOfVirtualNode(node);
}
private static LayerEdge LastEdge(IntEdge e) {
return e.LayerEdges[e.LayerEdges.Count - 1];
}
internal LayerEdge InEdgeOfVirtualNode(int node) {
return virtualNodesToInEdges[node - FirstVirtualNode];
}
/// <summary>
/// enumerates over the node outcoming edges
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public IEnumerable<LayerEdge> OutEdges(int node) {
if (node < BaseGraph.NodeCount)//original node
foreach (IntEdge e in BaseGraph.OutEdges(node)) {
if (e.Source != e.Target && e.LayerEdges!=null)
yield return FirstEdge(e);
} else if (node >= FirstVirtualNode)
yield return OutEdgeOfVirtualNode(node);
}
internal LayerEdge OutEdgeOfVirtualNode(int node) {
return virtualNodesToOutEdges[node - FirstVirtualNode];
}
private static LayerEdge FirstEdge(IntEdge e) {
return e.LayerEdges[0];
}
/// <summary>
/// returns the number of incoming edges for an edge
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public int InEdgesCount(int node) {
return RealInEdgesCount(node);
}
private int RealInEdgesCount(int node) {
return node < this.BaseGraph.NodeCount ? BaseGraph.InEdges(node).Count(e=>e.LayerEdges!=null): 1;
}
/// <summary>
/// returns the number of outcoming edges for an edge
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public int OutEdgesCount(int node) {
return RealOutEdgesCount(node);
}
private int RealOutEdgesCount(int node) {
return node < this.BaseGraph.NodeCount ? BaseGraph.OutEdges(node).Count(l=>l.LayerEdges!=null): 1;
}
/// <summary>
/// returns the node count
/// </summary>
public int NodeCount {
get { return this.totalNumberOfNodes; }
}
public bool IsRealNode(int node) {
return (node < this.BaseGraph.NodeCount);
}
public bool IsVirtualNode(int node) {
return !IsRealNode(node);
}
internal ProperLayeredGraph ReversedClone() {
List<IntEdge> reversedEdges = CreateReversedEdges();
return new ProperLayeredGraph(new BasicGraph<Node, IntEdge>(reversedEdges, this.BaseGraph.NodeCount));
}
private List<IntEdge> CreateReversedEdges() {
List<IntEdge> ret = new List<IntEdge>();
foreach (IntEdge e in BaseGraph.Edges)
if(!e.SelfEdge())
ret.Add(e.ReversedClone());
return ret;
}
internal IEnumerable<int> Succ(int node) {
foreach (LayerEdge le in this.OutEdges(node))
yield return le.Target;
}
internal IEnumerable<int> Pred(int node) {
foreach (LayerEdge le in this.InEdges(node))
yield return le.Source;
}
}
}
| |
// Copyright 2012 Applied Geographics, 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 GeoAPI.Geometries;
namespace AppGeo.Clients.ArcIms.ArcXml
{
[Serializable]
public class Layer : ICloneable
{
public const string XmlName = "LAYER";
public static Layer ReadFrom(ArcXmlReader reader)
{
try
{
Layer layer = new Layer();
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
string value = reader.ReadContentAsString();
if (value.Length > 0)
{
switch (reader.Name)
{
case "featurecount": layer.FeatureCount = Convert.ToInt32(value); break;
case "id": layer.ID = value; break;
case "name": layer.Name = value; break;
}
}
}
reader.MoveToElement();
}
return layer;
}
catch (Exception ex)
{
if (ex is ArcXmlException)
{
throw ex;
}
else
{
throw new ArcXmlException(String.Format("Could not read {0} element.", XmlName), ex);
}
}
}
public string ID = null;
public string Name = null;
public int FeatureCount = 0;
public string MaxScale = null;
public string MinScale = null;
public LayerType Type = LayerType.Acetate;
public bool Visible = true;
public Dataset Dataset = null;
public ImageProperties ImageProperties = null;
public Query Query = null;
public CoordSys CoordSys = null;
public Renderer Renderer = null;
public List<Object> Objects = null;
public Layer() { }
public Layer(string id)
{
ID = id;
}
public Layer(string id, LayerType type)
{
ID = id;
Type = type;
}
public LayerDef ToLayerDef()
{
return new LayerDef(ID);
}
public void Add(Object o)
{
if (Type != LayerType.Acetate)
{
throw new ArcXmlException("Layer is not of type Acetate, cannot add graphical objects");
}
if (Objects == null)
{
Objects = new List<Object>();
}
Objects.Add(o);
}
public void Add(Envelope envelope, Symbol symbol)
{
Add(new Object(envelope, symbol));
}
public void Add(IGeometry shape, Symbol symbol)
{
Add(new Object(shape, symbol));
}
public void Add(NorthArrow northArrow)
{
Add(new Object(northArrow));
}
public void Add(ScaleBar scaleBar)
{
Add(new Object(scaleBar));
}
public void Add(Text text)
{
Add(new Object(text));
}
public void Add(Text text, TextMarkerSymbol symbol)
{
Add(new Object(text, symbol));
}
public object Clone()
{
Layer clone = (Layer)this.MemberwiseClone();
if (CoordSys != null)
{
clone.CoordSys = (CoordSys)CoordSys.Clone();
}
if (Dataset != null)
{
clone.Dataset = (Dataset)Dataset.Clone();
}
if (Objects != null)
{
clone.Objects = new List<Object>();
foreach (Object obj in Objects)
{
clone.Objects.Add((Object)obj.Clone());
}
}
if (Query != null)
{
clone.Query = (Query)Query.Clone();
}
if (Renderer != null)
{
clone.Renderer = (Renderer)Renderer.Clone();
}
return clone;
}
public void WriteTo(ArcXmlWriter writer)
{
try
{
writer.WriteStartElement(XmlName);
if (!String.IsNullOrEmpty(ID))
{
writer.WriteAttributeString("id", ID);
}
if (Type != LayerType.None)
{
writer.WriteAttributeString("type", ArcXmlEnumConverter.ToArcXml(typeof(LayerType), Type));
}
if (!String.IsNullOrEmpty(MaxScale))
{
writer.WriteAttributeString("maxscale", MaxScale);
}
if (!String.IsNullOrEmpty(MinScale))
{
writer.WriteAttributeString("mincale", MinScale);
}
if (!String.IsNullOrEmpty(Name))
{
writer.WriteAttributeString("name", Name);
}
if (!Visible)
{
writer.WriteAttributeString("visible", "false");
}
if (CoordSys != null)
{
CoordSys.WriteTo(writer);
}
if (Dataset != null)
{
Dataset.WriteTo(writer);
}
if (ImageProperties != null)
{
ImageProperties.WriteTo(writer);
}
if (Objects != null)
{
foreach (Object obj in Objects)
{
obj.WriteTo(writer);
}
}
if (Query != null)
{
Query.WriteTo(writer);
}
if (Renderer != null)
{
Renderer.WriteTo(writer);
}
writer.WriteEndElement();
}
catch (Exception ex)
{
if (ex is ArcXmlException)
{
throw ex;
}
else
{
throw new ArcXmlException(String.Format("Could not write {0} object.", GetType().Name), ex);
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Avatar.Friends
{
/*
This module handles adding/removing friends, and the the presence
notification process for login/logoff of friends.
The presence notification works as follows:
- After the user initially connects to a region (so we now have a UDP
connection to work with), this module fetches the friends of user
(those are cached), their on-/offline status, and info about the
region they are in from the MessageServer.
- (*) It then informs the user about the on-/offline status of her friends.
- It then informs all online friends currently on this region-server about
user's new online status (this will save some network traffic, as local
messages don't have to be transferred inter-region, and it will be all
that has to be done in Standalone Mode).
- For the rest of the online friends (those not on this region-server),
this module uses the provided region-information to map users to
regions, and sends one notification to every region containing the
friends to inform on that server.
- The region-server will handle that in the following way:
- If it finds the friend, it informs her about the user being online.
- If it doesn't find the friend (maybe she TPed away in the meantime),
it stores that information.
- After it processed all friends, it returns the list of friends it
couldn't find.
- If this list isn't empty, the FriendsModule re-requests information
about those online friends that have been missed and starts at (*)
again until all friends have been found, or until it tried 3 times
(to prevent endless loops due to some uncaught error).
NOTE: Online/Offline notifications don't need to be sent on region change.
We implement two XMLRpc handlers here, handling all the inter-region things
we have to handle:
- On-/Offline-Notifications (bulk)
- Terminate Friendship messages (single)
*/
public class FriendsModule : IRegionModule, IFriendsModule
{
private class Transaction
{
public UUID agentID;
public string agentName;
public uint count;
public Transaction(UUID agentID, string agentName)
{
this.agentID = agentID;
this.agentName = agentName;
this.count = 1;
}
}
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Cache m_friendLists = new Cache(CacheFlags.AllowUpdate);
private Dictionary<UUID, ulong> m_rootAgents = new Dictionary<UUID, ulong>();
private Dictionary<UUID, UUID> m_pendingCallingcardRequests = new Dictionary<UUID,UUID>();
private Scene m_initialScene; // saves a lookup if we don't have a specific scene
private Dictionary<ulong, Scene> m_scenes = new Dictionary<ulong,Scene>();
private IMessageTransferModule m_TransferModule = null;
private IGridServices m_gridServices = null;
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config)
{
lock (m_scenes)
{
if (m_scenes.Count == 0)
{
MainServer.Instance.AddXmlRPCHandler("presence_update_bulk", processPresenceUpdateBulk);
MainServer.Instance.AddXmlRPCHandler("terminate_friend", processTerminateFriend);
m_friendLists.DefaultTTL = new TimeSpan(1, 0, 0); // store entries for one hour max
m_initialScene = scene;
}
if (!m_scenes.ContainsKey(scene.RegionInfo.RegionHandle))
m_scenes[scene.RegionInfo.RegionHandle] = scene;
}
scene.RegisterModuleInterface<IFriendsModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
scene.EventManager.OnMakeChildAgent += MakeChildAgent;
scene.EventManager.OnClientClosed += ClientClosed;
}
public void PostInitialise()
{
if (m_scenes.Count > 0)
{
m_TransferModule = m_initialScene.RequestModuleInterface<IMessageTransferModule>();
m_gridServices = m_initialScene.CommsManager.GridService;
}
if (m_TransferModule == null)
m_log.Error("[FRIENDS]: Unable to find a message transfer module, friendship offers will not work");
}
public void Close()
{
}
public string Name
{
get { return "FriendsModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
#region IInterregionFriendsComms
public List<UUID> InformFriendsInOtherRegion(UUID agentId, ulong destRegionHandle, List<UUID> friends, bool online)
{
List<UUID> tpdAway = new List<UUID>();
// destRegionHandle is a region on another server
RegionInfo info = m_gridServices.RequestNeighbourInfo(destRegionHandle);
if (info != null)
{
string httpServer = "http://" + info.ExternalEndPoint.Address + ":" + info.HttpPort + "/presence_update_bulk";
Hashtable reqParams = new Hashtable();
reqParams["agentID"] = agentId.ToString();
reqParams["agentOnline"] = online;
int count = 0;
foreach (UUID uuid in friends)
{
reqParams["friendID_" + count++] = uuid.ToString();
}
reqParams["friendCount"] = count;
IList parameters = new ArrayList();
parameters.Add(reqParams);
try
{
XmlRpcRequest request = new XmlRpcRequest("presence_update_bulk", parameters);
XmlRpcResponse response = request.Send(httpServer, 5000);
Hashtable respData = (Hashtable)response.Value;
count = (int)respData["friendCount"];
for (int i = 0; i < count; ++i)
{
UUID uuid;
if (UUID.TryParse((string)respData["friendID_" + i], out uuid)) tpdAway.Add(uuid);
}
}
catch (WebException e)
{
// Ignore connect failures, simulators come and go
//
if (!e.Message.Contains("ConnectFailure"))
{
m_log.Error("[OGS1 GRID SERVICES]: InformFriendsInOtherRegion XMLRPC failure: ", e);
}
}
catch (Exception e)
{
m_log.Error("[OGS1 GRID SERVICES]: InformFriendsInOtherRegion XMLRPC failure: ", e);
}
}
else m_log.WarnFormat("[OGS1 GRID SERVICES]: Couldn't find region {0}???", destRegionHandle);
return tpdAway;
}
public bool TriggerTerminateFriend(ulong destRegionHandle, UUID agentID, UUID exFriendID)
{
// destRegionHandle is a region on another server
RegionInfo info = m_gridServices.RequestNeighbourInfo(destRegionHandle);
if (info == null)
{
m_log.WarnFormat("[OGS1 GRID SERVICES]: Couldn't find region {0}", destRegionHandle);
return false; // region not found???
}
string httpServer = "http://" + info.ExternalEndPoint.Address + ":" + info.HttpPort + "/presence_update_bulk";
Hashtable reqParams = new Hashtable();
reqParams["agentID"] = agentID.ToString();
reqParams["friendID"] = exFriendID.ToString();
IList parameters = new ArrayList();
parameters.Add(reqParams);
try
{
XmlRpcRequest request = new XmlRpcRequest("terminate_friend", parameters);
XmlRpcResponse response = request.Send(httpServer, 5000);
Hashtable respData = (Hashtable)response.Value;
return (bool)respData["success"];
}
catch (Exception e)
{
m_log.Error("[OGS1 GRID SERVICES]: InformFriendsInOtherRegion XMLRPC failure: ", e);
return false;
}
}
#endregion
#region Incoming XMLRPC messages
/// <summary>
/// Receive presence information changes about clients in other regions.
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public XmlRpcResponse processPresenceUpdateBulk(XmlRpcRequest req, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)req.Params[0];
List<UUID> friendsNotHere = new List<UUID>();
// this is called with the expectation that all the friends in the request are on this region-server.
// But as some time passed since we checked (on the other region-server, via the MessagingServer),
// some of the friends might have teleported away.
// Actually, even now, between this line and the sending below, some people could TP away. So,
// we'll have to lock the m_rootAgents list for the duration to prevent/delay that.
lock (m_rootAgents)
{
List<ScenePresence> friendsHere = new List<ScenePresence>();
try
{
UUID agentID = new UUID((string)requestData["agentID"]);
bool agentOnline = (bool)requestData["agentOnline"];
int count = (int)requestData["friendCount"];
for (int i = 0; i < count; ++i)
{
UUID uuid;
if (UUID.TryParse((string)requestData["friendID_" + i], out uuid))
{
if (m_rootAgents.ContainsKey(uuid)) friendsHere.Add(GetRootPresenceFromAgentID(uuid));
else friendsNotHere.Add(uuid);
}
}
// now send, as long as they are still here...
UUID[] agentUUID = new UUID[] { agentID };
if (agentOnline)
{
foreach (ScenePresence agent in friendsHere)
{
agent.ControllingClient.SendAgentOnline(agentUUID);
}
}
else
{
foreach (ScenePresence agent in friendsHere)
{
agent.ControllingClient.SendAgentOffline(agentUUID);
}
}
}
catch(Exception e)
{
m_log.Warn("[FRIENDS]: Got exception while parsing presence_update_bulk request:", e);
}
}
// no need to lock anymore; if TPs happen now, worst case is that we have an additional agent in this region,
// which should be caught on the next iteration...
Hashtable result = new Hashtable();
int idx = 0;
foreach (UUID uuid in friendsNotHere)
{
result["friendID_" + idx++] = uuid.ToString();
}
result["friendCount"] = idx;
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
public XmlRpcResponse processTerminateFriend(XmlRpcRequest req, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)req.Params[0];
bool success = false;
UUID agentID;
UUID friendID;
if (requestData.ContainsKey("agentID") && UUID.TryParse((string)requestData["agentID"], out agentID) &&
requestData.ContainsKey("friendID") && UUID.TryParse((string)requestData["friendID"], out friendID))
{
// try to find it and if it is there, prevent it to vanish before we sent the message
lock (m_rootAgents)
{
if (m_rootAgents.ContainsKey(agentID))
{
m_log.DebugFormat("[FRIEND]: Sending terminate friend {0} to agent {1}", friendID, agentID);
GetRootPresenceFromAgentID(agentID).ControllingClient.SendTerminateFriend(friendID);
success = true;
}
}
}
// return whether we were successful
Hashtable result = new Hashtable();
result["success"] = success;
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
#endregion
#region Scene events
private void OnNewClient(IClientAPI client)
{
// All friends establishment protocol goes over instant message
// There's no way to send a message from the sim
// to a user to 'add a friend' without causing dialog box spam
// Subscribe to instant messages
client.OnInstantMessage += OnInstantMessage;
// Friend list management
client.OnApproveFriendRequest += OnApproveFriendRequest;
client.OnDenyFriendRequest += OnDenyFriendRequest;
client.OnTerminateFriendship += OnTerminateFriendship;
// ... calling card handling...
client.OnOfferCallingCard += OnOfferCallingCard;
client.OnAcceptCallingCard += OnAcceptCallingCard;
client.OnDeclineCallingCard += OnDeclineCallingCard;
// we need this one exactly once per agent session (see comments in the handler below)
client.OnEconomyDataRequest += OnEconomyDataRequest;
// if it leaves, we want to know, too
client.OnLogout += OnLogout;
}
private void ClientClosed(UUID AgentId, Scene scene)
{
// agent's client was closed. As we handle logout in OnLogout, this here has only to handle
// TPing away (root agent is closed) or TPing/crossing in a region far enough away (client
// agent is closed).
// NOTE: In general, this doesn't mean that the agent logged out, just that it isn't around
// in one of the regions here anymore.
lock (m_rootAgents)
{
if (m_rootAgents.ContainsKey(AgentId))
{
m_rootAgents.Remove(AgentId);
}
}
}
private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
{
lock (m_rootAgents)
{
m_rootAgents[avatar.UUID] = avatar.RegionHandle;
// Claim User! my user! Mine mine mine!
}
}
private void MakeChildAgent(ScenePresence avatar)
{
lock (m_rootAgents)
{
if (m_rootAgents.ContainsKey(avatar.UUID))
{
// only delete if the region matches. As this is a shared module, the avatar could be
// root agent in another region on this server.
if (m_rootAgents[avatar.UUID] == avatar.RegionHandle)
{
m_rootAgents.Remove(avatar.UUID);
// m_log.Debug("[FRIEND]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent");
}
}
}
}
#endregion
private ScenePresence GetRootPresenceFromAgentID(UUID AgentID)
{
ScenePresence returnAgent = null;
lock (m_scenes)
{
ScenePresence queryagent = null;
foreach (Scene scene in m_scenes.Values)
{
queryagent = scene.GetScenePresence(AgentID);
if (queryagent != null)
{
if (!queryagent.IsChildAgent)
{
returnAgent = queryagent;
break;
}
}
}
}
return returnAgent;
}
private ScenePresence GetAnyPresenceFromAgentID(UUID AgentID)
{
ScenePresence returnAgent = null;
lock (m_scenes)
{
ScenePresence queryagent = null;
foreach (Scene scene in m_scenes.Values)
{
queryagent = scene.GetScenePresence(AgentID);
if (queryagent != null)
{
returnAgent = queryagent;
break;
}
}
}
return returnAgent;
}
public void OfferFriendship(UUID fromUserId, IClientAPI toUserClient, string offerMessage)
{
CachedUserInfo userInfo = m_initialScene.CommsManager.UserProfileCacheService.GetUserDetails(fromUserId);
if (userInfo != null)
{
GridInstantMessage msg = new GridInstantMessage(
toUserClient.Scene, fromUserId, userInfo.UserProfile.Name, toUserClient.AgentId,
(byte)InstantMessageDialog.FriendshipOffered, offerMessage, false, Vector3.Zero);
FriendshipOffered(msg);
}
else
{
m_log.ErrorFormat("[FRIENDS]: No user found for id {0} in OfferFriendship()", fromUserId);
}
}
#region FriendRequestHandling
private void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
// Friend Requests go by Instant Message.. using the dialog param
// https://wiki.secondlife.com/wiki/ImprovedInstantMessage
if (im.dialog == (byte)InstantMessageDialog.FriendshipOffered) // 38
{
// fromAgentName is the *destination* name (the friend we offer friendship to)
ScenePresence initiator = GetAnyPresenceFromAgentID(new UUID(im.fromAgentID));
im.fromAgentName = initiator != null ? initiator.Name : "(hippo)";
FriendshipOffered(im);
}
else if (im.dialog == (byte)InstantMessageDialog.FriendshipAccepted) // 39
{
FriendshipAccepted(client, im);
}
else if (im.dialog == (byte)InstantMessageDialog.FriendshipDeclined) // 40
{
FriendshipDeclined(client, im);
}
}
/// <summary>
/// Invoked when a user offers a friendship.
/// </summary>
///
/// <param name="im"></param>
/// <param name="client"></param>
private void FriendshipOffered(GridInstantMessage im)
{
// this is triggered by the initiating agent:
// A local agent offers friendship to some possibly remote friend.
// A IM is triggered, processed here and sent to the friend (possibly in a remote region).
m_log.DebugFormat("[FRIEND]: Offer(38) - From: {0}, FromName: {1} To: {2}, Session: {3}, Message: {4}, Offline {5}",
im.fromAgentID, im.fromAgentName, im.toAgentID, im.imSessionID, im.message, im.offline);
// 1.20 protocol sends an UUID in the message field, instead of the friendship offer text.
// For interoperability, we have to clear that
if (Util.isUUID(im.message)) im.message = "";
// be sneeky and use the initiator-UUID as transactionID. This means we can be stateless.
// we have to look up the agent name on friendship-approval, though.
im.imSessionID = im.fromAgentID;
if (m_TransferModule != null)
{
// Send it to whoever is the destination.
// If new friend is local, it will send an IM to the viewer.
// If new friend is remote, it will cause a OnGridInstantMessage on the remote server
m_TransferModule.SendInstantMessage(
im,
delegate(bool success)
{
m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
}
);
}
}
/// <summary>
/// Invoked when a user accepts a friendship offer.
/// </summary>
/// <param name="im"></param>
/// <param name="client"></param>
private void FriendshipAccepted(IClientAPI client, GridInstantMessage im)
{
m_log.DebugFormat("[FRIEND]: 39 - from client {0}, agent {2} {3}, imsession {4} to {5}: {6} (dialog {7})",
client.AgentId, im.fromAgentID, im.fromAgentName, im.imSessionID, im.toAgentID, im.message, im.dialog);
}
/// <summary>
/// Invoked when a user declines a friendship offer.
/// </summary>
/// May not currently be used - see OnDenyFriendRequest() instead
/// <param name="im"></param>
/// <param name="client"></param>
private void FriendshipDeclined(IClientAPI client, GridInstantMessage im)
{
UUID fromAgentID = new UUID(im.fromAgentID);
UUID toAgentID = new UUID(im.toAgentID);
// declining the friendship offer causes a type 40 IM being sent to the (possibly remote) initiator
// toAgentID is initiator, fromAgentID declined friendship
m_log.DebugFormat("[FRIEND]: 40 - from client {0}, agent {1} {2}, imsession {3} to {4}: {5} (dialog {6})",
client != null ? client.AgentId.ToString() : "<null>",
fromAgentID, im.fromAgentName, im.imSessionID, im.toAgentID, im.message, im.dialog);
// Send the decline to whoever is the destination.
GridInstantMessage msg
= new GridInstantMessage(
client.Scene, fromAgentID, client.Name, toAgentID,
im.dialog, im.message, im.offline != 0, im.Position);
// If new friend is local, it will send an IM to the viewer.
// If new friend is remote, it will cause a OnGridInstantMessage on the remote server
m_TransferModule.SendInstantMessage(msg,
delegate(bool success) {
m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
}
);
}
private void OnGridInstantMessage(GridInstantMessage msg)
{
// This event won't be raised unless we have that agent,
// so we can depend on the above not trying to send
// via grid again
//m_log.DebugFormat("[FRIEND]: Got GridIM from {0}, to {1}, imSession {2}, message {3}, dialog {4}",
// msg.fromAgentID, msg.toAgentID, msg.imSessionID, msg.message, msg.dialog);
if (msg.dialog == (byte)InstantMessageDialog.FriendshipOffered ||
msg.dialog == (byte)InstantMessageDialog.FriendshipAccepted ||
msg.dialog == (byte)InstantMessageDialog.FriendshipDeclined)
{
// this should succeed as we *know* the root agent is here.
m_TransferModule.SendInstantMessage(msg,
delegate(bool success) {
//m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
}
);
}
if (msg.dialog == (byte)InstantMessageDialog.FriendshipAccepted)
{
// for accept friendship, we have to do a bit more
ApproveFriendship(new UUID(msg.fromAgentID), new UUID(msg.toAgentID), msg.fromAgentName);
}
}
private void ApproveFriendship(UUID fromAgentID, UUID toAgentID, string fromName)
{
m_log.DebugFormat("[FRIEND]: Approve friendship from {0} (ID: {1}) to {2}",
fromAgentID, fromName, toAgentID);
// a new friend was added in the initiator's and friend's data, so the cache entries are wrong now.
lock (m_friendLists)
{
m_friendLists.Invalidate(fromAgentID.ToString());
m_friendLists.Invalidate(toAgentID.ToString());
}
// now send presence update and add a calling card for the new friend
ScenePresence initiator = GetAnyPresenceFromAgentID(toAgentID);
if (initiator == null)
{
// quite wrong. Shouldn't happen.
m_log.WarnFormat("[FRIEND]: Coudn't find initiator of friend request {0}", toAgentID);
return;
}
m_log.DebugFormat("[FRIEND]: Tell {0} that {1} is online",
initiator.Name, fromName);
// tell initiator that friend is online
initiator.ControllingClient.SendAgentOnline(new UUID[] { fromAgentID });
// find the folder for the friend...
//InventoryFolderImpl folder =
// initiator.Scene.CommsManager.UserProfileCacheService.GetUserDetails(toAgentID).FindFolderForType((int)InventoryType.CallingCard);
IInventoryService invService = initiator.Scene.InventoryService;
InventoryFolderBase folder = invService.GetFolderForType(toAgentID, AssetType.CallingCard);
if (folder != null)
{
// ... and add the calling card
CreateCallingCard(initiator.ControllingClient, fromAgentID, folder.ID, fromName);
}
}
private void OnApproveFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders)
{
m_log.DebugFormat("[FRIEND]: Got approve friendship from {0} {1}, agentID {2}, tid {3}",
client.Name, client.AgentId, agentID, friendID);
// store the new friend persistently for both avatars
m_initialScene.StoreAddFriendship(friendID, agentID, (uint) FriendRights.CanSeeOnline);
// The cache entries aren't valid anymore either, as we just added a friend to both sides.
lock (m_friendLists)
{
m_friendLists.Invalidate(agentID.ToString());
m_friendLists.Invalidate(friendID.ToString());
}
// if it's a local friend, we don't have to do the lookup
ScenePresence friendPresence = GetAnyPresenceFromAgentID(friendID);
if (friendPresence != null)
{
m_log.Debug("[FRIEND]: Local agent detected.");
// create calling card
CreateCallingCard(client, friendID, callingCardFolders[0], friendPresence.Name);
// local message means OnGridInstantMessage won't be triggered, so do the work here.
friendPresence.ControllingClient.SendInstantMessage(
new GridInstantMessage(client.Scene, agentID,
client.Name, friendID,
(byte)InstantMessageDialog.FriendshipAccepted,
agentID.ToString(), false, Vector3.Zero));
ApproveFriendship(agentID, friendID, client.Name);
}
else
{
m_log.Debug("[FRIEND]: Remote agent detected.");
// fetch the friend's name for the calling card.
CachedUserInfo info = m_initialScene.CommsManager.UserProfileCacheService.GetUserDetails(friendID);
// create calling card
CreateCallingCard(client, friendID, callingCardFolders[0],
info.UserProfile.FirstName + " " + info.UserProfile.SurName);
// Compose (remote) response to friend.
GridInstantMessage msg = new GridInstantMessage(client.Scene, agentID, client.Name, friendID,
(byte)InstantMessageDialog.FriendshipAccepted,
agentID.ToString(), false, Vector3.Zero);
if (m_TransferModule != null)
{
m_TransferModule.SendInstantMessage(msg,
delegate(bool success) {
m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
}
);
}
}
// tell client that new friend is online
client.SendAgentOnline(new UUID[] { friendID });
}
private void OnDenyFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders)
{
m_log.DebugFormat("[FRIEND]: Got deny friendship from {0} {1}, agentID {2}, tid {3}",
client.Name, client.AgentId, agentID, friendID);
// Compose response to other agent.
GridInstantMessage msg = new GridInstantMessage(client.Scene, agentID, client.Name, friendID,
(byte)InstantMessageDialog.FriendshipDeclined,
agentID.ToString(), false, Vector3.Zero);
// send decline to initiator
if (m_TransferModule != null)
{
m_TransferModule.SendInstantMessage(msg,
delegate(bool success) {
m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
}
);
}
}
private void OnTerminateFriendship(IClientAPI client, UUID agentID, UUID exfriendID)
{
// client.AgentId == agentID!
// this removes the friends from the stored friendlists. After the next login, they will be gone...
m_initialScene.StoreRemoveFriendship(agentID, exfriendID);
// ... now tell the two involved clients that they aren't friends anymore.
// I don't know why we have to tell <agent>, as this was caused by her, but that's how it works in SL...
client.SendTerminateFriend(exfriendID);
// now send the friend, if online
ScenePresence presence = GetAnyPresenceFromAgentID(exfriendID);
if (presence != null)
{
m_log.DebugFormat("[FRIEND]: Sending terminate friend {0} to agent {1}", agentID, exfriendID);
presence.ControllingClient.SendTerminateFriend(agentID);
}
else
{
// retry 3 times, in case the agent TPed from the last known region...
for (int retry = 0; retry < 3; ++retry)
{
// wasn't sent, so ex-friend wasn't around on this region-server. Fetch info and try to send
UserAgentData data = m_initialScene.CommsManager.UserService.GetAgentByUUID(exfriendID);
if (null == data)
break;
if (!data.AgentOnline)
{
m_log.DebugFormat("[FRIEND]: {0} is offline, so not sending TerminateFriend", exfriendID);
break; // if ex-friend isn't online, we don't need to send
}
m_log.DebugFormat("[FRIEND]: Sending remote terminate friend {0} to agent {1}@{2}",
agentID, exfriendID, data.Handle);
// try to send to foreign region, retry if it fails (friend TPed away, for example)
if (TriggerTerminateFriend(data.Handle, exfriendID, agentID)) break;
}
}
// clean up cache: FriendList is wrong now...
lock (m_friendLists)
{
m_friendLists.Invalidate(agentID.ToString());
m_friendLists.Invalidate(exfriendID.ToString());
}
}
#endregion
#region CallingCards
private void OnOfferCallingCard(IClientAPI client, UUID destID, UUID transactionID)
{
m_log.DebugFormat("[CALLING CARD]: got offer from {0} for {1}, transaction {2}",
client.AgentId, destID, transactionID);
// This might be slightly wrong. On a multi-region server, we might get the child-agent instead of the root-agent
// (or the root instead of the child)
ScenePresence destAgent = GetAnyPresenceFromAgentID(destID);
if (destAgent == null)
{
client.SendAlertMessage("The person you have offered a card to can't be found anymore.");
return;
}
lock (m_pendingCallingcardRequests)
{
m_pendingCallingcardRequests[transactionID] = client.AgentId;
}
// inform the destination agent about the offer
destAgent.ControllingClient.SendOfferCallingCard(client.AgentId, transactionID);
}
private void CreateCallingCard(IClientAPI client, UUID creator, UUID folder, string name)
{
InventoryItemBase item = new InventoryItemBase();
item.AssetID = UUID.Zero;
item.AssetType = (int)AssetType.CallingCard;
item.BasePermissions = (uint)PermissionMask.Copy;
item.CreationDate = Util.UnixTimeSinceEpoch();
item.CreatorId = creator.ToString();
item.CurrentPermissions = item.BasePermissions;
item.Description = "";
item.EveryOnePermissions = (uint)PermissionMask.None;
item.Flags = 0;
item.Folder = folder;
item.GroupID = UUID.Zero;
item.GroupOwned = false;
item.ID = UUID.Random();
item.InvType = (int)InventoryType.CallingCard;
item.Name = name;
item.NextPermissions = item.EveryOnePermissions;
item.Owner = client.AgentId;
item.SalePrice = 10;
item.SaleType = (byte)SaleType.Not;
((Scene)client.Scene).AddInventoryItem(client, item);
}
private void OnAcceptCallingCard(IClientAPI client, UUID transactionID, UUID folderID)
{
m_log.DebugFormat("[CALLING CARD]: User {0} ({1} {2}) accepted tid {3}, folder {4}",
client.AgentId,
client.FirstName, client.LastName,
transactionID, folderID);
UUID destID;
lock (m_pendingCallingcardRequests)
{
if (!m_pendingCallingcardRequests.TryGetValue(transactionID, out destID))
{
m_log.WarnFormat("[CALLING CARD]: Got a AcceptCallingCard from {0} without an offer before.",
client.Name);
return;
}
// else found pending calling card request with that transaction.
m_pendingCallingcardRequests.Remove(transactionID);
}
ScenePresence destAgent = GetAnyPresenceFromAgentID(destID);
// inform sender of the card that destination declined the offer
if (destAgent != null) destAgent.ControllingClient.SendAcceptCallingCard(transactionID);
// put a calling card into the inventory of receiver
CreateCallingCard(client, destID, folderID, destAgent.Name);
}
private void OnDeclineCallingCard(IClientAPI client, UUID transactionID)
{
m_log.DebugFormat("[CALLING CARD]: User {0} (ID:{1}) declined card, tid {2}",
client.Name, client.AgentId, transactionID);
UUID destID;
lock (m_pendingCallingcardRequests)
{
if (!m_pendingCallingcardRequests.TryGetValue(transactionID, out destID))
{
m_log.WarnFormat("[CALLING CARD]: Got a AcceptCallingCard from {0} without an offer before.",
client.Name);
return;
}
// else found pending calling card request with that transaction.
m_pendingCallingcardRequests.Remove(transactionID);
}
ScenePresence destAgent = GetAnyPresenceFromAgentID(destID);
// inform sender of the card that destination declined the offer
if (destAgent != null) destAgent.ControllingClient.SendDeclineCallingCard(transactionID);
}
/// <summary>
/// Send presence information about a client to other clients in both this region and others.
/// </summary>
/// <param name="client"></param>
/// <param name="friendList"></param>
/// <param name="iAmOnline"></param>
private void SendPresenceState(IClientAPI client, List<FriendListItem> friendList, bool iAmOnline)
{
//m_log.DebugFormat("[FRIEND]: {0} logged {1}; sending presence updates", client.Name, iAmOnline ? "in" : "out");
if (friendList == null || friendList.Count == 0)
{
//m_log.DebugFormat("[FRIEND]: {0} doesn't have friends.", client.Name);
return; // nothing we can do if she doesn't have friends...
}
// collect sets of friendIDs; to send to (online and offline), and to receive from
// TODO: If we ever switch to .NET >= 3, replace those Lists with HashSets.
// I can't believe that we have Dictionaries, but no Sets, considering Java introduced them years ago...
List<UUID> friendIDsToSendTo = new List<UUID>();
List<UUID> candidateFriendIDsToReceive = new List<UUID>();
foreach (FriendListItem item in friendList)
{
if (((item.FriendListOwnerPerms | item.FriendPerms) & (uint)FriendRights.CanSeeOnline) != 0)
{
// friend is allowed to see my presence => add
if ((item.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0)
friendIDsToSendTo.Add(item.Friend);
if ((item.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0)
candidateFriendIDsToReceive.Add(item.Friend);
}
}
// we now have a list of "interesting" friends (which we have to find out on-/offline state for),
// friends we want to send our online state to (if *they* are online, too), and
// friends we want to receive online state for (currently unknown whether online or not)
// as this processing might take some time and friends might TP away, we try up to three times to
// reach them. Most of the time, we *will* reach them, and this loop won't loop
int retry = 0;
do
{
// build a list of friends to look up region-information and on-/offline-state for
List<UUID> friendIDsToLookup = new List<UUID>(friendIDsToSendTo);
foreach (UUID uuid in candidateFriendIDsToReceive)
{
if (!friendIDsToLookup.Contains(uuid)) friendIDsToLookup.Add(uuid);
}
m_log.DebugFormat(
"[FRIEND]: {0} to lookup, {1} to send to, {2} candidates to receive from for agent {3}",
friendIDsToLookup.Count, friendIDsToSendTo.Count, candidateFriendIDsToReceive.Count, client.Name);
// we have to fetch FriendRegionInfos, as the (cached) FriendListItems don't
// necessarily contain the correct online state...
Dictionary<UUID, FriendRegionInfo> friendRegions = m_initialScene.GetFriendRegionInfos(friendIDsToLookup);
m_log.DebugFormat(
"[FRIEND]: Found {0} regionInfos for {1} friends of {2}",
friendRegions.Count, friendIDsToLookup.Count, client.Name);
// argument for SendAgentOn/Offline; we shouldn't generate that repeatedly within loops.
UUID[] agentArr = new UUID[] { client.AgentId };
// first, send to friend presence state to me, if I'm online...
if (iAmOnline)
{
List<UUID> friendIDsToReceive = new List<UUID>();
for (int i = candidateFriendIDsToReceive.Count - 1; i >= 0; --i)
{
UUID uuid = candidateFriendIDsToReceive[i];
FriendRegionInfo info;
if (friendRegions.TryGetValue(uuid, out info) && info != null && info.isOnline)
{
friendIDsToReceive.Add(uuid);
}
}
m_log.DebugFormat(
"[FRIEND]: Sending {0} online friends to {1}", friendIDsToReceive.Count, client.Name);
if (friendIDsToReceive.Count > 0)
client.SendAgentOnline(friendIDsToReceive.ToArray());
// clear them for a possible second iteration; we don't have to repeat this
candidateFriendIDsToReceive.Clear();
}
// now, send my presence state to my friends
for (int i = friendIDsToSendTo.Count - 1; i >= 0; --i)
{
UUID uuid = friendIDsToSendTo[i];
FriendRegionInfo info;
if (friendRegions.TryGetValue(uuid, out info) && info != null && info.isOnline)
{
// any client is good enough, root or child...
ScenePresence agent = GetAnyPresenceFromAgentID(uuid);
if (agent != null)
{
//m_log.DebugFormat("[FRIEND]: Found local agent {0}", agent.Name);
// friend is online and on this server...
if (iAmOnline) agent.ControllingClient.SendAgentOnline(agentArr);
else agent.ControllingClient.SendAgentOffline(agentArr);
// done, remove it
friendIDsToSendTo.RemoveAt(i);
}
}
else
{
//m_log.DebugFormat("[FRIEND]: Friend {0} ({1}) is offline; not sending.", uuid, i);
// friend is offline => no need to try sending
friendIDsToSendTo.RemoveAt(i);
}
}
m_log.DebugFormat("[FRIEND]: Have {0} friends to contact via inter-region comms.", friendIDsToSendTo.Count);
// we now have all the friends left that are online (we think), but not on this region-server
if (friendIDsToSendTo.Count > 0)
{
// sort them into regions
Dictionary<ulong, List<UUID>> friendsInRegion = new Dictionary<ulong,List<UUID>>();
foreach (UUID uuid in friendIDsToSendTo)
{
ulong handle = friendRegions[uuid].regionHandle; // this can't fail as we filtered above already
List<UUID> friends;
if (!friendsInRegion.TryGetValue(handle, out friends))
{
friends = new List<UUID>();
friendsInRegion[handle] = friends;
}
friends.Add(uuid);
}
m_log.DebugFormat("[FRIEND]: Found {0} regions to send to.", friendRegions.Count);
// clear uuids list and collect missed friends in it for the next retry
friendIDsToSendTo.Clear();
// send bulk updates to the region
foreach (KeyValuePair<ulong, List<UUID>> pair in friendsInRegion)
{
//m_log.DebugFormat("[FRIEND]: Inform {0} friends in region {1} that user {2} is {3}line",
// pair.Value.Count, pair.Key, client.Name, iAmOnline ? "on" : "off");
friendIDsToSendTo.AddRange(InformFriendsInOtherRegion(client.AgentId, pair.Key, pair.Value, iAmOnline));
}
}
// now we have in friendIDsToSendTo only the agents left that TPed away while we tried to contact them.
// In most cases, it will be empty, and it won't loop here. But sometimes, we have to work harder and try again...
}
while (++retry < 3 && friendIDsToSendTo.Count > 0);
}
private void OnEconomyDataRequest(UUID agentID)
{
// KLUDGE: This is the only way I found to get a message (only) after login was completed and the
// client is connected enough to receive UDP packets).
// This packet seems to be sent only once, just after connection was established to the first
// region after login.
// We use it here to trigger a presence update; the old update-on-login was never be heard by
// the freshly logged in viewer, as it wasn't connected to the region at that time.
// TODO: Feel free to replace this by a better solution if you find one.
// get the agent. This should work every time, as we just got a packet from it
//ScenePresence agent = GetRootPresenceFromAgentID(agentID);
// KLUDGE 2: As this is sent quite early, the avatar isn't here as root agent yet. So, we have to cheat a bit
ScenePresence agent = GetAnyPresenceFromAgentID(agentID);
// just to be paranoid...
if (agent == null)
{
m_log.ErrorFormat("[FRIEND]: Got a packet from agent {0} who can't be found anymore!?", agentID);
return;
}
List<FriendListItem> fl;
lock (m_friendLists)
{
fl = (List<FriendListItem>)m_friendLists.Get(agent.ControllingClient.AgentId.ToString(),
m_initialScene.GetFriendList);
}
// tell everyone that we are online
SendPresenceState(agent.ControllingClient, fl, true);
}
private void OnLogout(IClientAPI remoteClient)
{
List<FriendListItem> fl;
lock (m_friendLists)
{
fl = (List<FriendListItem>)m_friendLists.Get(remoteClient.AgentId.ToString(),
m_initialScene.GetFriendList);
}
// tell everyone that we are offline
SendPresenceState(remoteClient, fl, false);
}
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// These helper methods are known to a NUTC intrinsic used to implement EqualityComparer<T> class.
// The compiler will instead replace the IL code within get_Default to call one of GetUnknownEquatableComparer, GetKnownGenericEquatableComparer,
// GetKnownNullableEquatableComparer, GetKnownEnumEquatableComparer or GetKnownObjectEquatableComparer based on what sort of
// type is being compared.
//
// In addition, there are a set of generic functions which are used by Array.IndexOf<T> to perform equality checking
// in a similar manner. Array.IndexOf<T> uses these functions instead of the EqualityComparer<T> infrastructure because constructing
// a full EqualityComparer<T> has substantial size costs due to Array.IndexOf<T> use within all arrays.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using Internal.IntrinsicSupport;
using Internal.Runtime.Augments;
namespace Internal.IntrinsicSupport
{
internal static class EqualityComparerHelpers
{
private static bool ImplementsIEquatable(RuntimeTypeHandle t)
{
EETypePtr objectType = t.ToEETypePtr();
EETypePtr iequatableType = typeof(IEquatable<>).TypeHandle.ToEETypePtr();
int interfaceCount = objectType.Interfaces.Count;
for (int i = 0; i < interfaceCount; i++)
{
EETypePtr interfaceType = objectType.Interfaces[i];
if (!interfaceType.IsGeneric)
continue;
if (interfaceType.GenericDefinition == iequatableType)
{
var instantiation = interfaceType.Instantiation;
if (instantiation.Length != 1)
continue;
if (instantiation[0] == objectType)
{
return true;
}
}
}
return false;
}
private static bool IsEnum(RuntimeTypeHandle t)
{
return t.ToEETypePtr().IsEnum;
}
// this function utilizes the template type loader to generate new
// EqualityComparer types on the fly
private static object GetComparer(RuntimeTypeHandle t)
{
RuntimeTypeHandle comparerType;
RuntimeTypeHandle openComparerType = default(RuntimeTypeHandle);
RuntimeTypeHandle comparerTypeArgument = default(RuntimeTypeHandle);
if (RuntimeAugments.IsNullable(t))
{
RuntimeTypeHandle nullableType = RuntimeAugments.GetNullableType(t);
if (ImplementsIEquatable(nullableType))
{
openComparerType = typeof(NullableEqualityComparer<>).TypeHandle;
comparerTypeArgument = nullableType;
}
}
if (IsEnum(t))
{
openComparerType = typeof(EnumEqualityComparer<>).TypeHandle;
comparerTypeArgument = t;
}
if (openComparerType.Equals(default(RuntimeTypeHandle)))
{
if (ImplementsIEquatable(t))
{
openComparerType = typeof(GenericEqualityComparer<>).TypeHandle;
comparerTypeArgument = t;
}
else
{
openComparerType = typeof(ObjectEqualityComparer<>).TypeHandle;
comparerTypeArgument = t;
}
}
bool success = RuntimeAugments.TypeLoaderCallbacks.TryGetConstructedGenericTypeForComponents(openComparerType, new RuntimeTypeHandle[] { comparerTypeArgument }, out comparerType);
if (!success)
{
Environment.FailFast("Unable to create comparer");
}
return RuntimeAugments.NewObject(comparerType);
}
//----------------------------------------------------------------------
// target functions of intrinsic replacement in EqualityComparer.get_Default
//----------------------------------------------------------------------
internal static EqualityComparer<T> GetUnknownEquatableComparer<T>()
{
return (EqualityComparer<T>)GetComparer(typeof(T).TypeHandle);
}
private static EqualityComparer<T> GetKnownGenericEquatableComparer<T>() where T : IEquatable<T>
{
return new GenericEqualityComparer<T>();
}
private static EqualityComparer<Nullable<U>> GetKnownNullableEquatableComparer<U>() where U : struct, IEquatable<U>
{
return new NullableEqualityComparer<U>();
}
private static EqualityComparer<T> GetKnownObjectEquatableComparer<T>()
{
return new ObjectEqualityComparer<T>();
}
private static EqualityComparer<T> GetKnownEnumEquatableComparer<T>() where T : struct
{
return new EnumEqualityComparer<T>();
}
//-----------------------------------------------------------------------
// Redirection target functions for redirecting behavior of Array.IndexOf
//-----------------------------------------------------------------------
// This one is an intrinsic that is used to make enum comparisions more efficient.
[Intrinsic]
internal static bool EnumOnlyEquals<T>(T x, T y) where T : struct
{
return x.Equals(y);
}
private static bool StructOnlyEqualsIEquatable<T>(T x, T y) where T : IEquatable<T>
{
return x.Equals(y);
}
private static bool StructOnlyEqualsNullable<T>(Nullable<T> x, Nullable<T> y) where T : struct, IEquatable<T>
{
if (x.HasValue)
{
if (y.HasValue)
return x.Value.Equals(y.Value);
return false;
}
if (y.HasValue)
return false;
return true;
}
// These functions look odd, as they are part of a complex series of compiler intrinsics
// designed to produce very high quality code for equality comparison cases without utilizing
// reflection like other platforms. The major complication is that the specification of
// IndexOf is that it is supposed to use IEquatable<T> if possible, but that requirement
// cannot be expressed in IL directly due to the lack of constraints.
// Instead, specialization at call time is used within the compiler.
//
// General Approach
// - Perform fancy redirection for EqualityComparerHelpers.GetComparerForReferenceTypesOnly<T>(). If T is a reference
// type or UniversalCanon, have this redirect to EqualityComparer<T>.get_Default, Otherwise, use
// the function as is. (will return null in that case)
// - Change the contents of the IndexOf functions to have a pair of loops. One for if
// GetComparerForReferenceTypesOnly returns null, and one for when it does not.
// - If it does not return null, call the EqualityComparer<T> code.
// - If it does return null, use a special function StructOnlyEquals<T>().
// - Calls to that function result in calls to a pair of helper function in
// EqualityComparerHelpers (StructOnlyEqualsIEquatable, or StructOnlyEqualsNullable)
// depending on whether or not they are the right function to call.
// - The end result is that in optimized builds, we have the same single function compiled size
// characteristics that the old EqualsOnlyComparer<T>.Equals function had, but we maintain
// correctness as well.
[Intrinsic]
internal static EqualityComparer<T> GetComparerForReferenceTypesOnly<T>()
{
#if PROJECTN
// When T is a reference type or a universal canon type, then this will redirect to EqualityComparer<T>.Default.
return null;
#else
return EqualityComparer<T>.Default;
#endif
}
[Intrinsic]
internal static bool StructOnlyEquals<T>(T left, T right)
{
return left.Equals(right);
}
}
}
namespace System.Collections.Generic
{
//-----------------------------------------------------------------------
// Implementations of EqualityComparer<T> for the various possible scenarios
// Names must match other runtimes for serialization
//-----------------------------------------------------------------------
// The methods in this class look identical to the inherited methods, but the calls
// to Equal bind to IEquatable<T>.Equals(T) instead of Object.Equals(Object)
[Serializable]
public sealed class GenericEqualityComparer<T> : EqualityComparer<T> where T : IEquatable<T>
{
public sealed override bool Equals(T x, T y)
{
if (x != null)
{
if (y != null)
return x.Equals(y);
return false;
}
if (y != null)
return false;
return true;
}
public sealed override int GetHashCode(T obj)
{
if (obj == null)
return 0;
return obj.GetHashCode();
}
// Equals method for the comparer itself.
public sealed override bool Equals(Object obj) => obj is GenericEqualityComparer<T>;
public sealed override int GetHashCode() => typeof(GenericEqualityComparer<T>).GetHashCode();
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class NullableEqualityComparer<T> : EqualityComparer<Nullable<T>> where T : struct, IEquatable<T>
{
public sealed override bool Equals(Nullable<T> x, Nullable<T> y)
{
if (x.HasValue)
{
if (y.HasValue)
return x.Value.Equals(y.Value);
return false;
}
if (y.HasValue)
return false;
return true;
}
public sealed override int GetHashCode(Nullable<T> obj)
{
return obj.GetHashCode();
}
// Equals method for the comparer itself.
public sealed override bool Equals(Object obj) => obj is NullableEqualityComparer<T>;
public sealed override int GetHashCode() => typeof(NullableEqualityComparer<T>).GetHashCode();
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class EnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct
{
public sealed override bool Equals(T x, T y)
{
return EqualityComparerHelpers.EnumOnlyEquals(x, y);
}
public sealed override int GetHashCode(T obj)
{
return obj.GetHashCode();
}
internal EnumEqualityComparer() { }
private EnumEqualityComparer(SerializationInfo info, StreamingContext context) { }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// For back-compat we need to serialize the comparers for enums with underlying types other than int as ObjectEqualityComparer
if (Type.GetTypeCode(Enum.GetUnderlyingType(typeof(T))) != TypeCode.Int32)
{
info.SetType(typeof(ObjectEqualityComparer<T>));
}
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) => obj is EnumEqualityComparer<T>;
public override int GetHashCode() => typeof(EnumEqualityComparer<T>).GetHashCode();
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class ObjectEqualityComparer<T> : EqualityComparer<T>
{
public sealed override bool Equals(T x, T y)
{
if (x != null)
{
if (y != null)
return x.Equals(y);
return false;
}
if (y != null)
return false;
return true;
}
public sealed override int GetHashCode(T obj)
{
if (obj == null)
return 0;
return obj.GetHashCode();
}
// Equals method for the comparer itself.
public sealed override bool Equals(Object obj)
{
if(obj == null)
{
return false;
}
// This needs to use GetType instead of typeof to avoid infinite recursion in the type loader
return obj.GetType().Equals(GetType());
}
// This needs to use GetType instead of typeof to avoid infinite recursion in the type loader
public sealed override int GetHashCode() => GetType().GetHashCode();
}
}
| |
// 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.Text;
using System.Diagnostics;
using System.Buffers;
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.
//
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;
private bool _leaveOpen;
// 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 = EncodingCache.UTF8NoBOM;
_encoder = _encoding.GetEncoder();
}
public BinaryWriter(Stream output) : this(output, EncodingCache.UTF8NoBOM, 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(nameof(output));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (!output.CanWrite)
throw new ArgumentException(SR.Argument_StreamNotWritable);
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 associated 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.
//
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(nameof(buffer));
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.
//
public unsafe virtual void Write(char ch)
{
if (Char.IsSurrogate(ch))
throw new ArgumentException(SR.Arg_SurrogatesNotAllowedAsSingleChar);
Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
int numBytes = 0;
fixed (byte* pBytes = &_buffer[0])
{
numBytes = _encoder.GetBytes(&ch, 1, pBytes, _buffer.Length, flush: 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(nameof(chars));
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.
//
public unsafe virtual void Write(double value)
{
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);
}
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.
//
public unsafe virtual void Write(float value)
{
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);
}
// 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.
//
public unsafe virtual void Write(String value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
int len = _encoding.GetByteCount(value);
Write7BitEncodedInt(len);
if (_largeByteBuffer == null)
{
_largeByteBuffer = new byte[LargeByteBufferSize];
_maxChars = _largeByteBuffer.Length / _encoding.GetMaxByteCount(1);
}
if (len <= _largeByteBuffer.Length)
{
//Debug.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;
checked
{
if (charStart < 0 || charCount < 0 || charStart > value.Length - charCount)
{
throw new ArgumentOutOfRangeException(nameof(charCount));
}
fixed (char* pChars = value)
{
fixed (byte* pBytes = &_largeByteBuffer[0])
{
byteLen = _encoder.GetBytes(pChars + charStart, charCount, pBytes, _largeByteBuffer.Length, charCount == numLeft);
}
}
}
#if DEBUG
totalBytes += byteLen;
Debug.Assert(totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
#endif
OutStream.Write(_largeByteBuffer, 0, byteLen);
charStart += charCount;
numLeft -= charCount;
}
#if DEBUG
Debug.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!");
#endif
}
}
public virtual void Write(ReadOnlySpan<byte> value)
{
if (GetType() == typeof(BinaryWriter))
{
OutStream.Write(value);
}
else
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(value.Length);
try
{
value.CopyTo(buffer);
Write(buffer, 0, value.Length);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
}
public virtual void Write(ReadOnlySpan<char> value)
{
byte[] bytes = ArrayPool<byte>.Shared.Rent(_encoding.GetMaxByteCount(value.Length));
try
{
int bytesWritten = _encoding.GetBytes(value, bytes);
Write(bytes, 0, bytesWritten);
}
finally
{
ArrayPool<byte>.Shared.Return(bytes);
}
}
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);
}
}
}
| |
// 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: synchronization primitive that can also be used for interprocess synchronization
**
**
=============================================================================*/
namespace System.Threading
{
using System;
using System.Threading;
using System.Runtime.CompilerServices;
using System.IO;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Security;
using System.Diagnostics;
using System.Diagnostics.Contracts;
public sealed class Mutex : WaitHandle
{
private static bool dummyBool;
internal class MutexSecurity
{
}
public Mutex(bool initiallyOwned, String name, out bool createdNew)
: this(initiallyOwned, name, out createdNew, (MutexSecurity)null)
{
}
internal unsafe Mutex(bool initiallyOwned, String name, out bool createdNew, MutexSecurity mutexSecurity)
{
if (name == string.Empty)
{
// Empty name is treated as an unnamed mutex. Set to null, and we will check for null from now on.
name = null;
}
#if PLATFORM_WINDOWS
if (name != null && System.IO.Path.MaxPath < name.Length)
{
throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name));
}
#endif // PLATFORM_WINDOWS
Contract.EndContractBlock();
Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
}
internal void CreateMutexWithGuaranteedCleanup(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs)
{
RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(MutexCleanupCode);
MutexCleanupInfo cleanupInfo = new MutexCleanupInfo(null, false);
MutexTryCodeHelper tryCodeHelper = new MutexTryCodeHelper(initiallyOwned, cleanupInfo, name, secAttrs, this);
RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(tryCodeHelper.MutexTryCode);
RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(
tryCode,
cleanupCode,
cleanupInfo);
createdNew = tryCodeHelper.m_newMutex;
}
internal class MutexTryCodeHelper
{
private bool m_initiallyOwned;
private MutexCleanupInfo m_cleanupInfo;
internal bool m_newMutex;
private String m_name;
private Win32Native.SECURITY_ATTRIBUTES m_secAttrs;
private Mutex m_mutex;
internal MutexTryCodeHelper(bool initiallyOwned, MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex)
{
Debug.Assert(name == null || name.Length != 0);
m_initiallyOwned = initiallyOwned;
m_cleanupInfo = cleanupInfo;
m_name = name;
m_secAttrs = secAttrs;
m_mutex = mutex;
}
internal void MutexTryCode(object userData)
{
SafeWaitHandle mutexHandle = null;
// try block
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
if (m_initiallyOwned)
{
m_cleanupInfo.inCriticalRegion = true;
}
}
int errorCode = 0;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
errorCode = CreateMutexHandle(m_initiallyOwned, m_name, m_secAttrs, out mutexHandle);
}
if (mutexHandle.IsInvalid)
{
mutexHandle.SetHandleAsInvalid();
if (m_name != null)
{
switch (errorCode)
{
#if PLATFORM_UNIX
case Win32Native.ERROR_FILENAME_EXCED_RANGE:
// On Unix, length validation is done by CoreCLR's PAL after converting to utf-8
throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Interop.Sys.MaxName), "name");
#endif
case Win32Native.ERROR_INVALID_HANDLE:
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, m_name));
}
}
__Error.WinIOError(errorCode, m_name);
}
m_newMutex = errorCode != Win32Native.ERROR_ALREADY_EXISTS;
m_mutex.SetHandleInternal(mutexHandle);
m_mutex.hasThreadAffinity = true;
}
}
private void MutexCleanupCode(Object userData, bool exceptionThrown)
{
MutexCleanupInfo cleanupInfo = (MutexCleanupInfo)userData;
// If hasThreadAffinity isn't true, we've thrown an exception in the above try, and we must free the mutex
// on this OS thread before ending our thread affninity.
if (!hasThreadAffinity)
{
if (cleanupInfo.mutexHandle != null && !cleanupInfo.mutexHandle.IsInvalid)
{
if (cleanupInfo.inCriticalRegion)
{
Win32Native.ReleaseMutex(cleanupInfo.mutexHandle);
}
cleanupInfo.mutexHandle.Dispose();
}
}
}
internal class MutexCleanupInfo
{
internal SafeWaitHandle mutexHandle;
internal bool inCriticalRegion;
internal MutexCleanupInfo(SafeWaitHandle mutexHandle, bool inCriticalRegion)
{
this.mutexHandle = mutexHandle;
this.inCriticalRegion = inCriticalRegion;
}
}
public Mutex(bool initiallyOwned, String name) : this(initiallyOwned, name, out dummyBool)
{
}
public Mutex(bool initiallyOwned) : this(initiallyOwned, null, out dummyBool)
{
}
public Mutex() : this(false, null, out dummyBool)
{
}
private Mutex(SafeWaitHandle handle)
{
SetHandleInternal(handle);
hasThreadAffinity = true;
}
public static Mutex OpenExisting(string name)
{
return OpenExisting(name, (MutexRights)0);
}
internal enum MutexRights
{
}
internal static Mutex OpenExisting(string name, MutexRights rights)
{
Mutex result;
switch (OpenExistingWorker(name, rights, out result))
{
case OpenExistingResult.NameNotFound:
throw new WaitHandleCannotBeOpenedException();
case OpenExistingResult.NameInvalid:
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
case OpenExistingResult.PathNotFound:
__Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, name);
return result; //never executes
default:
return result;
}
}
public static bool TryOpenExisting(string name, out Mutex result)
{
return OpenExistingWorker(name, (MutexRights)0, out result) == OpenExistingResult.Success;
}
private static OpenExistingResult OpenExistingWorker(string name, MutexRights rights, out Mutex result)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name), SR.ArgumentNull_WithParamName);
}
if (name.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
}
#if !PLATFORM_UNIX
if (System.IO.Path.MaxPath < name.Length)
{
throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name));
}
#endif
Contract.EndContractBlock();
result = null;
// To allow users to view & edit the ACL's, call OpenMutex
// with parameters to allow us to view & edit the ACL. This will
// fail if we don't have permission to view or edit the ACL's.
// If that happens, ask for less permissions.
SafeWaitHandle myHandle = Win32Native.OpenMutex(Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name);
int errorCode = 0;
if (myHandle.IsInvalid)
{
errorCode = Marshal.GetLastWin32Error();
#if PLATFORM_UNIX
if (name != null && errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE)
{
// On Unix, length validation is done by CoreCLR's PAL after converting to utf-8
throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Interop.Sys.MaxName), nameof(name));
}
#endif
if (Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode)
return OpenExistingResult.NameNotFound;
if (Win32Native.ERROR_PATH_NOT_FOUND == errorCode)
return OpenExistingResult.PathNotFound;
if (null != name && Win32Native.ERROR_INVALID_HANDLE == errorCode)
return OpenExistingResult.NameInvalid;
// this is for passed through Win32Native Errors
__Error.WinIOError(errorCode, name);
}
result = new Mutex(myHandle);
return OpenExistingResult.Success;
}
// Note: To call ReleaseMutex, you must have an ACL granting you
// MUTEX_MODIFY_STATE rights (0x0001). The other interesting value
// in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001).
public void ReleaseMutex()
{
if (Win32Native.ReleaseMutex(safeWaitHandle))
{
}
else
{
throw new ApplicationException(SR.Arg_SynchronizationLockException);
}
}
private static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle)
{
int errorCode;
while (true)
{
mutexHandle = Win32Native.CreateMutex(securityAttribute, initiallyOwned, name);
errorCode = Marshal.GetLastWin32Error();
if (!mutexHandle.IsInvalid) break;
if (errorCode != Win32Native.ERROR_ACCESS_DENIED) break;
// If a mutex with the name already exists, OS will try to open it with FullAccess.
// It might fail if we don't have enough access. In that case, we try to open the mutex will modify and synchronize access.
RuntimeHelpers.PrepareConstrainedRegions();
mutexHandle = Win32Native.OpenMutex(
Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE,
false,
name);
errorCode = !mutexHandle.IsInvalid ? Win32Native.ERROR_ALREADY_EXISTS : Marshal.GetLastWin32Error();
// There could be a race condition here, the other owner of the mutex can free the mutex,
// We need to retry creation in that case.
if (errorCode != Win32Native.ERROR_FILE_NOT_FOUND)
{
if (errorCode == Win32Native.ERROR_SUCCESS) errorCode = Win32Native.ERROR_ALREADY_EXISTS;
break;
}
}
return errorCode;
}
}
}
| |
//! \file ImageISG.cs
//! \date Tue Mar 17 10:01:44 2015
//! \brief ISM engine image format.
//
// Copyright (C) 2015 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Utility;
namespace GameRes.Formats.ISM
{
internal class IsgMetaData : ImageMetaData
{
public byte Type;
public int Colors;
public uint Packed;
public uint Unpacked;
}
[Export(typeof(ImageFormat))]
public class IsgFormat : ImageFormat
{
public override string Tag { get { return "ISG"; } }
public override string Description { get { return "ISM engine image format"; } }
public override uint Signature { get { return 0x204d5349u; } } // 'ISM '
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("IsgFormat.Write not implemented");
}
public override ImageMetaData ReadMetaData (Stream stream)
{
var header = new byte[0x24];
if (header.Length != stream.Read (header, 0, header.Length))
return null;
if (!Binary.AsciiEqual (header, "ISM IMAGEFILE\x00"))
return null;
int colors = header[0x23];
if (0 == colors)
colors = 256;
return new IsgMetaData
{
Width = LittleEndian.ToUInt16 (header, 0x1d),
Height = LittleEndian.ToUInt16 (header, 0x1f),
BPP = 8,
Type = header[0x10],
Colors = colors,
Packed = LittleEndian.ToUInt32 (header, 0x11),
Unpacked = LittleEndian.ToUInt32 (header, 0x15),
};
}
public override ImageData Read (Stream stream, ImageMetaData info)
{
var meta = info as IsgMetaData;
if (null == meta)
throw new ArgumentException ("IsgFormat.Read should be supplied with IsgMetaData", "info");
if (0x21 != meta.Type && 0x10 != meta.Type)
throw new InvalidFormatException ("Unsupported ISM image type");
stream.Position = 0x30;
using (var input = new Reader (stream, meta))
{
if (0x21 == meta.Type)
input.Unpack21();
else
input.Unpack10();
var palette = new BitmapPalette (input.Palette);
return ImageData.CreateFlipped (info, PixelFormats.Indexed8, palette, input.Data, (int)info.Width);
}
}
internal class Reader : IDisposable
{
BinaryReader m_input;
byte[] m_data;
Color[] m_palette;
int m_input_size;
public Color[] Palette { get { return m_palette; } }
public byte[] Data { get { return m_data; } }
public Reader (Stream file, IsgMetaData info)
{
int palette_size = (int)info.Colors*4;
var palette_data = new byte[Math.Max (0x400, palette_size)];
if (palette_size != file.Read (palette_data, 0, palette_size))
throw new InvalidFormatException();
m_palette = new Color[0x100];
for (int i = 0; i < m_palette.Length; ++i)
{
m_palette[i] = Color.FromRgb (palette_data[i*4+2], palette_data[i*4+1], palette_data[i*4]);
}
m_input = new BinaryReader (file, Encoding.ASCII, true);
m_input_size = (int)info.Packed;
m_data = new byte[info.Width * info.Height];
}
public void Unpack21 ()
{
int dst = 0;
var frame = new byte[2048];
int frame_pos = 2039;
int remaining = m_input_size;
byte ctl = m_input.ReadByte();
--remaining;
int bit = 0x80;
while (remaining > 0)
{
if (0 != (ctl & bit))
{
byte hi = m_input.ReadByte();
byte lo = m_input.ReadByte();
remaining -= 2;
int offset = (hi & 7) << 8 | lo;
for (int count = (hi >> 3) + 3; count > 0; --count)
{
byte p = frame[offset];
frame[frame_pos] = p;
m_data[dst++] = p;
offset = (offset + 1) & 0x7ff;
frame_pos = (frame_pos + 1) & 0x7ff;
}
}
else
{
byte p = m_input.ReadByte();
--remaining;
m_data[dst++] = p;
frame[frame_pos] = p;
frame_pos = (frame_pos + 1) & 0x7ff;
}
if (0 == (bit >>= 1))
{
ctl = m_input.ReadByte();
--remaining;
bit = 0x80;
}
}
}
public void Unpack10 ()
{
int dst = 0;
int remaining = m_input_size;
byte ctl = m_input.ReadByte();
--remaining;
int bit = 1;
while (remaining > 0)
{
byte p = m_input.ReadByte();
--remaining;
if (0 != (ctl & bit))
{
for (int count = 2 + m_input.ReadByte(); count > 0; --count)
m_data[dst++] = p;
--remaining;
}
else
{
m_data[dst++] = p;
}
if (0x100 == (bit <<= 1))
{
ctl = m_input.ReadByte();
--remaining;
bit = 1;
}
}
}
#region IDisposable Members
public void Dispose ()
{
if (null != m_input)
{
m_input.Dispose();
m_input = null;
}
GC.SuppressFinalize (this);
}
#endregion
}
}
}
| |
using UnityEngine;
using System.Collections;
public class RoarLoginModule : RoarModule
{
public delegate void RoarLoginModuleHandler();
public static event RoarLoginModuleHandler OnFullyLoggedIn; // logged in & stats fetched
public float statusWidth = 320;
public float statusHeight = 48;
public string statusNormalStyle = "StatusNormal";
public string statusErrorStyle = "StatusError";
public string textfieldStyle = "LoginLabel";
public float textfieldWidth = 240;
public float textfieldHeight = 32;
public float textFieldSpacing = 4;
public float buttonWidth = 240;
public float buttonHeight = 32;
public float spacingAboveButtons = 16;
public float spacingBetweenButtons = 4;
public float verticalOffset = -40;
public bool fetchPropertiesOnLogin = true;
public bool saveUsername = true;
public bool savePassword = false;
private static string KEY_USERNAME = "roar-username";
private static string KEY_PASSWORD = "roar-password";
private string status = "Supply a username and password to log in or to register a new account.";
private bool isError;
private string username = string.Empty;
private string password = string.Empty;
#if UNITY_EDITOR
private string latchedNameOfFocusedControl = string.Empty;
#endif
private Rect statusLabelRect;
private Rect usernameLabelRect;
private Rect usernameFieldRect;
private Rect passwordLabelRect;
private Rect passwordFieldRect;
private Rect submitButtonRect;
private Rect createButtonRect;
private bool networkActionInProgress;
protected override void Awake ()
{
base.Awake ();
if (saveUsername)
{
username = PlayerPrefs.GetString(KEY_USERNAME, string.Empty);
}
if (savePassword)
{
password = PlayerPrefs.GetString(KEY_PASSWORD, string.Empty);
}
}
protected override void Start()
{
base.Start();
float totalHeight = textfieldHeight + textFieldSpacing // label
+ textfieldHeight + textFieldSpacing // username
+ textfieldHeight + textFieldSpacing // password
+ spacingAboveButtons
+ buttonHeight + spacingBetweenButtons // log in
+ buttonHeight // register
;
float yAdjust = (parent.bounds.height/2 - totalHeight/2) + verticalOffset;
// initial layout, top to bottom
statusLabelRect = new Rect((parent.bounds.width/2 - statusWidth/2), yAdjust, statusWidth, statusHeight);
usernameLabelRect = new Rect((parent.bounds.width/2 - textfieldWidth/2), yAdjust, textfieldWidth, textfieldHeight);
usernameLabelRect.y += statusHeight + textFieldSpacing;
usernameFieldRect = usernameLabelRect;
usernameFieldRect.y += textfieldHeight + textFieldSpacing;
passwordLabelRect = usernameFieldRect;
passwordLabelRect.y += textfieldHeight + textFieldSpacing;
passwordFieldRect = passwordLabelRect;
passwordFieldRect.y += textfieldHeight + textFieldSpacing;
submitButtonRect = new Rect((parent.bounds.width/2 - buttonWidth/2), passwordFieldRect.y, buttonWidth, buttonHeight);
submitButtonRect.y += textfieldHeight + spacingAboveButtons;
createButtonRect = submitButtonRect;
createButtonRect.y += buttonHeight + spacingBetweenButtons;
}
protected override void DrawGUI()
{
GUI.Label(statusLabelRect, status, (isError) ? skin.FindStyle(statusErrorStyle) : skin.FindStyle(statusNormalStyle));
GUI.Label(usernameLabelRect, "Username", textfieldStyle);
#if UNITY_EDITOR
GUI.SetNextControlName("u");
#endif
username = GUI.TextField(usernameFieldRect, username);
GUI.Label(passwordLabelRect, "Password", textfieldStyle);
#if UNITY_EDITOR
GUI.SetNextControlName("p");
#endif
password = GUI.PasswordField(passwordFieldRect, password, '*');
#if UNITY_EDITOR
string nameOfFocusedControl = GUI.GetNameOfFocusedControl();
if (nameOfFocusedControl != string.Empty)
latchedNameOfFocusedControl = nameOfFocusedControl;
Event evt = Event.current;
if (latchedNameOfFocusedControl == "u")
{
if (evt.isKey && evt.type == EventType.KeyDown)
{
if (evt.keyCode == KeyCode.Backspace)
{
if (username.Length > 0)
username = username.Substring(0, username.Length-1);
}
else if (evt.character != '\0')
{
username += evt.character;
}
evt.Use();
}
}
else if (latchedNameOfFocusedControl == "p")
{
if (evt.isKey && evt.type == EventType.KeyDown)
{
if (evt.keyCode == KeyCode.Backspace)
{
if (password.Length > 0)
password = password.Substring(0, password.Length-1);
}
else if (evt.character != '\0')
{
password += evt.character;
}
evt.Use();
}
}
#endif
GUI.enabled = username.Length > 0 && password.Length > 0 && !networkActionInProgress;
if (GUI.Button(submitButtonRect, "Log In"))
{
#if UNITY_EDITOR
latchedNameOfFocusedControl = string.Empty;
#endif
status = "Logging in...";
networkActionInProgress = true;
if (saveUsername)
{
PlayerPrefs.SetString(KEY_USERNAME, username);
}
if (savePassword)
{
PlayerPrefs.SetString(KEY_PASSWORD, password);
}
if (Debug.isDebugBuild)
Debug.Log(string.Format("[Debug] Logging in as [{0}] with password [{1}].", username, password));
roar.Login(username, password, OnRoarLoginComplete);
}
if (GUI.Button(createButtonRect, "Create Account"))
{
#if UNITY_EDITOR
latchedNameOfFocusedControl = string.Empty;
#endif
status = "Creating new player account...";
networkActionInProgress = true;
roar.Create(username, password, OnRoarAccountCreateComplete);
}
GUI.enabled = true;
}
void OnRoarLoginComplete(Roar.CallbackInfo info)
{
if (Debug.isDebugBuild)
Debug.Log(string.Format("OnRoarLoginComplete ({0}): {1}", info.code, info.msg));
switch (info.code)
{
case 200: // (success)
isError = false;
// fetch the player's properties after successful login
if (fetchPropertiesOnLogin)
{
DefaultRoar.Instance.Properties.Fetch(OnRoarPropertiesFetched);
}
else
{
uiController.CurrentModulePanel = RoarModulePanel.Off;
networkActionInProgress = false;
}
break;
case 3: // Invalid name or password
default:
isError = true;
status = info.msg;
networkActionInProgress = false;
break;
}
}
void OnRoarAccountCreateComplete(Roar.CallbackInfo info)
{
if (Debug.isDebugBuild)
Debug.Log(string.Format("OnRoarAccountCreateComplete ({0}): {1}", info.code, info.msg));
switch (info.code)
{
case 200: // (success)
status = "Account successfully created. You can now log in.";
break;
case 3:
default:
isError = true;
status = info.msg;
break;
}
networkActionInProgress = false;
}
void OnRoarPropertiesFetched(Roar.CallbackInfo info)
{
networkActionInProgress = false;
uiController.CurrentModulePanel = RoarModulePanel.Off;
if (OnFullyLoggedIn != null) OnFullyLoggedIn();
}
#region Utility
public override void ResetToDefaultConfiguration()
{
base.ResetToDefaultConfiguration();
backgroundType = RoarModule.BackgroundType.ExtentedImage;
backgroundColor = new Color32(199,199,199,192);
extendedBackgroundWidth = 360;
extendedBackgroundHeight = 324;
statusWidth = 320;
statusHeight = 48;
statusNormalStyle = "StatusNormal";
statusErrorStyle = "StatusError";
textfieldWidth = 240;
textfieldHeight = 32;
textFieldSpacing = 4;
buttonWidth = 240;
buttonHeight = 32;
spacingAboveButtons = 16;
spacingBetweenButtons = 4;
verticalOffset = -40;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using CocosDenshion;
using CocosSharp;
namespace CocosBalloon
{
public class GameLayer : CCLayerGradient
{
private int _currWave; // current 'wave' number that we are on
private float _currTimeToReachTop; // current duration for a balloon to reach the top of the screen,
private int _maxAtOnce; // current max number of balloons that can be launched
private int increaseMaxBalloonCountEvery = 5; // increase ballon count after n waves
private float durationMultiplier = .975f; // reduces _currTimeToReachTop each wave
private int _numLives; // current lives left
private int _currScore; // current score
private bool _gameOver; // is game over
private float _maxLivesAchieved; // highest number of lives the player has had
private CCLabel _scoreLabel;
private CCLabel _livesLabel;
private CCParticleSun _sun;
private CCParticleRain _rain;
List<CCTexture2D> PeopleTextures { get; set; }
public static new CCScene Scene(List<CCTexture2D> textures, CCWindow window)
{
var hl = new GameLayer(textures);
var scene = new CCScene(window);
scene.AddChild(hl);
return scene;
}
public GameLayer(List<CCTexture2D> textures)
{
this.PeopleTextures = textures;
_currWave = 1;
_numLives = 5;
_maxLivesAchieved = _numLives;
_currTimeToReachTop = 2f;
_maxAtOnce = 2;
_currScore = 0;
_gameOver = false;
}
protected async override void AddedToScene()
{
base.AddedToScene();
// add sun and rain particle effects
var topOfscreen = this.VisibleBoundsWorldspace.Center.Offset(0f, this.VisibleBoundsWorldspace.MaxY/2f);
_sun = new CCParticleSun(topOfscreen.Offset(0f, 20f));
_rain = new CCParticleRain(topOfscreen) { Scale = 0 };
this.AddChild(_sun);
this.AddChild(_rain);
SetBackgroundColour();
// init labels
_scoreLabel = new CCLabel(String.Format("Score: {0}", _currScore), "Consolas", 18f) { Color = CCColor3B.Black }
.PlaceAt(.1f, .05f, this)
.WithTextAlignment(CCTextAlignment.Left);
_livesLabel = new CCLabel(String.Format("Lives: {0}", _numLives), "Consolas", 18f) { Color = CCColor3B.Black }
.PlaceAt(1f - .1f, .05f, this)
.WithTextAlignment(CCTextAlignment.Right);
// track game over state
var enteredGameOver = false;
var completedGameOver = false;
// launch waves of balloons while not game over
var r = new Random();
while (!(enteredGameOver && completedGameOver))
{
if (_gameOver)
enteredGameOver = true;
// wait before launching next set of balloons
if(!_gameOver)
await Task.Delay(TimeSpan.FromSeconds(_currTimeToReachTop));
// determine number of balloons to fire
// if game over, fire heaps for effect
var numBalloons = !_gameOver ? r.Next(1, _maxAtOnce + 1) : 500;
// generate the balloons
var balloons = Enumerable.Range(0, numBalloons)
.Select(_ =>
{
// pick a texture at random for the new balloon
var randomIndex = r.Next(0, this.PeopleTextures.Count - 1);
var randomTexture = this.PeopleTextures[randomIndex];
// create sprite with touch handler
return new CCSprite(randomTexture)
.WithTouchHelper(h => h.TouchBegan
.Where(__=> !_gameOver)
.Subscribe(___ => BalloonPopped(h)));
}).ToList();
// launch the balloons from the bottom of the screen
var i = 0;
balloons.ForEach(async b =>
{
// wait a little so that each balloons are slightly staggered
await Task.Delay(TimeSpan.FromMilliseconds(50 * (++i)));
// place under the screen
var randomXPos = r.NextFloat().Between(.2f, .8f);
b.PlaceAt(randomXPos, 1.1f, this);
// create the launch action
var timeToReachTop = _currTimeToReachTop.VaryBy(.15f); // use current duration with some variability
var targetPoint = new CCPoint(b.PositionX, b.VisibleBoundsWorldspace.MaxY + 50); // move to a point above the top of the screen;
var moveToTop = new CCMoveTo(timeToReachTop, targetPoint);
// create the fail action; this runs after the balloon reaches the top of the screen
// if the move action completes then this ballon was not tapped in time
var failAction = new CCCallFuncN(MissedBalloon);
// combine the move and fail in sequence
var seq = new CCSequence(moveToTop, failAction);
// launch the balloon
b.RunAction(seq);
});
if (_gameOver)
completedGameOver = true;
// after each round, increase the difficulty by reducing the time
// for balloons to reach the top
_currTimeToReachTop = _currTimeToReachTop * durationMultiplier;
_currWave++;
// if there have been enough waves, increase max balloon count
if (_currWave % increaseMaxBalloonCountEvery == 0)
_maxAtOnce = (int)(_maxAtOnce + 1);
}
}
private async void BalloonPopped(TouchHelper<CCSprite> h)
{
var poppedBalloon = h.Node;
// points scored relative to the speed of the balloons
_currScore += (int)(2000f - _currTimeToReachTop * 1000f);
_scoreLabel.Text = String.Format("Score: {0:N0}", _currScore);
// get an extra life each success
_numLives += 1;
_livesLabel.Text = String.Format("Lives: {0}", _numLives);
// update the background colour
SetBackgroundColour();
// stop the balloon from moving
poppedBalloon.StopAllActions();
// make it spin away
poppedBalloon.RunAction(new CCRepeatForever(new CCRotateBy(.1f, 360f)));
await poppedBalloon.RunActionsWithTask(new CCScaleTo(.5f, 0f));
//cleanup
poppedBalloon.RemoveFromParent();
}
private void MissedBalloon(CCNode balloon)
{
// if already game over, don't worry
if (_gameOver)
return;
// decrement lives and update label
_numLives -= 1;
_livesLabel.Text = String.Format("Lives: {0}", _numLives);
// update the background colour
SetBackgroundColour();
// if we are out of lives, it's game over time
if (_numLives <= 0)
GameOver();
// remove the balloon from the game
balloon.RemoveFromParent();
}
private async void GameOver()
{
_gameOver = true;
UpdateSun();
UpdateRain();
// switch the colour of the score labels against dark background
this._scoreLabel.Color = CCColor3B.White;
this._livesLabel.Color = CCColor3B.White;
// red means bad
this.StartColor = new CCColor3B(70, 0, 0);
this.EndColor = new CCColor3B(10, 0, 0);
// add background panel and game over label
var container = new CCNode
{
ContentSize = new CCSize(.85f*this.VisibleBoundsWorldspace.MaxX, .25f*this.VisibleBoundsWorldspace.MaxY),
}.PlaceAt(.5f, .5f, this);
var gameOverBG = new CCDrawNode() { ContentSize = container.ContentSize }
.FillWith(CCColor3B.DarkGray)
.PlaceAt(.5f, .5f, container);
var gameOverLabel = new CCLabel("GAME OVER", "Arial", 48f)
.PlaceAt(.5f, .5f, container)
.WithTextCentered();
var tapToRestartLabel = new CCLabel("[tap to restart]", "Arial", 12f) { Opacity = 0 }
.PlaceAt(.5f, .7f, container)
.WithTextCentered();
// blink the restart label
tapToRestartLabel.RunAction(new CCRepeatForever(new CCBlink(1f, 1)));
gameOverBG.ZOrder = 998;
tapToRestartLabel.ZOrder = 999;
gameOverLabel.ZOrder = 1000;
container.ZOrder = 1001;
// wait a few seconds before adding the touch listener so that you don't tap out of the game before seeing game over
await Task.Delay(2000);
tapToRestartLabel.Opacity = (byte) 255;
// add touch listener, restart game on touch
var touchListener = new CCEventListenerTouchAllAtOnce()
{
OnTouchesBegan = (touches, args) =>
{
// make sure the while loop terminates
// reload this scene
this.Director.ReplaceScene(new CCTransitionRotoZoom(.5f, GameLayer.Scene(this.PeopleTextures, this.Window)));
this.RemoveAllChildren(true);
}
};
this.AddEventListener(touchListener);
}
private void SetBackgroundColour()
{
var startVal = 150;
var endVal = 50;
var greenStart = (byte)(_numLives / _maxLivesAchieved * startVal);
var greenEnd = (byte)(_numLives / _maxLivesAchieved * endVal);
this.StartColor = new CCColor3B(0, greenStart, 0);
this.EndColor = new CCColor3B(0, greenEnd, 0);
UpdateSun();
UpdateRain();
}
private void UpdateSun()
{
var sunScale = (_numLives/_maxLivesAchieved)*10f;
_sun.StopAllActions();
_sun.RunAction(new CCScaleTo(.2f, sunScale));
}
private void UpdateRain()
{
if (_numLives / _maxLivesAchieved < .4f)
{
_rain.Scale = 1;
_rain.EmissionRate *= 2f;
_rain.Speed *= 2f;
}
else
_rain.Scale = 0;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Client.Methods.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.Client.Methods
{
/// <summary>
/// <para>HTTP PUT method. </para><para>The HTTP PUT method is defined in section 9.6 of : <blockquote><para>The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpPut
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpPut", AccessFlags = 33)]
public partial class HttpPut : global::Org.Apache.Http.Client.Methods.HttpEntityEnclosingRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "PUT";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpPut() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpPut(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpPut(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>Basic implementation of an HTTP request that can be modified.</para><para><para></para><para></para><title>Revision:</title><para>674186 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpEntityEnclosingRequestBase
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpEntityEnclosingRequestBase", AccessFlags = 1057)]
public abstract partial class HttpEntityEnclosingRequestBase : global::Org.Apache.Http.Client.Methods.HttpRequestBase, global::Org.Apache.Http.IHttpEntityEnclosingRequest
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpEntityEnclosingRequestBase() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getEntity
/// </java-name>
[Dot42.DexImport("getEntity", "()Lorg/apache/http/HttpEntity;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.IHttpEntity GetEntity() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHttpEntity);
}
/// <java-name>
/// setEntity
/// </java-name>
[Dot42.DexImport("setEntity", "(Lorg/apache/http/HttpEntity;)V", AccessFlags = 1)]
public virtual void SetEntity(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tells if this request should use the expect-continue handshake. The expect continue handshake gives the server a chance to decide whether to accept the entity enclosing request before the possibly lengthy entity is sent across the wire. </para>
/// </summary>
/// <returns>
/// <para>true if the expect continue handshake should be used, false if not. </para>
/// </returns>
/// <java-name>
/// expectContinue
/// </java-name>
[Dot42.DexImport("expectContinue", "()Z", AccessFlags = 1)]
public virtual bool ExpectContinue() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)]
public override object Clone() /* MethodBuilder.Create */
{
return default(object);
}
[Dot42.DexImport("org/apache/http/HttpRequest", "getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IRequestLine GetRequestLine() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IRequestLine);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1025)]
public override global::Org.Apache.Http.ProtocolVersion GetProtocolVersion() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.ProtocolVersion);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "containsHeader", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
public override bool ContainsHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader[] GetHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader[]);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader GetFirstHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader GetLastHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader[] GetAllHeaders() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader[]);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void AddHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)]
public override void AddHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void SetHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)]
public override void SetHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeaders", "([Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void SetHeaders(global::Org.Apache.Http.IHeader[] headers) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "removeHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void RemoveHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "removeHeaders", "(Ljava/lang/String;)V", AccessFlags = 1025)]
public override void RemoveHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "()Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeaderIterator HeaderIterator() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeaderIterator);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeaderIterator HeaderIterator(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeaderIterator);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
public override global::Org.Apache.Http.Params.IHttpParams GetParams() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)]
public override void SetParams(global::Org.Apache.Http.Params.IHttpParams @params) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
/// <java-name>
/// getEntity
/// </java-name>
public global::Org.Apache.Http.IHttpEntity Entity
{
[Dot42.DexImport("getEntity", "()Lorg/apache/http/HttpEntity;", AccessFlags = 1)]
get{ return GetEntity(); }
[Dot42.DexImport("setEntity", "(Lorg/apache/http/HttpEntity;)V", AccessFlags = 1)]
set{ SetEntity(value); }
}
public global::Org.Apache.Http.IRequestLine RequestLine
{
[Dot42.DexImport("org/apache/http/HttpRequest", "getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1025)]
get{ return GetRequestLine(); }
}
public global::Org.Apache.Http.ProtocolVersion ProtocolVersion
{
[Dot42.DexImport("org/apache/http/HttpMessage", "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1025)]
get{ return GetProtocolVersion(); }
}
public global::Org.Apache.Http.IHeader[] AllHeaders
{
[Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)]
get{ return GetAllHeaders(); }
}
public global::Org.Apache.Http.Params.IHttpParams Params
{
[Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
get{ return GetParams(); }
[Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)]
set{ SetParams(value); }
}
}
/// <summary>
/// <para>Basic implementation of an HTTP request that can be modified.</para><para><para></para><para></para><title>Revision:</title><para>674186 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpRequestBase
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpRequestBase", AccessFlags = 1057)]
public abstract partial class HttpRequestBase : global::Org.Apache.Http.Message.AbstractHttpMessage, global::Org.Apache.Http.Client.Methods.IHttpUriRequest, global::Org.Apache.Http.Client.Methods.IAbortableHttpRequest, global::Java.Lang.ICloneable
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpRequestBase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)]
public virtual string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the protocol version this message is compatible with. </para>
/// </summary>
/// <java-name>
/// getProtocolVersion
/// </java-name>
[Dot42.DexImport("getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1)]
public override global::Org.Apache.Http.ProtocolVersion GetProtocolVersion() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.ProtocolVersion);
}
/// <summary>
/// <para>Returns the URI this request uses, such as <code></code>. </para>
/// </summary>
/// <java-name>
/// getURI
/// </java-name>
[Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1)]
public virtual global::System.Uri GetURI() /* MethodBuilder.Create */
{
return default(global::System.Uri);
}
/// <summary>
/// <para>Returns the request line of this request. </para>
/// </summary>
/// <returns>
/// <para>the request line. </para>
/// </returns>
/// <java-name>
/// getRequestLine
/// </java-name>
[Dot42.DexImport("getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.IRequestLine GetRequestLine() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IRequestLine);
}
/// <java-name>
/// setURI
/// </java-name>
[Dot42.DexImport("setURI", "(Ljava/net/URI;)V", AccessFlags = 1)]
public virtual void SetURI(global::System.Uri uri) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setConnectionRequest
/// </java-name>
[Dot42.DexImport("setConnectionRequest", "(Lorg/apache/http/conn/ClientConnectionRequest;)V", AccessFlags = 1)]
public virtual void SetConnectionRequest(global::Org.Apache.Http.Conn.IClientConnectionRequest connRequest) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setReleaseTrigger
/// </java-name>
[Dot42.DexImport("setReleaseTrigger", "(Lorg/apache/http/conn/ConnectionReleaseTrigger;)V", AccessFlags = 1)]
public virtual void SetReleaseTrigger(global::Org.Apache.Http.Conn.IConnectionReleaseTrigger releaseTrigger) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Aborts this http request. Any active execution of this method should return immediately. If the request has not started, it will abort after the next execution. Aborting this request will cause all subsequent executions with this request to fail.</para><para><para>HttpClient::execute(HttpUriRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(HttpUriRequest, org.apache.http.protocol.HttpContext) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) </para></para>
/// </summary>
/// <java-name>
/// abort
/// </java-name>
[Dot42.DexImport("abort", "()V", AccessFlags = 1)]
public virtual void Abort() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests if the request execution has been aborted.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the request execution has been aborted, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isAborted
/// </java-name>
[Dot42.DexImport("isAborted", "()Z", AccessFlags = 1)]
public virtual bool IsAborted() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)]
public virtual object Clone() /* MethodBuilder.Create */
{
return default(object);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "containsHeader", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
public override bool ContainsHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader[] GetHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader[]);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader GetFirstHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader GetLastHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader[] GetAllHeaders() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader[]);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void AddHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)]
public override void AddHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void SetHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)]
public override void SetHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeaders", "([Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void SetHeaders(global::Org.Apache.Http.IHeader[] headers) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "removeHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void RemoveHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "removeHeaders", "(Ljava/lang/String;)V", AccessFlags = 1025)]
public override void RemoveHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "()Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeaderIterator HeaderIterator() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeaderIterator);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeaderIterator HeaderIterator(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeaderIterator);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
public override global::Org.Apache.Http.Params.IHttpParams GetParams() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)]
public override void SetParams(global::Org.Apache.Http.Params.IHttpParams @params) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetMethod(); }
}
/// <summary>
/// <para>Returns the protocol version this message is compatible with. </para>
/// </summary>
/// <java-name>
/// getProtocolVersion
/// </java-name>
public global::Org.Apache.Http.ProtocolVersion ProtocolVersion
{
[Dot42.DexImport("getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1)]
get{ return GetProtocolVersion(); }
}
/// <summary>
/// <para>Returns the URI this request uses, such as <code></code>. </para>
/// </summary>
/// <java-name>
/// getURI
/// </java-name>
public global::System.Uri URI
{
[Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1)]
get{ return GetURI(); }
[Dot42.DexImport("setURI", "(Ljava/net/URI;)V", AccessFlags = 1)]
set{ SetURI(value); }
}
/// <summary>
/// <para>Returns the request line of this request. </para>
/// </summary>
/// <returns>
/// <para>the request line. </para>
/// </returns>
/// <java-name>
/// getRequestLine
/// </java-name>
public global::Org.Apache.Http.IRequestLine RequestLine
{
[Dot42.DexImport("getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1)]
get{ return GetRequestLine(); }
}
public global::Org.Apache.Http.IHeader[] AllHeaders
{
[Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)]
get{ return GetAllHeaders(); }
}
}
/// <summary>
/// <para>HTTP POST method. </para><para>The HTTP POST method is defined in section 9.5 of : <blockquote><para>The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions: <ul><li><para>Annotation of existing resources </para></li><li><para>Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles </para></li><li><para>Providing a block of data, such as the result of submitting a form, to a data-handling process </para></li><li><para>Extending a database through an append operation </para></li></ul></para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpPost
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpPost", AccessFlags = 33)]
public partial class HttpPost : global::Org.Apache.Http.Client.Methods.HttpEntityEnclosingRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "POST";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpPost() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpPost(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpPost(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>Extended version of the HttpRequest interface that provides convenience methods to access request properties such as request URI and method type.</para><para><para></para><para></para><title>Revision:</title><para>659191 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpUriRequest
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpUriRequest", AccessFlags = 1537)]
public partial interface IHttpUriRequest : global::Org.Apache.Http.IHttpRequest
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetMethod() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the URI this request uses, such as <code></code>. </para>
/// </summary>
/// <java-name>
/// getURI
/// </java-name>
[Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1025)]
global::System.Uri GetURI() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Aborts execution of the request.</para><para></para>
/// </summary>
/// <java-name>
/// abort
/// </java-name>
[Dot42.DexImport("abort", "()V", AccessFlags = 1025)]
void Abort() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Tests if the request execution has been aborted.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the request execution has been aborted, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isAborted
/// </java-name>
[Dot42.DexImport("isAborted", "()Z", AccessFlags = 1025)]
bool IsAborted() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>HTTP DELETE method </para><para>The HTTP DELETE method is defined in section 9.7 of : <blockquote><para>The DELETE method requests that the origin server delete the resource identified by the Request-URI. [...] The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. </para></blockquote></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpDelete
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpDelete", AccessFlags = 33)]
public partial class HttpDelete : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "DELETE";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpDelete() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpDelete(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpDelete(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>HTTP GET method. </para><para>The HTTP GET method is defined in section 9.3 of : <blockquote><para>The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. </para></blockquote></para><para>GetMethods will follow redirect requests from the http server by default. This behavour can be disabled by calling setFollowRedirects(false).</para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpGet
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpGet", AccessFlags = 33)]
public partial class HttpGet : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "GET";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpGet() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpGet(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpGet(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>HTTP OPTIONS method. </para><para>The HTTP OPTIONS method is defined in section 9.2 of : <blockquote><para>The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpOptions
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpOptions", AccessFlags = 33)]
public partial class HttpOptions : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "OPTIONS";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpOptions() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpOptions(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpOptions(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getAllowedMethods
/// </java-name>
[Dot42.DexImport("getAllowedMethods", "(Lorg/apache/http/HttpResponse;)Ljava/util/Set;", AccessFlags = 1, Signature = "(Lorg/apache/http/HttpResponse;)Ljava/util/Set<Ljava/lang/String;>;")]
public virtual global::Java.Util.ISet<string> GetAllowedMethods(global::Org.Apache.Http.IHttpResponse response) /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<string>);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>HTTP HEAD method. </para><para>The HTTP HEAD method is defined in section 9.4 of : <blockquote><para>The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpHead
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpHead", AccessFlags = 33)]
public partial class HttpHead : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "HEAD";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpHead() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpHead(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpHead(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>HTTP TRACE method. </para><para>The HTTP TRACE method is defined in section 9.6 of : <blockquote><para>The TRACE method is used to invoke a remote, application-layer loop- back of the request message. The final recipient of the request SHOULD reflect the message received back to the client as the entity-body of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive a Max-Forwards value of zero (0) in the request (see section 14.31). A TRACE request MUST NOT include an entity. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpTrace
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpTrace", AccessFlags = 33)]
public partial class HttpTrace : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "TRACE";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpTrace() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpTrace(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpTrace(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>Interface representing an HTTP request that can be aborted by shutting down the underlying HTTP connection.</para><para><para></para><para></para><title>Revision:</title><para>639600 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/AbortableHttpRequest
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/AbortableHttpRequest", AccessFlags = 1537)]
public partial interface IAbortableHttpRequest
/* scope: __dot42__ */
{
/// <summary>
/// <para>Sets the ClientConnectionRequest callback that can be used to abort a long-lived request for a connection. If the request is already aborted, throws an IOException.</para><para><para>ClientConnectionManager </para><simplesectsep></simplesectsep><para>ThreadSafeClientConnManager </para></para>
/// </summary>
/// <java-name>
/// setConnectionRequest
/// </java-name>
[Dot42.DexImport("setConnectionRequest", "(Lorg/apache/http/conn/ClientConnectionRequest;)V", AccessFlags = 1025)]
void SetConnectionRequest(global::Org.Apache.Http.Conn.IClientConnectionRequest connRequest) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the ConnectionReleaseTrigger callback that can be used to abort an active connection. Typically, this will be the ManagedClientConnection itself. If the request is already aborted, throws an IOException. </para>
/// </summary>
/// <java-name>
/// setReleaseTrigger
/// </java-name>
[Dot42.DexImport("setReleaseTrigger", "(Lorg/apache/http/conn/ConnectionReleaseTrigger;)V", AccessFlags = 1025)]
void SetReleaseTrigger(global::Org.Apache.Http.Conn.IConnectionReleaseTrigger releaseTrigger) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Aborts this http request. Any active execution of this method should return immediately. If the request has not started, it will abort after the next execution. Aborting this request will cause all subsequent executions with this request to fail.</para><para><para>HttpClient::execute(HttpUriRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(HttpUriRequest, org.apache.http.protocol.HttpContext) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) </para></para>
/// </summary>
/// <java-name>
/// abort
/// </java-name>
[Dot42.DexImport("abort", "()V", AccessFlags = 1025)]
void Abort() /* MethodBuilder.Create */ ;
}
}
| |
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 RESTServiceTest.Areas.HelpPage.ModelDescriptions;
using RESTServiceTest.Areas.HelpPage.Models;
namespace RESTServiceTest.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);
}
}
}
}
| |
#if CORECLR
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace System.Management.Automation
{
#region Reflection and Type related extensions
#region Enums
[Flags]
internal enum MemberTypes
{
Constructor = 0x01,
Event = 0x02,
Field = 0x04,
Method = 0x08,
Property = 0x10,
All = 0xbf,
}
#endregion Enums
/// <summary>
/// The type extension methods within this partial class are only used for CoreCLR powershell.
///
/// * If you want to add an extension method that will be used by both FullCLR and CoreCLR powershell, please
/// add it to the 'PSTypeExtensions' partial class in 'ExtensionMethods.cs'.
/// * If you want to add an extension method that will be used only by CoreCLR powershell, please add it here.
/// </summary>
internal static partial class PSTypeExtensions
{
#region Miscs
internal static bool IsSubclassOf(this Type targetType, Type type)
{
return targetType.GetTypeInfo().IsSubclassOf(type);
}
#endregion Miscs
#region Interface
internal static Type GetInterface(this Type type, string name)
{
// The search is case-sensitive, as it's in the full CLR version
return GetInterface(type, name, false);
}
internal static Type GetInterface(this Type type, string name, bool ignoreCase)
{
var stringComparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
return type.GetTypeInfo().ImplementedInterfaces.FirstOrDefault(
implementedInterface => String.Equals(name, implementedInterface.Name, stringComparison));
}
#endregion Interface
#region Member
internal static MemberInfo[] GetMember(this Type type, string name, MemberTypes memberType, BindingFlags bindingAttr)
{
if (bindingAttr == 0)
{
return new MemberInfo[0];
}
var members = new List<MemberInfo>();
if ((memberType & MemberTypes.Field) != 0)
{
var fields = type.GetFields(name, bindingAttr);
if (fields != null)
{
for (int i = 0; i < fields.Length; i++)
{
members.Add(fields[i]);
}
}
}
if ((memberType & MemberTypes.Property) != 0)
{
var properties = type.GetProperties(name, bindingAttr);
if (properties != null)
{
for (int i = 0; i < properties.Length; i++)
{
members.Add(properties[i]);
}
}
}
return members.ToArray();
}
#endregion Member
#region Field
internal static FieldInfo[] GetFields(this Type type, string name, BindingFlags bindingFlags)
{
return GetFields(type, name, bindingFlags, false);
}
/// <summary>
/// GetFields
/// </summary>
internal static FieldInfo[] GetFields(this Type type, string name, BindingFlags bindingFlags, bool isNameNull)
{
if (!isNameNull && (name == null || (name = name.Trim()) == ""))
{
throw new PSArgumentNullException("name");
}
if (bindingFlags == 0)
{
return null;
}
Type currentType = type;
StringComparison strCompare = (bindingFlags & BindingFlags.IgnoreCase) != 0
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
var fields = new List<FieldInfo>();
bool isInHierarchy = false;
do
{
TypeInfo currentTypeInfo = currentType.GetTypeInfo();
foreach (FieldInfo field in currentTypeInfo.DeclaredFields)
{
if (!isNameNull && !String.Equals(name, field.Name, strCompare))
{
continue;
}
if (((bindingFlags & BindingFlags.Instance) != 0 && !field.IsStatic) ||
((bindingFlags & BindingFlags.Static) != 0 && field.IsStatic))
{
if (isInHierarchy)
{
// Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy;
// private static members in inherited classes are not included
if (!field.IsPublic && !(field.IsFamily && field.IsStatic))
{
continue;
}
}
if ((bindingFlags & BindingFlags.Public) != 0 && field.IsPublic)
{
fields.Add(field);
continue;
}
if ((bindingFlags & BindingFlags.NonPublic) != 0 && !field.IsPublic)
{
fields.Add(field);
}
}
}
if ((bindingFlags & BindingFlags.FlattenHierarchy) != 0 && (bindingFlags & BindingFlags.DeclaredOnly) == 0)
{
isInHierarchy = true;
currentType = currentTypeInfo.BaseType;
}
else
{
currentType = null;
}
} while (currentType != null);
return fields.ToArray();
}
#endregion Field
#region Property
internal static PropertyInfo[] GetProperties(this Type type, string name, BindingFlags bindingFlags)
{
return GetProperties(type, name, bindingFlags, false);
}
/// <summary>
/// GetProperty
/// </summary>
internal static PropertyInfo[] GetProperties(this Type type, string name, BindingFlags bindingFlags, bool isNameNull)
{
if (!isNameNull && (name == null || (name = name.Trim()) == ""))
{
throw new PSArgumentNullException("name");
}
if (bindingFlags == 0)
{
return null;
}
Type currentType = type;
StringComparison strCompare = (bindingFlags & BindingFlags.IgnoreCase) != 0
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
var properties = new List<PropertyInfo>();
bool isInHierarchy = false;
do
{
TypeInfo currentTypeInfo = currentType.GetTypeInfo();
foreach (PropertyInfo property in currentTypeInfo.DeclaredProperties)
{
if (!isNameNull && !String.Equals(name, property.Name, strCompare))
{
continue;
}
if (((bindingFlags & BindingFlags.Instance) != 0 && IsInstanceProperty(property)) ||
((bindingFlags & BindingFlags.Static) != 0 && IsStaticProperty(property)))
{
if (isInHierarchy)
{
// Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy;
// private static members in inherited classes are not included
if (!IsPublicProperty(property) && !(IsProtectedProperty(property) && IsStaticProperty(property)))
{
continue;
}
}
if ((bindingFlags & BindingFlags.Public) != 0 && IsPublicProperty(property))
{
properties.Add(property);
continue;
}
if ((bindingFlags & BindingFlags.NonPublic) != 0 && IsNonPublicProperty(property))
{
properties.Add(property);
continue;
}
}
}
if ((bindingFlags & BindingFlags.FlattenHierarchy) != 0 && (bindingFlags & BindingFlags.DeclaredOnly) == 0)
{
isInHierarchy = true;
currentType = currentTypeInfo.BaseType;
}
else
{
currentType = null;
}
} while (currentType != null);
return properties.ToArray();
}
#region Property Helper Methods
private static bool IsInstanceProperty(PropertyInfo property)
{
if (property.GetMethod != null && property.GetMethod.IsStatic)
{
return false;
}
if (property.SetMethod != null && property.SetMethod.IsStatic)
{
return false;
}
if (property.GetMethod == null && property.SetMethod == null)
{
return false;
}
return true;
}
private static bool IsStaticProperty(PropertyInfo property)
{
if (property.GetMethod != null && !property.GetMethod.IsStatic)
{
return false;
}
if (property.SetMethod != null && !property.SetMethod.IsStatic)
{
return false;
}
if (property.GetMethod == null && property.SetMethod == null)
{
return false;
}
return true;
}
private static bool IsPublicProperty(PropertyInfo property)
{
if ((property.GetMethod != null && property.GetMethod.IsPublic) || (property.SetMethod != null && property.SetMethod.IsPublic))
{
return true;
}
return false;
}
private static bool IsNonPublicProperty(PropertyInfo property)
{
if (property.GetMethod == null && property.SetMethod == null)
{
return false;
}
if (property.GetMethod != null && property.GetMethod.IsPublic)
{
return false;
}
if (property.SetMethod != null && property.SetMethod.IsPublic)
{
return false;
}
return true;
}
private static bool IsProtectedProperty(PropertyInfo property)
{
if (property.GetMethod == null && property.SetMethod == null)
{
return false;
}
if (property.GetMethod != null && !property.GetMethod.IsFamily)
{
return false;
}
if (property.SetMethod != null && !property.SetMethod.IsFamily)
{
return false;
}
return true;
}
#endregion Property Helper Methods
#endregion Property
#region Constructor
/// <summary>
/// Search for a constructor that matches the specified bindingFlags and parameter types
/// </summary>
internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, string binderNotUsed, Type[] types, string modifiersNotUsed)
{
if (binderNotUsed != null || modifiersNotUsed != null)
{
throw new ArgumentException("Parameters 'binder' and 'modifier' should not be used");
}
if (types == null || types.Any(element => element == null))
{
throw new ArgumentNullException("types");
}
ConstructorInfo[] results = GetConstructors(type, bindingFlags, null);
return results != null ? GetMatchingConstructor(results, types) : null;
}
internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, string binderNotUsed,
CallingConventions callConvention, Type[] types, string modifiersNotUsed)
{
if (binderNotUsed != null || modifiersNotUsed != null)
{
throw new ArgumentException("Parameters 'binder' and 'modifier' should not be used");
}
if (types == null || types.Any(element => element == null))
{
throw new ArgumentNullException("types");
}
ConstructorInfo[] results = GetConstructors(type, bindingFlags, callConvention);
return results != null ? GetMatchingConstructor(results, types) : null;
}
/// <summary>
/// Helper method - Get the matching constructor based on the parameter types
/// </summary>
private static ConstructorInfo GetMatchingConstructor(ConstructorInfo[] constructors, Type[] types)
{
// Compare the parameter types in two passes.
// The first pass is to check if the parameter types are exactly the same,
// The second pass is to check if the parameter types is assignable from the given argument types.
var matchConstructors = new List<ConstructorInfo>();
bool inSecondPass = false;
do
{
// Use 'for' loop to avoid construct new ArrayEnumerator object
for (int constructorIndex = 0; constructorIndex < constructors.Length; constructorIndex++)
{
var constructor = constructors[constructorIndex];
ParameterInfo[] parameters = constructor.GetParameters();
if (types.Length == parameters.Length)
{
bool success = true;
for (int typeIndex = 0; typeIndex < types.Length; typeIndex++)
{
if (!IsParameterTypeMatching(parameters[typeIndex].ParameterType, types[typeIndex], inSecondPass))
{
success = false;
break;
}
}
if (success)
{
matchConstructors.Add(constructor);
}
}
}
// Flip the 'inSecondPass' flag, so that we run another pass only if we're about
// to start the second pass and we didn't find anything from the first pass.
inSecondPass = !inSecondPass;
} while (matchConstructors.Count == 0 && inSecondPass);
if (matchConstructors.Count > 1)
{
throw new AmbiguousMatchException();
}
return matchConstructors.Count == 1 ? matchConstructors[0] : null;
}
/// <summary>
/// Constructors defined in the current type
/// </summary>
internal static ConstructorInfo[] GetConstructors(this Type type, BindingFlags bindingFlags, CallingConventions? callConvention)
{
if ((bindingFlags & BindingFlags.FlattenHierarchy) != 0)
{
throw new PSArgumentException("Invalid binding flags");
}
if (((bindingFlags & BindingFlags.Instance) != 0 && (bindingFlags & BindingFlags.Static) != 0) ||
((bindingFlags & BindingFlags.Instance) == 0 && (bindingFlags & BindingFlags.Static) == 0))
{
throw new PSArgumentException("Invalid binding flags");
}
// If bindingFlags is zero, return null.
if (bindingFlags == 0)
{
return null;
}
// If type is a generic parameter, return empty array
if (type.IsGenericParameter)
{
return new ConstructorInfo[0];
}
var ctors = new List<ConstructorInfo>();
foreach (ConstructorInfo ctor in type.GetTypeInfo().DeclaredConstructors)
{
/* CallingConventions is different on CoreCLR ...
* TODO -- find out how different and what problem it causes.
if (callConvention.HasValue && ctor.CallingConvention != callConvention.Value)
{
continue;
}
*/
if ((bindingFlags & BindingFlags.Instance) != 0 && ctor.IsStatic)
{
continue;
}
if ((bindingFlags & BindingFlags.Static) != 0 && !ctor.IsStatic)
{
continue;
}
if ((bindingFlags & BindingFlags.Public) != 0 && ctor.IsPublic)
{
ctors.Add(ctor);
continue;
}
if ((bindingFlags & BindingFlags.NonPublic) != 0 && !ctor.IsPublic)
{
ctors.Add(ctor);
continue;
}
}
return ctors.ToArray();
}
#endregion Constructor
#region Method
internal static MethodInfo GetMethod(this Type targetType, string name, BindingFlags bindingFlags, string binderNotUsed, Type[] types, string modifierNotUsed)
{
if (binderNotUsed != null || modifierNotUsed != null)
{
throw new ArgumentException("Parameters 'binderNotUsed' and 'modifier_NotUsed' should not be used.");
}
if (types == null || types.Any(element => element == null))
{
throw new ArgumentNullException("types");
}
MethodInfo[] methods = GetMethods(targetType, name, bindingFlags);
return methods != null ? GetMatchingMethod(methods, types) : null;
}
internal static MethodInfo GetMethod(this Type targetType, string name, BindingFlags bindingFlags, string binderNotUsed, CallingConventions callConvention, Type[] types, string modifierNotUsed)
{
if (binderNotUsed != null || modifierNotUsed != null)
{
throw new ArgumentException("Parameters 'binderNotUsed' and 'modifier_NotUsed' should not be used.");
}
if (types == null || types.Any(element => element == null))
{
throw new ArgumentNullException("types");
}
MethodInfo[] methods = GetMethods(targetType, name, bindingFlags, false, callConvention);
return methods != null ? GetMatchingMethod(methods, types) : null;
}
// Helper method
private static MethodInfo GetMatchingMethod(MethodInfo[] methods, Type[] types)
{
// Compare the parameter types in two passes.
// The first pass is to check if the parameter types are exactly the same,
// The second pass is to check if the parameter types is assignable from the given argument types.
var matchMethods = new List<MethodInfo>();
bool inSecondPass = false;
do
{
// Use for loop to avoid construct new ArrayEnumerator object
for (int methodIndex = 0; methodIndex < methods.Length; methodIndex++)
{
var method = methods[methodIndex];
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == types.Length)
{
bool success = true;
for (int typeIndex = 0; typeIndex < types.Length; typeIndex++)
{
if (!IsParameterTypeMatching(parameters[typeIndex].ParameterType, types[typeIndex], inSecondPass))
{
success = false;
break;
}
}
if (success)
{
matchMethods.Add(method);
}
}
}
// Flip the 'inSecondPass' flag, so that we run another pass only if we're about
// to start the second pass and we didn't find anything from the first pass.
inSecondPass = !inSecondPass;
} while (matchMethods.Count == 0 && inSecondPass);
if (matchMethods.Count > 1)
{
throw new AmbiguousMatchException();
}
return matchMethods.Count == 1 ? matchMethods[0] : null;
}
private static bool IsParameterTypeMatching(Type paramType, Type argType, bool inSecondPass)
{
return inSecondPass
? paramType.IsAssignableFrom(argType)
: paramType == argType;
}
internal static MethodInfo[] GetMethods(this Type type, string name, BindingFlags bindingFlags)
{
return GetMethods(type, name, bindingFlags, false, null);
}
internal static MethodInfo[] GetMethods(this Type type, string name, BindingFlags bindingFlags, bool isNameNull, CallingConventions? callConvention)
{
if (!isNameNull && (name == null || (name = name.Trim()) == ""))
{
throw new ArgumentNullException("name");
}
if (bindingFlags == 0)
{
return null;
}
Type currentType = type;
StringComparison strCompare = (bindingFlags & BindingFlags.IgnoreCase) != 0
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
var methods = new List<MethodInfo>();
bool isInHierarchy = false;
do
{
TypeInfo currentTypeInfo = currentType.GetTypeInfo();
foreach (MethodInfo method in currentTypeInfo.DeclaredMethods)
{
if (!isNameNull && !String.Equals(name, method.Name, strCompare))
{
continue;
}
if (callConvention.HasValue && method.CallingConvention != callConvention.Value)
{
continue;
}
if (((bindingFlags & BindingFlags.Instance) != 0 && !method.IsStatic) ||
((bindingFlags & BindingFlags.Static) != 0 && method.IsStatic))
{
if (isInHierarchy)
{
// Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy;
// private static members in inherited classes are not included
if (!method.IsPublic && !(method.IsFamily && method.IsStatic))
{
continue;
}
}
if ((bindingFlags & BindingFlags.Public) != 0 && method.IsPublic)
{
methods.Add(method);
continue;
}
if ((bindingFlags & BindingFlags.NonPublic) != 0 && !method.IsPublic)
{
methods.Add(method);
}
}
}
if ((bindingFlags & BindingFlags.FlattenHierarchy) != 0 && (bindingFlags & BindingFlags.DeclaredOnly) == 0)
{
isInHierarchy = true;
currentType = currentTypeInfo.BaseType;
}
else
{
currentType = null;
}
} while (currentType != null);
return methods.ToArray();
}
#endregion Method
#region TypeCode
private static readonly Dictionary<Type, TypeCode> s_typeCodeMap =
new Dictionary<Type, TypeCode>()
{
// 'DBNull = 2' is removed from 'System.TypeCode' in CoreCLR. We return
// '(TypeCode)2' for 'System.DBNull' to avoid any breaking changes.
{typeof(DBNull), (TypeCode)2},
{typeof(Boolean),TypeCode.Boolean},
{typeof(Char),TypeCode.Char},
{typeof(sbyte),TypeCode.SByte},
{typeof(byte), TypeCode.Byte},
{typeof(Int16),TypeCode.Int16},
{typeof(UInt16),TypeCode.UInt16},
{typeof(Int32),TypeCode.Int32},
{typeof(UInt32),TypeCode.UInt32},
{typeof(Int64),TypeCode.Int64},
{typeof(UInt64),TypeCode.UInt64},
{typeof(Single),TypeCode.Single},
{typeof(Double),TypeCode.Double},
{typeof(string),TypeCode.String},
{typeof(Decimal),TypeCode.Decimal},
{typeof(DateTime),TypeCode.DateTime},
};
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static TypeCode GetTypeCodeInCoreClr(Type type)
{
if (type == null)
return TypeCode.Empty;
if (s_typeCodeMap.ContainsKey(type))
return s_typeCodeMap[type];
if (type.GetTypeInfo().IsEnum)
return GetTypeCode(Enum.GetUnderlyingType(type));
return TypeCode.Object;
}
#endregion TypeCode
}
#endregion Reflection and Type related extensions
#region Environment Extensions
// TODO:CORECLR - Environment Extensions need serious work to refine.
internal enum EnvironmentVariableTarget
{
Process,
User,
Machine
}
internal static partial class Environment
{
#region Forward_To_System.Environment
#region Properties
public static int CurrentManagedThreadId
{
get
{
return System.Environment.CurrentManagedThreadId;
}
}
public static bool HasShutdownStarted
{
get
{
return System.Environment.HasShutdownStarted;
}
}
public static string NewLine
{
get
{
return System.Environment.NewLine;
}
}
public static int ProcessorCount
{
get
{
return System.Environment.ProcessorCount;
}
}
public static string StackTrace
{
get
{
return System.Environment.StackTrace;
}
}
public static int TickCount
{
get
{
return System.Environment.TickCount;
}
}
#endregion Properties
#region Methods
public static string ExpandEnvironmentVariables(string name)
{
return System.Environment.ExpandEnvironmentVariables(name);
}
public static void FailFast(string message)
{
System.Environment.FailFast(message);
}
public static void FailFast(string message, Exception exception)
{
System.Environment.FailFast(message, exception);
}
public static string GetEnvironmentVariable(string variable)
{
return System.Environment.GetEnvironmentVariable(variable);
}
public static IDictionary GetEnvironmentVariables()
{
return System.Environment.GetEnvironmentVariables();
}
public static void SetEnvironmentVariable(string variable, string value)
{
System.Environment.SetEnvironmentVariable(variable, value);
}
#endregion Methods
#endregion Forward_To_System.Environment
private const int MaxMachineNameLength = 256;
private static string[] s_commandLineArgs = new string[0];
public static string[] GetCommandLineArgs()
{
return s_commandLineArgs;
}
#region EnvironmentVariable_Extensions
/// <summary>
/// The code is mostly copied from the .NET implementation.
/// The only difference is how resource string is retrieved.
/// We use the same resource string as in .NET implementation.
/// </summary>
public static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target)
{
if (target == EnvironmentVariableTarget.Process)
{
return GetEnvironmentVariables();
}
#if UNIX
return null;
#else
if( target == EnvironmentVariableTarget.Machine)
{
using (RegistryKey environmentKey =
Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Session Manager\Environment", false))
{
return GetRegistryKeyNameValuePairs(environmentKey);
}
}
else // target == EnvironmentVariableTarget.User
{
using (RegistryKey environmentKey =
Registry.CurrentUser.OpenSubKey("Environment", false))
{
return GetRegistryKeyNameValuePairs(environmentKey);
}
}
#endif
}
/// <summary>
/// The code is mostly copied from the .NET implementation.
/// The only difference is how resource string is retrieved.
/// We use the same resource string as in .NET implementation.
/// </summary>
internal static IDictionary GetRegistryKeyNameValuePairs(RegistryKey registryKey)
{
Hashtable table = new Hashtable(20);
if (registryKey != null)
{
string[] names = registryKey.GetValueNames();
foreach (string name in names)
{
string value = registryKey.GetValue(name, "").ToString();
table.Add(name, value);
}
}
return table;
}
/// <summary>
/// The code is mostly copied from the .NET implementation.
/// The only difference is how resource string is retrieved.
/// We use the same resource string as in .NET implementation.
/// </summary>
public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target)
{
if (variable == null)
{
throw new ArgumentNullException("variable");
}
if (target == EnvironmentVariableTarget.Process)
{
return System.Environment.GetEnvironmentVariable(variable);
}
#if UNIX
return null;
#else
if (target == EnvironmentVariableTarget.Machine)
{
using (RegistryKey environmentKey =
Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Session Manager\Environment", false))
{
if (environmentKey == null) { return null; }
string value = environmentKey.GetValue(variable) as string;
return value;
}
}
else // target == EnvironmentVariableTarget.User
{
using (RegistryKey environmentKey = Registry.CurrentUser.OpenSubKey("Environment", false))
{
if (environmentKey == null) { return null; }
string value = environmentKey.GetValue(variable) as string;
return value;
}
}
#endif
}
#endregion EnvironmentVariable_Extensions
#region Property_Extensions
/// <summary>
/// UserDomainName
/// </summary>
public static string UserDomainName
{
get
{
#if UNIX
return Platform.NonWindowsGetDomainName();
#else
return WinGetUserDomainName();
#endif
}
}
/// <summary>
/// UserName
/// </summary>
public static string UserName
{
get
{
#if UNIX
return Platform.Unix.UserName;
#else
return WinGetUserName();
#endif
}
}
/// <summary>
/// MachineName
/// </summary>
public static string MachineName
{
get
{
return System.Environment.MachineName;
}
}
/// <summary>
/// OSVersion
/// </summary>
public static OperatingSystem OSVersion
{
get
{
if (s_os == null)
{
#if UNIX
// TODO:PSL use P/Invoke to provide proper version
// OSVersion will be back in CoreCLR 1.1
s_os = new Environment.OperatingSystem(new Version(1, 0, 0, 0), "");
#else
s_os = WinGetOSVersion();
#endif
}
return s_os;
}
}
private static volatile OperatingSystem s_os;
#endregion Property_Extensions
#region SpecialFolder_Extensions
/// <summary>
/// The code is copied from the .NET implementation.
/// </summary>
public static string GetFolderPath(SpecialFolder folder)
{
return InternalGetFolderPath(folder);
}
/// <summary>
/// The API set 'api-ms-win-shell-shellfolders-l1-1-0.dll' was removed from NanoServer, so we cannot depend on 'SHGetFolderPathW'
/// to get the special folder paths. Instead, we need to rely on the basic environment variables to get the special folder paths.
/// </summary>
/// <returns>
/// The path to the specified system special folder, if that folder physically exists on your computer.
/// Otherwise, an empty string ("").
/// </returns>
private static string InternalGetFolderPath(SpecialFolder folder)
{
// The API 'SHGetFolderPath' is not available on OneCore, so we have to rely on environment variables
string folderPath = null;
#if UNIX
switch (folder)
{
case SpecialFolder.ProgramFiles:
folderPath = "/bin";
if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
break;
case SpecialFolder.ProgramFilesX86:
folderPath = "/usr/bin";
if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
break;
case SpecialFolder.System:
case SpecialFolder.SystemX86:
folderPath = "/sbin";
if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
break;
case SpecialFolder.Personal:
folderPath = System.Environment.GetEnvironmentVariable("HOME");
break;
case SpecialFolder.LocalApplicationData:
folderPath = System.IO.Path.Combine(System.Environment.GetEnvironmentVariable("HOME"), ".config");
if (!System.IO.Directory.Exists(folderPath)) { System.IO.Directory.CreateDirectory(folderPath); }
break;
default:
throw new NotSupportedException();
}
#else
string systemRoot = null;
string userProfile = null;
switch (folder)
{
case SpecialFolder.ProgramFiles:
folderPath = System.Environment.GetEnvironmentVariable("ProgramFiles");
if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
break;
case SpecialFolder.ProgramFilesX86:
folderPath = System.Environment.GetEnvironmentVariable("ProgramFiles(x86)");
if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
break;
case SpecialFolder.System:
systemRoot = System.Environment.GetEnvironmentVariable("SystemRoot");
if (systemRoot != null)
{
folderPath = System.IO.Path.Combine(systemRoot, "system32");
if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
}
break;
case SpecialFolder.SystemX86:
systemRoot = System.Environment.GetEnvironmentVariable("SystemRoot");
if (systemRoot != null)
{
folderPath = System.IO.Path.Combine(systemRoot, "SysWOW64");
if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
}
break;
case SpecialFolder.MyDocuments: // same as SpecialFolder.Personal
userProfile = System.Environment.GetEnvironmentVariable("USERPROFILE");
if (userProfile != null)
{
folderPath = System.IO.Path.Combine(userProfile, "Documents");
// CSS doesn't include a Documents directory for each user, so we create one if needed.
if (!System.IO.Directory.Exists(folderPath)) { System.IO.Directory.CreateDirectory(folderPath); }
}
break;
case SpecialFolder.LocalApplicationData:
folderPath = System.Environment.GetEnvironmentVariable("LOCALAPPDATA");
// When powershell gets executed in SetupComplete.cmd during NanoServer's first boot, 'LOCALAPPDATA' won't be set yet.
// In this case, we need to return an alternate path, so that module auto-loading can continue to work properly.
if (folderPath == null)
{
// It's guaranteed by NanoServer team that 'USERPROFILE' will be already set when SetupComplete.cmd runs.
// So we use the path '%USERPROFILE%\AppData\Local' as an alternative in this case, and also set the env
// variable %LOCALAPPDATA% to it, so that modules running in PS can depend on this env variable.
userProfile = System.Environment.GetEnvironmentVariable("USERPROFILE");
if (userProfile != null)
{
string alternatePath = System.IO.Path.Combine(userProfile, @"AppData\Local");
if (System.IO.Directory.Exists(alternatePath))
{
System.Environment.SetEnvironmentVariable("LOCALAPPDATA", alternatePath);
folderPath = alternatePath;
}
}
}
else if (!System.IO.Directory.Exists(folderPath))
{
folderPath = null;
}
break;
default:
throw new NotSupportedException();
}
#endif
return folderPath ?? string.Empty;
}
#endregion SpecialFolder_Extensions
#region WinPlatform_Specific_Methods
#if !UNIX
/// <summary>
/// Windows UserDomainName implementation
/// </summary>
private static string WinGetUserDomainName()
{
StringBuilder domainName = new StringBuilder(1024);
uint domainNameLen = (uint)domainName.Capacity;
byte ret = Win32Native.GetUserNameEx(Win32Native.NameSamCompatible, domainName, ref domainNameLen);
if (ret == 1)
{
string samName = domainName.ToString();
int index = samName.IndexOf('\\');
if (index != -1)
{
return samName.Substring(0, index);
}
}
else
{
int errorCode = Marshal.GetLastWin32Error();
throw new InvalidOperationException(Win32Native.GetMessage(errorCode));
}
// Cannot use LookupAccountNameW to get DomainName because 'GetUserName' is not available in CSS and thus we cannot get the account.
throw new InvalidOperationException(CoreClrStubResources.CannotGetDomainName);
}
/// <summary>
/// Windows UserName implementation
/// </summary>
private static string WinGetUserName()
{
StringBuilder domainName = new StringBuilder(1024);
uint domainNameLen = (uint)domainName.Capacity;
byte ret = Win32Native.GetUserNameEx(Win32Native.NameSamCompatible, domainName, ref domainNameLen);
if (ret == 1)
{
string samName = domainName.ToString();
int index = samName.IndexOf('\\');
if (index != -1)
{
return samName.Substring(index + 1);
}
}
return string.Empty;
}
/// <summary>
/// Windows OSVersion implementation
/// </summary>
private static OperatingSystem WinGetOSVersion()
{
Win32Native.OSVERSIONINFOEX osviex = new Win32Native.OSVERSIONINFOEX();
osviex.OSVersionInfoSize = Marshal.SizeOf(osviex);
if (!Win32Native.GetVersionEx(ref osviex))
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode);
}
Version v = new Version(osviex.MajorVersion, osviex.MinorVersion, osviex.BuildNumber, (osviex.ServicePackMajor << 16) | osviex.ServicePackMinor);
return new OperatingSystem(v, osviex.CSDVersion);
}
/// <summary>
/// DllImport uses the ApiSet dll that is available on CSS, since this code
/// will only be included when building targeting CoreCLR.
/// </summary>
private static class Win32Native
{
internal const int NameSamCompatible = 2; // EXTENDED_NAME_FORMAT - NameSamCompatible
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
[DllImport("SspiCli.dll", CharSet = CharSet.Unicode, SetLastError = true)]
// Win32 return type is BOOLEAN (which is 1 byte and not BOOL which is 4bytes)
internal static extern byte GetUserNameEx(int format, [Out] StringBuilder domainName, ref uint domainNameLen);
[DllImport(PinvokeDllNames.FormatMessageDllName, CharSet = CharSet.Unicode)]
internal static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId,
int dwLanguageId, [Out]StringBuilder lpBuffer,
int nSize, IntPtr va_list_arguments);
[DllImport(PinvokeDllNames.GetVersionExDllName, CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool GetVersionEx(ref OSVERSIONINFOEX osVerEx);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct OSVERSIONINFOEX
{
// The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
public int OSVersionInfoSize;
public int MajorVersion;
public int MinorVersion;
public int BuildNumber;
public int PlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string CSDVersion;
public ushort ServicePackMajor;
public ushort ServicePackMinor;
public short SuiteMask;
public byte ProductType;
public byte Reserved;
}
/// <summary>
/// The code is mostly copied from the .NET implementation.
/// The only difference is how resource string is retrieved.
/// We use the same resource string as in .NET implementation.
/// </summary>
internal static string GetMessage(int errorCode)
{
StringBuilder sb = new StringBuilder(512);
int result = Win32Native.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
IntPtr.Zero, errorCode, 0, sb, sb.Capacity, IntPtr.Zero);
if (result != 0)
{
return sb.ToString();
}
else
{
return string.Format(CultureInfo.CurrentCulture, CoreClrStubResources.UnknownErrorNumber, errorCode);
}
}
}
#endif
#endregion WinPlatform_Specific_Methods
#region NestedTypes
// Porting note: MyDocuments does not exist on .NET Core, but Personal does, and
// they both point to your "documents repository," which on linux, is just the
// home directory.
/// <summary>
/// It only contains the values that get used in powershell
/// </summary>
internal enum SpecialFolder
{
Personal = 0x05,
MyDocuments = 0x05,
LocalApplicationData = 0x1c,
ProgramFiles = 0x26,
ProgramFilesX86 = 0x2a,
System = 0x25,
SystemX86 = 0x29,
}
/// <summary>
/// It only contains the properties that get used in powershell
/// </summary>
internal sealed class OperatingSystem
{
private Version _version;
private string _servicePack;
private string _versionString;
internal OperatingSystem(Version version, string servicePack)
{
if (version == null)
throw new ArgumentNullException("version");
_version = version;
_servicePack = servicePack;
}
/// <summary>
/// OS version
/// </summary>
public Version Version
{
get { return _version; }
}
/// <summary>
/// VersionString
/// </summary>
public string VersionString
{
get
{
if (_versionString != null)
{
return _versionString;
}
// It's always 'VER_PLATFORM_WIN32_NT' for NanoServer and IoT
const string os = "Microsoft Windows NT ";
if (string.IsNullOrEmpty(_servicePack))
{
_versionString = os + _version.ToString();
}
else
{
_versionString = os + _version.ToString(3) + " " + _servicePack;
}
return _versionString;
}
}
}
#endregion NestedTypes
}
#endregion Environment Extensions
#region Non-generic collection extensions
/// <summary>
/// Add the AttributeCollection type with stripped functionalities for powershell on CoreCLR.
/// The Adapter type has a protected abstract method 'PropertyAttributes' that returns an AttributeCollection
/// instance. Third party adapter may already implement this method and thus we cannot change the return
/// type for full powershell code. Therefore, we add the AttributeCollection type with minimal functionalities
/// so that the code also work with CoreCLR.
/// </summary>
public class AttributeCollection : ICollection, IEnumerable
{
/// <summary>
/// AttributeCollection
/// </summary>
public static readonly AttributeCollection Empty = new AttributeCollection(null);
#region Constructors
/// <summary>
/// AttributeCollection protected constructor
/// </summary>
protected AttributeCollection()
{
}
/// <summary>
/// AttributeCollection public constructor
/// </summary>
/// <param name="attributes"></param>
public AttributeCollection(params Attribute[] attributes)
{
if (attributes == null)
{
attributes = new Attribute[0];
}
_attributes = attributes;
for (int i = 0; i < attributes.Length; i++)
{
if (attributes[i] == null)
{
throw new ArgumentNullException("attributes");
}
}
}
#endregion Constructors
#region Methods
/// <summary>
/// Copies the collection to an array, starting at the specified index.
/// </summary>
/// <param name="array"></param>
/// <param name="index"></param>
public void CopyTo(Array array, int index)
{
Array.Copy(this.Attributes, 0, array, index, this.Attributes.Length);
}
/// <summary>
/// Gets an enumerator for this collection.
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
return this.Attributes.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion Methods
#region Properties
private readonly Attribute[] _attributes;
/// <summary>
/// Gets the attribute collection.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
protected virtual Attribute[] Attributes
{
get
{
return _attributes;
}
}
/// <summary>
/// Gets the number of attributes.
/// </summary>
public int Count
{
get
{
return this.Attributes.Length;
}
}
/// <summary>
/// Gets the attribute with the specified index number.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public virtual Attribute this[int index]
{
get
{
return this.Attributes[index];
}
}
int ICollection.Count
{
get
{
return this.Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return null;
}
}
#endregion Properties
}
#endregion Non-generic collection extensions
#region Misc extensions
/// <summary>
/// Add the Pointer type with stripped functionalities for PowerShell on CoreCLR.
/// We need this type because if a method returns a pointer, we need to wrap it into an object.
/// </summary>
public sealed class Pointer
{
private unsafe void* _ptr;
private Type _ptrType;
private Pointer()
{
}
#region Methods
/// <summary>
/// Boxes the supplied unmanaged memory pointer and the type associated with that pointer into a managed Pointer wrapper object.
/// The value and the type are saved so they can be accessed from the native code during an invocation.
/// </summary>
/// <param name="ptr"></param>
/// <param name="type"></param>
/// <returns></returns>
public static unsafe object Box(void* ptr, Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (!type.IsPointer)
{
throw new ArgumentException("Argument must be pointer", "ptr");
}
Pointer pointer = new Pointer();
pointer._ptr = ptr;
pointer._ptrType = type;
return pointer;
}
/// <summary>
/// Returns the stored pointer.
/// </summary>
/// <param name="ptr"></param>
/// <returns></returns>
public static unsafe void* Unbox(object ptr)
{
var pointer = ptr as Pointer;
if (pointer == null)
{
throw new ArgumentException("Argument must be pointer", "ptr");
}
return ((Pointer)ptr)._ptr;
}
#endregion Methods
}
internal static class ListExtensions
{
internal static void ForEach<T>(this List<T> list, Action<T> action)
{
if (list == null)
{
throw new ArgumentNullException("list");
}
if (action == null)
{
throw new ArgumentNullException("action");
}
for (int i = 0; i < list.Count; i++)
{
action(list[i]);
}
}
}
internal static class X509StoreExtensions
{
/// <summary>
/// X509Store.Close() is not in CoreCLR and it's supposed to be replaced by X509Store.Dispose().
/// However, X509Store.Dispose() is not supported until .NET 4.6. So we have to have this extension
/// method 'Close' for X509Store for OneCore powershell, so that it works for both Full/Core CLR.
/// </summary>
internal static void Close(this System.Security.Cryptography.X509Certificates.X509Store x509Store)
{
x509Store.Dispose();
}
}
#endregion Misc extensions
}
namespace Microsoft.PowerShell.CoreCLR
{
using System.IO;
using System.Management.Automation;
/// <summary>
/// AssemblyExtensions
/// </summary>
public static class AssemblyExtensions
{
/// <summary>
/// Load an assembly given its file path.
/// </summary>
/// <param name="assemblyPath">The path of the file that contains the manifest of the assembly.</param>
/// <returns>The loaded assembly.</returns>
public static Assembly LoadFrom(string assemblyPath)
{
return ClrFacade.LoadFrom(assemblyPath);
}
/// <summary>
/// Load an assembly given its byte stream
/// </summary>
/// <param name="assembly">The byte stream of assembly</param>
/// <returns>The loaded assembly</returns>
public static Assembly LoadFrom(Stream assembly)
{
return ClrFacade.LoadFrom(assembly);
}
}
}
#endif
| |
// OutputWindow.cs
//
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// *************************************************************************
//
// Name: OutputWindow.cs
//
// Created: 19-02-2008 SharedCache.com, rschuetz
// Modified: 19-02-2008 SharedCache.com, rschuetz : Creation
// *************************************************************************
using System;
namespace SharedCache.WinServiceCommon.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// Contains the output from the Inflation process.
/// We need to have a window so that we can refer backwards into the output stream
/// to repeat stuff.<br/>
/// Author of the original java version : John Leuner
/// </summary>
public class OutputWindow
{
#region Constants
const int WindowSize = 1 << 15;
const int WindowMask = WindowSize - 1;
#endregion
#region Instance Fields
byte[] window = new byte[WindowSize]; //The window is 2^15 bytes
int windowEnd;
int windowFilled;
#endregion
/// <summary>
/// Write a byte to this output window
/// </summary>
/// <param name="value">value to write</param>
/// <exception cref="InvalidOperationException">
/// if window is full
/// </exception>
public void Write(int value)
{
if (windowFilled++ == WindowSize)
{
throw new InvalidOperationException("Window full");
}
window[windowEnd++] = (byte)value;
windowEnd &= WindowMask;
}
private void SlowRepeat(int repStart, int length, int distance)
{
while (length-- > 0)
{
window[windowEnd++] = window[repStart++];
windowEnd &= WindowMask;
repStart &= WindowMask;
}
}
/// <summary>
/// Append a byte pattern already in the window itself
/// </summary>
/// <param name="length">length of pattern to copy</param>
/// <param name="distance">distance from end of window pattern occurs</param>
/// <exception cref="InvalidOperationException">
/// If the repeated data overflows the window
/// </exception>
public void Repeat(int length, int distance)
{
if ((windowFilled += length) > WindowSize)
{
throw new InvalidOperationException("Window full");
}
int repStart = (windowEnd - distance) & WindowMask;
int border = WindowSize - length;
if ((repStart <= border) && (windowEnd < border))
{
if (length <= distance)
{
System.Array.Copy(window, repStart, window, windowEnd, length);
windowEnd += length;
}
else
{
// We have to copy manually, since the repeat pattern overlaps.
while (length-- > 0)
{
window[windowEnd++] = window[repStart++];
}
}
}
else
{
SlowRepeat(repStart, length, distance);
}
}
/// <summary>
/// Copy from input manipulator to internal window
/// </summary>
/// <param name="input">source of data</param>
/// <param name="length">length of data to copy</param>
/// <returns>the number of bytes copied</returns>
public int CopyStored(StreamManipulator input, int length)
{
length = Math.Min(Math.Min(length, WindowSize - windowFilled), input.AvailableBytes);
int copied;
int tailLen = WindowSize - windowEnd;
if (length > tailLen)
{
copied = input.CopyBytes(window, windowEnd, tailLen);
if (copied == tailLen)
{
copied += input.CopyBytes(window, 0, length - tailLen);
}
}
else
{
copied = input.CopyBytes(window, windowEnd, length);
}
windowEnd = (windowEnd + copied) & WindowMask;
windowFilled += copied;
return copied;
}
/// <summary>
/// Copy dictionary to window
/// </summary>
/// <param name="dictionary">source dictionary</param>
/// <param name="offset">offset of start in source dictionary</param>
/// <param name="length">length of dictionary</param>
/// <exception cref="InvalidOperationException">
/// If window isnt empty
/// </exception>
public void CopyDict(byte[] dictionary, int offset, int length)
{
if (dictionary == null)
{
throw new ArgumentNullException("dictionary");
}
if (windowFilled > 0)
{
throw new InvalidOperationException();
}
if (length > WindowSize)
{
offset += length - WindowSize;
length = WindowSize;
}
System.Array.Copy(dictionary, offset, window, 0, length);
windowEnd = length & WindowMask;
}
/// <summary>
/// Get remaining unfilled space in window
/// </summary>
/// <returns>Number of bytes left in window</returns>
public int GetFreeSpace()
{
return WindowSize - windowFilled;
}
/// <summary>
/// Get bytes available for output in window
/// </summary>
/// <returns>Number of bytes filled</returns>
public int GetAvailable()
{
return windowFilled;
}
/// <summary>
/// Copy contents of window to output
/// </summary>
/// <param name="output">buffer to copy to</param>
/// <param name="offset">offset to start at</param>
/// <param name="len">number of bytes to count</param>
/// <returns>The number of bytes copied</returns>
/// <exception cref="InvalidOperationException">
/// If a window underflow occurs
/// </exception>
public int CopyOutput(byte[] output, int offset, int len)
{
int copyEnd = windowEnd;
if (len > windowFilled)
{
len = windowFilled;
}
else
{
copyEnd = (windowEnd - windowFilled + len) & WindowMask;
}
int copied = len;
int tailLen = len - copyEnd;
if (tailLen > 0)
{
System.Array.Copy(window, WindowSize - tailLen, output, offset, tailLen);
offset += tailLen;
len = copyEnd;
}
System.Array.Copy(window, copyEnd - len, output, offset, len);
windowFilled -= copied;
if (windowFilled < 0)
{
throw new InvalidOperationException();
}
return copied;
}
/// <summary>
/// Reset by clearing window so <see cref="GetAvailable">GetAvailable</see> returns 0
/// </summary>
public void Reset()
{
windowFilled = windowEnd = 0;
}
}
}
| |
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Directory = Lucene.Net.Store.Directory;
/// <summary>
/// An <see cref="IndexDeletionPolicy"/> that wraps any other
/// <see cref="IndexDeletionPolicy"/> and adds the ability to hold and later release
/// snapshots of an index. While a snapshot is held, the <see cref="IndexWriter"/> will
/// not remove any files associated with it even if the index is otherwise being
/// actively, arbitrarily changed. Because we wrap another arbitrary
/// <see cref="IndexDeletionPolicy"/>, this gives you the freedom to continue using
/// whatever <see cref="IndexDeletionPolicy"/> you would normally want to use with your
/// index.
///
/// <para/>
/// This class maintains all snapshots in-memory, and so the information is not
/// persisted and not protected against system failures. If persistence is
/// important, you can use <see cref="PersistentSnapshotDeletionPolicy"/>.
/// <para/>
/// @lucene.experimental
/// </summary>
public class SnapshotDeletionPolicy : IndexDeletionPolicy
{
/// <summary>
/// Records how many snapshots are held against each
/// commit generation
/// </summary>
protected IDictionary<long, int> m_refCounts = new Dictionary<long, int>();
/// <summary>
/// Used to map gen to <see cref="IndexCommit"/>. </summary>
protected IDictionary<long?, IndexCommit> m_indexCommits = new Dictionary<long?, IndexCommit>();
/// <summary>
/// Wrapped <see cref="IndexDeletionPolicy"/> </summary>
private IndexDeletionPolicy primary;
/// <summary>
/// Most recently committed <see cref="IndexCommit"/>. </summary>
protected IndexCommit m_lastCommit;
/// <summary>
/// Used to detect misuse </summary>
private bool initCalled;
/// <summary>
/// Sole constructor, taking the incoming
/// <see cref="IndexDeletionPolicy"/> to wrap.
/// </summary>
public SnapshotDeletionPolicy(IndexDeletionPolicy primary)
{
this.primary = primary;
}
public override void OnCommit<T>(IList<T> commits)
{
lock (this)
{
primary.OnCommit(WrapCommits(commits));
m_lastCommit = commits[commits.Count - 1];
}
}
public override void OnInit<T>(IList<T> commits)
{
lock (this)
{
initCalled = true;
primary.OnInit(WrapCommits(commits));
foreach (IndexCommit commit in commits)
{
if (m_refCounts.ContainsKey(commit.Generation))
{
m_indexCommits[commit.Generation] = commit;
}
}
if (commits.Count > 0)
{
m_lastCommit = commits[commits.Count - 1];
}
}
}
/// <summary>
/// Release a snapshotted commit.
/// </summary>
/// <param name="commit">
/// the commit previously returned by <see cref="Snapshot()"/> </param>
public virtual void Release(IndexCommit commit)
{
lock (this)
{
long gen = commit.Generation;
ReleaseGen(gen);
}
}
/// <summary>
/// Release a snapshot by generation. </summary>
protected internal virtual void ReleaseGen(long gen)
{
if (!initCalled)
{
throw new InvalidOperationException("this instance is not being used by IndexWriter; be sure to use the instance returned from writer.getConfig().getIndexDeletionPolicy()");
}
int? refCount = m_refCounts[gen];
if (refCount == null)
{
throw new ArgumentException("commit gen=" + gen + " is not currently snapshotted");
}
int refCountInt = (int)refCount;
if (Debugging.AssertsEnabled) Debugging.Assert(refCountInt > 0);
refCountInt--;
if (refCountInt == 0)
{
m_refCounts.Remove(gen);
m_indexCommits.Remove(gen);
}
else
{
m_refCounts[gen] = refCountInt;
}
}
/// <summary>
/// Increments the refCount for this <see cref="IndexCommit"/>. </summary>
protected internal virtual void IncRef(IndexCommit ic)
{
lock (this)
{
long gen = ic.Generation;
int refCount;
int refCountInt;
if (!m_refCounts.TryGetValue(gen, out refCount))
{
m_indexCommits[gen] = m_lastCommit;
refCountInt = 0;
}
else
{
refCountInt = (int)refCount;
}
m_refCounts[gen] = refCountInt + 1;
}
}
/// <summary>
/// Snapshots the last commit and returns it. Once a commit is 'snapshotted,' it is protected
/// from deletion (as long as this <see cref="IndexDeletionPolicy"/> is used). The
/// snapshot can be removed by calling <see cref="Release(IndexCommit)"/> followed
/// by a call to <see cref="IndexWriter.DeleteUnusedFiles()"/>.
///
/// <para/>
/// <b>NOTE:</b> while the snapshot is held, the files it references will not
/// be deleted, which will consume additional disk space in your index. If you
/// take a snapshot at a particularly bad time (say just before you call
/// <see cref="IndexWriter.ForceMerge(int)"/>) then in the worst case this could consume an extra 1X of your
/// total index size, until you release the snapshot.
/// </summary>
/// <exception cref="InvalidOperationException">
/// if this index does not have any commits yet </exception>
/// <returns> the <see cref="IndexCommit"/> that was snapshotted. </returns>
public virtual IndexCommit Snapshot()
{
lock (this)
{
if (!initCalled)
{
throw new InvalidOperationException("this instance is not being used by IndexWriter; be sure to use the instance returned from writer.getConfig().getIndexDeletionPolicy()");
}
if (m_lastCommit == null)
{
// No commit yet, eg this is a new IndexWriter:
throw new InvalidOperationException("No index commit to snapshot");
}
IncRef(m_lastCommit);
return m_lastCommit;
}
}
/// <summary>
/// Returns all <see cref="IndexCommit"/>s held by at least one snapshot. </summary>
public virtual IList<IndexCommit> GetSnapshots()
{
lock (this)
{
return new List<IndexCommit>(m_indexCommits.Values);
}
}
/// <summary>
/// Returns the total number of snapshots currently held. </summary>
public virtual int SnapshotCount
{
get
{
lock (this)
{
int total = 0;
foreach (var refCount in m_refCounts.Values)
{
total += refCount;
}
return total;
}
}
}
/// <summary>
/// Retrieve an <see cref="IndexCommit"/> from its generation;
/// returns <c>null</c> if this <see cref="IndexCommit"/> is not currently
/// snapshotted
/// </summary>
public virtual IndexCommit GetIndexCommit(long gen)
{
lock (this)
{
return m_indexCommits[gen];
}
}
public override object Clone()
{
lock (this)
{
SnapshotDeletionPolicy other = (SnapshotDeletionPolicy)base.Clone();
other.primary = (IndexDeletionPolicy)this.primary.Clone();
other.m_lastCommit = null;
other.m_refCounts = new Dictionary<long, int>(m_refCounts);
other.m_indexCommits = new Dictionary<long?, IndexCommit>(m_indexCommits);
return other;
}
}
/// <summary>
/// Wraps each <see cref="IndexCommit"/> as a
/// <see cref="SnapshotCommitPoint"/>.
/// </summary>
private IList<IndexCommit> WrapCommits<T>(IList<T> commits)
where T : IndexCommit
{
IList<IndexCommit> wrappedCommits = new List<IndexCommit>(commits.Count);
foreach (IndexCommit ic in commits)
{
wrappedCommits.Add(new SnapshotCommitPoint(this, ic));
}
return wrappedCommits;
}
/// <summary>
/// Wraps a provided <see cref="IndexCommit"/> and prevents it
/// from being deleted.
/// </summary>
private class SnapshotCommitPoint : IndexCommit
{
private readonly SnapshotDeletionPolicy outerInstance;
/// <summary>
/// The <see cref="IndexCommit"/> we are preventing from deletion. </summary>
protected IndexCommit m_cp;
/// <summary>
/// Creates a <see cref="SnapshotCommitPoint"/> wrapping the provided
/// <see cref="IndexCommit"/>.
/// </summary>
protected internal SnapshotCommitPoint(SnapshotDeletionPolicy outerInstance, IndexCommit cp)
{
this.outerInstance = outerInstance;
this.m_cp = cp;
}
public override string ToString()
{
return "SnapshotDeletionPolicy.SnapshotCommitPoint(" + m_cp + ")";
}
public override void Delete()
{
lock (outerInstance)
{
// Suppress the delete request if this commit point is
// currently snapshotted.
if (!outerInstance.m_refCounts.ContainsKey(m_cp.Generation))
{
m_cp.Delete();
}
}
}
public override Directory Directory => m_cp.Directory;
public override ICollection<string> FileNames => m_cp.FileNames;
public override long Generation => m_cp.Generation;
public override string SegmentsFileName => m_cp.SegmentsFileName;
public override IDictionary<string, string> UserData => m_cp.UserData;
public override bool IsDeleted => m_cp.IsDeleted;
public override int SegmentCount => m_cp.SegmentCount;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Security
{
public abstract class AuthenticatedStream : System.IO.Stream
{
protected AuthenticatedStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen) { }
public abstract bool IsAuthenticated { get; }
public abstract bool IsEncrypted { get; }
public abstract bool IsMutuallyAuthenticated { get; }
public abstract bool IsServer { get; }
public abstract bool IsSigned { get; }
public bool LeaveInnerStreamOpen { get { throw null; } }
protected System.IO.Stream InnerStream { get { throw null; } }
protected override void Dispose(bool disposing) { }
}
public enum EncryptionPolicy
{
AllowNoEncryption = 1,
NoEncryption = 2,
RequireEncryption = 0,
}
public delegate System.Security.Cryptography.X509Certificates.X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection localCertificates, System.Security.Cryptography.X509Certificates.X509Certificate remoteCertificate, string[] acceptableIssuers);
public partial class NegotiateStream : AuthenticatedStream
{
public NegotiateStream(System.IO.Stream innerStream) : base(innerStream, false) { }
public NegotiateStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen) : base(innerStream, leaveInnerStreamOpen) { }
public override bool CanRead { get { throw null; } }
public override bool CanSeek { get { throw null; } }
public override bool CanTimeout { get { throw null; } }
public override bool CanWrite { get { throw null; } }
public virtual System.Security.Principal.TokenImpersonationLevel ImpersonationLevel { get { throw null; } }
public override bool IsAuthenticated { get { throw null; } }
public override bool IsEncrypted { get { throw null; } }
public override bool IsMutuallyAuthenticated { get { throw null; } }
public override bool IsServer { get { throw null; } }
public override bool IsSigned { get { throw null; } }
public override long Length { get { throw null; } }
public override long Position { get { throw null; } set { } }
public override int ReadTimeout { get { throw null; } set { } }
public virtual System.Security.Principal.IIdentity RemoteIdentity { get { throw null; } }
public override int WriteTimeout { get { throw null; } set { } }
public virtual void AuthenticateAsClient() { }
public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, string targetName) { }
public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName) { }
public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { }
public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { }
public virtual void AuthenticateAsServer() { }
public virtual void AuthenticateAsServer(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy) { }
public virtual void AuthenticateAsServer(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { }
public virtual void AuthenticateAsServer(NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { }
public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync() { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName) { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName) { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync() { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy) { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsClient(System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsServer(AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual IAsyncResult BeginAuthenticateAsServer(System.Net.NetworkCredential credential, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual IAsyncResult BeginAuthenticateAsServer(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { throw null; }
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { throw null; }
protected override void Dispose(bool disposing) { }
public virtual void EndAuthenticateAsClient(System.IAsyncResult asyncResult) { }
public virtual void EndAuthenticateAsServer(System.IAsyncResult asyncResult) { }
public override int EndRead(IAsyncResult asyncResult) { throw null; }
public override void EndWrite(IAsyncResult asyncResult) { }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
public override int Read(byte[] buffer, int offset, int count) { throw null; }
public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; }
public override void SetLength(long value) { }
public override void Write(byte[] buffer, int offset, int count) { }
}
public enum ProtectionLevel
{
None = 0,
Sign = 1,
EncryptAndSign = 2
}
public delegate bool RemoteCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors);
public class SslServerAuthenticationOptions
{
public bool AllowRenegotiation { get { throw null; } set { } }
public X509Certificate ServerCertificate { get { throw null; } set { } }
public bool ClientCertificateRequired { get { throw null; } set { } }
public SslProtocols EnabledSslProtocols { get { throw null; } set { } }
public X509RevocationMode CertificateRevocationCheckMode { get { throw null; } set { } }
public List<SslApplicationProtocol> ApplicationProtocols { get { throw null; } set { } }
public RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get { throw null; } set { } }
public EncryptionPolicy EncryptionPolicy { get { throw null; } set { } }
}
public partial class SslClientAuthenticationOptions
{
public bool AllowRenegotiation { get { throw null; } set { } }
public string TargetHost { get { throw null; } set { } }
public X509CertificateCollection ClientCertificates { get { throw null; } set { } }
public LocalCertificateSelectionCallback LocalCertificateSelectionCallback { get { throw null; } set { } }
public SslProtocols EnabledSslProtocols { get { throw null; } set { } }
public X509RevocationMode CertificateRevocationCheckMode { get { throw null; } set { } }
public List<SslApplicationProtocol> ApplicationProtocols { get { throw null; } set { } }
public RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get { throw null; } set { } }
public EncryptionPolicy EncryptionPolicy { get { throw null; } set { } }
}
public readonly partial struct SslApplicationProtocol : IEquatable<SslApplicationProtocol>
{
private readonly object _dummy;
public static readonly SslApplicationProtocol Http2;
public static readonly SslApplicationProtocol Http11;
public SslApplicationProtocol(byte[] protocol) { throw null; }
public SslApplicationProtocol(string protocol) { throw null; }
public ReadOnlyMemory<byte> Protocol { get { throw null; } }
public bool Equals(SslApplicationProtocol other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override string ToString() { throw null; }
public static bool operator ==(SslApplicationProtocol left, SslApplicationProtocol right) { throw null; }
public static bool operator !=(SslApplicationProtocol left, SslApplicationProtocol right) { throw null; }
}
public partial class SslStream : AuthenticatedStream
{
public SslStream(System.IO.Stream innerStream) : base(innerStream, false) { }
public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen) : base(innerStream, leaveInnerStreamOpen) { }
public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback userCertificateValidationCallback) : base(innerStream, leaveInnerStreamOpen) { }
public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback userCertificateSelectionCallback) : base(innerStream, leaveInnerStreamOpen) { }
public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback userCertificateSelectionCallback, System.Net.Security.EncryptionPolicy encryptionPolicy) : base(innerStream, leaveInnerStreamOpen) { }
public SslApplicationProtocol NegotiatedApplicationProtocol { get { throw null; } }
public override bool CanRead { get { throw null; } }
public override bool CanSeek { get { throw null; } }
public override bool CanTimeout { get { throw null; } }
public override bool CanWrite { get { throw null; } }
public virtual bool CheckCertRevocationStatus { get { throw null; } }
public virtual System.Security.Authentication.CipherAlgorithmType CipherAlgorithm { get { throw null; } }
public virtual int CipherStrength { get { throw null; } }
public virtual System.Security.Authentication.HashAlgorithmType HashAlgorithm { get { throw null; } }
public virtual int HashStrength { get { throw null; } }
public override bool IsAuthenticated { get { throw null; } }
public override bool IsEncrypted { get { throw null; } }
public override bool IsMutuallyAuthenticated { get { throw null; } }
public override bool IsServer { get { throw null; } }
public override bool IsSigned { get { throw null; } }
public virtual System.Security.Authentication.ExchangeAlgorithmType KeyExchangeAlgorithm { get { throw null; } }
public virtual int KeyExchangeStrength { get { throw null; } }
public override long Length { get { throw null; } }
public virtual System.Security.Cryptography.X509Certificates.X509Certificate LocalCertificate { get { throw null; } }
public override long Position { get { throw null; } set { } }
public override int ReadTimeout { get { throw null; } set { } }
public virtual System.Security.Cryptography.X509Certificates.X509Certificate RemoteCertificate { get { throw null; } }
public virtual System.Security.Authentication.SslProtocols SslProtocol { get { throw null; } }
public System.Net.TransportContext TransportContext { get { throw null; } }
public override int WriteTimeout { get { throw null; } set { } }
public virtual void AuthenticateAsClient(string targetHost) { }
public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { }
public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, bool checkCertificateRevocation) { }
public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate) { }
public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { }
public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { }
public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost) { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, bool checkCertificateRevocation) { throw null; }
public Task AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken) { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate) { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { throw null; }
public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { throw null; }
public Task AuthenticateAsServerAsync(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, bool checkCertificateRevocation, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { throw null; }
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { throw null; }
protected override void Dispose(bool disposing) { }
public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult) { }
public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult) { }
public override int EndRead(IAsyncResult asyncResult) { throw null; }
public override void EndWrite(IAsyncResult asyncResult) { }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
public override int Read(byte[] buffer, int offset, int count) { throw null; }
public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; }
public override void SetLength(long value) { }
public virtual System.Threading.Tasks.Task ShutdownAsync() { throw null; }
public void Write(byte[] buffer) { }
public override void Write(byte[] buffer, int offset, int count) { }
}
}
namespace System.Security.Authentication
{
public partial class AuthenticationException : System.SystemException
{
public AuthenticationException() { }
public AuthenticationException(string message) { }
public AuthenticationException(string message, System.Exception innerException) { }
protected AuthenticationException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
}
public partial class InvalidCredentialException : System.Security.Authentication.AuthenticationException
{
public InvalidCredentialException() { }
public InvalidCredentialException(string message) { }
public InvalidCredentialException(string message, System.Exception innerException) { }
protected InvalidCredentialException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
}
}
namespace System.Security.Authentication.ExtendedProtection
{
public partial class ExtendedProtectionPolicy : System.Runtime.Serialization.ISerializable
{
public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement) { }
public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ChannelBinding customChannelBinding) { }
public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ProtectionScenario protectionScenario, System.Collections.ICollection customServiceNames) { }
public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ProtectionScenario protectionScenario, System.Security.Authentication.ExtendedProtection.ServiceNameCollection customServiceNames) { }
protected ExtendedProtectionPolicy(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public System.Security.Authentication.ExtendedProtection.ChannelBinding CustomChannelBinding { get { throw null; } }
public System.Security.Authentication.ExtendedProtection.ServiceNameCollection CustomServiceNames { get { throw null; } }
public static bool OSSupportsExtendedProtection { get { throw null; } }
public System.Security.Authentication.ExtendedProtection.PolicyEnforcement PolicyEnforcement { get { throw null; } }
public System.Security.Authentication.ExtendedProtection.ProtectionScenario ProtectionScenario { get { throw null; } }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public override string ToString() { throw null; }
}
public enum PolicyEnforcement
{
Always = 2,
Never = 0,
WhenSupported = 1,
}
public enum ProtectionScenario
{
TransportSelected = 0,
TrustedProxy = 1,
}
public partial class ServiceNameCollection : System.Collections.ReadOnlyCollectionBase
{
public ServiceNameCollection(System.Collections.ICollection items) { }
public bool Contains(string searchServiceName) { throw null; }
public System.Security.Authentication.ExtendedProtection.ServiceNameCollection Merge(System.Collections.IEnumerable serviceNames) { throw null; }
public System.Security.Authentication.ExtendedProtection.ServiceNameCollection Merge(string serviceName) { throw null; }
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using GameDataEditor;
public class GDESchemaManagerWindow : GDEManagerWindowBase {
private string newSchemaName = string.Empty;
private Dictionary<string, int> basicFieldTypeSelectedDict = new Dictionary<string, int>();
private Dictionary<string, int> customSchemaTypeSelectedDict = new Dictionary<string, int>();
private Dictionary<string, string> newBasicFieldName = new Dictionary<string, string>();
private HashSet<string> isBasicList = new HashSet<string>();
private HashSet<string> isBasic2DList = new HashSet<string>();
private Dictionary<string, string> newCustomFieldName = new Dictionary<string, string>();
private HashSet<string> isCustomList = new HashSet<string>();
private HashSet<string> isCustom2DList = new HashSet<string>();
private List<string> deletedFields = new List<string>();
private Dictionary<List<string>, Dictionary<string, object>> renamedFields = new Dictionary<List<string>, Dictionary<string, object>>();
private Dictionary<string, string> renamedSchemas = new Dictionary<string, string>();
#region OnGUI/Header Methods
protected override void OnGUI()
{
mainHeaderText = GDEConstants.DefineDataHeader;
// Set the header color
headerColor = GDESettings.Instance.DefineDataColor.ToColor();
headerColor.a = 1f;
if (shouldRebuildEntriesList || entriesToDraw == null || GDEItemManager.ShouldReloadSchemas)
{
entriesToDraw = GetEntriesToDraw(GDEItemManager.AllSchemas);
shouldRebuildEntriesList = false;
shouldRecalculateHeights = true;
GDEItemManager.ShouldReloadSchemas = false;
}
base.OnGUI();
DrawExpandCollapseAllFoldout(GDEItemManager.AllSchemas.Keys.ToArray(), GDEConstants.SchemaListHeader);
float currentGroupHeightTotal = CalculateGroupHeightsTotal();
scrollViewHeight = drawHelper.HeightToBottomOfWindow();
scrollViewY = drawHelper.TopOfLine();
verticalScrollbarPosition = GUI.BeginScrollView(new Rect(drawHelper.CurrentLinePosition, scrollViewY, drawHelper.FullWindowWidth(), scrollViewHeight),
verticalScrollbarPosition,
new Rect(drawHelper.CurrentLinePosition, scrollViewY, drawHelper.ScrollViewWidth(), currentGroupHeightTotal));
foreach(KeyValuePair<string, Dictionary<string, object>> schema in entriesToDraw)
{
float currentGroupHeight;
if (!groupHeights.TryGetValue(schema.Key, out currentGroupHeight))
currentGroupHeight = GDEConstants.LineHeight;
if (drawHelper.IsVisible(verticalScrollbarPosition, scrollViewHeight, scrollViewY, currentGroupHeight) <= 0)
DrawEntry(schema.Key, schema.Value);
else
{
drawHelper.NewLine(currentGroupHeight/GDEConstants.LineHeight);
}
}
GUI.EndScrollView();
// Remove any schemas that were deleted
foreach(string deletedSchemaKey in deleteEntries)
Remove(deletedSchemaKey);
deleteEntries.Clear();
// Rename any schemas that were renamed
string error;
foreach(KeyValuePair<string, string> pair in renamedSchemas)
{
if (!GDEItemManager.RenameSchema(pair.Key, pair.Value, out error))
EditorUtility.DisplayDialog(GDEConstants.ErrorLbl, string.Format(GDEConstants.CouldNotRenameFormat, pair.Key, pair.Value, error), GDEConstants.OkLbl);
}
renamedSchemas.Clear();
// Clone any schemas
foreach(string schemaKey in cloneEntries)
Clone(schemaKey);
cloneEntries.Clear();
}
#endregion
#region Draw Methods
protected override void DrawCreateSection()
{
float topOfSection = drawHelper.TopOfLine() + 4f;
float bottomOfSection = 0;
float leftBoundary = 0;
drawHelper.DrawSubHeader(GDEConstants.CreateNewSchemaHeader, headerColor, GDEConstants.SizeCreateSubHeaderKey);
size.x = 100;
GUI.Label(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), GDEConstants.SchemaNameLbl);
drawHelper.CurrentLinePosition += (size.x + 2);
if (drawHelper.CurrentLinePosition > leftBoundary)
leftBoundary = drawHelper.CurrentLinePosition;
size.x = 120;
newSchemaName = EditorGUI.TextField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), newSchemaName);
drawHelper.CurrentLinePosition += (size.x + 2);
if (drawHelper.CurrentLinePosition > leftBoundary)
leftBoundary = drawHelper.CurrentLinePosition;
content.text = GDEConstants.CreateNewSchemaBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeCreateNewSchemaBtnKey, content, GUI.skin.button, out size);
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
{
if (Create(newSchemaName))
{
newSchemaName = string.Empty;
GUI.FocusControl(string.Empty);
}
}
drawHelper.CurrentLinePosition += (size.x + 6f);
if (drawHelper.CurrentLinePosition > leftBoundary)
leftBoundary = drawHelper.CurrentLinePosition;
drawHelper.NewLine();
bottomOfSection = drawHelper.TopOfLine();
drawHelper.DrawSectionSeparator();
leftBoundary += 5f;
// Draw rate box
Vector2 forumLinkSize;
Vector2 rateLinkSize;
content.text = GDEConstants.ForumLinkText;
drawHelper.TryGetCachedSize(GDEConstants.SizeForumLinkTextKey, content, linkStyle, out forumLinkSize);
content.text = GDEConstants.RateMeText;
drawHelper.TryGetCachedSize(GDEConstants.SizeRateMeTextKey, content, linkStyle, out rateLinkSize);
float boxWidth = Math.Max(forumLinkSize.x, rateLinkSize.x);
content.text = GDEConstants.ForumLinkText;
if (GUI.Button(new Rect(leftBoundary+(boxWidth-forumLinkSize.x)/2f+5.5f, bottomOfSection-size.y-10f, forumLinkSize.x, forumLinkSize.y), content, linkStyle))
{
Application.OpenURL(GDEConstants.ForumURL);
}
content.text = GDEConstants.RateMeText;
if(GUI.Button(new Rect(leftBoundary+(boxWidth-rateLinkSize.x)/2f+5.5f, topOfSection+10f, rateLinkSize.x, rateLinkSize.y), content, linkStyle))
{
Application.OpenURL(GDEConstants.RateMeURL);
}
DrawRateBox(leftBoundary, topOfSection, boxWidth+10f, bottomOfSection-topOfSection);
}
private void DrawAddFieldSection(string schemaKey, Dictionary<string, object> schemaData)
{
drawHelper.CurrentLinePosition += GDEConstants.Indent;
content.text = GDEConstants.NewFieldHeader;
drawHelper.TryGetCachedSize(GDEConstants.SizeNewFieldHeaderKey, content, labelStyle, out size);
GUI.Label(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content, labelStyle);
drawHelper.NewLine();
drawHelper.CurrentLinePosition += GDEConstants.Indent;
// ***** Basic Field Type Group ***** //
size.x = 120;
GUI.Label(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), GDEConstants.BasicFieldTypeLbl);
drawHelper.CurrentLinePosition += (size.x + 2);
// Basic field type selected
int basicFieldTypeIndex;
if (!basicFieldTypeSelectedDict.TryGetValue(schemaKey, out basicFieldTypeIndex))
{
basicFieldTypeIndex = 0;
basicFieldTypeSelectedDict.TryAddValue(schemaKey, basicFieldTypeIndex);
}
size.x = 80;
int newBasicFieldTypeIndex = EditorGUI.Popup(new Rect(drawHelper.CurrentLinePosition, drawHelper.PopupTop(), size.x, drawHelper.StandardHeight()), basicFieldTypeIndex, GDEItemManager.BasicFieldTypeStringArray);
drawHelper.CurrentLinePosition += (size.x + 6);
if (newBasicFieldTypeIndex != basicFieldTypeIndex && GDEItemManager.BasicFieldTypeStringArray.IsValidIndex(newBasicFieldTypeIndex))
{
basicFieldTypeIndex = newBasicFieldTypeIndex;
basicFieldTypeSelectedDict.TryAddOrUpdateValue(schemaKey, basicFieldTypeIndex);
}
// Basic field type name field
string newBasicFieldNameText = string.Empty;
if (!newBasicFieldName.TryGetValue(schemaKey, out newBasicFieldNameText))
{
newBasicFieldName.Add(schemaKey, string.Empty);
newBasicFieldNameText = string.Empty;
}
size.x = 70;
GUI.Label(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), GDEConstants.FieldNameLbl);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 120;
newBasicFieldNameText = EditorGUI.TextField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), newBasicFieldNameText);
drawHelper.CurrentLinePosition += (size.x + 6);
if (!newBasicFieldNameText.Equals(newBasicFieldName[schemaKey]))
newBasicFieldName[schemaKey] = newBasicFieldNameText;
// Basic field type isList checkbox
bool isBasicListTemp = isBasicList.Contains(schemaKey);
content.text = GDEConstants.IsListLbl;
drawHelper.TryGetCachedSize(GDEConstants.SizeIsListLblKey, content, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 15;
isBasicListTemp = EditorGUI.Toggle(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), isBasicListTemp);
drawHelper.CurrentLinePosition += (size.x + 6);
if (isBasicListTemp && !isBasicList.Contains(schemaKey))
{
isBasicList.Add(schemaKey);
// Turn 2D List off
isBasic2DList.Remove(schemaKey);
}
else if (!isBasicListTemp && isBasicList.Contains(schemaKey))
isBasicList.Remove(schemaKey);
// Basic field type is2DList checkbox
bool isBasic2DListTemp = isBasic2DList.Contains(schemaKey);
content.text = GDEConstants.Is2DListLbl;
drawHelper.TryGetCachedSize(GDEConstants.SizeIs2DListLblKey, content, EditorStyles.label, out size);
GUI.Label(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), content);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 15;
isBasic2DListTemp = EditorGUI.Toggle(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), isBasic2DListTemp);
drawHelper.CurrentLinePosition += (size.x + 6);
if (isBasic2DListTemp && !isBasic2DList.Contains(schemaKey))
{
isBasic2DList.Add(schemaKey);
// Turn off 1D List
isBasicList.Remove(schemaKey);
}
else if (!isBasic2DListTemp && isBasic2DList.Contains(schemaKey))
isBasic2DList.Remove(schemaKey);
content.text = GDEConstants.AddFieldBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeAddFieldBtnKey, content, GUI.skin.button, out size);
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
{
if (AddBasicField(GDEItemManager.BasicFieldTypes[basicFieldTypeIndex], schemaKey, schemaData, newBasicFieldNameText, isBasicListTemp, isBasic2DListTemp))
{
isBasicList.Remove(schemaKey);
newBasicFieldName.TryAddOrUpdateValue(schemaKey, string.Empty);
newBasicFieldNameText = string.Empty;
GUI.FocusControl(string.Empty);
}
}
drawHelper.NewLine();
// ****** Custom Field Type Group ****** //
drawHelper.CurrentLinePosition += GDEConstants.Indent;
size.x = 120;
GUI.Label(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), GDEConstants.CustomFieldTypeLbl);
drawHelper.CurrentLinePosition += (size.x + 2);
List<string> customTypeList = GDEItemManager.AllSchemas.Keys.ToList();
customTypeList.Remove(schemaKey);
string[] customTypes = customTypeList.ToArray();
int customSchemaTypeIndex;
if (!customSchemaTypeSelectedDict.TryGetValue(schemaKey, out customSchemaTypeIndex))
{
customSchemaTypeIndex = 0;
customSchemaTypeSelectedDict.TryAddValue(schemaKey, customSchemaTypeIndex);
}
// Custom schema type selected
size.x = 80;
int newCustomSchemaTypeSelected = EditorGUI.Popup(new Rect(drawHelper.CurrentLinePosition, drawHelper.PopupTop(), size.x, drawHelper.StandardHeight()), customSchemaTypeIndex, customTypes);
drawHelper.CurrentLinePosition += (size.x + 6);
if (newCustomSchemaTypeSelected != customSchemaTypeIndex && customTypes.IsValidIndex(newCustomSchemaTypeSelected))
{
customSchemaTypeIndex = newCustomSchemaTypeSelected;
customSchemaTypeSelectedDict.TryAddOrUpdateValue(schemaKey, customSchemaTypeIndex);
}
// Custom field type name field
string newCustomFieldNameText = string.Empty;
if (!newCustomFieldName.TryGetValue(schemaKey, out newCustomFieldNameText))
{
newCustomFieldName.Add(schemaKey, string.Empty);
newCustomFieldNameText = string.Empty;
}
size.x = 70;
GUI.Label(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), GDEConstants.FieldNameLbl);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 120;
newCustomFieldNameText = EditorGUI.TextField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), newCustomFieldNameText);
drawHelper.CurrentLinePosition += (size.x + 6);
if (!newCustomFieldNameText.Equals(newCustomFieldName[schemaKey]))
newCustomFieldName[schemaKey] = newCustomFieldNameText;
// Custom field type isList checkbox
bool isCustomListTemp = isCustomList.Contains(schemaKey);
size.x = 38;
GUI.Label(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), GDEConstants.IsListLbl);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 15;
isCustomListTemp = EditorGUI.Toggle(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), isCustomListTemp);
drawHelper.CurrentLinePosition += (size.x + 6);
if (isCustomListTemp && !isCustomList.Contains(schemaKey))
{
isCustomList.Add(schemaKey);
// Turn off 2D List
isCustom2DList.Remove(schemaKey);
}
else if(!isCustomListTemp && isCustomList.Contains(schemaKey))
isCustomList.Remove(schemaKey);
// Custom field type is2DList checkbox
bool isCustom2DListTemp = isCustom2DList.Contains(schemaKey);
content.text = GDEConstants.Is2DListLbl;
drawHelper.TryGetCachedSize(GDEConstants.SizeIs2DListLblKey, content, EditorStyles.label, out size);
GUI.Label(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 15;
isCustom2DListTemp = EditorGUI.Toggle(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), isCustom2DListTemp);
drawHelper.CurrentLinePosition += (size.x + 6);
if (isCustom2DListTemp && !isCustom2DList.Contains(schemaKey))
{
isCustom2DList.Add(schemaKey);
// Turn off 1D List
isCustomList.Remove(schemaKey);
}
else if (!isCustom2DListTemp && isCustom2DList.Contains(schemaKey))
isCustom2DList.Remove(schemaKey);
content.text = GDEConstants.AddCustomFieldBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeAddCustomFieldBtnKey, content, GUI.skin.button, out size);
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
{
if (!customTypes.IsValidIndex(customSchemaTypeIndex) || customTypes.Length.Equals(0))
{
EditorUtility.DisplayDialog(GDEConstants.ErrorLbl, GDEConstants.InvalidCustomFieldType, GDEConstants.OkLbl);
}
else if (AddCustomField(customTypes[customSchemaTypeIndex], schemaKey, schemaData, newCustomFieldNameText, isCustomListTemp, isCustom2DListTemp))
{
isCustomList.Remove(schemaKey);
newCustomFieldName.TryAddOrUpdateValue(schemaKey, string.Empty);
newCustomFieldNameText = string.Empty;
GUI.FocusControl(string.Empty);
}
}
}
protected override void DrawEntry(string schemaKey, Dictionary<string, object> schemaData)
{
float beginningHeight = drawHelper.CurrentHeight();
// Start drawing below
bool isOpen = DrawFoldout(GDEConstants.SchemaLbl + " ", schemaKey, schemaKey, schemaKey, RenameSchema);
drawHelper.NewLine();
if (isOpen)
{
bool shouldDrawSpace = false;
bool didDrawSpaceForSection = false;
bool isFirstSection = true;
int listDimension = 0;
// Draw the basic types
foreach(BasicFieldType fieldType in GDEItemManager.BasicFieldTypes)
{
List<string> fieldKeys = GDEItemManager.SchemaFieldKeysOfType(schemaKey, fieldType.ToString(), 0);
foreach(string fieldKey in fieldKeys)
{
drawHelper.CurrentLinePosition += GDEConstants.Indent;
DrawSingleField(schemaKey, fieldKey, schemaData);
shouldDrawSpace = true;
isFirstSection = false;
}
}
// Draw the custom types
foreach(string fieldKey in GDEItemManager.SchemaCustomFieldKeys(schemaKey, 0))
{
if (shouldDrawSpace && !didDrawSpaceForSection && !isFirstSection)
{
drawHelper.NewLine(0.5f);
}
drawHelper.CurrentLinePosition += GDEConstants.Indent;
DrawSingleField(schemaKey, fieldKey, schemaData);
shouldDrawSpace = true;
isFirstSection = false;
didDrawSpaceForSection = true;
}
didDrawSpaceForSection = false;
// Draw the lists
for(int dimension=1; dimension <=2; dimension++)
{
foreach(BasicFieldType fieldType in GDEItemManager.BasicFieldTypes)
{
List<string> fieldKeys = GDEItemManager.SchemaFieldKeysOfType(schemaKey, fieldType.ToString(), dimension);
foreach(string fieldKey in fieldKeys)
{
string isListKey = string.Format(GDMConstants.MetaDataFormat, GDMConstants.IsListPrefix, fieldKey);
schemaData.TryGetInt(isListKey, out listDimension);
if (shouldDrawSpace && !didDrawSpaceForSection && !isFirstSection)
{
drawHelper.NewLine(0.5f);
}
drawHelper.CurrentLinePosition += GDEConstants.Indent;
if (listDimension == 1)
DrawListField(schemaKey, schemaData, fieldKey);
else
Draw2DListField(schemaKey, schemaData, fieldKey);
shouldDrawSpace = true;
didDrawSpaceForSection = true;
isFirstSection = false;
}
}
didDrawSpaceForSection = false;
}
// Draw the custom lists
for(int dimension=1; dimension <=2; dimension++)
{
foreach(string fieldKey in GDEItemManager.SchemaCustomFieldKeys(schemaKey, dimension))
{
if (shouldDrawSpace && !didDrawSpaceForSection && !isFirstSection)
{
drawHelper.NewLine(0.5f);
}
drawHelper.CurrentLinePosition += GDEConstants.Indent;
if (dimension == 1)
DrawListField(schemaKey, schemaData, fieldKey);
else
Draw2DListField(schemaKey, schemaData, fieldKey);
shouldDrawSpace = true;
didDrawSpaceForSection = true;
isFirstSection = false;
}
}
didDrawSpaceForSection = false;
drawHelper.NewLine();
DrawAddFieldSection(schemaKey, schemaData);
drawHelper.NewLine(2f);
DrawEntryFooter(GDEConstants.CloneSchema, GDEConstants.SizeCloneSchemaKey, schemaKey);
// Remove any fields that were deleted above
foreach(string deletedKey in deletedFields)
RemoveField(schemaKey, schemaData, deletedKey);
deletedFields.Clear();
// Rename any fields that were renamed
string error;
string oldFieldKey;
string newFieldKey;
foreach(KeyValuePair<List<string>, Dictionary<string, object>> pair in renamedFields)
{
oldFieldKey = pair.Key[0];
newFieldKey = pair.Key[1];
if (!GDEItemManager.RenameSchemaField(oldFieldKey, newFieldKey, schemaKey, pair.Value, out error))
EditorUtility.DisplayDialog(GDEConstants.ErrorLbl, string.Format(GDEConstants.CouldNotRenameFormat, oldFieldKey, newFieldKey, error), GDEConstants.OkLbl);
}
renamedFields.Clear();
}
float newGroupHeight = drawHelper.CurrentHeight() - beginningHeight;
float currentGroupHeight;
groupHeights.TryGetValue(schemaKey, out currentGroupHeight);
if (!newGroupHeight.NearlyEqual(currentGroupHeight))
{
currentGroupHeightTotal -= currentGroupHeight;
currentGroupHeightTotal += newGroupHeight;
}
SetGroupHeight(schemaKey, newGroupHeight);
}
void DrawSingleField(string schemaKey, string fieldKey, Dictionary<string, object> schemaData)
{
string fieldPreviewKey = schemaKey+"_"+fieldKey;
string fieldType;
schemaData.TryGetString(string.Format(GDMConstants.MetaDataFormat, GDMConstants.TypePrefix, fieldKey), out fieldType);
BasicFieldType fieldTypeEnum = BasicFieldType.Undefined;
if (Enum.IsDefined(typeof(BasicFieldType), fieldType))
{
fieldTypeEnum = (BasicFieldType)Enum.Parse(typeof(BasicFieldType), fieldType);
fieldType = GDEItemManager.GetVariableTypeFor(fieldTypeEnum);
}
content.text = fieldType;
drawHelper.TryGetCachedSize(schemaKey+fieldKey+GDEConstants.TypeSuffix, content, labelStyle, out size);
size.x = Math.Max(size.x, GDEConstants.MinLabelWidth);
GUI.Label(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content, labelStyle);
drawHelper.CurrentLinePosition += (size.x + 2);
string editFieldKey = string.Format(GDMConstants.MetaDataFormat, schemaKey, fieldKey);
DrawEditableLabel(fieldKey, editFieldKey, RenameSchemaField, schemaData);
switch(fieldTypeEnum)
{
case BasicFieldType.Bool:
DrawBool(fieldKey, schemaData, GDEConstants.DefaultValueLbl);
break;
case BasicFieldType.Int:
DrawInt(fieldKey, schemaData, GDEConstants.DefaultValueLbl);
break;
case BasicFieldType.Float:
DrawFloat(fieldKey, schemaData, GDEConstants.DefaultValueLbl);
break;
case BasicFieldType.String:
DrawString(fieldKey, schemaData, GDEConstants.DefaultValueLbl);
break;
case BasicFieldType.Vector2:
DrawVector2(fieldKey, schemaData, GDEConstants.DefaultValueLbl);
break;
case BasicFieldType.Vector3:
DrawVector3(fieldKey, schemaData, GDEConstants.DefaultValueLbl);
break;
case BasicFieldType.Vector4:
DrawVector4(fieldKey, schemaData, GDEConstants.DefaultValueLbl);
break;
case BasicFieldType.Color:
DrawColor(fieldKey, schemaData, GDEConstants.DefaultValueLbl);
break;
case BasicFieldType.GameObject:
DrawObject<GameObject>(fieldPreviewKey, fieldKey, schemaData, GDEConstants.DefaultValueLbl);
break;
case BasicFieldType.Texture2D:
DrawObject<Texture2D>(fieldPreviewKey, fieldKey, schemaData, GDEConstants.DefaultValueLbl);
break;
case BasicFieldType.Material:
DrawObject<Material>(fieldPreviewKey, fieldKey, schemaData, GDEConstants.DefaultValueLbl);
break;
case BasicFieldType.AudioClip:
DrawAudio(fieldPreviewKey, fieldKey, schemaData, GDEConstants.DefaultValueLbl);
break;
default:
DrawCustom(fieldKey, schemaData, false);
break;
}
content.text = GDEConstants.DeleteBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeDeleteBtnKey, content, GUI.skin.button, out size);
if (fieldTypeEnum.Equals(BasicFieldType.Vector2) ||
fieldTypeEnum.Equals(BasicFieldType.Vector3) ||
fieldTypeEnum.Equals(BasicFieldType.Vector4))
{
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.VerticalMiddleOfLine(), size.x, size.y), content))
deletedFields.Add(fieldKey);
drawHelper.NewLine(GDEConstants.VectorFieldBuffer+1);
}
else
{
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
deletedFields.Add(fieldKey);
drawHelper.NewLine();
}
}
void DrawListField(string schemaKey, Dictionary<string, object> schemaData, string fieldKey)
{
try
{
string foldoutKey = string.Format(GDMConstants.MetaDataFormat, schemaKey, fieldKey);
bool newFoldoutState;
bool currentFoldoutState = listFieldFoldoutState.Contains(foldoutKey);
object defaultResizeValue = null;
string fieldType;
schemaData.TryGetString(string.Format(GDMConstants.MetaDataFormat, GDMConstants.TypePrefix, fieldKey), out fieldType);
BasicFieldType fieldTypeEnum = BasicFieldType.Undefined;
if (Enum.IsDefined(typeof(BasicFieldType), fieldType))
{
fieldTypeEnum = (BasicFieldType)Enum.Parse(typeof(BasicFieldType), fieldType);
fieldType = GDEItemManager.GetVariableTypeFor(fieldTypeEnum);
defaultResizeValue = GDEItemManager.GetDefaultValueForType(fieldTypeEnum);
}
content.text = string.Format("List<{0}>", fieldType);
drawHelper.TryGetCachedSize(schemaKey+fieldKey+GDEConstants.TypeSuffix, content, EditorStyles.foldout, out size);
size.x = Math.Max(size.x, GDEConstants.MinLabelWidth);
newFoldoutState = EditorGUI.Foldout(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), currentFoldoutState, content);
drawHelper.CurrentLinePosition += (size.x + 2);
DrawEditableLabel(fieldKey, string.Format(GDMConstants.MetaDataFormat, schemaKey, fieldKey), RenameSchemaField, schemaData);
if (newFoldoutState != currentFoldoutState)
{
if (newFoldoutState)
listFieldFoldoutState.Add(foldoutKey);
else
listFieldFoldoutState.Remove(foldoutKey);
}
object temp = null;
IList list = null;
if (schemaData.TryGetValue(fieldKey, out temp))
list = temp as IList;
content.text = GDEConstants.DefaultSizeLbl;
drawHelper.TryGetCachedSize(GDEConstants.SizeDefaultSizeLblKey, content, EditorStyles.label, out size);
GUI.Label(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
int newListCount;
string listCountKey = string.Format(GDMConstants.MetaDataFormat, schemaKey, fieldKey);
if (newListCountDict.ContainsKey(listCountKey))
{
newListCount = newListCountDict[listCountKey];
}
else
{
newListCount = list.Count;
newListCountDict.Add(listCountKey, newListCount);
}
size.x = 40;
newListCount = EditorGUI.IntField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), newListCount);
drawHelper.CurrentLinePosition += (size.x + 2);
newListCountDict[listCountKey] = newListCount;
content.text = GDEConstants.ResizeBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeResizeBtnKey, content, GUI.skin.button, out size);
if (newListCount != list.Count)
{
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
ResizeList(list, newListCount, defaultResizeValue);
drawHelper.CurrentLinePosition += (size.x + 2);
}
content.text = GDEConstants.DeleteBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeDeleteBtnKey, content, GUI.skin.button, out size);
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
deletedFields.Add(fieldKey);
drawHelper.NewLine();
if (newFoldoutState)
{
for (int i = 0; i < list.Count; i++)
{
drawHelper.CurrentLinePosition += GDEConstants.Indent*2;
content.text = string.Format("[{0}]:", i);
switch (fieldTypeEnum) {
case BasicFieldType.Bool:
{
DrawListBool(content, i, Convert.ToBoolean((object)list[i]), list);
drawHelper.NewLine();
break;
}
case BasicFieldType.Int:
{
DrawListInt(content, i, Convert.ToInt32((object)list[i]), list);
drawHelper.NewLine();
break;
}
case BasicFieldType.Float:
{
DrawListFloat(content, i, Convert.ToSingle((object)list[i]), list);
drawHelper.NewLine();
break;
}
case BasicFieldType.String:
{
DrawListString(content, i, list[i] as string, list);
drawHelper.NewLine();
break;
}
case BasicFieldType.Vector2:
{
DrawListVector2(content, i, list[i] as Dictionary<string, object>, list);
drawHelper.NewLine(GDEConstants.VectorFieldBuffer+1);
break;
}
case BasicFieldType.Vector3:
{
DrawListVector3(content, i, list[i] as Dictionary<string, object>, list);
drawHelper.NewLine(GDEConstants.VectorFieldBuffer+1);
break;
}
case BasicFieldType.Vector4:
{
DrawListVector4(content, i, list[i] as Dictionary<string, object>, list);
drawHelper.NewLine(GDEConstants.VectorFieldBuffer+1);
break;
}
case BasicFieldType.Color:
{
DrawListColor(content, i, list[i] as Dictionary<string, object>, list);
drawHelper.NewLine();
break;
}
case BasicFieldType.GameObject:
{
DrawListObject<GameObject>(foldoutKey+i, content, i, list[i] as GameObject, list);
drawHelper.NewLine();
break;
}
case BasicFieldType.Texture2D:
{
DrawListObject<Texture2D>(foldoutKey+i, content, i, list[i] as Texture2D, list);
drawHelper.NewLine();
break;
}
case BasicFieldType.Material:
{
DrawListObject<Material>(foldoutKey+i, content, i, list[i] as Material, list);
drawHelper.NewLine();
break;
}
case BasicFieldType.AudioClip:
{
DrawListAudio(foldoutKey+i, content, i, list[i] as AudioClip, list);
drawHelper.NewLine();
break;
}
default:
{
DrawListCustom(content, i, list[i] as string, list, false);
drawHelper.NewLine();
break;
}
}
}
}
}
catch(Exception ex)
{
Debug.LogError(ex);
}
}
void Draw2DListField(string schemaKey, Dictionary<string, object> schemaData, string fieldKey)
{
try
{
string foldoutKey = string.Format(GDMConstants.MetaDataFormat, schemaKey, fieldKey);
bool newFoldoutState;
bool currentFoldoutState = listFieldFoldoutState.Contains(foldoutKey);
object defaultResizeValue;
string fieldType;
schemaData.TryGetString(string.Format(GDMConstants.MetaDataFormat, GDMConstants.TypePrefix, fieldKey), out fieldType);
BasicFieldType fieldTypeEnum = BasicFieldType.Undefined;
if (Enum.IsDefined(typeof(BasicFieldType), fieldType))
{
fieldTypeEnum = (BasicFieldType)Enum.Parse(typeof(BasicFieldType), fieldType);
fieldType = GDEItemManager.GetVariableTypeFor(fieldTypeEnum);
}
content.text = string.Format("List<List<{0}>>", fieldType);
drawHelper.TryGetCachedSize(schemaKey+fieldKey+GDEConstants.TypeSuffix, content, EditorStyles.foldout, out size);
size.x = Math.Max(size.x, GDEConstants.MinLabelWidth);
newFoldoutState = EditorGUI.Foldout(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), currentFoldoutState, content);
drawHelper.CurrentLinePosition += (size.x + 2);
DrawEditableLabel(fieldKey, string.Format(GDMConstants.MetaDataFormat, schemaKey, fieldKey), RenameSchemaField, schemaData);
if (newFoldoutState != currentFoldoutState)
{
if (newFoldoutState)
listFieldFoldoutState.Add(foldoutKey);
else
listFieldFoldoutState.Remove(foldoutKey);
}
object temp = null;
IList list = null;
if (schemaData.TryGetValue(fieldKey, out temp))
list = temp as IList;
content.text = GDEConstants.DefaultSizeLbl;
drawHelper.TryGetCachedSize(GDEConstants.SizeDefaultSizeLblKey, content, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
int newListCount;
string listCountKey = string.Format(GDMConstants.MetaDataFormat, schemaKey, fieldKey);
if (newListCountDict.ContainsKey(listCountKey))
{
newListCount = newListCountDict[listCountKey];
}
else
{
newListCount = list.Count;
newListCountDict.Add(listCountKey, newListCount);
}
size.x = 40;
newListCount = EditorGUI.IntField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), newListCount);
drawHelper.CurrentLinePosition += (size.x + 2);
newListCountDict[listCountKey] = newListCount;
content.text = GDEConstants.ResizeBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeResizeBtnKey, content, GUI.skin.button, out size);
if (newListCount != list.Count)
{
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
{
if (GDEItemManager.IsUnityType(fieldTypeEnum))
defaultResizeValue = Activator.CreateInstance(list.GetType().GetGenericArguments()[0]);
else
defaultResizeValue = new List<object>();
ResizeList(list, newListCount, defaultResizeValue);
}
drawHelper.CurrentLinePosition += (size.x + 2);
}
content.text = GDEConstants.DeleteBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeDeleteBtnKey, content, GUI.skin.button, out size);
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
deletedFields.Add(fieldKey);
drawHelper.NewLine();
if (newFoldoutState)
{
defaultResizeValue = GDEItemManager.GetDefaultValueForType(fieldTypeEnum);
for (int index = 0; index < list.Count; index++)
{
IList subList = list[index] as IList;
drawHelper.CurrentLinePosition += GDEConstants.Indent*2;
content.text = string.Format("[{0}]: List<{1}>", index, fieldType);
bool isOpen = DrawFoldout(content.text, foldoutKey+"_"+index, string.Empty, string.Empty, null);
// Draw resize
content.text = GDEConstants.DefaultSizeLbl;
drawHelper.TryGetCachedSize(GDEConstants.SizeDefaultSizeLblKey, content, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
listCountKey = string.Format(GDMConstants.MetaDataFormat, schemaKey, fieldKey)+"_"+index;
if (newListCountDict.ContainsKey(listCountKey))
{
newListCount = newListCountDict[listCountKey];
}
else
{
newListCount = subList.Count;
newListCountDict.Add(listCountKey, newListCount);
}
size.x = 40;
newListCount = EditorGUI.IntField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), newListCount);
drawHelper.CurrentLinePosition += (size.x + 2);
newListCountDict[listCountKey] = newListCount;
content.text = GDEConstants.ResizeBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeResizeBtnKey, content, GUI.skin.button, out size);
if (newListCount != subList.Count)
{
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
ResizeList(subList, newListCount, defaultResizeValue);
drawHelper.CurrentLinePosition += (size.x + 2);
}
drawHelper.NewLine();
if (isOpen)
{
for (int x = 0; x < subList.Count; x++)
{
drawHelper.CurrentLinePosition += GDEConstants.Indent*3;
content.text = string.Format("[{0}][{1}]:", index, x);
switch (fieldTypeEnum)
{
case BasicFieldType.Bool:
{
DrawListBool(content, x, Convert.ToBoolean((object)subList[x]), subList);
drawHelper.NewLine();
break;
}
case BasicFieldType.Int:
{
DrawListInt(content, x, Convert.ToInt32((object)subList[x]), subList);
drawHelper.NewLine();
break;
}
case BasicFieldType.Float:
{
DrawListFloat(content, x, Convert.ToSingle((object)subList[x]), subList);
drawHelper.NewLine();
break;
}
case BasicFieldType.String:
{
DrawListString(content, x, subList[x] as string, subList);
drawHelper.NewLine();
break;
}
case BasicFieldType.Vector2:
{
DrawListVector2(content, x, subList[x] as Dictionary<string, object>, subList);
drawHelper.NewLine(GDEConstants.VectorFieldBuffer+1);
break;
}
case BasicFieldType.Vector3:
{
DrawListVector3(content, x, subList[x] as Dictionary<string, object>, subList);
drawHelper.NewLine(GDEConstants.VectorFieldBuffer+1);
break;
}
case BasicFieldType.Vector4:
{
DrawListVector4(content, x, subList[x] as Dictionary<string, object>, subList);
drawHelper.NewLine(GDEConstants.VectorFieldBuffer+1);
break;
}
case BasicFieldType.Color:
{
DrawListColor(content, x, subList[x] as Dictionary<string, object>, subList);
drawHelper.NewLine();
break;
}
case BasicFieldType.GameObject:
{
DrawListObject<GameObject>(foldoutKey+index+"_"+x, content, x, subList[x] as GameObject, subList);
drawHelper.NewLine();
break;
}
case BasicFieldType.Texture2D:
{
DrawListObject<Texture2D>(foldoutKey+index+"_"+x, content, x, subList[x] as Texture2D, subList);
drawHelper.NewLine();
break;
}
case BasicFieldType.Material:
{
DrawListObject<Material>(foldoutKey+index+"_"+x, content, x, subList[x] as Material, subList);
drawHelper.NewLine();
break;
}
case BasicFieldType.AudioClip:
{
DrawListAudio(foldoutKey+index+"_"+x, content, x, subList[x] as AudioClip, subList);
drawHelper.NewLine();
break;
}
default:
{
DrawListCustom(content, x, subList[x] as string, subList, false);
drawHelper.NewLine();
break;
}
}
}
}
}
}
}
catch(Exception ex)
{
Debug.LogError(ex);
}
}
#endregion
#region Filter Methods
protected override bool ShouldFilter(string schemaKey, Dictionary<string, object> schemaData)
{
bool schemaKeyMatch = schemaKey.ToLower().Contains(filterText.ToLower());
bool fieldKeyMatch = !GDEItemManager.ShouldFilterByField(schemaKey, filterText);
// Return if the schema keys don't contain the filter text or
// if the schema fields don't contain the filter text
if (!schemaKeyMatch && !fieldKeyMatch)
return true;
return false;
}
protected override bool DrawFilterSection()
{
bool clearSearch = base.DrawFilterSection();
size.x = 200;
int totalItems = GDEItemManager.AllSchemas.Count;
string itemText = totalItems != 1 ? GDEConstants.ItemsLbl : GDEConstants.ItemLbl;
if (!string.IsNullOrEmpty(filterText))
{
float pos = drawHelper.TopOfLine()+drawHelper.LineHeight*.1f;
string resultText = string.Format(GDEConstants.SearchResultFormat, NumberOfItemsBeingShown(), totalItems, itemText);
GUI.Label(new Rect(drawHelper.CurrentLinePosition, pos, size.x, drawHelper.StandardHeight()), resultText);
drawHelper.CurrentLinePosition += (size.x + 2);
}
drawHelper.NewLine(1.25f);
return clearSearch;
}
#endregion
#region Add/Remove Field Methods
private bool AddBasicField(BasicFieldType type, string schemaKey, Dictionary<string, object> schemaData, string newFieldName, bool isList, bool is2DList)
{
bool result = true;
object defaultValue = GDEItemManager.GetDefaultValueForType(type);
string error;
if (GDEItemManager.AddBasicFieldToSchema(type, schemaKey, schemaData, newFieldName, out error, isList, is2DList, defaultValue))
{
SetNeedToSave(true);
HighlightNew(newFieldName);
}
else
{
EditorUtility.DisplayDialog(GDEConstants.ErrorCreatingField, error, GDEConstants.OkLbl);
result = false;
}
return result;
}
private bool AddCustomField(string customType, string schemaKey, Dictionary<string, object> schemaData, string newFieldName, bool isList, bool is2DList)
{
bool result = true;
string error;
if (GDEItemManager.AddCustomFieldToSchema(customType, schemaKey, schemaData, newFieldName, isList, is2DList, out error))
{
SetNeedToSave(true);
HighlightNew(newFieldName);
}
else
{
EditorUtility.DisplayDialog(GDEConstants.ErrorCreatingField, error, GDEConstants.OkLbl);
result = false;
}
return result;
}
private void RemoveField(string schemaKey, Dictionary<string, object> schemaData, string deletedFieldKey)
{
newListCountDict.Remove(string.Format(GDMConstants.MetaDataFormat, schemaKey, deletedFieldKey));
GDEItemManager.RemoveFieldFromSchema(schemaKey, schemaData, deletedFieldKey);
SetNeedToSave(true);
}
#endregion
#region Load/Save Schema Methods
protected override void Load()
{
base.Load();
newSchemaName = string.Empty;
basicFieldTypeSelectedDict.Clear();
customSchemaTypeSelectedDict.Clear();
newBasicFieldName.Clear();
isBasicList.Clear();
newCustomFieldName.Clear();
isCustomList.Clear();
deletedFields.Clear();
renamedFields.Clear();
renamedSchemas.Clear();
}
protected override bool NeedToSave()
{
return GDEItemManager.SchemasNeedSave;
}
protected override void SetNeedToSave(bool shouldSave)
{
GDEItemManager.SchemasNeedSave = shouldSave;
}
#endregion
#region Create/Remove Schema Methods
protected override bool Create(object data)
{
bool result = true;
string key = data as string;
string error;
result = GDEItemManager.AddSchema(key, new Dictionary<string, object>(), out error);
if (result)
{
SetNeedToSave(true);
SetFoldout(true, key);
HighlightNew(key);
}
else
{
EditorUtility.DisplayDialog(GDEConstants.ErrorCreatingSchema, error, GDEConstants.OkLbl);
result = false;
}
return result;
}
protected override void Remove(string key)
{
// Show a warning if we have items using this schema
List<string> items = GDEItemManager.GetItemsOfSchemaType(key);
bool shouldDelete = true;
if (items!= null && items.Count > 0)
{
string itemWord = items.Count == 1 ? GDEConstants.ItemLbl : GDEConstants.ItemsLbl;
shouldDelete = EditorUtility.DisplayDialog(string.Format(GDEConstants.DeleteWarningFormat, items.Count, itemWord), GDEConstants.SureDeleteSchema, GDEConstants.DeleteSchemaBtn, GDEConstants.CancelBtn);
}
if (shouldDelete)
{
GDEItemManager.RemoveSchema(key, true);
SetNeedToSave(true);
}
}
protected override bool Clone(string key)
{
bool result = true;
string error;
string newKey;
result = GDEItemManager.CloneSchema(key, out newKey, out error);
if (result)
{
SetNeedToSave(true);
SetFoldout(true, newKey);
HighlightNew(newKey);
}
else
{
EditorUtility.DisplayDialog(GDEConstants.ErrorCloningSchema, error, GDEConstants.OkLbl);
result = false;
}
return result;
}
#endregion
#region Helper Methods
protected override float CalculateGroupHeightsTotal()
{
if (!shouldRecalculateHeights)
return currentGroupHeightTotal;
currentGroupHeightTotal = 0;
float entryHeight = 0;
foreach(var entry in entriesToDraw)
{
groupHeights.TryGetValue(entry.Key, out entryHeight);
if (entryHeight < GDEConstants.LineHeight)
{
entryHeight = GDEConstants.LineHeight;
SetGroupHeight(entry.Key, entryHeight);
}
currentGroupHeightTotal += entryHeight;
}
shouldRecalculateHeights = false;
return currentGroupHeightTotal;
}
protected override string FilePath()
{
return GDEItemManager.DataFilePath;
}
#endregion
#region Rename Methods
protected bool RenameSchema(string oldSchemaKey, string newSchemaKey, Dictionary<string, object> data, out string error)
{
error = string.Empty;
renamedSchemas.Add(oldSchemaKey, newSchemaKey);
return true;
}
protected bool RenameSchemaField(string oldFieldKey, string newFieldKey, Dictionary<string, object> schemaData, out string error)
{
error = string.Empty;
List<string> fieldKeys = new List<string>(){oldFieldKey, newFieldKey};
renamedFields.Add(fieldKeys, schemaData);
return true;
}
#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;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.Isam.Esent;
using Microsoft.Isam.Esent.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Esent
{
internal partial class EsentPersistentStorage : AbstractPersistentStorage
{
private const string StorageExtension = "vbcs.cache";
private const string PersistentStorageFileName = "storage.ide";
private readonly ConcurrentDictionary<string, int> _nameTableCache;
private readonly EsentStorage _esentStorage;
public EsentPersistentStorage(
IOptionService optionService, string workingFolderPath, string solutionFilePath, Action<AbstractPersistentStorage> disposer) :
base(optionService, workingFolderPath, solutionFilePath, disposer)
{
// solution must exist in disk. otherwise, we shouldn't be here at all.
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(solutionFilePath));
var databaseFile = GetDatabaseFile(workingFolderPath);
this.EsentDirectory = Path.GetDirectoryName(databaseFile);
if (!Directory.Exists(this.EsentDirectory))
{
Directory.CreateDirectory(this.EsentDirectory);
}
_nameTableCache = new ConcurrentDictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var enablePerformanceMonitor = optionService.GetOption(InternalFeatureOnOffOptions.EsentPerformanceMonitor);
_esentStorage = new EsentStorage(databaseFile, enablePerformanceMonitor);
}
public static string GetDatabaseFile(string workingFolderPath)
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(workingFolderPath));
return Path.Combine(workingFolderPath, StorageExtension, PersistentStorageFileName);
}
public void Initialize()
{
_esentStorage.Initialize();
}
public string EsentDirectory { get; private set; }
public override Task<Stream> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
if (!PersistenceEnabled)
{
return SpecializedTasks.Default<Stream>();
}
int nameId;
EsentStorage.Key key;
if (!TryGetProjectAndDocumentKey(document, out key) ||
!TryGetUniqueNameId(name, out nameId))
{
return SpecializedTasks.Default<Stream>();
}
var stream = EsentExceptionWrapper(key, nameId, ReadStream, cancellationToken);
return Task.FromResult(stream);
}
public override Task<Stream> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
if (!PersistenceEnabled)
{
return SpecializedTasks.Default<Stream>();
}
int nameId;
EsentStorage.Key key;
if (!TryGetProjectKey(project, out key) ||
!TryGetUniqueNameId(name, out nameId))
{
return SpecializedTasks.Default<Stream>();
}
var stream = EsentExceptionWrapper(key, nameId, ReadStream, cancellationToken);
return Task.FromResult(stream);
}
public override Task<Stream> ReadStreamAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
if (!PersistenceEnabled)
{
return SpecializedTasks.Default<Stream>();
}
int nameId;
if (!TryGetUniqueNameId(name, out nameId))
{
return SpecializedTasks.Default<Stream>();
}
var stream = EsentExceptionWrapper(nameId, ReadStream, cancellationToken);
return Task.FromResult(stream);
}
private Stream ReadStream(EsentStorage.Key key, int nameId, object unused1, object unused2, CancellationToken cancellationToken)
{
using (var accessor = GetAccessor(key))
using (var esentStream = accessor.GetReadStream(key, nameId))
{
if (esentStream == null)
{
return null;
}
// this will copy over esent stream and let it go.
return SerializableBytes.CreateReadableStream(esentStream, cancellationToken);
}
}
private Stream ReadStream(int nameId, object unused1, object unused2, object unused3, CancellationToken cancellationToken)
{
using (var accessor = _esentStorage.GetSolutionTableAccessor())
using (var esentStream = accessor.GetReadStream(nameId))
{
if (esentStream == null)
{
return null;
}
// this will copy over esent stream and let it go.
return SerializableBytes.CreateReadableStream(esentStream, cancellationToken);
}
}
public override Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
Contract.ThrowIfNull(stream);
if (!PersistenceEnabled)
{
return SpecializedTasks.False;
}
int nameId;
EsentStorage.Key key;
if (!TryGetProjectAndDocumentKey(document, out key) ||
!TryGetUniqueNameId(name, out nameId))
{
return SpecializedTasks.False;
}
var success = EsentExceptionWrapper(key, nameId, stream, WriteStream, cancellationToken);
return success ? SpecializedTasks.True : SpecializedTasks.False;
}
public override Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
Contract.ThrowIfNull(stream);
if (!PersistenceEnabled)
{
return SpecializedTasks.False;
}
int nameId;
EsentStorage.Key key;
if (!TryGetProjectKey(project, out key) ||
!TryGetUniqueNameId(name, out nameId))
{
return SpecializedTasks.False;
}
var success = EsentExceptionWrapper(key, nameId, stream, WriteStream, cancellationToken);
return success ? SpecializedTasks.True : SpecializedTasks.False;
}
public override Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
Contract.ThrowIfNull(stream);
if (!PersistenceEnabled)
{
return SpecializedTasks.False;
}
int nameId;
if (!TryGetUniqueNameId(name, out nameId))
{
return SpecializedTasks.False;
}
var success = EsentExceptionWrapper(nameId, stream, WriteStream, cancellationToken);
return success ? SpecializedTasks.True : SpecializedTasks.False;
}
private bool WriteStream(EsentStorage.Key key, int nameId, Stream stream, object unused1, CancellationToken cancellationToken)
{
using (var accessor = GetAccessor(key))
using (var esentStream = accessor.GetWriteStream(key, nameId))
{
WriteToStream(stream, esentStream, cancellationToken);
return accessor.ApplyChanges();
}
}
private bool WriteStream(int nameId, Stream stream, object unused1, object unused2, CancellationToken cancellationToken)
{
using (var accessor = _esentStorage.GetSolutionTableAccessor())
using (var esentStream = accessor.GetWriteStream(nameId))
{
WriteToStream(stream, esentStream, cancellationToken);
return accessor.ApplyChanges();
}
}
public override void Close()
{
_esentStorage.Close();
}
private bool TryGetUniqueNameId(string name, out int id)
{
return TryGetUniqueId(name, false, out id);
}
private bool TryGetUniqueFileId(string path, out int id)
{
return TryGetUniqueId(path, true, out id);
}
private bool TryGetUniqueId(string value, bool fileCheck, out int id)
{
id = default(int);
if (string.IsNullOrWhiteSpace(value))
{
return false;
}
// if we already know, get the id
if (_nameTableCache.TryGetValue(value, out id))
{
return true;
}
// we only persist for things that actually exist
if (fileCheck && !File.Exists(value))
{
return false;
}
try
{
id = _nameTableCache.GetOrAdd(value, v =>
{
// okay, get one from esent
var uniqueIdValue = fileCheck ? FilePathUtilities.GetRelativePath(Path.GetDirectoryName(SolutionFilePath), v) : v;
return _esentStorage.GetUniqueId(uniqueIdValue);
});
}
catch (Exception ex)
{
// if we get fatal errors from esent such as disk out of space or log file corrupted by other process and etc
// don't crash VS, but let VS know it can't use esent. we will gracefully recover issue by using memory.
EsentLogger.LogException(ex);
return false;
}
return true;
}
private static void WriteToStream(Stream inputStream, Stream esentStream, CancellationToken cancellationToken)
{
var buffer = SharedPools.ByteArray.Allocate();
try
{
int bytesRead;
do
{
cancellationToken.ThrowIfCancellationRequested();
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
esentStream.Write(buffer, 0, bytesRead);
}
}
while (bytesRead > 0);
// flush the data and trim column size of necessary
esentStream.Flush();
}
finally
{
SharedPools.ByteArray.Free(buffer);
}
}
private EsentStorage.ProjectDocumentTableAccessor GetAccessor(EsentStorage.Key key)
{
return key.DocumentIdOpt.HasValue ?
(EsentStorage.ProjectDocumentTableAccessor)_esentStorage.GetDocumentTableAccessor() :
(EsentStorage.ProjectDocumentTableAccessor)_esentStorage.GetProjectTableAccessor();
}
private bool TryGetProjectAndDocumentKey(Document document, out EsentStorage.Key key)
{
key = default(EsentStorage.Key);
int projectId;
int projectNameId;
int documentId;
if (!TryGetProjectId(document.Project, out projectId, out projectNameId) ||
!TryGetUniqueFileId(document.FilePath, out documentId))
{
return false;
}
key = new EsentStorage.Key(projectId, projectNameId, documentId);
return true;
}
private bool TryGetProjectKey(Project project, out EsentStorage.Key key)
{
key = default(EsentStorage.Key);
int projectId;
int projectNameId;
if (!TryGetProjectId(project, out projectId, out projectNameId))
{
return false;
}
key = new EsentStorage.Key(projectId, projectNameId);
return true;
}
private bool TryGetProjectId(Project project, out int projectId, out int projectNameId)
{
projectId = default(int);
projectNameId = default(int);
return TryGetUniqueFileId(project.FilePath, out projectId) && TryGetUniqueNameId(project.Name, out projectNameId);
}
private TResult EsentExceptionWrapper<TArg1, TResult>(TArg1 arg1, Func<TArg1, object, object, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TResult>(
TArg1 arg1, TArg2 arg2, Func<TArg1, TArg2, object, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, arg2, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TArg3, TResult>(
TArg1 arg1, TArg2 arg2, TArg3 arg3, Func<TArg1, TArg2, TArg3, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, arg2, arg3, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TArg3, TArg4, TResult>(
TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, Func<TArg1, TArg2, TArg3, TArg4, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
try
{
return func(arg1, arg2, arg3, arg4, cancellationToken);
}
catch (EsentInvalidSesidException)
{
// operation was in-fly when Esent instance was shutdown - ignore the error
}
catch (OperationCanceledException)
{
}
catch (EsentException ex)
{
if (!_esentStorage.IsClosed)
{
// ignore esent exception if underlying storage was closed
// there is not much we can do here.
// internally we use it as a way to cache information between sessions anyway.
// no functionality will be affected by this except perf
Logger.Log(FunctionId.PersistenceService_WriteAsyncFailed, "Esent Failed : " + ex.Message);
}
}
catch (Exception ex)
{
// ignore exception
// there is not much we can do here.
// internally we use it as a way to cache information between sessions anyway.
// no functionality will be affected by this except perf
Logger.Log(FunctionId.PersistenceService_WriteAsyncFailed, "Failed : " + ex.Message);
}
return default(TResult);
}
}
}
| |
/*
* SVM.NET Library
* Copyright (C) 2008 Matthew Johnson
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Threading;
namespace SVM
{
/// <summary>
/// A transform which learns the mean and variance of a sample set and uses these to transform new data
/// so that it has zero mean and unit variance.
/// </summary>
public class GaussianTransform : IRangeTransform
{
private double[] _means;
private double[] _stddevs;
/// <summary>
/// Determines the Gaussian transform for the provided problem.
/// </summary>
/// <param name="prob">The Problem to analyze</param>
/// <returns>The Gaussian transform for the problem</returns>
public static GaussianTransform Compute(Problem prob)
{
int[] counts = new int[prob.MaxIndex];
double[] means = new double[prob.MaxIndex];
foreach (Node[] sample in prob.X)
{
for (int i = 0; i < sample.Length; i++)
{
means[sample[i].Index-1] += sample[i].Value;
counts[sample[i].Index-1]++;
}
}
for (int i = 0; i < prob.MaxIndex; i++)
{
if (counts[i] == 0)
counts[i] = 2;
means[i] /= counts[i];
}
double[] stddevs = new double[prob.MaxIndex];
foreach (Node[] sample in prob.X)
{
for (int i = 0; i < sample.Length; i++)
{
double diff = sample[i].Value - means[sample[i].Index - 1];
stddevs[sample[i].Index - 1] += diff * diff;
}
}
for (int i = 0; i < prob.MaxIndex; i++)
{
if (stddevs[i] == 0)
continue;
stddevs[i] /= (counts[i] - 1);
stddevs[i] = Math.Sqrt(stddevs[i]);
}
return new GaussianTransform(means, stddevs);
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="means">Means in each dimension</param>
/// <param name="stddevs">Standard deviation in each dimension</param>
public GaussianTransform(double[] means, double[] stddevs)
{
_means = means;
_stddevs = stddevs;
}
/// <summary>
/// Saves the transform to the disk. The samples are not stored, only the
/// statistics.
/// </summary>
/// <param name="stream">The destination stream</param>
/// <param name="transform">The transform</param>
public static void Write(Stream stream, GaussianTransform transform)
{
TemporaryCulture.Start();
StreamWriter output = new StreamWriter(stream);
output.WriteLine(transform._means.Length);
for (int i = 0; i < transform._means.Length; i++)
output.WriteLine("{0} {1}", transform._means[i], transform._stddevs[i]);
output.Flush();
TemporaryCulture.Stop();
}
/// <summary>
/// Reads a GaussianTransform from the provided stream.
/// </summary>
/// <param name="stream">The source stream</param>
/// <returns>The transform</returns>
public static GaussianTransform Read(Stream stream)
{
TemporaryCulture.Start();
StreamReader input = new StreamReader(stream);
int length = int.Parse(input.ReadLine(), CultureInfo.InvariantCulture);
double[] means = new double[length];
double[] stddevs = new double[length];
for (int i = 0; i < length; i++)
{
string[] parts = input.ReadLine().Split();
means[i] = double.Parse(parts[0], CultureInfo.InvariantCulture);
stddevs[i] = double.Parse(parts[1], CultureInfo.InvariantCulture);
}
TemporaryCulture.Stop();
return new GaussianTransform(means, stddevs);
}
/// <summary>
/// Saves the transform to the disk. The samples are not stored, only the
/// statistics.
/// </summary>
/// <param name="filename">The destination filename</param>
/// <param name="transform">The transform</param>
public static void Write(string filename, GaussianTransform transform)
{
FileStream output = File.Open(filename, FileMode.Create);
try
{
Write(output, transform);
}
finally
{
output.Close();
}
}
/// <summary>
/// Reads a GaussianTransform from the provided stream.
/// </summary>
/// <param name="filename">The source filename</param>
/// <returns>The transform</returns>
public static GaussianTransform Read(string filename)
{
FileStream input = File.Open(filename, FileMode.Open);
try
{
return Read(input);
}
finally
{
input.Close();
}
}
#region IRangeTransform Members
/// <summary>
/// Transform the input value using the transform stored for the provided index.
/// </summary>
/// <param name="input">Input value</param>
/// <param name="index">Index of the transform to use</param>
/// <returns>The transformed value</returns>
public double Transform(double input, int index)
{
index--;
if (_stddevs[index] == 0)
return 0;
double diff = input - _means[index];
diff /= _stddevs[index];
return diff;
}
/// <summary>
/// Transforms the input array.
/// </summary>
/// <param name="input">The array to transform</param>
/// <returns>The transformed array</returns>
public Node[] Transform(Node[] input)
{
Node[] output = new Node[input.Length];
for (int i = 0; i < output.Length; i++)
{
int index = input[i].Index;
double value = input[i].Value;
output[i] = new Node(index, Transform(value, index));
}
return output;
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="BinHexDecoder.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
namespace System.Xml
{
internal class BinHexDecoder : IncrementalReadDecoder {
//
// Fields
//
byte[] buffer;
int startIndex;
int curIndex;
int endIndex;
bool hasHalfByteCached;
byte cachedHalfByte;
//
// IncrementalReadDecoder interface
//
internal override int DecodedCount {
get {
return curIndex - startIndex;
}
}
internal override bool IsFull {
get {
return curIndex == endIndex;
}
}
#if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY
[System.Security.SecuritySafeCritical]
#endif
internal override unsafe int Decode(char[] chars, int startPos, int len) {
if ( chars == null ) {
throw new ArgumentNullException( "chars" );
}
if ( len < 0 ) {
throw new ArgumentOutOfRangeException( "len" );
}
if ( startPos < 0 ) {
throw new ArgumentOutOfRangeException( "startPos" );
}
if ( chars.Length - startPos < len ) {
throw new ArgumentOutOfRangeException( "len" );
}
if ( len == 0 ) {
return 0;
}
int bytesDecoded, charsDecoded;
fixed ( char* pChars = &chars[startPos] ) {
fixed ( byte* pBytes = &buffer[curIndex] ) {
Decode( pChars, pChars + len, pBytes, pBytes + ( endIndex - curIndex ),
ref this.hasHalfByteCached, ref this.cachedHalfByte, out charsDecoded, out bytesDecoded );
}
}
curIndex += bytesDecoded;
return charsDecoded;
}
#if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY
[System.Security.SecuritySafeCritical]
#endif
internal override unsafe int Decode(string str, int startPos, int len) {
if ( str == null ) {
throw new ArgumentNullException( "str" );
}
if ( len < 0 ) {
throw new ArgumentOutOfRangeException( "len" );
}
if ( startPos < 0 ) {
throw new ArgumentOutOfRangeException( "startPos" );
}
if ( str.Length - startPos < len ) {
throw new ArgumentOutOfRangeException( "len" );
}
if ( len == 0 ) {
return 0;
}
int bytesDecoded, charsDecoded;
fixed ( char* pChars = str ) {
fixed ( byte* pBytes = &buffer[curIndex] ) {
Decode( pChars + startPos, pChars + startPos + len, pBytes, pBytes + ( endIndex - curIndex ),
ref this.hasHalfByteCached, ref this.cachedHalfByte, out charsDecoded, out bytesDecoded );
}
}
curIndex += bytesDecoded;
return charsDecoded;
}
internal override void Reset() {
this.hasHalfByteCached = false;
this.cachedHalfByte = 0;
}
internal override void SetNextOutputBuffer( Array buffer, int index, int count ) {
Debug.Assert( buffer != null );
Debug.Assert( count >= 0 );
Debug.Assert( index >= 0 );
Debug.Assert( buffer.Length - index >= count );
Debug.Assert( ( buffer as byte[] ) != null );
this.buffer = (byte[])buffer;
this.startIndex = index;
this.curIndex = index;
this.endIndex = index + count;
}
//
// Static methods
//
#if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY
[System.Security.SecuritySafeCritical]
#endif
public static unsafe byte[] Decode(char[] chars, bool allowOddChars) {
if ( chars == null ) {
throw new ArgumentNullException( "chars" );
}
int len = chars.Length;
if ( len == 0 ) {
return new byte[0];
}
byte[] bytes = new byte[ ( len + 1 ) / 2 ];
int bytesDecoded, charsDecoded;
bool hasHalfByteCached = false;
byte cachedHalfByte = 0;
fixed ( char* pChars = &chars[0] ) {
fixed ( byte* pBytes = &bytes[0] ) {
Decode( pChars, pChars + len, pBytes, pBytes + bytes.Length, ref hasHalfByteCached, ref cachedHalfByte, out charsDecoded, out bytesDecoded );
}
}
if ( hasHalfByteCached && !allowOddChars ) {
throw new XmlException( Res.Xml_InvalidBinHexValueOddCount, new string( chars ) );
}
if ( bytesDecoded < bytes.Length ) {
byte[] tmp = new byte[ bytesDecoded ];
Array.Copy( bytes, 0, tmp, 0, bytesDecoded );
bytes = tmp;
}
return bytes;
}
//
// Private methods
//
#if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY
[System.Security.SecurityCritical]
#endif
private static unsafe void Decode(char* pChars, char* pCharsEndPos,
byte* pBytes, byte* pBytesEndPos,
ref bool hasHalfByteCached, ref byte cachedHalfByte,
out int charsDecoded, out int bytesDecoded ) {
#if DEBUG
Debug.Assert( pCharsEndPos - pChars >= 0 );
Debug.Assert( pBytesEndPos - pBytes >= 0 );
#endif
char* pChar = pChars;
byte* pByte = pBytes;
XmlCharType xmlCharType = XmlCharType.Instance;
while ( pChar < pCharsEndPos && pByte < pBytesEndPos ) {
byte halfByte;
char ch = *pChar++;
if ( ch >= 'a' && ch <= 'f' ) {
halfByte = (byte)(ch - 'a' + 10);
}
else if ( ch >= 'A' && ch <= 'F' ) {
halfByte = (byte)(ch - 'A' + 10);
}
else if ( ch >= '0' && ch <= '9' ) {
halfByte = (byte)(ch - '0');
}
else if ( ( xmlCharType.charProperties[ch] & XmlCharType.fWhitespace ) != 0 ) { // else if ( xmlCharType.IsWhiteSpace( ch ) ) {
continue;
}
else {
throw new XmlException( Res.Xml_InvalidBinHexValue, new string( pChars, 0, (int)( pCharsEndPos - pChars ) ) );
}
if ( hasHalfByteCached ) {
*pByte++ = (byte)( ( cachedHalfByte << 4 ) + halfByte );
hasHalfByteCached = false;
}
else {
cachedHalfByte = halfByte;
hasHalfByteCached = true;
}
}
bytesDecoded = (int)(pByte - pBytes);
charsDecoded = (int)(pChar - pChars);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Automation;
using System.Windows.Input;
using System.Windows.Interop;
using EnvDTE;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Options;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Project;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools;
using Microsoft.Win32;
using TestUtilities.Python;
using Process = System.Diagnostics.Process;
namespace TestUtilities.UI.Python {
class PythonVisualStudioApp : VisualStudioApp {
private bool _deletePerformanceSessions;
private PythonPerfExplorer _perfTreeView;
private PythonPerfToolBar _perfToolBar;
public PythonVisualStudioApp(DTE dte = null)
: base(dte) {
var service = ServiceProvider.GetPythonToolsService();
Assert.IsNotNull(service, "Failed to get PythonToolsService");
// Disable AutoListIdentifiers for tests
var ao = service.AdvancedOptions;
Assert.IsNotNull(ao, "Failed to get AdvancedOptions");
var oldALI = ao.AutoListIdentifiers;
ao.AutoListIdentifiers = false;
var orwoodProp = Dte.Properties["Environment", "ProjectsAndSolution"].Item("OnRunWhenOutOfDate");
Assert.IsNotNull(orwoodProp, "Failed to get OnRunWhenOutOfDate property");
var oldOrwood = orwoodProp.Value;
orwoodProp.Value = 1;
OnDispose(() => {
ao.AutoListIdentifiers = oldALI;
orwoodProp.Value = oldOrwood;
});
}
protected override void Dispose(bool disposing) {
if (!IsDisposed) {
try {
InteractiveWindow.CloseAll(this);
} catch (Exception ex) {
Console.WriteLine("Error while closing all interactive windows");
Console.WriteLine(ex);
}
if (_deletePerformanceSessions) {
try {
dynamic profiling = Dte.GetObject("PythonProfiling");
for (dynamic session = profiling.GetSession(1);
session != null;
session = profiling.GetSession(1)) {
profiling.RemoveSession(session, true);
}
} catch (Exception ex) {
Console.WriteLine("Error while cleaning up profiling sessions");
Console.WriteLine(ex);
}
}
}
base.Dispose(disposing);
}
// Constants for passing to CreateProject
private const string _templateLanguageName = "Python";
public static string TemplateLanguageName {
get {
return _templateLanguageName;
}
}
public const string PythonApplicationTemplate = "ConsoleAppProject.zip";
public const string EmptyWebProjectTemplate = "EmptyWebProject.zip";
public const string BottleWebProjectTemplate = "WebProjectBottle.zip";
public const string FlaskWebProjectTemplate = "WebProjectFlask.zip";
public const string DjangoWebProjectTemplate = "DjangoProject.zip";
public const string WorkerRoleProjectTemplate = "WorkerRoleProject.zip";
public const string EmptyFileTemplate = "EmptyPyFile.zip";
public const string WebRoleSupportTemplate = "AzureCSWebRole.zip";
public const string WorkerRoleSupportTemplate = "AzureCSWorkerRole.zip";
/// <summary>
/// Opens and activates the solution explorer window.
/// </summary>
public void OpenPythonPerformance() {
try {
_deletePerformanceSessions = true;
Dte.ExecuteCommand("Python.PerformanceExplorer");
} catch {
// If the package is not loaded yet then the command may not
// work. Force load the package by opening the Launch dialog.
using (var dialog = new PythonPerfTarget(OpenDialogWithDteExecuteCommand("Python.LaunchProfiling"))) {
}
Dte.ExecuteCommand("Python.PerformanceExplorer");
}
}
/// <summary>
/// Opens and activates the solution explorer window.
/// </summary>
public PythonPerfTarget LaunchPythonProfiling() {
_deletePerformanceSessions = true;
return new PythonPerfTarget(OpenDialogWithDteExecuteCommand("Python.LaunchProfiling"));
}
/// <summary>
/// Provides access to the Python profiling tree view.
/// </summary>
public PythonPerfExplorer PythonPerformanceExplorerTreeView {
get {
if (_perfTreeView == null) {
var element = Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(
AutomationElement.ClassNameProperty,
"SysTreeView32"
),
new PropertyCondition(
AutomationElement.NameProperty,
"Python Performance"
)
)
);
_perfTreeView = new PythonPerfExplorer(element);
}
return _perfTreeView;
}
}
/// <summary>
/// Provides access to the Python profiling tool bar
/// </summary>
public PythonPerfToolBar PythonPerformanceExplorerToolBar {
get {
if (_perfToolBar == null) {
var element = Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(
AutomationElement.ClassNameProperty,
"ToolBar"
),
new PropertyCondition(
AutomationElement.NameProperty,
"Python Performance"
)
)
);
_perfToolBar = new PythonPerfToolBar(element);
}
return _perfToolBar;
}
}
public InteractiveWindow GetInteractiveWindow(string title) {
AutomationElement element = null;
for (int i = 0; i < 5 && element == null; i++) {
element = Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(
AutomationElement.NameProperty,
title
),
new PropertyCondition(
AutomationElement.ControlTypeProperty,
ControlType.Pane
)
)
);
if (element == null) {
System.Threading.Thread.Sleep(100);
}
}
if (element == null) {
DumpVS();
return null;
}
return new InteractiveWindow(
title,
element.FindFirst(
TreeScope.Descendants,
new PropertyCondition(
AutomationElement.AutomationIdProperty,
"WpfTextView"
)
),
this
);
}
internal Document WaitForDocument(string docName) {
for (int i = 0; i < 100; i++) {
try {
return Dte.Documents.Item(docName);
} catch {
System.Threading.Thread.Sleep(100);
}
}
throw new InvalidOperationException("Document not opened: " + docName);
}
/// <summary>
/// Selects the given interpreter as the default.
/// </summary>
/// <remarks>
/// This method should always be called as a using block.
/// </remarks>
public DefaultInterpreterSetter SelectDefaultInterpreter(PythonVersion python) {
return new DefaultInterpreterSetter(
InterpreterService.FindInterpreter(python.Id, python.Version.ToVersion()),
ServiceProvider
);
}
public DefaultInterpreterSetter SelectDefaultInterpreter(PythonVersion interp, string installPackages) {
interp.AssertInstalled();
if (interp.IsIronPython && !string.IsNullOrEmpty(installPackages)) {
Assert.Inconclusive("Package installation not supported on IronPython");
}
var interpreterService = InterpreterService;
var factory = interpreterService.FindInterpreter(interp.Id, interp.Configuration.Version);
var defaultInterpreterSetter = new DefaultInterpreterSetter(factory);
try {
if (!string.IsNullOrEmpty(installPackages)) {
Pip.InstallPip(ServiceProvider, factory, false).Wait();
foreach (var package in installPackages.Split(' ', ',', ';').Select(s => s.Trim()).Where(s => !string.IsNullOrEmpty(s))) {
Pip.Install(ServiceProvider, factory, package, false).Wait();
}
}
var result = defaultInterpreterSetter;
defaultInterpreterSetter = null;
return result;
} finally {
if (defaultInterpreterSetter != null) {
defaultInterpreterSetter.Dispose();
}
}
}
public IInterpreterOptionsService InterpreterService {
get {
var model = GetService<IComponentModel>(typeof(SComponentModel));
var service = model.GetService<IInterpreterOptionsService>();
Assert.IsNotNull(service, "Unable to get InterpreterOptionsService");
return service;
}
}
public TreeNode CreateVirtualEnvironment(EnvDTE.Project project, out string envName) {
string dummy;
return CreateVirtualEnvironment(project, out envName, out dummy);
}
public TreeNode CreateVirtualEnvironment(EnvDTE.Project project, out string envName, out string envPath) {
var environmentsNode = OpenSolutionExplorer().FindChildOfProject(
project,
SR.GetString(SR.Environments)
);
environmentsNode.Select();
using (var pss = new ProcessScope("python")) {
using (var createVenv = AutomationDialog.FromDte(this, "Python.AddVirtualEnvironment")) {
envPath = new TextBox(createVenv.FindByAutomationId("VirtualEnvPath")).GetValue();
var baseInterp = new ComboBox(createVenv.FindByAutomationId("BaseInterpreter")).GetSelectedItemName();
envName = string.Format("{0} ({1})", envPath, baseInterp);
Console.WriteLine("Expecting environment named: {0}", envName);
// Force a wait for the view to be updated.
var wnd = (DialogWindowVersioningWorkaround)HwndSource.FromHwnd(
new IntPtr(createVenv.Element.Current.NativeWindowHandle)
).RootVisual;
wnd.Dispatcher.Invoke(() => {
var view = (AddVirtualEnvironmentView)wnd.DataContext;
return view.UpdateInterpreter(view.BaseInterpreter);
}).Wait();
createVenv.ClickButtonByAutomationId("Create");
createVenv.ClickButtonAndClose("Close", nameIsAutomationId: true);
}
var nowRunning = pss.WaitForNewProcess(TimeSpan.FromMinutes(1));
if (nowRunning == null || !nowRunning.Any()) {
Assert.Fail("Failed to see python process start to create virtualenv");
}
foreach (var p in nowRunning) {
if (p.HasExited) {
continue;
}
try {
p.WaitForExit(30000);
} catch (Win32Exception ex) {
Console.WriteLine("Error waiting for process ID {0}\n{1}", p.Id, ex);
}
}
}
try {
return OpenSolutionExplorer().WaitForChildOfProject(
project,
SR.GetString(SR.Environments),
envName
);
} finally {
var text = GetOutputWindowText("General");
if (!string.IsNullOrEmpty(text)) {
Console.WriteLine("** Output Window text");
Console.WriteLine(text);
Console.WriteLine("***");
Console.WriteLine();
}
}
}
public TreeNode AddExistingVirtualEnvironment(EnvDTE.Project project, string envPath, out string envName) {
var environmentsNode = OpenSolutionExplorer().FindChildOfProject(
project,
SR.GetString(SR.Environments)
);
environmentsNode.Select();
using (var createVenv = AutomationDialog.FromDte(this, "Python.AddVirtualEnvironment")) {
new TextBox(createVenv.FindByAutomationId("VirtualEnvPath")).SetValue(envPath);
var baseInterp = new ComboBox(createVenv.FindByAutomationId("BaseInterpreter")).GetSelectedItemName();
envName = string.Format("{0} ({1})", Path.GetFileName(envPath), baseInterp);
Console.WriteLine("Expecting environment named: {0}", envName);
createVenv.ClickButtonAndClose("Add", nameIsAutomationId: true);
}
return OpenSolutionExplorer().WaitForChildOfProject(
project,
SR.GetString(SR.Environments),
envName
);
}
public IPythonOptions Options {
get {
return (IPythonOptions)Dte.GetObject("VsPython");
}
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace Mercurial.Versions
{
/// <summary>
/// This attribute can be applied to <see cref="MercurialVersionBase"/> descendants
/// to specify which version(s) they apply to.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
[SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "This is just a shortcut for the other constructor, no new properties introduced.")]
public sealed class MercurialVersionAttribute : Attribute, IComparable<MercurialVersionAttribute>, IEquatable<MercurialVersionAttribute>
{
/// <summary>
/// This is the backing field for the <see cref="FromVersionString"/> property.
/// </summary>
private readonly string _FromVersionString = string.Empty;
/// <summary>
/// This is the backing field for the <see cref="ToVersionString"/> property.
/// </summary>
private readonly string _ToVersionString = string.Empty;
/// <summary>
/// Initializes a new instance of the <see cref="MercurialVersionAttribute"/> class.
/// </summary>
/// <param name="fromVersionString">
/// The lower-bound of the supported version, inclusive.
/// </param>
/// <param name="toVersionString">
/// The upper-bound of the supported version, inclusive.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="fromVersionString"/> is <c>null</c>.</para>
/// <para>- or -</para>
/// <para><paramref name="toVersionString"/> is <c>null</c>.</para>
/// </exception>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "string", Justification = "There are multiple ways to access the same version here, as a Version and as a string, keeping the name as-is.")]
public MercurialVersionAttribute(string fromVersionString, string toVersionString)
{
if (fromVersionString == null)
throw new ArgumentNullException("fromVersionString");
if (toVersionString == null)
throw new ArgumentNullException("toVersionString");
_FromVersionString = fromVersionString;
_ToVersionString = toVersionString;
}
/// <summary>
/// Initializes a new instance of the <see cref="MercurialVersionAttribute"/> class.
/// </summary>
/// <param name="versionString">
/// The lower-bound and upper-bound of the supported version, inclusive.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="versionString"/> is <c>null</c>.</para>
/// </exception>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "string", Justification = "There are multiple ways to access the same version here, as a Version and as a string, keeping the name as-is.")]
public MercurialVersionAttribute(string versionString)
: this(versionString, versionString)
{
// Do nothing here
}
/// <summary>
/// Gets the lower-bound of the supported version, inclusive.
/// </summary>
public string FromVersionString
{
get
{
return _FromVersionString;
}
}
/// <summary>
/// Gets the <see cref="FromVersionString"/> as a properly formatted <see cref="Version"/>, with missing
/// pieces appropriately set.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Incorrect format for <see cref="FromVersionString"/>.
/// </exception>
public Version FromVersion
{
get
{
string[] parts = FromVersionString.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
switch (parts.Length)
{
case 0:
return new Version(0, 0, 0, 0);
case 1:
return new Version(
int.Parse(parts[0], CultureInfo.InvariantCulture),
0,
0,
0);
case 2:
return new Version(
int.Parse(parts[0], CultureInfo.InvariantCulture),
int.Parse(parts[1], CultureInfo.InvariantCulture),
0,
0);
case 3:
return new Version(
int.Parse(parts[0], CultureInfo.InvariantCulture),
int.Parse(parts[1], CultureInfo.InvariantCulture),
int.Parse(parts[2], CultureInfo.InvariantCulture),
0);
case 4:
return new Version(
int.Parse(parts[0], CultureInfo.InvariantCulture),
int.Parse(parts[1], CultureInfo.InvariantCulture),
int.Parse(parts[2], CultureInfo.InvariantCulture),
int.Parse(parts[3], CultureInfo.InvariantCulture));
default:
throw new InvalidOperationException("Incorrect format for FromVersionString");
}
}
}
/// <summary>
/// Gets the upper-bound of the supported version, inclusive.
/// </summary>
public string ToVersionString
{
get
{
return _ToVersionString;
}
}
/// <summary>
/// Gets the <see cref="ToVersionString"/> as a properly formatted <see cref="Version"/>, with missing
/// pieces appropriately set.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Incorrect format for <see cref="ToVersionString"/>.
/// </exception>
public Version ToVersion
{
get
{
string[] parts = ToVersionString.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
switch (parts.Length)
{
case 0:
return new Version(65535, 65535, 65535, 65535);
case 1:
return new Version(
int.Parse(parts[0], CultureInfo.InvariantCulture),
65535,
65535,
65535);
case 2:
return new Version(
int.Parse(parts[0], CultureInfo.InvariantCulture),
int.Parse(parts[1], CultureInfo.InvariantCulture),
65535,
65535);
case 3:
return new Version(
int.Parse(parts[0], CultureInfo.InvariantCulture),
int.Parse(parts[1], CultureInfo.InvariantCulture),
int.Parse(parts[2], CultureInfo.InvariantCulture),
65535);
case 4:
return new Version(
int.Parse(parts[0], CultureInfo.InvariantCulture),
int.Parse(parts[1], CultureInfo.InvariantCulture),
int.Parse(parts[2], CultureInfo.InvariantCulture),
int.Parse(parts[3], CultureInfo.InvariantCulture));
default:
throw new InvalidOperationException("Incorrect format for ToVersionString");
}
}
}
/// <summary>
/// Determines if the specified version is a match against this attribute.
/// </summary>
/// <param name="version">
/// The version to compare against <see cref="FromVersionString"/> and <see cref="ToVersionString"/>.
/// </param>
/// <returns>
/// <c>true</c> if <paramref name="version"/> is between <see cref="FromVersionString"/> and <see cref="ToVersionString"/>,
/// inclusive; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="version"/> is <c>null</c>.</para>
/// </exception>
public bool IsMatch(Version version)
{
if (version == null)
throw new ArgumentNullException("version");
return FromVersion <= version && version <= ToVersion;
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">
/// An object to compare with this object.
/// </param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Comparison only handles encapsulating overlaps.
/// </exception>
public int CompareTo(MercurialVersionAttribute other)
{
// null always before anything else
if (other == null)
return +1;
if (FromVersion == other.FromVersion && ToVersion == other.ToVersion)
return 0;
// first determine if we have overlap
bool overlap = ToVersion >= other.FromVersion && FromVersion <= other.ToVersion;
if (overlap)
{
if (FromVersion <= other.FromVersion && ToVersion >= other.ToVersion)
return +1;
if (other.FromVersion <= FromVersion && other.ToVersion >= ToVersion)
return -1;
throw new InvalidOperationException("Comparison only handles encapsulating overlaps");
}
if (ToVersion < other.FromVersion)
return -1;
return +1;
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
/// <param name="other">
/// An object to compare with this object.
/// </param>
public bool Equals(MercurialVersionAttribute other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return base.Equals(other) && Equals(other._FromVersionString, _FromVersionString) && Equals(other._ToVersionString, _ToVersionString);
}
/// <summary>
/// Returns a value that indicates whether this instance is equal to a specified object.
/// </summary>
/// <returns>
/// true if <paramref name="obj"/> equals the type and value of this instance; otherwise, false.
/// </returns>
/// <param name="obj">
/// An <see cref="Object"/> to compare with this instance or null.
/// </param>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
return Equals(obj as MercurialVersionAttribute);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>
/// A 32-bit signed integer hash code.
/// </returns>
public override int GetHashCode()
{
unchecked
{
int result = base.GetHashCode();
result = (result * 397) ^ (_FromVersionString != null ? _FromVersionString.GetHashCode() : 0);
result = (result * 397) ^ (_ToVersionString != null ? _ToVersionString.GetHashCode() : 0);
return result;
}
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">
/// The left operand to the == operator.
/// </param>
/// <param name="right">
/// The right operand to the == operator.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator ==(MercurialVersionAttribute left, MercurialVersionAttribute right)
{
return Equals(left, right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">
/// The left operand to the != operator.
/// </param>
/// <param name="right">
/// The right operand to the != operator.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator !=(MercurialVersionAttribute left, MercurialVersionAttribute right)
{
return !Equals(left, right);
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">
/// The left operand to the < operator.
/// </param>
/// <param name="right">
/// The right operand to the < operator.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator <(MercurialVersionAttribute left, MercurialVersionAttribute right)
{
if (left == null && right == null)
return false;
if (left == null)
return true;
return left.CompareTo(right) < 0;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">
/// The left operand to the > operator.
/// </param>
/// <param name="right">
/// The right operand to the > operator.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator >(MercurialVersionAttribute left, MercurialVersionAttribute right)
{
if (left == null && right == null)
return false;
if (left == null)
return true;
return left.CompareTo(right) > 0;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApplication.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
#pragma warning disable 1591 // disable warning on missing comments
using System;
using Adaptive.SimpleBinaryEncoding;
namespace Adaptive.SimpleBinaryEncoding.PerfTests.Bench.SBE.FIX
{
public sealed partial class NewOrder
{
public const ushort BlockLength = (ushort)156;
public const ushort TemplateId = (ushort)68;
public const ushort SchemaId = (ushort)2;
public const ushort Schema_Version = (ushort)0;
public const string SematicType = "D";
private readonly NewOrder _parentMessage;
private DirectBuffer _buffer;
private int _offset;
private int _limit;
private int _actingBlockLength;
private int _actingVersion;
public int Offset { get { return _offset; } }
public NewOrder()
{
_parentMessage = this;
}
public void WrapForEncode(DirectBuffer buffer, int offset)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = BlockLength;
_actingVersion = Schema_Version;
Limit = offset + _actingBlockLength;
}
public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = actingBlockLength;
_actingVersion = actingVersion;
Limit = offset + _actingBlockLength;
}
public int Size
{
get
{
return _limit - _offset;
}
}
public int Limit
{
get
{
return _limit;
}
set
{
_buffer.CheckLimit(_limit);
_limit = value;
}
}
public const int AccountId = 1;
public static string AccountMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte AccountNullValue = (byte)0;
public const byte AccountMinValue = (byte)32;
public const byte AccountMaxValue = (byte)126;
public const int AccountLength = 12;
public byte GetAccount(int index)
{
if (index < 0 || index >= 12)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 0 + (index * 1));
}
public void SetAccount(int index, byte value)
{
if (index < 0 || index >= 12)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 0 + (index * 1), value);
}
public const string AccountCharacterEncoding = "UTF-8";
public int GetAccount(byte[] dst, int dstOffset)
{
const int length = 12;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 0, dst, dstOffset, length);
return length;
}
public void SetAccount(byte[] src, int srcOffset)
{
const int length = 12;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 0, src, srcOffset, length);
}
public const int ClOrdIDId = 11;
public static string ClOrdIDMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte ClOrdIDNullValue = (byte)0;
public const byte ClOrdIDMinValue = (byte)32;
public const byte ClOrdIDMaxValue = (byte)126;
public const int ClOrdIDLength = 20;
public byte GetClOrdID(int index)
{
if (index < 0 || index >= 20)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 12 + (index * 1));
}
public void SetClOrdID(int index, byte value)
{
if (index < 0 || index >= 20)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 12 + (index * 1), value);
}
public const string ClOrdIDCharacterEncoding = "UTF-8";
public int GetClOrdID(byte[] dst, int dstOffset)
{
const int length = 20;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 12, dst, dstOffset, length);
return length;
}
public void SetClOrdID(byte[] src, int srcOffset)
{
const int length = 20;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 12, src, srcOffset, length);
}
public const int HandInstId = 21;
public static string HandInstMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public HandInst HandInst
{
get
{
return (HandInst)_buffer.CharGet(_offset + 32);
}
set
{
_buffer.CharPut(_offset + 32, (byte)value);
}
}
public const int CustOrderHandlingInstId = 1031;
public static string CustOrderHandlingInstMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public CustOrderHandlingInst CustOrderHandlingInst
{
get
{
return (CustOrderHandlingInst)_buffer.CharGet(_offset + 33);
}
set
{
_buffer.CharPut(_offset + 33, (byte)value);
}
}
public const int OrderQtyId = 38;
public static string OrderQtyMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Qty";
}
return "";
}
private readonly IntQty32 _orderQty = new IntQty32();
public IntQty32 OrderQty
{
get
{
_orderQty.Wrap(_buffer, _offset + 34, _actingVersion);
return _orderQty;
}
}
public const int OrdTypeId = 40;
public static string OrdTypeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public OrdType OrdType
{
get
{
return (OrdType)_buffer.CharGet(_offset + 38);
}
set
{
_buffer.CharPut(_offset + 38, (byte)value);
}
}
public const int PriceId = 44;
public static string PriceMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Price";
}
return "";
}
private readonly OptionalPrice _price = new OptionalPrice();
public OptionalPrice Price
{
get
{
_price.Wrap(_buffer, _offset + 39, _actingVersion);
return _price;
}
}
public const int SideId = 54;
public static string SideMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public Side Side
{
get
{
return (Side)_buffer.CharGet(_offset + 48);
}
set
{
_buffer.CharPut(_offset + 48, (byte)value);
}
}
public const int SymbolId = 55;
public static string SymbolMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte SymbolNullValue = (byte)0;
public const byte SymbolMinValue = (byte)32;
public const byte SymbolMaxValue = (byte)126;
public const int SymbolLength = 6;
public byte GetSymbol(int index)
{
if (index < 0 || index >= 6)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 49 + (index * 1));
}
public void SetSymbol(int index, byte value)
{
if (index < 0 || index >= 6)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 49 + (index * 1), value);
}
public const string SymbolCharacterEncoding = "UTF-8";
public int GetSymbol(byte[] dst, int dstOffset)
{
const int length = 6;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 49, dst, dstOffset, length);
return length;
}
public void SetSymbol(byte[] src, int srcOffset)
{
const int length = 6;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 49, src, srcOffset, length);
}
public const int TimeInForceId = 59;
public static string TimeInForceMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public TimeInForce TimeInForce
{
get
{
return (TimeInForce)_buffer.CharGet(_offset + 55);
}
set
{
_buffer.CharPut(_offset + 55, (byte)value);
}
}
public const int TransactTimeId = 60;
public static string TransactTimeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "UTCTimestamp";
}
return "";
}
public const ulong TransactTimeNullValue = 0x8000000000000000UL;
public const ulong TransactTimeMinValue = 0x0UL;
public const ulong TransactTimeMaxValue = 0x7fffffffffffffffUL;
public ulong TransactTime
{
get
{
return _buffer.Uint64GetLittleEndian(_offset + 56);
}
set
{
_buffer.Uint64PutLittleEndian(_offset + 56, value);
}
}
public const int ManualOrderIndicatorId = 1028;
public static string ManualOrderIndicatorMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public BooleanType ManualOrderIndicator
{
get
{
return (BooleanType)_buffer.Uint8Get(_offset + 64);
}
set
{
_buffer.Uint8Put(_offset + 64, (byte)value);
}
}
public const int AllocAccountId = 79;
public static string AllocAccountMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte AllocAccountNullValue = (byte)0;
public const byte AllocAccountMinValue = (byte)32;
public const byte AllocAccountMaxValue = (byte)126;
public const int AllocAccountLength = 10;
public byte GetAllocAccount(int index)
{
if (index < 0 || index >= 10)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 65 + (index * 1));
}
public void SetAllocAccount(int index, byte value)
{
if (index < 0 || index >= 10)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 65 + (index * 1), value);
}
public const string AllocAccountCharacterEncoding = "UTF-8";
public int GetAllocAccount(byte[] dst, int dstOffset)
{
const int length = 10;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 65, dst, dstOffset, length);
return length;
}
public void SetAllocAccount(byte[] src, int srcOffset)
{
const int length = 10;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 65, src, srcOffset, length);
}
public const int StopPxId = 99;
public static string StopPxMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Price";
}
return "";
}
private readonly OptionalPrice _stopPx = new OptionalPrice();
public OptionalPrice StopPx
{
get
{
_stopPx.Wrap(_buffer, _offset + 75, _actingVersion);
return _stopPx;
}
}
public const int SecurityDescId = 107;
public static string SecurityDescMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte SecurityDescNullValue = (byte)0;
public const byte SecurityDescMinValue = (byte)32;
public const byte SecurityDescMaxValue = (byte)126;
public const int SecurityDescLength = 20;
public byte GetSecurityDesc(int index)
{
if (index < 0 || index >= 20)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 84 + (index * 1));
}
public void SetSecurityDesc(int index, byte value)
{
if (index < 0 || index >= 20)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 84 + (index * 1), value);
}
public const string SecurityDescCharacterEncoding = "UTF-8";
public int GetSecurityDesc(byte[] dst, int dstOffset)
{
const int length = 20;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 84, dst, dstOffset, length);
return length;
}
public void SetSecurityDesc(byte[] src, int srcOffset)
{
const int length = 20;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 84, src, srcOffset, length);
}
public const int MinQtyId = 110;
public static string MinQtyMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Qty";
}
return "";
}
private readonly IntQty32 _minQty = new IntQty32();
public IntQty32 MinQty
{
get
{
_minQty.Wrap(_buffer, _offset + 104, _actingVersion);
return _minQty;
}
}
public const int SecurityTypeId = 167;
public static string SecurityTypeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte SecurityTypeNullValue = (byte)0;
public const byte SecurityTypeMinValue = (byte)32;
public const byte SecurityTypeMaxValue = (byte)126;
public const int SecurityTypeLength = 3;
public byte GetSecurityType(int index)
{
if (index < 0 || index >= 3)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 108 + (index * 1));
}
public void SetSecurityType(int index, byte value)
{
if (index < 0 || index >= 3)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 108 + (index * 1), value);
}
public const string SecurityTypeCharacterEncoding = "UTF-8";
public int GetSecurityType(byte[] dst, int dstOffset)
{
const int length = 3;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 108, dst, dstOffset, length);
return length;
}
public void SetSecurityType(byte[] src, int srcOffset)
{
const int length = 3;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 108, src, srcOffset, length);
}
public const int CustomerOrFirmId = 204;
public static string CustomerOrFirmMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public CustomerOrFirm CustomerOrFirm
{
get
{
return (CustomerOrFirm)_buffer.Uint8Get(_offset + 111);
}
set
{
_buffer.Uint8Put(_offset + 111, (byte)value);
}
}
public const int MaxShowId = 210;
public static string MaxShowMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Qty";
}
return "";
}
private readonly IntQty32 _maxShow = new IntQty32();
public IntQty32 MaxShow
{
get
{
_maxShow.Wrap(_buffer, _offset + 112, _actingVersion);
return _maxShow;
}
}
public const int ExpireDateId = 432;
public static string ExpireDateMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ushort ExpireDateNullValue = (ushort)65535;
public const ushort ExpireDateMinValue = (ushort)0;
public const ushort ExpireDateMaxValue = (ushort)65534;
public ushort ExpireDate
{
get
{
return _buffer.Uint16GetLittleEndian(_offset + 116);
}
set
{
_buffer.Uint16PutLittleEndian(_offset + 116, value);
}
}
public const int SelfMatchPreventionIDId = 7928;
public static string SelfMatchPreventionIDMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte SelfMatchPreventionIDNullValue = (byte)0;
public const byte SelfMatchPreventionIDMinValue = (byte)32;
public const byte SelfMatchPreventionIDMaxValue = (byte)126;
public const int SelfMatchPreventionIDLength = 12;
public byte GetSelfMatchPreventionID(int index)
{
if (index < 0 || index >= 12)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 118 + (index * 1));
}
public void SetSelfMatchPreventionID(int index, byte value)
{
if (index < 0 || index >= 12)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 118 + (index * 1), value);
}
public const string SelfMatchPreventionIDCharacterEncoding = "UTF-8";
public int GetSelfMatchPreventionID(byte[] dst, int dstOffset)
{
const int length = 12;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 118, dst, dstOffset, length);
return length;
}
public void SetSelfMatchPreventionID(byte[] src, int srcOffset)
{
const int length = 12;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 118, src, srcOffset, length);
}
public const int CtiCodeId = 9702;
public static string CtiCodeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public CtiCode CtiCode
{
get
{
return (CtiCode)_buffer.CharGet(_offset + 130);
}
set
{
_buffer.CharPut(_offset + 130, (byte)value);
}
}
public const int GiveUpFirmId = 9707;
public static string GiveUpFirmMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte GiveUpFirmNullValue = (byte)0;
public const byte GiveUpFirmMinValue = (byte)32;
public const byte GiveUpFirmMaxValue = (byte)126;
public const int GiveUpFirmLength = 3;
public byte GetGiveUpFirm(int index)
{
if (index < 0 || index >= 3)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 131 + (index * 1));
}
public void SetGiveUpFirm(int index, byte value)
{
if (index < 0 || index >= 3)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 131 + (index * 1), value);
}
public const string GiveUpFirmCharacterEncoding = "UTF-8";
public int GetGiveUpFirm(byte[] dst, int dstOffset)
{
const int length = 3;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 131, dst, dstOffset, length);
return length;
}
public void SetGiveUpFirm(byte[] src, int srcOffset)
{
const int length = 3;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 131, src, srcOffset, length);
}
public const int CmtaGiveupCDId = 9708;
public static string CmtaGiveupCDMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte CmtaGiveupCDNullValue = (byte)0;
public const byte CmtaGiveupCDMinValue = (byte)32;
public const byte CmtaGiveupCDMaxValue = (byte)126;
public const int CmtaGiveupCDLength = 2;
public byte GetCmtaGiveupCD(int index)
{
if (index < 0 || index >= 2)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 134 + (index * 1));
}
public void SetCmtaGiveupCD(int index, byte value)
{
if (index < 0 || index >= 2)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 134 + (index * 1), value);
}
public const string CmtaGiveupCDCharacterEncoding = "UTF-8";
public int GetCmtaGiveupCD(byte[] dst, int dstOffset)
{
const int length = 2;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 134, dst, dstOffset, length);
return length;
}
public void SetCmtaGiveupCD(byte[] src, int srcOffset)
{
const int length = 2;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 134, src, srcOffset, length);
}
public const int CorrelationClOrdIDId = 9717;
public static string CorrelationClOrdIDMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte CorrelationClOrdIDNullValue = (byte)0;
public const byte CorrelationClOrdIDMinValue = (byte)32;
public const byte CorrelationClOrdIDMaxValue = (byte)126;
public const int CorrelationClOrdIDLength = 20;
public byte GetCorrelationClOrdID(int index)
{
if (index < 0 || index >= 20)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 136 + (index * 1));
}
public void SetCorrelationClOrdID(int index, byte value)
{
if (index < 0 || index >= 20)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 136 + (index * 1), value);
}
public const string CorrelationClOrdIDCharacterEncoding = "UTF-8";
public int GetCorrelationClOrdID(byte[] dst, int dstOffset)
{
const int length = 20;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 136, dst, dstOffset, length);
return length;
}
public void SetCorrelationClOrdID(byte[] src, int srcOffset)
{
const int length = 20;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 136, src, srcOffset, length);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MathNet.Numerics.Statistics;
using SimShift.Map.Splines;
using CubicSpline = MathNet.Numerics.Interpolation.CubicSpline;
namespace SimShift.MapTool
{
public class Ets2Mapper
{
public bool Loading { get; private set; }
public string SectorFolder { get; private set; }
public string[] SectorFiles { get; private set; }
public string PrefabFolder { get; private set; }
public string[] PrefabFiles { get; private set; }
public string LUTFolder { get; private set; }
public List<Ets2Sector> Sectors { get; private set; }
public ConcurrentDictionary<ulong, Ets2Node> Nodes = new ConcurrentDictionary<ulong, Ets2Node>();
public ConcurrentDictionary<ulong, Ets2Item> Items = new ConcurrentDictionary<ulong, Ets2Item>();
public Dictionary<string, Ets2Item> Cities = new Dictionary<string, Ets2Item>();
public Dictionary<Tuple<string, string>, Ets2Item> Companies = new Dictionary<Tuple<string, string>, Ets2Item>();
/*** SOME ITEMS CROSS MULTIPLE SECTORS; PENDING SEARCH REQUESTS ***/
private List<Ets2ItemSearchRequest> ItemSearchRequests { get; set; }
/*** VARIOUS LOOK UP TABLES (LUTs) TO FIND CERTAIN GAME ITEMS ***/
internal List<Ets2Prefab> PrefabsLookup = new List<Ets2Prefab>();
private List<Ets2Company> CompaniesLookup = new List<Ets2Company>();
private Dictionary<int, Ets2Prefab> PrefabLookup = new Dictionary<int, Ets2Prefab>();
private Dictionary<ulong, string> CitiesLookup = new Dictionary<ulong, string>();
private Dictionary<uint, Ets2RoadLook> RoadLookup = new Dictionary<uint, Ets2RoadLook>();
public Ets2Mapper(string sectorFolder, string prefabFolder, string lut)
{
SectorFolder = sectorFolder;
PrefabFolder = prefabFolder;
SectorFiles = Directory.GetFiles(sectorFolder, "*.base");
PrefabFiles = Directory.GetFiles(prefabFolder, "*.ppd", SearchOption.AllDirectories);
LUTFolder = lut;
}
public Ets2Item FindClosestRoadPrefab(PointF location)
{
// Find road or prefab closest by
var closestPrefab =
Items.Values.Where(x => x.HideUI==false && x.Type == Ets2ItemType.Prefab && x.Prefab != null && x.Prefab.Curves.Any())
.OrderBy(x => Math.Sqrt(Math.Pow(location.X - x.PrefabNode.X, 2) + Math.Pow(location.Y - x.PrefabNode.Z, 2)))
.FirstOrDefault();
return closestPrefab;
}
/// <summary>
/// Navigate from X/Y to X/Y coordinates
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
public Ets2NavigationRoute NavigateTo(PointF from, PointF to)
{
var start = FindClosestRoadPrefab(from);
var end = FindClosestRoadPrefab(to);
Console.WriteLine("Navigating from " + start.ItemUID.ToString("X16") + " to " + end.ItemUID.ToString("X16"));
// Look up pre-fab closest by these 2 points
return new Ets2NavigationRoute(start,end, new Ets2Point(from), new Ets2Point(to), this);
}
/// <summary>
/// Navigate to city from X/Y point
/// </summary>
/// <param name="from"></param>
/// <param name="city"></param>
public Ets2NavigationRoute NavigateTo(PointF from, string city)
{
if (Cities.ContainsKey(city) == false)
return null;
var cityPoint = new PointF(Cities[city].StartNode.X, Cities[city].StartNode.Z);
var start = FindClosestRoadPrefab(from);
var end = FindClosestRoadPrefab(cityPoint);
return new Ets2NavigationRoute(start,end, new Ets2Point(from), null, this);
}
/// <summary>
/// Navigate to city company from X/Y point
/// </summary>
/// <param name="from"></param>
/// <param name="city"></param>
/// <param name="company"></param>
public Ets2NavigationRoute NavigateTo(PointF from, string city, string company)
{
throw new NotImplementedException();
}
private void LoadLUT()
{
// PREFABS
var sii = LUTFolder + "-prefab.sii";
var csv = LUTFolder + "-prefab.csv";
Dictionary<string, string> prefab2file = new Dictionary<string, string>();
Dictionary<int, string> idx2prefab = new Dictionary<int, string>();
var csvLines = File.ReadAllLines(csv);
foreach (var k in csvLines)
{
var d = k.Split(",".ToCharArray());
int idx;
if (int.TryParse(d[2], NumberStyles.HexNumber, null, out idx))
{
if (idx2prefab.ContainsKey(idx) == false)
idx2prefab.Add(idx, d[1]);
}
}
var siiLines = File.ReadAllLines(sii);
var prefab = string.Empty;
var file = string.Empty;
foreach (var k in siiLines)
{
if (k.Trim() == "}")
{
if (prefab != string.Empty && file != string.Empty)
{
prefab2file.Add(prefab, file);
}
prefab = string.Empty;
file = string.Empty;
}
if (k.StartsWith("prefab_model"))
{
var d = k.Split(":".ToCharArray()).Select(x => x.Trim()).ToArray();
if (d[1].Length > 3)
{
prefab = d[1].Substring(0, d[1].Length - 1).Trim();
}
}
if (k.Contains("prefab_desc"))
{
var d = k.Split("\"".ToCharArray());
file = d[1].Trim();
}
}
// Link all prefabs
foreach (var id2fab in idx2prefab)
{
if (prefab2file.ContainsKey(id2fab.Value))
{
var f = prefab2file[id2fab.Value];
var obj = PrefabsLookup.FirstOrDefault(x => x.IsFile(f));
if (obj != null)
{
obj.IDX = id2fab.Key;
obj.IDSII = id2fab.Value;
PrefabLookup.Add(id2fab.Key, obj);
}
}
}
// COMPANIES
CompaniesLookup = File.ReadAllLines(LUTFolder + "-companies.csv").Select(x => new Ets2Company(x, this)).ToList();
// CITIES
CitiesLookup = File.ReadAllLines(LUTFolder + "-cities.csv").Select(x =>
{
var d = x.Split(",".ToCharArray());
var id = ulong.Parse(d[0], NumberStyles.HexNumber);
var city = d[1];
return new KeyValuePair<ulong, string>(id, city);
}).ToDictionary(x => x.Key, x => x.Value);
// ROAD LOOKS
RoadLookup = File.ReadAllLines(LUTFolder + "-roads.csv").Select(x =>
{
var d = x.Split(",".ToCharArray());
var id = uint.Parse(d[0], NumberStyles.HexNumber);
var look = d[1];
var lookObj = new Ets2RoadLook(look,this);
return new KeyValuePair<uint, Ets2RoadLook>(id, lookObj);
}).ToDictionary(x => x.Key, x => x.Value);
}
public void Parse()
{
ThreadPool.SetMaxThreads(2, 2);
Loading = true;
// First load prefabs
PrefabsLookup = PrefabFiles.Select(x => new Ets2Prefab(this, x)).ToList();
// Load all LUTs
LoadLUT();
ItemSearchRequests = new List<Ets2ItemSearchRequest>();
Sectors = SectorFiles.Select(x => new Ets2Sector(this, x)).ToList();
// 2-stage process so we can validate node UID's at item stage
ThreadPool.SetMaxThreads(1, 1);
Parallel.ForEach(Sectors, (sec) => sec.ParseNodes());
Parallel.ForEach(Sectors, (sec) => sec.ParseItems());
Loading = false;
// Now find all that were not ofund
ItemSearchRequests.Clear();
Console.WriteLine(ItemSearchRequests.Count +
" were not found; attempting to search them through all sectors");
foreach (var req in ItemSearchRequests)
{
Ets2Item item = Sectors.Select(sec => sec.FindItem(req.ItemUID)).FirstOrDefault(tmp => tmp != null);
if (item == null)
{
Console.WriteLine("Still couldn't find node " + req.ItemUID.ToString("X16"));
}
else
{
if (req.IsBackward)
{
item.Apply(req.Node);
req.Node.BackwardItem = item;
}
if (req.IsForward)
{
item.Apply(req.Node);
req.Node.ForwardItem = item;
}
if (item.StartNode == null && item.StartNodeUID != null)
{
Ets2Node startNode;
if (Nodes.TryGetValue(item.StartNodeUID, out startNode))
item.Apply(startNode);
}
if (item.EndNode == null && item.EndNodeUID != null)
{
Ets2Node endNode;
if (Nodes.TryGetValue(item.EndNodeUID, out endNode))
item.Apply(endNode);
}
Console.Write(".");
}
}
// Navigation cache
BuildNavigationCache();
// Lookup all cities
Cities = Items.Values.Where(x => x.Type == Ets2ItemType.City).GroupBy(x=>x.City).Select(x=>x.FirstOrDefault()).ToDictionary(x => x.City, x => x);
Console.WriteLine(Items.Values.Count(x => x.Type == Ets2ItemType.Building) + " buildings were found");
Console.WriteLine(Items.Values.Count(x => x.Type == Ets2ItemType.Road) + " roads were found");
Console.WriteLine(Items.Values.Count(x => x.Type == Ets2ItemType.Prefab) + " prefabs were found");
Console.WriteLine(Items.Values.Count(x => x.Type == Ets2ItemType.Prefab && x.Prefab != null && x.Prefab.Curves.Any()) + " road prefabs were found");
Console.WriteLine(Items.Values.Count(x => x.Type == Ets2ItemType.Service) + " service points were found");
Console.WriteLine(Items.Values.Count(x => x.Type == Ets2ItemType.Company) + " companies were found");
Console.WriteLine(Items.Values.Count(x => x.Type == Ets2ItemType.City) + " cities were found");
}
private void BuildNavigationCache()
{
// The idea of navigation cache is that we calculate distances between nodes
// The nodes we identify as prefabs (cross points etc.)
// Distance between them are the roads
// This way we don't have to walk through each road segment (which can be hundreds or thousands) each time we want to know the node-node length
// This is a reduction of approximately 6x
Dictionary<ulong, Dictionary<ulong, float>> cache = new Dictionary<ulong, Dictionary<ulong, float>>();
foreach (var prefab in Items.Values.Where(x => x.HideUI == false && x.Type == Ets2ItemType.Prefab))
{
foreach (var node in prefab.NodesList.Values)
{
var endNode = default(Ets2Item);
var fw = node.ForwardItem != null && node.ForwardItem.Type == Ets2ItemType.Road;
var road = node.ForwardItem != null && node.ForwardItem.Type == Ets2ItemType.Prefab
? node.BackwardItem
: node.ForwardItem;
var totalLength = 0.0f;
var weight = 0.0f;
List<Ets2Item> roadList = new List<Ets2Item>();
while (road != null)
{
if (road.StartNode == null || road.EndNode == null)
break;
var length =
(float)Math.Sqrt(Math.Pow(road.StartNode.X - road.EndNode.X, 2) +
Math.Pow(road.StartNode.Z - road.EndNode.Z, 2));
var spd = 1;
if (road.RoadLook != null)
{
if (road.RoadLook.IsExpress) spd = 25;
if (road.RoadLook.IsLocal) spd = 45;
if (road.RoadLook.IsHighway) spd = 70;
}
totalLength += length;
weight += length / spd;
roadList.Add(road);
if (fw)
{
road = road.EndNode == null?null: road.EndNode.ForwardItem;
if (road != null && road.Type == Ets2ItemType.Prefab)
{
endNode = road;
break;
}
}
else
{
road = road.StartNode == null ? null : road.StartNode.BackwardItem;
if (road != null && road.Type == Ets2ItemType.Prefab)
{
endNode = road;
break;
}
}
}
if (prefab.ItemUID == 0x002935DED8C0345C)
{
Console.WriteLine(node.NodeUID.ToString("X16") + " following to " + endNode.ItemUID.ToString("X16"));
}
// If there is no end-node found, it is a dead-end road.
if (endNode != null && prefab != endNode)
{
if (prefab.Navigation.ContainsKey(endNode) == false)
{
prefab.Navigation.Add(endNode,
new Tuple<float, float, IEnumerable<Ets2Item>>(weight, totalLength, roadList));
}
if (endNode.Navigation.ContainsKey(prefab) == false)
{
var reversedRoadList = new List<Ets2Item>(roadList);
reversedRoadList.Reverse();
endNode.Navigation.Add(prefab,
new Tuple<float, float, IEnumerable<Ets2Item>>(weight, totalLength, reversedRoadList));
}
}
}
}
}
public void Find(Ets2Node node, ulong item, bool isBackward)
{
var req = new Ets2ItemSearchRequest
{
ItemUID = item,
Node = node,
IsBackward = isBackward,
IsForward = !isBackward
};
ItemSearchRequests.Add(req);
}
public string LookupCityID(ulong id)
{
return !CitiesLookup.ContainsKey(id) ? string.Empty : CitiesLookup[id];
}
public Ets2Prefab LookupPrefab(int prefabId)
{
if (PrefabLookup.ContainsKey(prefabId))
return PrefabLookup[prefabId];
else
return null;
}
public Ets2RoadLook LookupRoadLookID(uint lookId)
{
if (RoadLookup.ContainsKey(lookId))
return RoadLookup[lookId];
else
return null;
}
}
}
| |
// <copyright file="MainWindowForm.cs" company="Public Domain">
// Released into the public domain
// </copyright>
// This file is part of the C# Finder application. It is free and
// unencumbered software released into the public domain as detailed
// in the UNLICENSE file in the top level directory of this distribution
namespace Finder
{
using System.Linq; // Required for Any, Count and Where methods in Linq
/// <summary>
/// This class provides the main window form
/// </summary>
public partial class MainWindowForm : System.Windows.Forms.Form
{
/// <summary>
/// The class that will perform the processing of the files in the selected directory
/// </summary>
private Processing theProcessing;
/// <summary>
/// The class that will provide for auto-completion for the text box in which to enter the search term
/// </summary>
private System.Windows.Forms.AutoCompleteStringCollection theSearchTermTextBoxAutoCompletion;
/// <summary>
/// Initializes a new instance of the MainWindowForm class
/// </summary>
public MainWindowForm()
{
this.InitializeComponent();
// Set the text of the title bar of the main window form to the identification for the application
// The name, version and date for the application are provided in the Constants class
this.Text =
Constants.Name +
Properties.Resources.SpaceCharacter +
Constants.Version +
Properties.Resources.SpaceCharacter +
Constants.Date;
// Reset the main window form
// Pass true as we want to reset the size of the main window form in this case
this.ResetMainWindowForm(true);
// Initialise the class that will perform the processing of the source file
this.theProcessing = new Processing(this);
// Initialise the class that will provide for auto-completion for the text box in which to enter the search term
this.theSearchTermTextBoxAutoCompletion =
new System.Windows.Forms.AutoCompleteStringCollection();
// Add the text box in which to enter the search term to the set for which auto-completion will be provided
this.theSearchTermTextBoxAutoCompletion.Add(this.theSearchTermTextBox.Text);
// Set up the parameters for the auto-completion to be provided to the text box in which to enter the search term
this.theSearchTermTextBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.theSearchTermTextBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
this.theSearchTermTextBox.AutoCompleteCustomSource = this.theSearchTermTextBoxAutoCompletion;
}
//// Button Events
/// <summary>
/// Processes the button click event for the "Select Directory" button
/// </summary>
/// <param name="sender">The sender for the button click event</param>
/// <param name="e">The arguments for the button click event</param>
private void SelectDirectoryButton_Click(object sender, System.EventArgs e)
{
// Start the dialog at the file initially set or resultant from the last time it was used (whichever happened most recently)
this.theSelectDirectoryFolderBrowserDialog.SelectedPath = this.theSelectedDirectoryTextBox.Text;
// Open the dialog to select a file path and check whether the OK action key was selected
if (this.theSelectDirectoryFolderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Reset the main window form
// Pass false as we do not want to reset the size of the main window form in this case
this.ResetMainWindowForm(false);
// Output the selected file path to the text box that displays the selected directory
this.theSelectedDirectoryTextBox.Text =
this.theSelectDirectoryFolderBrowserDialog.SelectedPath;
// Enable, focus on and select the text box in which to enter the search term
this.MoveToSearchTermTextBox();
}
}
/// <summary>
/// Processes the button click event for the "Search" button
/// </summary>
/// <param name="sender">The sender for the button click event</param>
/// <param name="e">The arguments for the button click event</param>
private void SearchButton_Click(object sender, System.EventArgs e)
{
// Only enable searching for the term in the text box if it contains text
if (this.theSearchTermTextBox.Text.Length > 0)
{
// Add the entered search term text to the set used for auto-completion
this.theSearchTermTextBox.AutoCompleteCustomSource.Add(this.theSearchTermTextBox.Text);
// Perform the search for the search term text in the files in the supplied directory
this.PerformSearchInDirectory();
}
}
/// <summary>
/// Processes the button click event for the "Reset" button
/// </summary>
/// <param name="sender">The sender for the button click event</param>
/// <param name="e">The arguments for the button click event</param>
private void ResetButton_Click(object sender, System.EventArgs e)
{
// Reset the main window form
// Pass true as we want to reset the size of the main window form in this case
this.ResetMainWindowForm(true);
}
/// <summary>
/// Processes the button click event for the "Exit" button
/// </summary>
/// <param name="sender">The sender for the button click event</param>
/// <param name="e">The arguments for the button click event</param>
private void ExitButton_Click(object sender, System.EventArgs e)
{
this.Close();
}
//// Text Box Events
/// <summary>
/// Processes the text changed event for the the text box in which to enter the search term
/// </summary>
/// <param name="sender">The sender for the text changed event</param>
/// <param name="e">The arguments for the text changed event</param>
private void SearchTermTextBox_TextChanged(object sender, System.EventArgs e)
{
// Only enable the "Search" button if the text box in
// which to enter the search term if it contains text
if (this.theSearchTermTextBox.Text.Length > 0)
{
this.theSearchButton.Enabled = true;
}
else
{
this.theSearchButton.Enabled = false;
}
}
/// <summary>
/// Processes the key down event for the text box in which to enter the search term
/// </summary>
/// <param name="sender">The sender for the key down event</param>
/// <param name="e">The arguments for the key down event</param>
private void SearchTermTextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == System.Windows.Forms.Keys.Enter)
{
// Only enable clicking Enter in the text box in which
// to enter the search term if it contains text
if (this.theSearchTermTextBox.Text.Length > 0)
{
// Add the entered search term text to the set used for auto-completion
this.theSearchTermTextBox.AutoCompleteCustomSource.Add(this.theSearchTermTextBox.Text);
// Perform the search for the search term text in the files in the supplied directory
this.PerformSearchInDirectory();
}
}
}
/// <summary>
/// Processes the click event for the rich text box that displays the instances of the search term text that were found in the currently selected file
/// </summary>
/// <param name="sender">The sender for the click event</param>
/// <param name="e">The arguments for the click event</param>
private void FoundSearchTermRichTextBox_Click(object sender, System.EventArgs e)
{
// Reflect the selection of an instance in the rich text box
this.theProcessing.ReflectSelectedInstance();
}
/// <summary>
/// Processes the double click event for the rich text box that displays the instances of the search term text that were found in the currently selected file
/// </summary>
/// <param name="sender">The sender for the double click event</param>
/// <param name="e">The arguments for the double click event</param>
private void FoundSearchTermRichTextBox_DoubleClick(object sender, System.EventArgs e)
{
// Reflect the selection of an instance in the rich text box
// Capture the line number in the file returned so we can use it for opening to the correct line
string theFileLineNumber = this.theProcessing.ReflectSelectedInstance();
// Open the file containing the selected instance in the rich text box
Processing.OpenFile(
this.theFoundFilesListBox.SelectedItem.ToString(),
theFileLineNumber);
}
/// <summary>
/// Processes the mouse up event for the rich text box that displays the instances of the search term text that were found in the currently selected file
/// </summary>
/// <param name="sender">The sender for the mouse up event</param>
/// <param name="e">The arguments for the mouse up event</param>
private void FoundSearchTermRichTextBox_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
// Clear the selection of the text in the rich text box
this.theFoundSearchTermRichTextBox.SelectionLength = 0;
}
/// <summary>
/// Processes the key down event for the rich text box that displays the instances of the search term text that were found in the currently selected file
/// </summary>
/// <param name="sender">The sender for the key down event</param>
/// <param name="e">The arguments for the key down event</param>
private void FoundSearchTermRichTextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == System.Windows.Forms.Keys.Enter)
{
// Reflect the selection of an instance in the rich text box
// Capture the line number in the file returned so we can use it for opening to the correct line
string theFileLineNumber = this.theProcessing.ReflectSelectedInstance();
// Open the file containing the selected instance in the rich text box
Processing.OpenFile(
this.theFoundFilesListBox.SelectedItem.ToString(),
theFileLineNumber);
}
}
/// <summary>
/// Processes the key up event for the rich text box that displays the instances of the search term text that were found in the currently selected file
/// </summary>
/// <param name="sender">The sender for the key up event</param>
/// <param name="e">The arguments for the key up event</param>
private void FoundSearchTermRichTextBox_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == System.Windows.Forms.Keys.Up ||
e.KeyCode == System.Windows.Forms.Keys.Down)
{
// Reflect the selection of an instance in the rich text box
this.theProcessing.ReflectSelectedInstance();
// Clear the selection of the text in the rich text box
this.theFoundSearchTermRichTextBox.SelectionLength = 0;
}
else
{
// Clear the selection of the text in the rich text box
this.theFoundSearchTermRichTextBox.SelectionLength = 0;
}
}
//// List Box Events
/// <summary>
/// Processes the selected index changed event for the list box that displays the files in which instances of the search term text was found
/// </summary>
/// <param name="sender">The sender for the selected index changed event</param>
/// <param name="e">The arguments for the selected index changed event</param>
private void FoundFilesListBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
// Reflect a change to the selected index for the list box that displays the files in which instances of the search term text was found
this.theProcessing.ReflectSelectedIndexChange();
}
/// <summary>
/// Processes the double click event for the list box that displays the files in which instances of the search term text was found
/// </summary>
/// <param name="sender">The sender for the double click event</param>
/// <param name="e">The arguments for the double click event</param>
private void FoundFilesListBox_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
{
// Open the file double clicked on in the list box
Processing.OpenFile(
this.theFoundFilesListBox.SelectedItem.ToString(),
null);
}
/// <summary>
/// Processes the key down event for the list box that displays the files in which instances of the search term text was found
/// </summary>
/// <param name="sender">The sender for the key down event</param>
/// <param name="e">The arguments for the key down event</param>
private void FoundFilesListBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == System.Windows.Forms.Keys.Enter)
{
// On clicking enter on an item in the list box move to the first line of the rich text box that displays the instances of the search term text that were found in the currently selected file
this.theFoundSearchTermRichTextBox
.Select(0, 1);
this.theFoundSearchTermRichTextBox
.ScrollToCaret();
this.theFoundSearchTermRichTextBox
.DeselectAll();
// Reflect the selection of an instance in the rich text box
this.theProcessing.ReflectSelectedInstance();
// Clear the selection of the text in the rich text box
this.theFoundSearchTermRichTextBox.SelectionLength = 0;
this.theFoundSearchTermRichTextBox.Focus();
}
}
//// Check Box Events
/// <summary>
/// Processes the checked changed event for the check box that indicates whether to include all files while searching
/// </summary>
/// <param name="sender">The sender for the checked changed event</param>
/// <param name="e">The arguments for the checked changed event</param>
private void AllCheckBox_CheckedChanged(object sender, System.EventArgs e)
{
// Check if the checked changed event follows the "All" check
// box in the "File Types" group box becoming checked or not
if (this.theAllCheckBox.Checked)
{
// The "All" check box in the "File Types" group box became checked
// Disable the specific check boxes in the "File Types" group box
this.theCPlusPlusSourceCheckBox.Enabled = false;
this.theCPlusPlusCHeaderCheckBox.Enabled = false;
this.theCSourceCheckBox.Enabled = false;
this.theCSharpCheckBox.Enabled = false;
}
else
{
// The "All" check box in the "File Types" group box became not checked
// Enable the specific check boxes in the "File Types" group box
this.theCPlusPlusSourceCheckBox.Enabled = true;
this.theCPlusPlusCHeaderCheckBox.Enabled = true;
this.theCSourceCheckBox.Enabled = true;
this.theCSharpCheckBox.Enabled = true;
}
// Reset the specific check boxes in the "File Types" group box to all checked
this.theCPlusPlusSourceCheckBox.Checked = true;
this.theCPlusPlusCHeaderCheckBox.Checked = true;
this.theCSourceCheckBox.Checked = true;
this.theCSharpCheckBox.Checked = true;
}
//// Processing
/// <summary>
/// Performs the search for the search term text in the files in the supplied directory
/// </summary>
private void PerformSearchInDirectory()
{
// Disable the "Search" button while the search is being performed
this.theSearchButton
.Enabled = false;
this.theSearchButton
.Refresh();
// Disable the text box in which to enter the search term while the search is being performed
this.theSearchTermTextBox
.Enabled = false;
this.theSearchTermTextBox
.Refresh();
// Perform the search for the search term text in the files in the supplied directory
if (this.theProcessing.PerformSearchInDirectory(this.theSelectedDirectoryTextBox.Text))
{
//// The search found at least one instance of the search term text in the files in the supplied directory
// Enable the text box in which to enter the search term again now the search has been performed
this.theSearchTermTextBox
.Enabled = true;
this.theSearchTermTextBox
.Refresh();
}
else
{
//// The search did not find any instances of the search term text in the files in the supplied directory
// Enable, focus on and select the text box in which to enter the search term so we can try again
this.MoveToSearchTermTextBox();
}
// Enable the "Search" button again now the search has been performed
this.theSearchButton
.Enabled = true;
this.theSearchButton
.Refresh();
}
/// <summary>
/// Enable, focus on and select the text box in which to enter the search term
/// </summary>
private void MoveToSearchTermTextBox()
{
// Enable the text box in which to enter the search term
this.theSearchTermTextBox
.Enabled = true;
// Focus on the text box in which to enter the search term
this.theSearchTermTextBox
.Focus();
// Select all the text in the text box in which to enter the search term
this.theSearchTermTextBox
.SelectAll();
// Refresh the text box in which to enter the search term
this.theSearchTermTextBox
.Refresh();
}
/// <summary>
/// Reset the main window form
/// </summary>
/// <param name="isResetWindowFormSize">Boolean flag to indicate whether to reset the size of the main window form</param>
private void ResetMainWindowForm(bool isResetWindowFormSize)
{
if (isResetWindowFormSize)
{
// Reset the size of the main window form
this.Size = new System.Drawing.Size(1100, 600);
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
}
// Enable the "Select Directory" button
this.theSelectDirectoryButton.Enabled = true;
// Disable the "Search" button
this.theSearchButton.Enabled = false;
// Reset and disable the text box that displays the selected directory
this.theSelectedDirectoryTextBox.Text = string.Empty;
this.theSelectedDirectoryTextBox.Enabled = false;
// Clear and disable the text box in which to enter the search term
this.theSearchTermTextBoxLabel.Visible = true;
this.theSearchTermTextBox.Text = string.Empty;
this.theSearchTermTextBox.Enabled = false;
this.theSearchTermTextBox.Visible = true;
// Clear and disable the rich text box that displays the instances of the search term text that were found in the currently selected file
this.theFoundSearchTermRichTextBox.Clear();
this.theFoundSearchTermRichTextBox.Enabled = false;
// Clear and disable the list box that displays the files in which instances of the search term text was found
this.theFoundFilesListBox.Items.Clear();
this.theFoundFilesListBox.ClearSelected();
this.theFoundFilesListBox.Enabled = false;
// Reset and hide the progress bar that shows progress during the search
this.thePerformSearchProgressBarLabel.Visible = false;
this.thePerformSearchProgressBar.Value = 0;
this.thePerformSearchProgressBar.Enabled = false;
this.thePerformSearchProgressBar.Visible = false;
// Reset the check boxes in the "Inclusions" group box to all disabled
this.theSearchRecursivelyCheckBox.Checked = true;
// Reset the check boxes in the "Exclusions" group box to all disabled
this.theIgnoreCommentsCheckBox.Checked = false;
this.theCaseSensitiveCheckBox.Checked = false;
// Reset the "All" check box in the "File Types" group box to not checked and enabled
this.theAllCheckBox.Checked = false;
this.theAllCheckBox.Enabled = true;
// Reset the specific check boxes in the "File Types" group box to all checked and enabled
this.theCPlusPlusSourceCheckBox.Checked = true;
this.theCPlusPlusSourceCheckBox.Enabled = true;
this.theCPlusPlusCHeaderCheckBox.Checked = true;
this.theCPlusPlusCHeaderCheckBox.Enabled = true;
this.theCSourceCheckBox.Checked = true;
this.theCSourceCheckBox.Enabled = true;
this.theCSharpCheckBox.Checked = true;
this.theCSharpCheckBox.Enabled = true;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
** PURPOSE: Helpers for XML input & output
**
===========================================================*/
namespace System.Security.Util {
using System;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.IO;
using System.Text;
using System.Runtime.CompilerServices;
using PermissionState = System.Security.Permissions.PermissionState;
using BindingFlags = System.Reflection.BindingFlags;
using Assembly = System.Reflection.Assembly;
using System.Threading;
using System.Globalization;
using System.Reflection;
using System.Diagnostics.Contracts;
internal static class XMLUtil
{
//
// Warning: Element constructors have side-effects on their
// third argument.
//
private const String BuiltInPermission = "System.Security.Permissions.";
#if FEATURE_CAS_POLICY
private const String BuiltInMembershipCondition = "System.Security.Policy.";
private const String BuiltInCodeGroup = "System.Security.Policy.";
private const String BuiltInApplicationSecurityManager = "System.Security.Policy.";
private static readonly char[] sepChar = {',', ' '};
#endif
public static SecurityElement
NewPermissionElement (IPermission ip)
{
return NewPermissionElement (ip.GetType ().FullName) ;
}
public static SecurityElement
NewPermissionElement (String name)
{
SecurityElement ecr = new SecurityElement( "Permission" );
ecr.AddAttribute( "class", name );
return ecr;
}
public static void
AddClassAttribute( SecurityElement element, Type type, String typename )
{
// Replace any quotes with apostrophes so that we can include quoted materials
// within classnames. Notably the assembly name member 'loc' uses a quoted string.
// NOTE: this makes assumptions as to what reflection is expecting for a type string
// it will need to be updated if reflection changes what it wants.
if ( typename == null )
typename = type.FullName;
Contract.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName);
element.AddAttribute( "class", typename + ", " + type.Module.Assembly.FullName.Replace( '\"', '\'' ) );
}
internal static bool ParseElementForAssemblyIdentification(SecurityElement el,
out String className,
out String assemblyName, // for example "WindowsBase"
out String assemblyVersion)
{
className = null;
assemblyName = null;
assemblyVersion = null;
String fullClassName = el.Attribute( "class" );
if (fullClassName == null)
{
return false;
}
if (fullClassName.IndexOf('\'') >= 0)
{
fullClassName = fullClassName.Replace( '\'', '\"' );
}
int commaIndex = fullClassName.IndexOf( ',' );
int namespaceClassNameLength;
// If the classname is tagged with assembly information, find where
// the assembly information begins.
if (commaIndex == -1)
{
return false;
}
namespaceClassNameLength = commaIndex;
className = fullClassName.Substring(0, namespaceClassNameLength);
String assemblyFullName = fullClassName.Substring(commaIndex + 1);
AssemblyName an = new AssemblyName(assemblyFullName);
assemblyName = an.Name;
assemblyVersion = an.Version.ToString();
return true;
}
[System.Security.SecurityCritical] // auto-generated
private static bool
ParseElementForObjectCreation( SecurityElement el,
String requiredNamespace,
out String className,
out int classNameStart,
out int classNameLength )
{
className = null;
classNameStart = 0;
classNameLength = 0;
int requiredNamespaceLength = requiredNamespace.Length;
String fullClassName = el.Attribute( "class" );
if (fullClassName == null)
{
throw new ArgumentException( Environment.GetResourceString( "Argument_NoClass" ) );
}
if (fullClassName.IndexOf('\'') >= 0)
{
fullClassName = fullClassName.Replace( '\'', '\"' );
}
if (!PermissionToken.IsMscorlibClassName( fullClassName ))
{
return false;
}
int commaIndex = fullClassName.IndexOf( ',' );
int namespaceClassNameLength;
// If the classname is tagged with assembly information, find where
// the assembly information begins.
if (commaIndex == -1)
{
namespaceClassNameLength = fullClassName.Length;
}
else
{
namespaceClassNameLength = commaIndex;
}
// Only if the length of the class name is greater than the namespace info
// on our requiredNamespace do we continue
// with our check.
if (namespaceClassNameLength > requiredNamespaceLength)
{
// Make sure we are in the required namespace.
if (fullClassName.StartsWith(requiredNamespace, StringComparison.Ordinal))
{
className = fullClassName;
classNameLength = namespaceClassNameLength - requiredNamespaceLength;
classNameStart = requiredNamespaceLength;
return true;
}
}
return false;
}
#if FEATURE_CAS_POLICY
public static String SecurityObjectToXmlString(Object ob)
{
if(ob == null)
return "";
PermissionSet pset = ob as PermissionSet;
if(pset != null)
return pset.ToXml().ToString();
return ((IPermission)ob).ToXml().ToString();
}
[System.Security.SecurityCritical] // auto-generated
public static Object XmlStringToSecurityObject(String s)
{
if(s == null)
return null;
if(s.Length < 1)
return null;
return SecurityElement.FromString(s).ToSecurityObject();
}
#endif // FEATURE_CAS_POLICY
[SecuritySafeCritical]
public static IPermission
CreatePermission (SecurityElement el, PermissionState permState, bool ignoreTypeLoadFailures)
{
if (el == null || !(el.Tag.Equals("Permission") || el.Tag.Equals("IPermission")) )
throw new ArgumentException( String.Format( null, Environment.GetResourceString( "Argument_WrongElementType" ), "<Permission>" ) ) ;
Contract.EndContractBlock();
String className;
int classNameLength;
int classNameStart;
if (!ParseElementForObjectCreation( el,
BuiltInPermission,
out className,
out classNameStart,
out classNameLength ))
{
goto USEREFLECTION;
}
// We have a built in permission, figure out which it is.
// UIPermission
// FileIOPermission
// SecurityPermission
// PrincipalPermission
// ReflectionPermission
// FileDialogPermission
// EnvironmentPermission
// GacIdentityPermission
// UrlIdentityPermission
// SiteIdentityPermission
// ZoneIdentityPermission
// KeyContainerPermission
// UnsafeForHostPermission
// HostProtectionPermission
// StrongNameIdentityPermission
#if !FEATURE_CORECLR
// IsolatedStorageFilePermission
#endif
// RegistryPermission
// PublisherIdentityPermission
switch (classNameLength)
{
case 12:
// UIPermission
if (String.Compare(className, classNameStart, "UIPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new UIPermission( permState );
else
goto USEREFLECTION;
case 16:
// FileIOPermission
if (String.Compare(className, classNameStart, "FileIOPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new FileIOPermission( permState );
else
goto USEREFLECTION;
case 18:
// RegistryPermission
// SecurityPermission
if (className[classNameStart] == 'R')
{
if (String.Compare(className, classNameStart, "RegistryPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new RegistryPermission( permState );
else
goto USEREFLECTION;
}
else
{
if (String.Compare(className, classNameStart, "SecurityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new SecurityPermission( permState );
else
goto USEREFLECTION;
}
#if !FEATURE_CORECLR
case 19:
// PrincipalPermission
if (String.Compare(className, classNameStart, "PrincipalPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new PrincipalPermission( permState );
else
goto USEREFLECTION;
#endif // !FEATURE_CORECLR
case 20:
// ReflectionPermission
// FileDialogPermission
if (className[classNameStart] == 'R')
{
if (String.Compare(className, classNameStart, "ReflectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new ReflectionPermission( permState );
else
goto USEREFLECTION;
}
else
{
if (String.Compare(className, classNameStart, "FileDialogPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new FileDialogPermission( permState );
else
goto USEREFLECTION;
}
case 21:
// EnvironmentPermission
// UrlIdentityPermission
// GacIdentityPermission
if (className[classNameStart] == 'E')
{
if (String.Compare(className, classNameStart, "EnvironmentPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new EnvironmentPermission( permState );
else
goto USEREFLECTION;
}
else if (className[classNameStart] == 'U')
{
if (String.Compare(className, classNameStart, "UrlIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new UrlIdentityPermission( permState );
else
goto USEREFLECTION;
}
else
{
if (String.Compare(className, classNameStart, "GacIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new GacIdentityPermission( permState );
else
goto USEREFLECTION;
}
case 22:
// SiteIdentityPermission
// ZoneIdentityPermission
// KeyContainerPermission
if (className[classNameStart] == 'S')
{
if (String.Compare(className, classNameStart, "SiteIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new SiteIdentityPermission( permState );
else
goto USEREFLECTION;
}
else if (className[classNameStart] == 'Z')
{
if (String.Compare(className, classNameStart, "ZoneIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new ZoneIdentityPermission( permState );
else
goto USEREFLECTION;
}
else
{
if (String.Compare(className, classNameStart, "KeyContainerPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new KeyContainerPermission( permState );
else
goto USEREFLECTION;
}
case 24:
// HostProtectionPermission
if (String.Compare(className, classNameStart, "HostProtectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new HostProtectionPermission( permState );
else
goto USEREFLECTION;
#if FEATURE_X509 && FEATURE_CAS_POLICY
case 27:
// PublisherIdentityPermission
if (String.Compare(className, classNameStart, "PublisherIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new PublisherIdentityPermission( permState );
else
goto USEREFLECTION;
#endif // FEATURE_X509 && FEATURE_CAS_POLICY
case 28:
// StrongNameIdentityPermission
if (String.Compare(className, classNameStart, "StrongNameIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new StrongNameIdentityPermission( permState );
else
goto USEREFLECTION;
#if !FEATURE_CORECLR
case 29:
// IsolatedStorageFilePermission
if (String.Compare(className, classNameStart, "IsolatedStorageFilePermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new IsolatedStorageFilePermission( permState );
else
goto USEREFLECTION;
#endif
default:
goto USEREFLECTION;
}
USEREFLECTION:
Object[] objs = new Object[1];
objs[0] = permState;
Type permClass = null;
IPermission perm = null;
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
permClass = GetClassFromElement(el, ignoreTypeLoadFailures);
if (permClass == null)
return null;
if (!(typeof(IPermission).IsAssignableFrom(permClass)))
throw new ArgumentException( Environment.GetResourceString("Argument_NotAPermissionType") );
perm = (IPermission) Activator.CreateInstance(permClass, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, objs, null );
return perm;
}
#if FEATURE_CAS_POLICY
#pragma warning disable 618 // CodeGroups are obsolete
[System.Security.SecuritySafeCritical] // auto-generated
public static CodeGroup
CreateCodeGroup (SecurityElement el)
{
if (el == null || !el.Tag.Equals("CodeGroup"))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "<CodeGroup>" ) ) ;
Contract.EndContractBlock();
String className;
int classNameLength;
int classNameStart;
if (!ParseElementForObjectCreation( el,
BuiltInCodeGroup,
out className,
out classNameStart,
out classNameLength ))
{
goto USEREFLECTION;
}
switch (classNameLength)
{
case 12:
// NetCodeGroup
if (String.Compare(className, classNameStart, "NetCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
return new NetCodeGroup();
else
goto USEREFLECTION;
case 13:
// FileCodeGroup
if (String.Compare(className, classNameStart, "FileCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
return new FileCodeGroup();
else
goto USEREFLECTION;
case 14:
// UnionCodeGroup
if (String.Compare(className, classNameStart, "UnionCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
return new UnionCodeGroup();
else
goto USEREFLECTION;
case 19:
// FirstMatchCodeGroup
if (String.Compare(className, classNameStart, "FirstMatchCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
return new FirstMatchCodeGroup();
else
goto USEREFLECTION;
default:
goto USEREFLECTION;
}
USEREFLECTION:
Type groupClass = null;
CodeGroup group = null;
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
groupClass = GetClassFromElement(el, true);
if (groupClass == null)
return null;
if (!(typeof(CodeGroup).IsAssignableFrom(groupClass)))
throw new ArgumentException( Environment.GetResourceString("Argument_NotACodeGroupType") );
group = (CodeGroup) Activator.CreateInstance(groupClass, true);
Contract.Assert( groupClass.Module.Assembly != Assembly.GetExecutingAssembly(),
"This path should not get called for mscorlib based classes" );
return group;
}
#pragma warning restore 618
[System.Security.SecurityCritical] // auto-generated
internal static IMembershipCondition
CreateMembershipCondition( SecurityElement el )
{
if (el == null || !el.Tag.Equals("IMembershipCondition"))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "<IMembershipCondition>" ) ) ;
Contract.EndContractBlock();
String className;
int classNameStart;
int classNameLength;
if (!ParseElementForObjectCreation( el,
BuiltInMembershipCondition,
out className,
out classNameStart,
out classNameLength ))
{
goto USEREFLECTION;
}
// We have a built in membership condition, figure out which it is.
// Here's the list of built in membership conditions as of 9/17/2002
// System.Security.Policy.AllMembershipCondition
// System.Security.Policy.URLMembershipCondition
// System.Security.Policy.SHA1MembershipCondition
// System.Security.Policy.SiteMembershipCondition
// System.Security.Policy.ZoneMembershipCondition
// System.Security.Policy.PublisherMembershipCondition
// System.Security.Policy.StrongNameMembershipCondition
// System.Security.Policy.ApplicationMembershipCondition
// System.Security.Policy.DomainApplicationMembershipCondition
// System.Security.Policy.ApplicationDirectoryMembershipCondition
switch (classNameLength)
{
case 22:
// AllMembershipCondition
// URLMembershipCondition
if (className[classNameStart] == 'A')
{
if (String.Compare(className, classNameStart, "AllMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
return new AllMembershipCondition();
else
goto USEREFLECTION;
}
else
{
if (String.Compare(className, classNameStart, "UrlMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
return new UrlMembershipCondition();
else
goto USEREFLECTION;
}
case 23:
// HashMembershipCondition
// SiteMembershipCondition
// ZoneMembershipCondition
if (className[classNameStart] == 'H')
{
if (String.Compare(className, classNameStart, "HashMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
return new HashMembershipCondition();
else
goto USEREFLECTION;
}
else if (className[classNameStart] == 'S')
{
if (String.Compare(className, classNameStart, "SiteMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
return new SiteMembershipCondition();
else
goto USEREFLECTION;
}
else
{
if (String.Compare(className, classNameStart, "ZoneMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
return new ZoneMembershipCondition();
else
goto USEREFLECTION;
}
case 28:
// PublisherMembershipCondition
if (String.Compare(className, classNameStart, "PublisherMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
return new PublisherMembershipCondition();
else
goto USEREFLECTION;
case 29:
// StrongNameMembershipCondition
if (String.Compare(className, classNameStart, "StrongNameMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
return new StrongNameMembershipCondition();
else
goto USEREFLECTION;
case 39:
// ApplicationDirectoryMembershipCondition
if (String.Compare(className, classNameStart, "ApplicationDirectoryMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
return new ApplicationDirectoryMembershipCondition();
else
goto USEREFLECTION;
default:
goto USEREFLECTION;
}
USEREFLECTION:
Type condClass = null;
IMembershipCondition cond = null;
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
condClass = GetClassFromElement(el, true);
if (condClass == null)
return null;
if (!(typeof(IMembershipCondition).IsAssignableFrom(condClass)))
throw new ArgumentException( Environment.GetResourceString("Argument_NotAMembershipCondition") );
cond = (IMembershipCondition) Activator.CreateInstance(condClass, true);
return cond;
}
#endif //#if FEATURE_CAS_POLICY
internal static Type
GetClassFromElement (SecurityElement el, bool ignoreTypeLoadFailures)
{
String className = el.Attribute( "class" );
if (className == null)
{
if (ignoreTypeLoadFailures)
return null;
else
throw new ArgumentException( String.Format( null, Environment.GetResourceString("Argument_InvalidXMLMissingAttr"), "class") );
}
if (ignoreTypeLoadFailures)
{
try
{
return Type.GetType(className, false, false);
}
catch (SecurityException)
{
return null;
}
}
else
return Type.GetType(className, true, false);
}
public static bool
IsPermissionElement (IPermission ip,
SecurityElement el)
{
if (!el.Tag.Equals ("Permission") && !el.Tag.Equals ("IPermission"))
return false;
return true;
}
public static bool
IsUnrestricted (SecurityElement el)
{
String sUnrestricted = el.Attribute( "Unrestricted" );
if (sUnrestricted == null)
return false;
return sUnrestricted.Equals( "true" ) || sUnrestricted.Equals( "TRUE" ) || sUnrestricted.Equals( "True" );
}
public static String BitFieldEnumToString( Type type, Object value )
{
int iValue = (int)value;
if (iValue == 0)
return Enum.GetName( type, 0 );
StringBuilder result = StringBuilderCache.Acquire();
bool first = true;
int flag = 0x1;
for (int i = 1; i < 32; ++i)
{
if ((flag & iValue) != 0)
{
String sFlag = Enum.GetName( type, flag );
if (sFlag == null)
continue;
if (!first)
{
result.Append( ", " );
}
result.Append( sFlag );
first = false;
}
flag = flag << 1;
}
return StringBuilderCache.GetStringAndRelease(result);
}
}
}
| |
using System;
using NUnit.Framework;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class ElementFindingTest : DriverTestFixture
{
// By.id positive
[Test]
public void ShouldBeAbleToFindASingleElementById()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.Id("linkId"));
Assert.AreEqual("linkId", element.GetAttribute("id"));
}
[Test]
[IgnoreBrowser(Browser.Android, "Bug in Android's XPath library.")]
public void ShouldBeAbleToFindMultipleElementsById()
{
driver.Url = nestedPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("2"));
Assert.AreEqual(8, elements.Count);
}
// By.id negative
[Test]
public void ShouldNotBeAbleToLocateByIdASingleElementThatDoesNotExist()
{
driver.Url = formsPage;
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.Id("nonExistentButton")));
}
[Test]
public void ShouldNotBeAbleToLocateByIdMultipleElementsThatDoNotExist()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("nonExistentButton"));
Assert.AreEqual(0, elements.Count);
}
[Test]
public void FindingASingleElementByEmptyIdShouldThrow()
{
driver.Url = formsPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => driver.FindElement(By.Id("")));
}
[Test]
public void FindingMultipleElementsByEmptyIdShouldThrow()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id(""));
Assert.AreEqual(0, elements.Count);
}
[Test]
public void FindingASingleElementByIdWithSpaceShouldThrow()
{
driver.Url = formsPage;
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.Id("nonexistent button")));
}
[Test]
public void FindingMultipleElementsByIdWithSpaceShouldThrow()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("nonexistent button"));
Assert.AreEqual(0, elements.Count);
}
// By.Name positive
[Test]
public void ShouldBeAbleToFindASingleElementByName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("checky"));
Assert.AreEqual("furrfu", element.GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByName()
{
driver.Url = nestedPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name("checky"));
Assert.Greater(elements.Count, 1);
}
[Test]
public void ShouldBeAbleToFindAnElementThatDoesNotSupportTheNameProperty()
{
driver.Url = nestedPage;
IWebElement element = driver.FindElement(By.Name("div1"));
Assert.AreEqual("div1", element.GetAttribute("name"));
}
// By.Name negative
[Test]
public void ShouldNotBeAbleToLocateByNameASingleElementThatDoesNotExist()
{
driver.Url = formsPage;
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.Name("nonExistentButton")));
}
[Test]
public void ShouldNotBeAbleToLocateByNameMultipleElementsThatDoNotExist()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name("nonExistentButton"));
Assert.AreEqual(0, elements.Count);
}
[Test]
public void FindingASingleElementByEmptyNameShouldThrow()
{
driver.Url = formsPage;
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.Name("")));
}
[Test]
public void FindingMultipleElementsByEmptyNameShouldThrow()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name(""));
Assert.AreEqual(0, elements.Count);
}
[Test]
public void FindingASingleElementByNameWithSpaceShouldThrow()
{
driver.Url = formsPage;
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.Name("nonexistent button")));
}
[Test]
public void FindingMultipleElementsByNameWithSpaceShouldThrow()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name("nonexistent button"));
Assert.AreEqual(0, elements.Count);
}
// By.tagName positive
[Test]
public void ShouldBeAbleToFindASingleElementByTagName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.TagName("input"));
Assert.AreEqual("input", element.TagName.ToLower());
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByTagName()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("input"));
Assert.Greater(elements.Count, 1);
}
// By.tagName negative
[Test]
public void ShouldNotBeAbleToLocateByTagNameASingleElementThatDoesNotExist()
{
driver.Url = formsPage;
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.TagName("nonExistentButton")));
}
[Test]
public void ShouldNotBeAbleToLocateByTagNameMultipleElementsThatDoNotExist()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("nonExistentButton"));
Assert.AreEqual(0, elements.Count);
}
[Test]
public void FindingASingleElementByEmptyTagNameShouldThrow()
{
driver.Url = formsPage;
Assert.Throws<InvalidSelectorException>(() => driver.FindElement(By.TagName("")));
}
[Test]
public void FindingMultipleElementsByEmptyTagNameShouldThrow()
{
driver.Url = formsPage;
Assert.Throws<InvalidSelectorException>(() => driver.FindElements(By.TagName("")));;
}
[Test]
public void FindingASingleElementByTagNameWithSpaceShouldThrow()
{
driver.Url = formsPage;
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.TagName("nonexistent button")));
}
[Test]
public void FindingMultipleElementsByTagNameWithSpaceShouldThrow()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("nonexistent button"));
Assert.AreEqual(0, elements.Count);
}
// By.ClassName positive
[Test]
public void ShouldBeAbleToFindASingleElementByClass()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("extraDiv"));
Assert.IsTrue(element.Text.StartsWith("Another div starts here."));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByClassName()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("nameC"));
Assert.Greater(elements.Count, 1);
}
[Test]
public void ShouldFindElementByClassWhenItIsTheFirstNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameA"));
Assert.AreEqual("An H2 title", element.Text);
}
[Test]
public void ShouldFindElementByClassWhenItIsTheLastNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameC"));
Assert.AreEqual("An H2 title", element.Text);
}
[Test]
public void ShouldFindElementByClassWhenItIsInTheMiddleAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameBnoise"));
Assert.AreEqual("An H2 title", element.Text);
}
[Test]
public void ShouldFindElementByClassWhenItsNameIsSurroundedByWhitespace()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("spaceAround"));
Assert.AreEqual("Spaced out", element.Text);
}
[Test]
public void ShouldFindElementsByClassWhenItsNameIsSurroundedByWhitespace()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("spaceAround"));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("Spaced out", elements[0].Text);
}
// By.ClassName negative
[Test]
public void ShouldNotFindElementByClassWhenTheNameQueriedIsShorterThanCandidateName()
{
driver.Url = xhtmlTestPage;
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.ClassName("nameB")));
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
public void FindingASingleElementByEmptyClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElement(By.ClassName("")); });
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingMultipleElementsByEmptyClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElements(By.ClassName("")); });
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingASingleElementByCompoundClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws<InvalidSelectorException>(() => driver.FindElement(By.ClassName("a b")));
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingMultipleElementsByCompoundClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws<InvalidSelectorException>(() => driver.FindElements(By.ClassName("a b")));
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingASingleElementByInvalidClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElement(By.ClassName("!@#$%^&*")); });
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingMultipleElementsByInvalidClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElements(By.ClassName("!@#$%^&*")); });
}
// By.XPath positive
[Test]
public void ShouldBeAbleToFindASingleElementByXPath()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.XPath("//h1"));
Assert.AreEqual("XHTML Might Be The Future", element.Text);
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByXPath()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("//div"));
Assert.AreEqual(13, elements.Count);
}
[Test]
public void ShouldBeAbleToFindManyElementsRepeatedlyByXPath()
{
driver.Url = xhtmlTestPage;
String xpathString = "//node()[contains(@id,'id')]";
Assert.AreEqual(3, driver.FindElements(By.XPath(xpathString)).Count);
xpathString = "//node()[contains(@id,'nope')]";
Assert.AreEqual(0, driver.FindElements(By.XPath(xpathString)).Count);
}
[Test]
public void ShouldBeAbleToIdentifyElementsByClass()
{
driver.Url = xhtmlTestPage;
IWebElement header = driver.FindElement(By.XPath("//h1[@class='header']"));
Assert.AreEqual("XHTML Might Be The Future", header.Text);
}
[Test]
public void ShouldBeAbleToFindAnElementByXPathWithMultipleAttributes()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(
By.XPath("//form[@name='optional']/input[@type='submit' and @value='Click!']"));
Assert.AreEqual("input", element.TagName.ToLower());
Assert.AreEqual("Click!", element.GetAttribute("value"));
}
[Test]
public void FindingALinkByXpathShouldLocateAnElementWithTheGivenText()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.XPath("//a[text()='click me']"));
Assert.AreEqual("click me", element.Text);
}
[Test]
public void FindingALinkByXpathUsingContainsKeywordShouldWork()
{
driver.Url = nestedPage;
IWebElement element = driver.FindElement(By.XPath("//a[contains(.,'hello world')]"));
Assert.IsTrue(element.Text.Contains("hello world"));
}
// By.XPath negative
[Test]
public void ShouldThrowAnExceptionWhenThereIsNoLinkToClick()
{
driver.Url = xhtmlTestPage;
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.XPath("//a[@id='Not here']")));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInDriverFindElement()
{
driver.Url = formsPage;
Assert.Throws<InvalidSelectorException>(() => driver.FindElement(By.XPath("this][isnot][valid")));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInDriverFindElements()
{
if (TestUtilities.IsIE6(driver))
{
// Ignoring xpath error test in IE6
return;
}
driver.Url = formsPage;
Assert.Throws<InvalidSelectorException>(() => driver.FindElements(By.XPath("this][isnot][valid")));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInElementFindElement()
{
driver.Url = formsPage;
IWebElement body = driver.FindElement(By.TagName("body"));
Assert.Throws<InvalidSelectorException>(() => body.FindElement(By.XPath("this][isnot][valid")));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInElementFindElements()
{
driver.Url = formsPage;
IWebElement body = driver.FindElement(By.TagName("body"));
Assert.Throws<InvalidSelectorException>(() => body.FindElements(By.XPath("this][isnot][valid")));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInDriverFindElement()
{
driver.Url = formsPage;
Assert.Throws<InvalidSelectorException>(() => driver.FindElement(By.XPath("count(//input)")));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInDriverFindElements()
{
if (TestUtilities.IsIE6(driver))
{
// Ignoring xpath error test in IE6
return;
}
driver.Url = formsPage;
Assert.Throws<InvalidSelectorException>(() => driver.FindElements(By.XPath("count(//input)")));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInElementFindElement()
{
driver.Url = formsPage;
IWebElement body = driver.FindElement(By.TagName("body"));
Assert.Throws<InvalidSelectorException>(() => body.FindElement(By.XPath("count(//input)")));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInElementFindElements()
{
if (TestUtilities.IsIE6(driver))
{
// Ignoring xpath error test in IE6
return;
}
driver.Url = formsPage;
IWebElement body = driver.FindElement(By.TagName("body"));
Assert.Throws<InvalidSelectorException>(() => body.FindElements(By.XPath("count(//input)")));
}
// By.CssSelector positive
[Test]
public void ShouldBeAbleToFindASingleElementByCssSelector()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.CssSelector("div.content"));
Assert.AreEqual("div", element.TagName.ToLower());
Assert.AreEqual("content", element.GetAttribute("class"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByCssSelector()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.CssSelector("p"));
Assert.Greater(elements.Count, 1);
}
[Test]
public void ShouldBeAbleToFindASingleElementByCompoundCssSelector()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.CssSelector("div.extraDiv, div.content"));
Assert.AreEqual("div", element.TagName.ToLower());
Assert.AreEqual("content", element.GetAttribute("class"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByCompoundCssSelector()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.CssSelector("div.extraDiv, div.content"));
Assert.Greater(elements.Count, 1);
Assert.AreEqual("content", elements[0].GetAttribute("class"));
Assert.AreEqual("extraDiv", elements[1].GetAttribute("class"));
}
[Test]
[IgnoreBrowser(Browser.IE, "IE supports only short version option[selected]")]
public void ShouldBeAbleToFindAnElementByBooleanAttributeUsingCssSelector()
{
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("locators_tests/boolean_attribute_selected.html"));
IWebElement element = driver.FindElement(By.CssSelector("option[selected='selected']"));
Assert.AreEqual("two", element.GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToFindAnElementByBooleanAttributeUsingShortCssSelector()
{
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("locators_tests/boolean_attribute_selected.html"));
IWebElement element = driver.FindElement(By.CssSelector("option[selected]"));
Assert.AreEqual("two", element.GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToFindAnElementByBooleanAttributeUsingShortCssSelectorOnHtml4Page()
{
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("locators_tests/boolean_attribute_selected_html4.html"));
IWebElement element = driver.FindElement(By.CssSelector("option[selected]"));
Assert.AreEqual("two", element.GetAttribute("value"));
}
// By.CssSelector negative
[Test]
public void ShouldNotFindElementByCssSelectorWhenThereIsNoSuchElement()
{
driver.Url = xhtmlTestPage;
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.CssSelector(".there-is-no-such-class")));
}
[Test]
public void ShouldNotFindElementsByCssSelectorWhenThereIsNoSuchElement()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.CssSelector(".there-is-no-such-class"));
Assert.AreEqual(0, elements.Count);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
public void FindingASingleElementByEmptyCssSelectorShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElement(By.CssSelector("")); });
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingMultipleElementsByEmptyCssSelectorShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElements(By.CssSelector("")); });
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws InvalidElementStateException")]
public void FindingASingleElementByInvalidCssSelectorShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElement(By.CssSelector("//a/b/c[@id='1']")); });
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws InvalidElementStateException")]
[IgnoreBrowser(Browser.Opera, "Throws InvalidElementStateException")]
public void FindingMultipleElementsByInvalidCssSelectorShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElements(By.CssSelector("//a/b/c[@id='1']")); });
}
// By.linkText positive
[Test]
public void ShouldBeAbleToFindALinkByText()
{
driver.Url = xhtmlTestPage;
IWebElement link = driver.FindElement(By.LinkText("click me"));
Assert.AreEqual("click me", link.Text);
}
[Test]
public void ShouldBeAbleToFindMultipleLinksByText()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("click me"));
Assert.AreEqual(2, elements.Count, "Expected 2 links, got " + elements.Count);
}
[Test]
public void ShouldFindElementByLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.LinkText("Link=equalssign"));
Assert.AreEqual("linkWithEqualsSign", element.GetAttribute("id"));
}
[Test]
public void ShouldFindMultipleElementsByLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("Link=equalssign"));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("linkWithEqualsSign", elements[0].GetAttribute("id"));
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void FindsByLinkTextOnXhtmlPage()
{
if (TestUtilities.IsOldIE(driver))
{
// Old IE doesn't render XHTML pages, don't try loading XHTML pages in it
return;
}
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("actualXhtmlPage.xhtml"));
string linkText = "Foo";
IWebElement element = driver.FindElement(By.LinkText(linkText));
Assert.AreEqual(linkText, element.Text);
}
[Test]
[IgnoreBrowser(Browser.Remote)]
public void LinkWithFormattingTags()
{
driver.Url = (simpleTestPage);
IWebElement elem = driver.FindElement(By.Id("links"));
IWebElement res = elem.FindElement(By.PartialLinkText("link with formatting tags"));
Assert.AreEqual("link with formatting tags", res.Text);
}
[Test]
public void DriverCanGetLinkByLinkTestIgnoringTrailingWhitespace()
{
driver.Url = simpleTestPage;
IWebElement link = driver.FindElement(By.LinkText("link with trailing space"));
Assert.AreEqual("linkWithTrailingSpace", link.GetAttribute("id"));
Assert.AreEqual("link with trailing space", link.Text);
}
// By.linkText negative
[Test]
public void ShouldNotBeAbleToLocateByLinkTextASingleElementThatDoesNotExist()
{
driver.Url = xhtmlTestPage;
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.LinkText("Not here either")));
}
[Test]
public void ShouldNotBeAbleToLocateByLinkTextMultipleElementsThatDoNotExist()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("Not here either"));
Assert.AreEqual(0, elements.Count);
}
// By.partialLinkText positive
[Test]
public void ShouldBeAbleToFindMultipleElementsByPartialLinkText()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.PartialLinkText("ick me"));
Assert.AreEqual(2, elements.Count);
}
[Test]
public void ShouldBeAbleToFindASingleElementByPartialLinkText()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.PartialLinkText("anon"));
Assert.IsTrue(element.Text.Contains("anon"));
}
[Test]
public void ShouldFindElementByPartialLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.PartialLinkText("Link="));
Assert.AreEqual("linkWithEqualsSign", element.GetAttribute("id"));
}
[Test]
public void ShouldFindMultipleElementsByPartialLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.PartialLinkText("Link="));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("linkWithEqualsSign", elements[0].GetAttribute("id"));
}
// Misc tests
[Test]
public void DriverShouldBeAbleToFindElementsAfterLoadingMoreThanOnePageAtATime()
{
driver.Url = formsPage;
driver.Url = xhtmlTestPage;
IWebElement link = driver.FindElement(By.LinkText("click me"));
Assert.AreEqual("click me", link.Text);
}
// You don't want to ask why this is here
[Test]
public void WhenFindingByNameShouldNotReturnById()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("id-name1"));
Assert.AreEqual("name", element.GetAttribute("value"));
element = driver.FindElement(By.Id("id-name1"));
Assert.AreEqual("id", element.GetAttribute("value"));
element = driver.FindElement(By.Name("id-name2"));
Assert.AreEqual("name", element.GetAttribute("value"));
element = driver.FindElement(By.Id("id-name2"));
Assert.AreEqual("id", element.GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToFindAHiddenElementsByName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("hidden"));
Assert.AreEqual("hidden", element.GetAttribute("name"));
}
[Test]
public void ShouldNotBeAbleToFindAnElementOnABlankPage()
{
driver.Url = "about:blank";
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.TagName("a")));
}
[Test]
[NeedsFreshDriver(IsCreatedBeforeTest = true)]
[IgnoreBrowser(Browser.IPhone)]
public void ShouldNotBeAbleToLocateASingleElementOnABlankPage()
{
// Note we're on the default start page for the browser at this point.
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.Id("nonExistantButton")));
}
[Test]
[IgnoreBrowser(Browser.Android, "Just not working")]
[IgnoreBrowser(Browser.Opera, "Just not working")]
public void AnElementFoundInADifferentFrameIsStale()
{
driver.Url = missedJsReferencePage;
driver.SwitchTo().Frame("inner");
IWebElement element = driver.FindElement(By.Id("oneline"));
driver.SwitchTo().DefaultContent();
Assert.Throws<StaleElementReferenceException>(() => { string foo = element.Text; });
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void AnElementFoundInADifferentFrameViaJsCanBeUsed()
{
driver.Url = missedJsReferencePage;
try
{
driver.SwitchTo().Frame("inner");
IWebElement first = driver.FindElement(By.Id("oneline"));
driver.SwitchTo().DefaultContent();
IWebElement element = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(
"return frames[0].document.getElementById('oneline');");
driver.SwitchTo().Frame("inner");
IWebElement second = driver.FindElement(By.Id("oneline"));
Assert.AreEqual(first, element);
Assert.AreEqual(second, element);
}
finally
{
driver.SwitchTo().DefaultContent();
}
}
/////////////////////////////////////////////////
// Tests unique to the .NET bindings
/////////////////////////////////////////////////
[Test]
public void ShouldReturnTitleOfPageIfSet()
{
driver.Url = xhtmlTestPage;
Assert.AreEqual(driver.Title, "XHTML Test Page");
driver.Url = simpleTestPage;
Assert.AreEqual(driver.Title, "Hello WebDriver");
}
[Test]
public void ShouldBeAbleToClickOnLinkIdentifiedByText()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.LinkText("click me")).Click();
WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title is not 'We Arrive Here'");
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldBeAbleToClickOnLinkIdentifiedById()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.Id("linkId")).Click();
WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title is not 'We Arrive Here'");
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldFindAnElementBasedOnId()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("checky"));
Assert.IsFalse(element.Selected);
}
[Test]
public void ShouldBeAbleToFindChildrenOfANode()
{
driver.Url = selectableItemsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("/html/head"));
IWebElement head = elements[0];
ReadOnlyCollection<IWebElement> importedScripts = head.FindElements(By.TagName("script"));
Assert.AreEqual(importedScripts.Count, 3);
}
[Test]
public void ReturnAnEmptyListWhenThereAreNoChildrenOfANode()
{
driver.Url = xhtmlTestPage;
IWebElement table = driver.FindElement(By.Id("table"));
ReadOnlyCollection<IWebElement> rows = table.FindElements(By.TagName("tr"));
Assert.AreEqual(rows.Count, 0);
}
[Test]
public void ShouldFindElementsByName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("checky"));
Assert.AreEqual(element.GetAttribute("value"), "furrfu");
}
[Test]
public void ShouldFindElementsByClassWhenItIsTheFirstNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameA"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindElementsByClassWhenItIsTheLastNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameC"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindElementsByClassWhenItIsInTheMiddleAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameBnoise"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindGrandChildren()
{
driver.Url = formsPage;
IWebElement form = driver.FindElement(By.Id("nested_form"));
form.FindElement(By.Name("x"));
}
[Test]
public void ShouldNotFindElementOutSideTree()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("login"));
Assert.Throws<NoSuchElementException>(() => element.FindElement(By.Name("x")));
}
[Test]
public void ShouldReturnElementsThatDoNotSupportTheNameProperty()
{
driver.Url = nestedPage;
driver.FindElement(By.Name("div1"));
// If this works, we're all good
}
[Test]
[Category("Javascript")]
public void ShouldBeAbleToClickOnLinksWithNoHrefAttribute()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.LinkText("No href"));
element.Click();
// if any exception is thrown, we won't get this far. Sanity check
Assert.AreEqual("Changed", driver.Title);
}
[Test]
[Category("Javascript")]
public void RemovingAnElementDynamicallyFromTheDomShouldCauseAStaleRefException()
{
driver.Url = javascriptPage;
IWebElement toBeDeleted = driver.FindElement(By.Id("deleted"));
Assert.IsTrue(toBeDeleted.Displayed);
driver.FindElement(By.Id("delete")).Click();
Assert.Throws<StaleElementReferenceException>(() => { bool displayedAfterDelete = toBeDeleted.Displayed; });
}
[Test]
public void FindingByTagNameShouldNotIncludeParentElementIfSameTagType()
{
driver.Url = xhtmlTestPage;
IWebElement parent = driver.FindElement(By.Id("my_span"));
Assert.AreEqual(2, parent.FindElements(By.TagName("div")).Count);
Assert.AreEqual(2, parent.FindElements(By.TagName("span")).Count);
}
[Test]
public void FindingByCssShouldNotIncludeParentElementIfSameTagType()
{
driver.Url = xhtmlTestPage;
IWebElement parent = driver.FindElement(By.CssSelector("div#parent"));
IWebElement child = parent.FindElement(By.CssSelector("div"));
Assert.AreEqual("child", child.GetAttribute("id"));
}
[Test]
public void FindingByXPathShouldNotIncludeParentElementIfSameTagType()
{
driver.Url = xhtmlTestPage;
IWebElement parent = driver.FindElement(By.Id("my_span"));
Assert.AreEqual(2, parent.FindElements(By.TagName("div")).Count);
Assert.AreEqual(2, parent.FindElements(By.TagName("span")).Count);
}
[Test]
public void ShouldBeAbleToInjectXPathEngineIfNeeded()
{
driver.Url = alertsPage;
driver.FindElement(By.XPath("//body"));
driver.FindElement(By.XPath("//h1"));
driver.FindElement(By.XPath("//div"));
driver.FindElement(By.XPath("//p"));
driver.FindElement(By.XPath("//a"));
}
[Test]
public void ShouldFindElementByLinkTextContainingDoubleQuote()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.LinkText("link with \" (double quote)"));
Assert.AreEqual("quote", element.GetAttribute("id"));
}
[Test]
public void ShouldFindElementByLinkTextContainingBackslash()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.LinkText("link with \\ (backslash)"));
Assert.AreEqual("backslash", element.GetAttribute("id"));
}
private bool SupportsSelectorApi()
{
IJavaScriptExecutor javascriptDriver = driver as IJavaScriptExecutor;
IFindsByCssSelector cssSelectorDriver = driver as IFindsByCssSelector;
return (cssSelectorDriver != null) && (javascriptDriver != null);
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
using WOSI.CallButler.Data;
using WOSI.CallButler.Data.DataProviders;
using WOSI.CallButler.Data.DataProviders.Local;
using CallButler.Telecom;
using CallButler.Service.Services;
using WOSI.Utilities;
using NET.Remoting;
using System.IO;
using Microsoft.Win32;
namespace CallButler.Service
{
internal partial class CallButlerService : ServiceBase
{
private CallButlerDataProviderBase dataProvider;
private ManagementInterfaceService managementInterfaceServer;
private TcpRemotingServer tcpManagementDataServer;
private PipeRemotingServer pipeManagementDataServer;
//private KinesisService emService;
private TelecomProviderBase telecomProvider;
private ScriptService scriptService;
private PBXRegistrarService pbxRegistrar;
//private ExtensionStateService extStateService;
private VoicemailMailerService vmMailerService;
private VoicemailService vmService;
public static DialPlanManagerService DialPlanManager;
private Utilities.PluginManagement.PluginManager pluginManager;
private string currentIP;
private string lastErrorMessage;
private delegate void ClearMenuItemsDelagate();
private ClearMenuItemsDelagate clearMenuItemsHandler;
public CallButlerService()
{
// Load our private label file
Service.Services.PrivateLabelService.LoadPrivateLabelFile();
clearMenuItemsHandler = new ClearMenuItemsDelagate(ClearMenuItemsProc);
System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
Version appVersion = a.GetName().Version;
string appVersionString = appVersion.ToString();
currentIP = WOSI.Utilities.NetworkUtils.GetCurrentIpAddress();
InitializeComponent();
LoadStartupOption();
mnuLoadOnStartup.Click += new EventHandler(mnuLoadOnStartup_Click);
mnuManageCallButler.Click += new EventHandler(mnuManageCallButler_Click);
mnuManageCallButler.Image = Properties.Resources.nut_and_bolt_16;
mnuExit.Click += new EventHandler(mnuExit_Click);
mnuExit.Image = Properties.Resources.exit_16;
mnuPlugins.Image = Properties.Resources.gear_connection_16;
// Set our default language
if (Properties.Settings.Default.DefaultLanguage == null || Properties.Settings.Default.DefaultLanguage.Length == 0)
{
Properties.Settings.Default.DefaultLanguage = WOSI.Utilities.GlobalizationUtils.GetTopParentCulture(System.Threading.Thread.CurrentThread.CurrentCulture).IetfLanguageTag;
Properties.Settings.Default.Save();
}
LoggingService.NewLogEntry += new EventHandler<LogEntryEventArgs>(LoggingService_NewLogEntry);
}
private void LoadStartupOption()
{
/*RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
if (regKey != null)
{
if (regKey.GetValue(Properties.Settings.Default.ProductDescription) == null)
{
mnuLoadOnStartup.CheckState = CheckState.Unchecked;
}
else
{
mnuLoadOnStartup.CheckState = CheckState.Checked;
}
}*/
}
void mnuLoadOnStartup_Click(object sender, EventArgs e)
{
/*RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
if (mnuLoadOnStartup.Checked)
{
mnuLoadOnStartup.CheckState = CheckState.Checked;
regKey.SetValue(Properties.Settings.Default.ProductDescription, Application.ExecutablePath + " -a");
}
else
{
if (regKey.GetValue(Properties.Settings.Default.ProductDescription) != null)
{
mnuLoadOnStartup.CheckState = CheckState.Unchecked;
regKey.DeleteValue(Properties.Settings.Default.ProductDescription);
}
}*/
}
#region Menu Events
void mnuManageCallButler_Click(object sender, EventArgs e)
{
string callButlerManagerPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), Properties.Settings.Default.CallButlerManagementAppLocation);
if (File.Exists(callButlerManagerPath))
{
System.Diagnostics.Process.Start(callButlerManagerPath);
}
else
{
MessageBox.Show(Services.PrivateLabelService.ReplaceProductName("The CallButler management application does not appear to be installed on this computer.\r\nPlease run the CallButler setup program again to install it."), Services.PrivateLabelService.ReplaceProductName("CallButler Manager Not Found"), MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
void mnuExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
#endregion
#region Public Properties
public bool NotifyIconVisible
{
get
{
return notifyIcon.Visible;
}
set
{
notifyIcon.Visible = value;
}
}
#endregion
#region Public Service Control Methods
private void CreateManagementChannels()
{
// Create our management interface server
managementInterfaceServer = new ManagementInterfaceService();
managementInterfaceServer.Initialize(this, null, null, null, null, null, null);
if (Properties.Settings.Default.EnableRemoteManagement)
{
// Create our remoting object for our management server
tcpManagementDataServer = new TcpRemotingServer("CallButler TCP Management Server (" + Properties.Settings.Default.ProductID + ")", "CallButlerManagementServer", Properties.Settings.Default.ManagementServicePort, (MarshalByRefObject)managementInterfaceServer);
tcpManagementDataServer.OnAuthentication += new EventHandler<NET.Remoting.Channels.AuthenticationEventArgs>(managementDataServer_OnAuthentication);
tcpManagementDataServer.OnManagementAllowed += new EventHandler<NET.Remoting.Channels.ManagementAllowedEventArgs>(managementDataServer_OnManagementAllowed);
}
pipeManagementDataServer = new PipeRemotingServer("CallButler PIPE Management Server (" + Properties.Settings.Default.ProductID + ")", "CallButlerManagementServer", Properties.Settings.Default.ManagementServicePort, (MarshalByRefObject)managementInterfaceServer);
pipeManagementDataServer.OnAuthentication += new EventHandler<NET.Remoting.Channels.AuthenticationEventArgs>(managementDataServer_OnAuthentication);
pipeManagementDataServer.OnManagementAllowed += new EventHandler<NET.Remoting.Channels.ManagementAllowedEventArgs>(managementDataServer_OnManagementAllowed);
pipeManagementDataServer.StartServer();
}
private void Initialize()
{
if (Properties.Settings.Default.ProductID != null && Properties.Settings.Default.ProductID.Length > 0)
{
lastErrorMessage = null;
notifyIcon.Text = Properties.Settings.Default.ProductDescription;
// Load our application permissions
//Licensing.Management.AppPermissions.LoadPermissionData(Properties.Settings.Default.ProductID, Properties.Resources.Permissions);
// Load our dataprovider
System.Collections.Specialized.NameValueCollection settings = new System.Collections.Specialized.NameValueCollection();
switch (Properties.Settings.Default.DataProviderType)
{
case LocalCallButlerDataProviderTypes.XmlDataProvider:
// Create our settings
settings["RootDataDirectory"] = WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.XmlDataRootDirectory);
settings["RootGreetingSoundDirectory"] = WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.GreetingSoundRootDirectory);
dataProvider = new CallButlerXmlDataProvider();
dataProvider.Connect(settings);
break;
/*case LocalCallButlerDataProviderTypes.SqlServerDataProvider:
settings["RootDataDirectory"] = WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.XmlDataRootDirectory);
settings["RootGreetingSoundDirectory"] = WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.GreetingSoundRootDirectory);
settings["ConnectionString"] = Properties.Settings.Default.SqlConnectionString;
dataProvider = new CallButlerSQLServerDataProvider();
dataProvider.Connect(settings);
break;*/
}
/*if (Properties.Settings.Default.EnableKinesisServer)
{
extStateService = new ExtensionStateService(dataProvider);
}*/
// Create our telecom provider
int lineCount = /*Math.Min(*/ Properties.Settings.Default.LineCount; /*, Licensing.Management.AppPermissions.StatGetPermissionScalar("MaxLineCount"));*/
switch (Properties.Settings.Default.TelecomProviderType)
{
case TelecomProviders.inTELIPhoneTelecomProvider:
{
telecomProvider = new inTELIPhoneTelecomProvider(mnuServiceOptions, notifyIcon, lineCount, Properties.Settings.Default.UseStun, Properties.Settings.Default.StunServer, Properties.Settings.Default.SipPort, Properties.Settings.Default.UseInternalAddressForSIPMessages);
// Register all of our profiles
//if (Licensing.Management.AppPermissions.StatIsPermitted("Providers"))
//{
WOSI.CallButler.Data.CallButlerDataset.ProvidersDataTable providers = dataProvider.GetProviders(Properties.Settings.Default.CustomerID);
foreach (WOSI.CallButler.Data.CallButlerDataset.ProvidersRow provider in providers)
{
if (provider.IsEnabled)
{
telecomProvider.Register(provider.ProviderID, provider);
}
}
//}
// Start our PBX registrar engine
if (Properties.Settings.Default.EnablePBX /*&& Licensing.Management.AppPermissions.StatIsPermitted("PBX.Registrar")*/)
{
pbxRegistrar = new PBXRegistrarService(telecomProvider, dataProvider/*, extStateService*/);
}
break;
}
}
// Initialize our codecs
if (Properties.Settings.Default.AudioCodecs != null && Properties.Settings.Default.AudioCodecs.Length > 0)
telecomProvider.SetAudioCodecs(Properties.Settings.Default.AudioCodecs);
// Create our plugin manager object
pluginManager = new Utilities.PluginManagement.PluginManager();
// Create our voicemail mailer service
vmMailerService = new VoicemailMailerService();
// Initialize our voicemail service
vmService = new VoicemailService(dataProvider, pbxRegistrar, pluginManager, vmMailerService);
// Create our script server
scriptService = new ScriptService(telecomProvider, dataProvider, vmService, vmMailerService, pluginManager, pbxRegistrar/*, extStateService*/);
// Load our plugins
CallButler.Service.Plugin.CallButlerServiceContext serviceContext = new CallButler.Service.Plugin.CallButlerServiceContext(scriptService);
pluginManager.LoadPlugins(WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.PluginDirectory), "*.dll", true, typeof(CallButler.Service.Plugin.CallButlerServicePlugin));
foreach (CallButler.Service.Plugin.CallButlerServicePlugin plugin in pluginManager.Plugins)
{
try
{
plugin.Load(serviceContext);
}
catch
{
}
}
try
{
mnuPlugins.Visible = false;
mnuSeparator4.Visible = false;
}
catch
{
}
// Initialize our management interface
managementInterfaceServer.Initialize(this, dataProvider, telecomProvider, scriptService, pluginManager, pbxRegistrar, vmService);
// Create our default greetings if this the first time we've run
if (Properties.Settings.Default.FirstTimeRun)
{
WOSI.CallButler.Data.CallButlerDataset.LocalizedGreetingsDataTable lgTable = new CallButlerDataset.LocalizedGreetingsDataTable();
WOSI.CallButler.Data.CallButlerDataset.LocalizedGreetingsRow lgRow;
if (dataProvider.GetGreeting(Properties.Settings.Default.CustomerID, WOSI.CallButler.Data.Constants.WelcomeGreetingGuid) == null)
{
lgRow = lgTable.NewLocalizedGreetingsRow();
lgRow.GreetingID = WOSI.CallButler.Data.Constants.WelcomeGreetingGuid;
lgRow.LanguageID = "en";
lgRow.LocalizedGreetingID = Guid.NewGuid();
lgRow.Type = (short)WOSI.CallButler.Data.GreetingType.SoundGreeting;
lgTable.AddLocalizedGreetingsRow(lgRow);
}
if (dataProvider.GetGreeting(Properties.Settings.Default.CustomerID, WOSI.CallButler.Data.Constants.MainMenuGreetingGuid) == null)
{
lgRow = lgTable.NewLocalizedGreetingsRow();
lgRow.GreetingID = WOSI.CallButler.Data.Constants.MainMenuGreetingGuid;
lgRow.LanguageID = "en";
lgRow.LocalizedGreetingID = Guid.NewGuid();
lgRow.Type = (short)WOSI.CallButler.Data.GreetingType.SoundGreeting;
lgTable.AddLocalizedGreetingsRow(lgRow);
}
managementInterfaceServer.PersistLocalizedGreeting(Properties.Settings.Default.CustomerID, lgTable);
Properties.Settings.Default.FirstTimeRun = false;
Properties.Settings.Default.Save();
}
// Setup our default language
if (Properties.Settings.Default.DefaultLanguage.Length == 0)
{
Properties.Settings.Default.DefaultLanguage = System.Globalization.CultureInfo.CurrentCulture.IetfLanguageTag;
Properties.Settings.Default.Save();
}
telecomProvider.Startup();
CallButlerService.DialPlanManager = new DialPlanManagerService(pbxRegistrar, dataProvider, telecomProvider);
if (tcpManagementDataServer != null)
tcpManagementDataServer.StartServer();
// Create our extension management service
/*if (Properties.Settings.Default.EnableKinesisServer)
{
emService = new KinesisService(dataProvider, extStateService, scriptService, vmService);
emService.Start();
}*/
}
}
private void ClearMenuItemsProc()
{
mnuServiceOptions.DropDownItems.Clear();
}
private void DeInitialize()
{
if (mnuMain.InvokeRequired)
mnuMain.Invoke(clearMenuItemsHandler);
else
mnuServiceOptions.DropDownItems.Clear();
/*if (extStateService != null)
{
extStateService.ClearState();
extStateService = null;
}
if (emService != null)
{
emService.Stop();
emService.Dispose();
emService = null;
}*/
if (pluginManager != null)
{
// Unload our plugins
foreach (CallButler.Service.Plugin.CallButlerServicePlugin plugin in pluginManager.Plugins)
{
plugin.Unload();
}
pluginManager.UnloadPlugins();
pluginManager = null;
}
if (scriptService != null)
{
scriptService.Shutdown();
scriptService = null;
}
if (vmMailerService != null)
{
vmMailerService = null;
}
if (vmService != null)
{
vmService = null;
}
dataProvider = null;
if (CallButlerService.DialPlanManager != null)
{
CallButlerService.DialPlanManager = null;
}
if (pbxRegistrar != null)
{
pbxRegistrar.Shutdown();
pbxRegistrar = null;
}
if (telecomProvider != null)
{
telecomProvider.Shutdown();
telecomProvider = null;
}
if (tcpManagementDataServer != null)
tcpManagementDataServer.StopServer();
GC.Collect();
}
public void StartService(string[] args)
{
if (Properties.Settings.Default.EnablePerformanceCounters)
PerformanceCounterService.Initialize();
CreateManagementChannels();
Initialize();
}
public void StopService()
{
/*if (emService != null)
{
emService.Stop();
emService.Dispose();
emService = null;
}
if (extStateService != null)
{
extStateService.ClearState();
extStateService = null;
}*/
if(managementInterfaceServer != null)
managementInterfaceServer = null;
if (tcpManagementDataServer != null)
{
tcpManagementDataServer.StopServer();
tcpManagementDataServer = null;
}
if (pipeManagementDataServer != null)
{
pipeManagementDataServer.StopServer();
pipeManagementDataServer = null;
}
if (vmMailerService != null)
{
vmMailerService = null;
}
if (vmService != null)
{
vmService = null;
}
DeInitialize();
PerformanceCounterService.ResetCounters();
}
public void RestartService(bool async)
{
DeInitialize();
System.Threading.Thread.Sleep(500);
Initialize();
}
void tcpClientManagementDataServer_OnManagementAllowed(object sender, NET.Remoting.Channels.ManagementAllowedEventArgs e)
{
try
{
int ext = Convert.ToInt32(e.Extension);
bool allow = false;
WOSI.CallButler.Data.CallButlerDataset.ExtensionsRow row = dataProvider.GetExtensionNumber(Properties.Settings.Default.CustomerID, ext);
if (row != null)
{
allow = row.EnableManagement;
}
e.ManagementAllowed = allow;
}
catch
{
e.ManagementAllowed = false;
}
}
void tcpClientManagementDataServer_OnAuthentication(object sender, NET.Remoting.Channels.AuthenticationEventArgs e)
{
e.IsAuthenticated = managementInterfaceServer.Authenticate(e.CustomerID, e.ExtensionNumber, e.Password);
}
void managementDataServer_OnManagementAllowed(object sender, NET.Remoting.Channels.ManagementAllowedEventArgs e)
{
if (Properties.Settings.Default.EnableRemoteManagement == false)
{
if (currentIP.Equals(e.IpAddress) || e.IpAddress.Equals("127.0.0.1") || e.IpAddress.ToLower().Equals("localhost"))
{
e.ManagementAllowed = true;
}
else
{
e.ManagementAllowed = false;
}
}
else
{
e.ManagementAllowed = true;
}
}
void managementDataServer_OnAuthentication(object sender, NET.Remoting.Channels.AuthenticationEventArgs e)
{
e.IsAuthenticated = managementInterfaceServer.Authenticate(e.CustomerID, e.ExtensionNumber, e.Password);
}
#endregion
#region Logging Events
void LoggingService_NewLogEntry(object sender, LogEntryEventArgs e)
{
// Send an Email with our error, but only if it's new.
if (Properties.Settings.Default.SendLogErrorEmails && e.IsError && e.Message != lastErrorMessage)
{
try
{
lastErrorMessage = e.Message;
string smtpPassword = "";
if (Properties.Settings.Default.SMTPPassword.Length > 0)
smtpPassword = WOSI.Utilities.CryptoUtils.Decrypt(Properties.Settings.Default.SMTPPassword, WOSI.CallButler.Data.Constants.EncryptionPassword);
WOSI.Utilities.EmailUtils.SendEmail(Properties.Settings.Default.SMTPEmailFrom, Properties.Settings.Default.LogErrorEmailAddress, Services.PrivateLabelService.ReplaceProductName("A CallButler Error Has Been Logged"), e.Message, Properties.Settings.Default.SMTPServer, Properties.Settings.Default.SMTPPort, Properties.Settings.Default.SMTPUseSSL, Properties.Settings.Default.SMTPUsername, smtpPassword);
}
catch
{
}
}
}
#endregion
protected override void OnStart(string[] args)
{
StartService(null);
}
protected override void OnStop()
{
StopService();
}
private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
{
}
}
}
| |
/*
* Copyright 2012-2021 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <[email protected]>
*/
using System;
using System.Reflection;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI;
using Net.Pkcs11Interop.HighLevelAPI.MechanismParams;
using NUnit.Framework;
using HLA40 = Net.Pkcs11Interop.HighLevelAPI40;
using HLA41 = Net.Pkcs11Interop.HighLevelAPI41;
using HLA80 = Net.Pkcs11Interop.HighLevelAPI80;
using HLA81 = Net.Pkcs11Interop.HighLevelAPI81;
using LLA40 = Net.Pkcs11Interop.LowLevelAPI40;
using LLA41 = Net.Pkcs11Interop.LowLevelAPI41;
using LLA80 = Net.Pkcs11Interop.LowLevelAPI80;
using LLA81 = Net.Pkcs11Interop.LowLevelAPI81;
// Note: Code in this file is maintained manually.
namespace Net.Pkcs11Interop.Tests.HighLevelAPI
{
/// <summary>
/// Mechanism tests.
/// </summary>
[TestFixture()]
public class _14_MechanismTest
{
/// <summary>
/// Mechanism dispose test.
/// </summary>
[Test()]
public void _01_DisposeMechanismTest()
{
byte[] parameter = new byte[8];
System.Random rng = new Random();
rng.NextBytes(parameter);
// Unmanaged memory for mechanism parameter stored in low level CK_MECHANISM struct
// is allocated by constructor class implementing IMechanism interface.
IMechanism mechanism1 = Settings.Factories.MechanismFactory.Create(CKM.CKM_DES_CBC, parameter);
// Do something interesting with mechanism
// This unmanaged memory is freed by Dispose() method.
mechanism1.Dispose();
// Mechanism class can be used in using statement which defines a scope
// at the end of which an object will be disposed (and unmanaged memory freed).
using (IMechanism mechanism2 = Settings.Factories.MechanismFactory.Create(CKM.CKM_DES_CBC, parameter))
{
// Do something interesting with mechanism
}
#pragma warning disable 0219
// Explicit calling of Dispose() method can also be ommitted
// and this is the prefered way how to use Mechanism class.
IMechanism mechanism3 = Settings.Factories.MechanismFactory.Create(CKM.CKM_DES_CBC, parameter);
// Do something interesting with mechanism
// Dispose() method will be called (and unmanaged memory freed) by GC eventually
// but we cannot be sure when will this occur.
#pragma warning restore 0219
}
/// <summary>
/// Mechanism with empty parameter test.
/// </summary>
[Test()]
public void _02_EmptyParameterTest()
{
// Create mechanism without the parameter
IMechanism mechanism = Settings.Factories.MechanismFactory.Create(CKM.CKM_RSA_PKCS);
Assert.IsTrue(mechanism.Type == ConvertUtils.UInt64FromCKM(CKM.CKM_RSA_PKCS));
// We access private Mechanism member just for the testing purposes
if (Platform.NativeULongSize == 4)
{
if (Platform.StructPackingSize == 0)
{
HLA40.Mechanism mechanism40 = (HLA40.Mechanism)mechanism;
LLA40.CK_MECHANISM ckMechanism40 = (LLA40.CK_MECHANISM)typeof(HLA40.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism40);
Assert.IsTrue(ckMechanism40.Mechanism == ConvertUtils.UInt32FromCKM(CKM.CKM_RSA_PKCS));
Assert.IsTrue(ckMechanism40.Parameter == IntPtr.Zero);
Assert.IsTrue(ckMechanism40.ParameterLen == 0);
}
else
{
HLA41.Mechanism mechanism41 = (HLA41.Mechanism)mechanism;
LLA41.CK_MECHANISM ckMechanism41 = (LLA41.CK_MECHANISM)typeof(HLA41.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism41);
Assert.IsTrue(ckMechanism41.Mechanism == ConvertUtils.UInt32FromCKM(CKM.CKM_RSA_PKCS));
Assert.IsTrue(ckMechanism41.Parameter == IntPtr.Zero);
Assert.IsTrue(ckMechanism41.ParameterLen == 0);
}
}
else
{
if (Platform.StructPackingSize == 0)
{
HLA80.Mechanism mechanism80 = (HLA80.Mechanism)mechanism;
LLA80.CK_MECHANISM ckMechanism80 = (LLA80.CK_MECHANISM)typeof(HLA80.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism80);
Assert.IsTrue(ckMechanism80.Mechanism == ConvertUtils.UInt64FromCKM(CKM.CKM_RSA_PKCS));
Assert.IsTrue(ckMechanism80.Parameter == IntPtr.Zero);
Assert.IsTrue(ckMechanism80.ParameterLen == 0);
}
else
{
HLA81.Mechanism mechanism81 = (HLA81.Mechanism)mechanism;
LLA81.CK_MECHANISM ckMechanism81 = (LLA81.CK_MECHANISM)typeof(HLA81.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism81);
Assert.IsTrue(ckMechanism81.Mechanism == ConvertUtils.UInt64FromCKM(CKM.CKM_RSA_PKCS));
Assert.IsTrue(ckMechanism81.Parameter == IntPtr.Zero);
Assert.IsTrue(ckMechanism81.ParameterLen == 0);
}
}
}
/// <summary>
/// Mechanism with byte array parameter test.
/// </summary>
[Test()]
public void _03_ByteArrayParameterTest()
{
byte[] parameter = new byte[16];
System.Random rng = new Random();
rng.NextBytes(parameter);
// Create mechanism with the byte array parameter
IMechanism mechanism = Settings.Factories.MechanismFactory.Create(CKM.CKM_AES_CBC, parameter);
Assert.IsTrue(mechanism.Type == ConvertUtils.UInt64FromCKM(CKM.CKM_AES_CBC));
// We access private members here just for the testing purposes
if (Platform.NativeULongSize == 4)
{
if (Platform.StructPackingSize == 0)
{
HLA40.Mechanism mechanism40 = (HLA40.Mechanism)mechanism;
LLA40.CK_MECHANISM ckMechanism40 = (LLA40.CK_MECHANISM)typeof(HLA40.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism40);
Assert.IsTrue(ckMechanism40.Mechanism == ConvertUtils.UInt32FromCKM(CKM.CKM_AES_CBC));
Assert.IsTrue(ckMechanism40.Parameter != IntPtr.Zero);
Assert.IsTrue(Convert.ToInt32(ckMechanism40.ParameterLen) == parameter.Length);
}
else
{
HLA41.Mechanism mechanism41 = (HLA41.Mechanism)mechanism;
LLA41.CK_MECHANISM ckMechanism41 = (LLA41.CK_MECHANISM)typeof(HLA41.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism41);
Assert.IsTrue(ckMechanism41.Mechanism == ConvertUtils.UInt32FromCKM(CKM.CKM_AES_CBC));
Assert.IsTrue(ckMechanism41.Parameter != IntPtr.Zero);
Assert.IsTrue(Convert.ToInt32(ckMechanism41.ParameterLen) == parameter.Length);
}
}
else
{
if (Platform.StructPackingSize == 0)
{
HLA80.Mechanism mechanism80 = (HLA80.Mechanism)mechanism;
LLA80.CK_MECHANISM ckMechanism80 = (LLA80.CK_MECHANISM)typeof(HLA80.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism80);
Assert.IsTrue(ckMechanism80.Mechanism == ConvertUtils.UInt64FromCKM(CKM.CKM_AES_CBC));
Assert.IsTrue(ckMechanism80.Parameter != IntPtr.Zero);
Assert.IsTrue(Convert.ToInt32(ckMechanism80.ParameterLen) == parameter.Length);
}
else
{
HLA81.Mechanism mechanism81 = (HLA81.Mechanism)mechanism;
LLA81.CK_MECHANISM ckMechanism81 = (LLA81.CK_MECHANISM)typeof(HLA81.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism81);
Assert.IsTrue(ckMechanism81.Mechanism == ConvertUtils.UInt64FromCKM(CKM.CKM_AES_CBC));
Assert.IsTrue(ckMechanism81.Parameter != IntPtr.Zero);
Assert.IsTrue(Convert.ToInt32(ckMechanism81.ParameterLen) == parameter.Length);
}
}
parameter = null;
// Create mechanism with null byte array parameter
mechanism = Settings.Factories.MechanismFactory.Create(CKM.CKM_AES_CBC, parameter);
Assert.IsTrue(mechanism.Type == ConvertUtils.UInt64FromCKM(CKM.CKM_AES_CBC));
// We access private members here just for the testing purposes
if (Platform.NativeULongSize == 4)
{
if (Platform.StructPackingSize == 0)
{
HLA40.Mechanism mechanism40 = (HLA40.Mechanism)mechanism;
LLA40.CK_MECHANISM ckMechanism40 = (LLA40.CK_MECHANISM)typeof(HLA40.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism40);
Assert.IsTrue(ckMechanism40.Mechanism == ConvertUtils.UInt32FromCKM(CKM.CKM_AES_CBC));
Assert.IsTrue(ckMechanism40.Parameter == IntPtr.Zero);
Assert.IsTrue(ckMechanism40.ParameterLen == 0);
}
else
{
HLA41.Mechanism mechanism41 = (HLA41.Mechanism)mechanism;
LLA41.CK_MECHANISM ckMechanism41 = (LLA41.CK_MECHANISM)typeof(HLA41.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism41);
Assert.IsTrue(ckMechanism41.Mechanism == ConvertUtils.UInt32FromCKM(CKM.CKM_AES_CBC));
Assert.IsTrue(ckMechanism41.Parameter == IntPtr.Zero);
Assert.IsTrue(ckMechanism41.ParameterLen == 0);
}
}
else
{
if (Platform.StructPackingSize == 0)
{
HLA80.Mechanism mechanism80 = (HLA80.Mechanism)mechanism;
LLA80.CK_MECHANISM ckMechanism80 = (LLA80.CK_MECHANISM)typeof(HLA80.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism80);
Assert.IsTrue(ckMechanism80.Mechanism == ConvertUtils.UInt64FromCKM(CKM.CKM_AES_CBC));
Assert.IsTrue(ckMechanism80.Parameter == IntPtr.Zero);
Assert.IsTrue(ckMechanism80.ParameterLen == 0);
}
else
{
HLA81.Mechanism mechanism81 = (HLA81.Mechanism)mechanism;
LLA81.CK_MECHANISM ckMechanism81 = (LLA81.CK_MECHANISM)typeof(HLA81.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism81);
Assert.IsTrue(ckMechanism81.Mechanism == ConvertUtils.UInt64FromCKM(CKM.CKM_AES_CBC));
Assert.IsTrue(ckMechanism81.Parameter == IntPtr.Zero);
Assert.IsTrue(ckMechanism81.ParameterLen == 0);
}
}
}
/// <summary>
/// Mechanism with object as parameter test.
/// </summary>
[Test()]
public void _04_ObjectParameterTest()
{
byte[] data = new byte[24];
System.Random rng = new Random();
rng.NextBytes(data);
// Specify mechanism parameters
ICkKeyDerivationStringData parameter = Settings.Factories.MechanismParamsFactory.CreateCkKeyDerivationStringData(data);
// Create mechanism with the object as parameter
IMechanism mechanism = Settings.Factories.MechanismFactory.Create(CKM.CKM_XOR_BASE_AND_DATA, parameter);
Assert.IsTrue(mechanism.Type == ConvertUtils.UInt64FromCKM(CKM.CKM_XOR_BASE_AND_DATA));
// We access private Mechanism member here just for the testing purposes
if (Platform.NativeULongSize == 4)
{
if (Platform.StructPackingSize == 0)
{
HLA40.Mechanism mechanism40 = (HLA40.Mechanism)mechanism;
LLA40.CK_MECHANISM ckMechanism40 = (LLA40.CK_MECHANISM)typeof(HLA40.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism40);
Assert.IsTrue(ckMechanism40.Mechanism == ConvertUtils.UInt32FromCKM(CKM.CKM_XOR_BASE_AND_DATA));
Assert.IsTrue(ckMechanism40.Parameter != IntPtr.Zero);
Assert.IsTrue(Convert.ToInt32(ckMechanism40.ParameterLen) == UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_KEY_DERIVATION_STRING_DATA)));
}
else
{
HLA41.Mechanism mechanism41 = (HLA41.Mechanism)mechanism;
LLA41.CK_MECHANISM ckMechanism41 = (LLA41.CK_MECHANISM)typeof(HLA41.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism41);
Assert.IsTrue(ckMechanism41.Mechanism == ConvertUtils.UInt32FromCKM(CKM.CKM_XOR_BASE_AND_DATA));
Assert.IsTrue(ckMechanism41.Parameter != IntPtr.Zero);
Assert.IsTrue(Convert.ToInt32(ckMechanism41.ParameterLen) == UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_KEY_DERIVATION_STRING_DATA)));
}
}
else
{
if (Platform.StructPackingSize == 0)
{
HLA80.Mechanism mechanism80 = (HLA80.Mechanism)mechanism;
LLA80.CK_MECHANISM ckMechanism80 = (LLA80.CK_MECHANISM)typeof(HLA80.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism80);
Assert.IsTrue(ckMechanism80.Mechanism == ConvertUtils.UInt64FromCKM(CKM.CKM_XOR_BASE_AND_DATA));
Assert.IsTrue(ckMechanism80.Parameter != IntPtr.Zero);
Assert.IsTrue(Convert.ToInt32(ckMechanism80.ParameterLen) == UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_KEY_DERIVATION_STRING_DATA)));
}
else
{
HLA81.Mechanism mechanism81 = (HLA81.Mechanism)mechanism;
LLA81.CK_MECHANISM ckMechanism81 = (LLA81.CK_MECHANISM)typeof(HLA81.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism81);
Assert.IsTrue(ckMechanism81.Mechanism == ConvertUtils.UInt64FromCKM(CKM.CKM_XOR_BASE_AND_DATA));
Assert.IsTrue(ckMechanism81.Parameter != IntPtr.Zero);
Assert.IsTrue(Convert.ToInt32(ckMechanism81.ParameterLen) == UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_KEY_DERIVATION_STRING_DATA)));
}
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcdv = Google.Cloud.Dialogflow.V2;
using sys = System;
namespace Google.Cloud.Dialogflow.V2
{
/// <summary>Resource name for the <c>KnowledgeBase</c> resource.</summary>
public sealed partial class KnowledgeBaseName : gax::IResourceName, sys::IEquatable<KnowledgeBaseName>
{
/// <summary>The possible contents of <see cref="KnowledgeBaseName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/knowledgeBases/{knowledge_base}</c>.
/// </summary>
ProjectKnowledgeBase = 1,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/knowledgeBases/{knowledge_base}</c>
/// .
/// </summary>
ProjectLocationKnowledgeBase = 2,
}
private static gax::PathTemplate s_projectKnowledgeBase = new gax::PathTemplate("projects/{project}/knowledgeBases/{knowledge_base}");
private static gax::PathTemplate s_projectLocationKnowledgeBase = new gax::PathTemplate("projects/{project}/locations/{location}/knowledgeBases/{knowledge_base}");
/// <summary>Creates a <see cref="KnowledgeBaseName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="KnowledgeBaseName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static KnowledgeBaseName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new KnowledgeBaseName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="KnowledgeBaseName"/> with the pattern
/// <c>projects/{project}/knowledgeBases/{knowledge_base}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="knowledgeBaseId">The <c>KnowledgeBase</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="KnowledgeBaseName"/> constructed from the provided ids.</returns>
public static KnowledgeBaseName FromProjectKnowledgeBase(string projectId, string knowledgeBaseId) =>
new KnowledgeBaseName(ResourceNameType.ProjectKnowledgeBase, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), knowledgeBaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(knowledgeBaseId, nameof(knowledgeBaseId)));
/// <summary>
/// Creates a <see cref="KnowledgeBaseName"/> with the pattern
/// <c>projects/{project}/locations/{location}/knowledgeBases/{knowledge_base}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="knowledgeBaseId">The <c>KnowledgeBase</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="KnowledgeBaseName"/> constructed from the provided ids.</returns>
public static KnowledgeBaseName FromProjectLocationKnowledgeBase(string projectId, string locationId, string knowledgeBaseId) =>
new KnowledgeBaseName(ResourceNameType.ProjectLocationKnowledgeBase, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), knowledgeBaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(knowledgeBaseId, nameof(knowledgeBaseId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KnowledgeBaseName"/> with pattern
/// <c>projects/{project}/knowledgeBases/{knowledge_base}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="knowledgeBaseId">The <c>KnowledgeBase</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="KnowledgeBaseName"/> with pattern
/// <c>projects/{project}/knowledgeBases/{knowledge_base}</c>.
/// </returns>
public static string Format(string projectId, string knowledgeBaseId) =>
FormatProjectKnowledgeBase(projectId, knowledgeBaseId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KnowledgeBaseName"/> with pattern
/// <c>projects/{project}/knowledgeBases/{knowledge_base}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="knowledgeBaseId">The <c>KnowledgeBase</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="KnowledgeBaseName"/> with pattern
/// <c>projects/{project}/knowledgeBases/{knowledge_base}</c>.
/// </returns>
public static string FormatProjectKnowledgeBase(string projectId, string knowledgeBaseId) =>
s_projectKnowledgeBase.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(knowledgeBaseId, nameof(knowledgeBaseId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KnowledgeBaseName"/> with pattern
/// <c>projects/{project}/locations/{location}/knowledgeBases/{knowledge_base}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="knowledgeBaseId">The <c>KnowledgeBase</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="KnowledgeBaseName"/> with pattern
/// <c>projects/{project}/locations/{location}/knowledgeBases/{knowledge_base}</c>.
/// </returns>
public static string FormatProjectLocationKnowledgeBase(string projectId, string locationId, string knowledgeBaseId) =>
s_projectLocationKnowledgeBase.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(knowledgeBaseId, nameof(knowledgeBaseId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="KnowledgeBaseName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/knowledgeBases/{knowledge_base}</c></description></item>
/// <item>
/// <description><c>projects/{project}/locations/{location}/knowledgeBases/{knowledge_base}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="knowledgeBaseName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="KnowledgeBaseName"/> if successful.</returns>
public static KnowledgeBaseName Parse(string knowledgeBaseName) => Parse(knowledgeBaseName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="KnowledgeBaseName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/knowledgeBases/{knowledge_base}</c></description></item>
/// <item>
/// <description><c>projects/{project}/locations/{location}/knowledgeBases/{knowledge_base}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="knowledgeBaseName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="KnowledgeBaseName"/> if successful.</returns>
public static KnowledgeBaseName Parse(string knowledgeBaseName, bool allowUnparsed) =>
TryParse(knowledgeBaseName, allowUnparsed, out KnowledgeBaseName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KnowledgeBaseName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/knowledgeBases/{knowledge_base}</c></description></item>
/// <item>
/// <description><c>projects/{project}/locations/{location}/knowledgeBases/{knowledge_base}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="knowledgeBaseName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KnowledgeBaseName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string knowledgeBaseName, out KnowledgeBaseName result) =>
TryParse(knowledgeBaseName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KnowledgeBaseName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/knowledgeBases/{knowledge_base}</c></description></item>
/// <item>
/// <description><c>projects/{project}/locations/{location}/knowledgeBases/{knowledge_base}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="knowledgeBaseName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KnowledgeBaseName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string knowledgeBaseName, bool allowUnparsed, out KnowledgeBaseName result)
{
gax::GaxPreconditions.CheckNotNull(knowledgeBaseName, nameof(knowledgeBaseName));
gax::TemplatedResourceName resourceName;
if (s_projectKnowledgeBase.TryParseName(knowledgeBaseName, out resourceName))
{
result = FromProjectKnowledgeBase(resourceName[0], resourceName[1]);
return true;
}
if (s_projectLocationKnowledgeBase.TryParseName(knowledgeBaseName, out resourceName))
{
result = FromProjectLocationKnowledgeBase(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(knowledgeBaseName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private KnowledgeBaseName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string knowledgeBaseId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
KnowledgeBaseId = knowledgeBaseId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="KnowledgeBaseName"/> class from the component parts of pattern
/// <c>projects/{project}/knowledgeBases/{knowledge_base}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="knowledgeBaseId">The <c>KnowledgeBase</c> ID. Must not be <c>null</c> or empty.</param>
public KnowledgeBaseName(string projectId, string knowledgeBaseId) : this(ResourceNameType.ProjectKnowledgeBase, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), knowledgeBaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(knowledgeBaseId, nameof(knowledgeBaseId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>KnowledgeBase</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string KnowledgeBaseId { get; }
/// <summary>
/// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectKnowledgeBase: return s_projectKnowledgeBase.Expand(ProjectId, KnowledgeBaseId);
case ResourceNameType.ProjectLocationKnowledgeBase: return s_projectLocationKnowledgeBase.Expand(ProjectId, LocationId, KnowledgeBaseId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as KnowledgeBaseName);
/// <inheritdoc/>
public bool Equals(KnowledgeBaseName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(KnowledgeBaseName a, KnowledgeBaseName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(KnowledgeBaseName a, KnowledgeBaseName b) => !(a == b);
}
public partial class KnowledgeBase
{
/// <summary>
/// <see cref="gcdv::KnowledgeBaseName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::KnowledgeBaseName KnowledgeBaseName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::KnowledgeBaseName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListKnowledgeBasesRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project))
{
return project;
}
if (gagr::LocationName.TryParse(Parent, out gagr::LocationName location))
{
return location;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetKnowledgeBaseRequest
{
/// <summary>
/// <see cref="gcdv::KnowledgeBaseName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::KnowledgeBaseName KnowledgeBaseName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::KnowledgeBaseName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateKnowledgeBaseRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project))
{
return project;
}
if (gagr::LocationName.TryParse(Parent, out gagr::LocationName location))
{
return location;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteKnowledgeBaseRequest
{
/// <summary>
/// <see cref="gcdv::KnowledgeBaseName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::KnowledgeBaseName KnowledgeBaseName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::KnowledgeBaseName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.