context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//------------------------------------------------------------------------------
// <copyright file="events.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System.Configuration.Provider;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.Data;
using System.Data.SqlClient;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web.DataAccess;
using System.Web.Util;
////////////
// Events
////////////
[PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
public class SqlWebEventProvider : BufferedWebEventProvider, IInternalWebEventProvider {
const int SQL_MAX_NTEXT_SIZE = 1073741823;
const int NO_LIMIT = -1;
const string SP_LOG_EVENT = "dbo.aspnet_WebEvent_LogEvent";
string _sqlConnectionString;
int _maxEventDetailsLength = NO_LIMIT;
int _commandTimeout = -1;
int _SchemaVersionCheck;
int _connectionCount = 0;
DateTime _retryDate = DateTime.MinValue; // Won't try sending unless DateTime.UtcNow is > _retryDate
protected internal SqlWebEventProvider() { }
public override void Initialize(string name, NameValueCollection config) {
Debug.Trace("SqlWebEventProvider", "Initializing: name=" + name);
_SchemaVersionCheck = 0;
string temp = null;
ProviderUtil.GetAndRemoveStringAttribute(config, "connectionStringName", name, ref temp);
ProviderUtil.GetAndRemoveStringAttribute(config, "connectionString", name, ref _sqlConnectionString);
if (!String.IsNullOrEmpty(temp)) {
if (!String.IsNullOrEmpty(_sqlConnectionString)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Only_one_connection_string_allowed));
}
_sqlConnectionString = SqlConnectionHelper.GetConnectionString(temp, true, true);
if (_sqlConnectionString == null || _sqlConnectionString.Length < 1) {
throw new ConfigurationErrorsException(SR.GetString(SR.Connection_string_not_found, temp));
}
}
else {
// If a connection string is specified explicitly, verify that its not using integrated security
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(_sqlConnectionString);
if (builder.IntegratedSecurity) {
throw new ConfigurationErrorsException(SR.GetString(SR.Cannot_use_integrated_security));
}
}
if (String.IsNullOrEmpty(_sqlConnectionString)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Must_specify_connection_string_or_name, temp));
}
ProviderUtil.GetAndRemovePositiveOrInfiniteAttribute(config, "maxEventDetailsLength", name, ref _maxEventDetailsLength);
if (_maxEventDetailsLength == ProviderUtil.Infinite) {
_maxEventDetailsLength = NO_LIMIT;
}
else if (_maxEventDetailsLength > SQL_MAX_NTEXT_SIZE) {
throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_max_event_details_length, name, _maxEventDetailsLength.ToString(CultureInfo.CurrentCulture)));
}
ProviderUtil.GetAndRemovePositiveAttribute(config, "commandTimeout", name, ref _commandTimeout);
base.Initialize(name, config);
}
private void CheckSchemaVersion(SqlConnection connection) {
string[] features = { "Health Monitoring" };
string version = "1";
SecUtility.CheckSchemaVersion( this, connection, features, version, ref _SchemaVersionCheck );
}
public override void ProcessEventFlush(WebEventBufferFlushInfo flushInfo) {
Debug.Trace("SqlWebEventProvider", "EventBufferFlush called: " +
"NotificationType=" + flushInfo.NotificationType +
", NotificationSequence=" + flushInfo.NotificationSequence +
", Events.Count=" + flushInfo.Events.Count);
WriteToSQL(flushInfo.Events, flushInfo.EventsDiscardedSinceLastNotification,
flushInfo.LastNotificationUtc);
}
void PrepareParams(SqlCommand sqlCommand) {
sqlCommand.Parameters.Add(new SqlParameter("@EventId", SqlDbType.Char, 32));
sqlCommand.Parameters.Add(new SqlParameter("@EventTimeUtc", SqlDbType.DateTime));
sqlCommand.Parameters.Add(new SqlParameter("@EventTime", SqlDbType.DateTime));
sqlCommand.Parameters.Add(new SqlParameter("@EventType", SqlDbType.NVarChar, 256));
sqlCommand.Parameters.Add(new SqlParameter("@EventSequence", SqlDbType.Decimal));
sqlCommand.Parameters.Add(new SqlParameter("@EventOccurrence", SqlDbType.Decimal));
sqlCommand.Parameters.Add(new SqlParameter("@EventCode", SqlDbType.Int));
sqlCommand.Parameters.Add(new SqlParameter("@EventDetailCode", SqlDbType.Int));
sqlCommand.Parameters.Add(new SqlParameter("@Message", SqlDbType.NVarChar, 1024));
sqlCommand.Parameters.Add(new SqlParameter("@ApplicationPath", SqlDbType.NVarChar, 256));
sqlCommand.Parameters.Add(new SqlParameter("@ApplicationVirtualPath", SqlDbType.NVarChar, 256));
sqlCommand.Parameters.Add(new SqlParameter("@MachineName", SqlDbType.NVarChar, 256));
sqlCommand.Parameters.Add(new SqlParameter("@RequestUrl", SqlDbType.NVarChar, 1024));
sqlCommand.Parameters.Add(new SqlParameter("@ExceptionType", SqlDbType.NVarChar, 256));
sqlCommand.Parameters.Add(new SqlParameter("@Details", SqlDbType.NText));
}
void FillParams(SqlCommand sqlCommand, WebBaseEvent eventRaised) {
Exception exception = null;
WebRequestInformation reqInfo = null;
string details = null;
WebApplicationInformation appInfo = WebBaseEvent.ApplicationInformation;
int n = 0;
sqlCommand.Parameters[n++].Value = eventRaised.EventID.ToString("N", CultureInfo.InstalledUICulture); // @EventId
sqlCommand.Parameters[n++].Value = eventRaised.EventTimeUtc; // @EventTimeUtc
sqlCommand.Parameters[n++].Value = eventRaised.EventTime; // @EventTime
sqlCommand.Parameters[n++].Value = eventRaised.GetType().ToString(); // @EventType
sqlCommand.Parameters[n++].Value = eventRaised.EventSequence; // @EventSequence
sqlCommand.Parameters[n++].Value = eventRaised.EventOccurrence; // @EventOccurrence
sqlCommand.Parameters[n++].Value = eventRaised.EventCode; // @EventCode
sqlCommand.Parameters[n++].Value = eventRaised.EventDetailCode; // @EventDetailCode
sqlCommand.Parameters[n++].Value = eventRaised.Message; // @Message
sqlCommand.Parameters[n++].Value = appInfo.ApplicationPath; // @ApplicationPath
sqlCommand.Parameters[n++].Value = appInfo.ApplicationVirtualPath; // @ApplicationVirtualPath
sqlCommand.Parameters[n++].Value = appInfo.MachineName; // @MachineName
//
// @RequestUrl
if (eventRaised is WebRequestEvent) {
reqInfo = ((WebRequestEvent)eventRaised).RequestInformation;
}
else if (eventRaised is WebRequestErrorEvent) {
reqInfo = ((WebRequestErrorEvent)eventRaised).RequestInformation;
}
else if (eventRaised is WebErrorEvent) {
reqInfo = ((WebErrorEvent)eventRaised).RequestInformation;
}
else if (eventRaised is WebAuditEvent) {
reqInfo = ((WebAuditEvent)eventRaised).RequestInformation;
}
sqlCommand.Parameters[n++].Value = (reqInfo != null) ? reqInfo.RequestUrl : Convert.DBNull;
// @ExceptionType
if (eventRaised is WebBaseErrorEvent) {
exception = ((WebBaseErrorEvent)eventRaised).ErrorException;
}
sqlCommand.Parameters[n++].Value = (exception != null) ? exception.GetType().ToString() : Convert.DBNull;
// @Details
details = eventRaised.ToString();
if (_maxEventDetailsLength != NO_LIMIT &&
details.Length > _maxEventDetailsLength) {
details = details.Substring(0, _maxEventDetailsLength);
}
sqlCommand.Parameters[n++].Value = details;
}
[PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
[SqlClientPermission(SecurityAction.Assert, Unrestricted = true)]
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
void WriteToSQL(WebBaseEventCollection events, int eventsDiscardedByBuffer, DateTime lastNotificationUtc) {
// We don't want to send any more events until we've waited until the _retryDate (which defaults to minValue)
if (_retryDate > DateTime.UtcNow) {
return;
}
try {
SqlConnectionHolder sqlConnHolder = SqlConnectionHelper.GetConnection(_sqlConnectionString, true);
SqlCommand sqlCommand = new SqlCommand(SP_LOG_EVENT);
CheckSchemaVersion(sqlConnHolder.Connection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Connection = sqlConnHolder.Connection;
if (_commandTimeout > -1) {
sqlCommand.CommandTimeout = _commandTimeout;
}
PrepareParams(sqlCommand);
try {
sqlConnHolder.Open(null, true);
Interlocked.Increment(ref _connectionCount);
if (eventsDiscardedByBuffer != 0) {
WebBaseEvent infoEvent = new WebBaseEvent(
SR.GetString(SR.Sql_webevent_provider_events_dropped,
eventsDiscardedByBuffer.ToString(CultureInfo.InstalledUICulture),
lastNotificationUtc.ToString("r", CultureInfo.InstalledUICulture)),
null,
WebEventCodes.WebEventProviderInformation,
WebEventCodes.SqlProviderEventsDropped);
FillParams(sqlCommand, infoEvent);
sqlCommand.ExecuteNonQuery();
}
foreach (WebBaseEvent eventRaised in events) {
FillParams(sqlCommand, eventRaised);
sqlCommand.ExecuteNonQuery();
}
}
#if DBG
catch (Exception e) {
Debug.Trace("SqlWebEventProvider", "ExecuteNonQuery failed: " + e);
throw;
}
#endif
finally {
sqlConnHolder.Close();
Interlocked.Decrement(ref _connectionCount);
}
#if (!DBG)
try {
#endif
EventProcessingComplete(events);
#if (!DBG)
}
catch {
// Ignore all errors.
}
#endif
}
catch {
// For any failure, we will wait at least 30 seconds or _commandTimeout before trying again
double timeout = 30;
if (_commandTimeout > -1) {
timeout = (double)_commandTimeout;
}
_retryDate = DateTime.UtcNow.AddSeconds(timeout);
throw;
}
}
public override void ProcessEvent(WebBaseEvent eventRaised)
{
if (UseBuffering) {
base.ProcessEvent(eventRaised);
}
else {
Debug.Trace("SqlWebEventProvider", "Writing event to SQL: event=" + eventRaised.GetType().Name);
WriteToSQL(new WebBaseEventCollection(eventRaised), 0, new DateTime(0));
}
}
protected virtual void EventProcessingComplete(WebBaseEventCollection raisedEvents) {
}
public override void Shutdown() {
try {
Flush();
}
finally {
base.Shutdown();
}
// VSWhidbey 531556: Need to wait until all connections are gone before returning here
// Sleep for 2x the command timeout in 1 sec intervals then give up, default timeout is 30 sec
if (_connectionCount > 0) {
int sleepAttempts = _commandTimeout*2;
if (sleepAttempts <= 0) {
sleepAttempts = 60;
}
// Check every second
while (_connectionCount > 0 && sleepAttempts > 0) {
--sleepAttempts;
Thread.Sleep(1000);
}
}
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using JetBrains.Annotations;
namespace NLog.UnitTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Xunit;
using NLog.Common;
using NLog.Config;
using NLog.Targets;
#if NET4_5
using System.Threading.Tasks;
using Microsoft.Practices.Unity;
#endif
public class LogManagerTests : NLogTestBase
{
[Fact]
public void GetLoggerTest()
{
ILogger loggerA = LogManager.GetLogger("A");
ILogger loggerA2 = LogManager.GetLogger("A");
ILogger loggerB = LogManager.GetLogger("B");
Assert.Same(loggerA, loggerA2);
Assert.NotSame(loggerA, loggerB);
Assert.Equal("A", loggerA.Name);
Assert.Equal("B", loggerB.Name);
}
[Fact]
public void GarbageCollectionTest()
{
string uniqueLoggerName = Guid.NewGuid().ToString();
ILogger loggerA1 = LogManager.GetLogger(uniqueLoggerName);
GC.Collect();
ILogger loggerA2 = LogManager.GetLogger(uniqueLoggerName);
Assert.Same(loggerA1, loggerA2);
}
static WeakReference GetWeakReferenceToTemporaryLogger()
{
string uniqueLoggerName = Guid.NewGuid().ToString();
return new WeakReference(LogManager.GetLogger(uniqueLoggerName));
}
[Fact]
public void GarbageCollection2Test()
{
WeakReference wr = GetWeakReferenceToTemporaryLogger();
// nobody's holding a reference to this Logger anymore, so GC.Collect(2) should free it
GC.Collect();
Assert.False(wr.IsAlive);
}
[Fact]
public void NullLoggerTest()
{
ILogger l = LogManager.CreateNullLogger();
Assert.Equal(String.Empty, l.Name);
}
[Fact]
public void ThrowExceptionsTest()
{
FileTarget ft = new FileTarget();
ft.FileName = ""; // invalid file name
SimpleConfigurator.ConfigureForTargetLogging(ft);
LogManager.ThrowExceptions = false;
LogManager.GetLogger("A").Info("a");
LogManager.ThrowExceptions = true;
try
{
LogManager.GetLogger("A").Info("a");
Assert.True(false, "Should not be reached.");
}
catch
{
Assert.True(true);
}
LogManager.ThrowExceptions = false;
}
//[Fact(Skip="Side effects to other unit tests.")]
public void GlobalThresholdTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog globalThreshold='Info'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Assert.Equal(LogLevel.Info, LogManager.GlobalThreshold);
// nothing gets logged because of globalThreshold
LogManager.GetLogger("A").Debug("xxx");
AssertDebugLastMessage("debug", "");
// lower the threshold
LogManager.GlobalThreshold = LogLevel.Trace;
LogManager.GetLogger("A").Debug("yyy");
AssertDebugLastMessage("debug", "yyy");
// raise the threshold
LogManager.GlobalThreshold = LogLevel.Info;
// this should be yyy, meaning that the target is in place
// only rules have been modified.
LogManager.GetLogger("A").Debug("zzz");
AssertDebugLastMessage("debug", "yyy");
LogManager.Shutdown();
LogManager.Configuration = null;
}
[Fact]
public void DisableLoggingTest_UsingStatement()
{
const string LoggerConfig = @"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='DisableLoggingTest_UsingStatement_A' levels='Trace' writeTo='debug' />
<logger name='DisableLoggingTest_UsingStatement_B' levels='Error' writeTo='debug' />
</rules>
</nlog>";
// Disable/Enable logging should affect ALL the loggers.
ILogger loggerA = LogManager.GetLogger("DisableLoggingTest_UsingStatement_A");
ILogger loggerB = LogManager.GetLogger("DisableLoggingTest_UsingStatement_B");
LogManager.Configuration = CreateConfigurationFromString(LoggerConfig);
// The starting state for logging is enable.
Assert.True(LogManager.IsLoggingEnabled());
loggerA.Trace("TTT");
AssertDebugLastMessage("debug", "TTT");
loggerB.Error("EEE");
AssertDebugLastMessage("debug", "EEE");
loggerA.Trace("---");
AssertDebugLastMessage("debug", "---");
using (LogManager.DisableLogging())
{
Assert.False(LogManager.IsLoggingEnabled());
// The last of LastMessage outside using statement should be returned.
loggerA.Trace("TTT");
AssertDebugLastMessage("debug", "---");
loggerB.Error("EEE");
AssertDebugLastMessage("debug", "---");
}
Assert.True(LogManager.IsLoggingEnabled());
loggerA.Trace("TTT");
AssertDebugLastMessage("debug", "TTT");
loggerB.Error("EEE");
AssertDebugLastMessage("debug", "EEE");
LogManager.Shutdown();
LogManager.Configuration = null;
}
[Fact]
public void DisableLoggingTest_WithoutUsingStatement()
{
const string LoggerConfig = @"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='DisableLoggingTest_WithoutUsingStatement_A' levels='Trace' writeTo='debug' />
<logger name='DisableLoggingTest_WithoutUsingStatement_B' levels='Error' writeTo='debug' />
</rules>
</nlog>";
// Disable/Enable logging should affect ALL the loggers.
ILogger loggerA = LogManager.GetLogger("DisableLoggingTest_WithoutUsingStatement_A");
ILogger loggerB = LogManager.GetLogger("DisableLoggingTest_WithoutUsingStatement_B");
LogManager.Configuration = CreateConfigurationFromString(LoggerConfig);
// The starting state for logging is enable.
Assert.True(LogManager.IsLoggingEnabled());
loggerA.Trace("TTT");
AssertDebugLastMessage("debug", "TTT");
loggerB.Error("EEE");
AssertDebugLastMessage("debug", "EEE");
loggerA.Trace("---");
AssertDebugLastMessage("debug", "---");
LogManager.DisableLogging();
Assert.False(LogManager.IsLoggingEnabled());
// The last value of LastMessage before DisableLogging() should be returned.
loggerA.Trace("TTT");
AssertDebugLastMessage("debug", "---");
loggerB.Error("EEE");
AssertDebugLastMessage("debug", "---");
LogManager.EnableLogging();
Assert.True(LogManager.IsLoggingEnabled());
loggerA.Trace("TTT");
AssertDebugLastMessage("debug", "TTT");
loggerB.Error("EEE");
AssertDebugLastMessage("debug", "EEE");
LogManager.Shutdown();
LogManager.Configuration = null;
}
#if !SILVERLIGHT
private int _reloadCounter = 0;
private void WaitForConfigReload(int counter)
{
while (_reloadCounter < counter)
{
System.Threading.Thread.Sleep(100);
}
}
private void OnConfigReloaded(object sender, LoggingConfigurationReloadedEventArgs e)
{
Console.WriteLine("OnConfigReloaded success={0}", e.Succeeded);
_reloadCounter++;
}
private bool IsMacOsX()
{
#if MONO
if (Directory.Exists("/Library/Frameworks/Mono.framework/"))
{
return true;
}
#endif
return false;
}
[Fact]
public void AutoReloadTest()
{
if (IsMacOsX())
{
// skip this on Mac OS, since it requires root permissions for
// filesystem watcher
return;
}
using (new InternalLoggerScope())
{
string fileName = Path.GetTempFileName();
try
{
_reloadCounter = 0;
LogManager.ConfigurationReloaded += OnConfigReloaded;
using (StreamWriter fs = File.CreateText(fileName))
{
fs.Write(@"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
}
LogManager.Configuration = new XmlLoggingConfiguration(fileName);
AssertDebugCounter("debug", 0);
ILogger logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
InternalLogger.Info("Rewriting test file...");
// now write the file again
using (StreamWriter fs = File.CreateText(fileName))
{
fs.Write(@"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
}
InternalLogger.Info("Rewritten.");
WaitForConfigReload(1);
logger.Debug("aaa");
AssertDebugLastMessage("debug", "xxx aaa");
// write the file again, this time make an error
using (StreamWriter fs = File.CreateText(fileName))
{
fs.Write(@"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
}
WaitForConfigReload(2);
logger.Debug("bbb");
AssertDebugLastMessage("debug", "xxx bbb");
// write the corrected file again
using (StreamWriter fs = File.CreateText(fileName))
{
fs.Write(@"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='zzz ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
}
WaitForConfigReload(3);
logger.Debug("ccc");
AssertDebugLastMessage("debug", "zzz ccc");
}
finally
{
LogManager.ConfigurationReloaded -= OnConfigReloaded;
if (File.Exists(fileName))
File.Delete(fileName);
}
}
}
#endif
[Fact]
public void GivenCurrentClass_WhenGetCurrentClassLogger_ThenLoggerShouldBeCurrentClass()
{
var logger = LogManager.GetCurrentClassLogger();
Assert.Equal(this.GetType().FullName, logger.Name);
}
private static class ImAStaticClass
{
[UsedImplicitly]
private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();
static ImAStaticClass() { }
public static void DummyToInvokeInitializers() { }
}
[Fact]
public void GetCurrentClassLogger_static_class()
{
ImAStaticClass.DummyToInvokeInitializers();
}
private abstract class ImAAbstractClass
{
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Object"/> class.
/// </summary>
protected ImAAbstractClass()
{
Logger Logger = NLog.LogManager.GetCurrentClassLogger();
}
}
private class InheritedFromAbstractClass : ImAAbstractClass
{
}
/// <summary>
/// Creating instance in a static ctor should not be a problm
/// </summary>
[Fact]
public void GetCurrentClassLogger_abstract_class()
{
var instance = new InheritedFromAbstractClass();
}
/// <summary>
/// I'm a class which isn't inhereting from Logger
/// </summary>
private class ImNotALogger
{
}
/// <summary>
/// ImNotALogger inherits not from Logger , but should not throw an exception
/// </summary>
[Fact]
public void GetLogger_wrong_loggertype_should_continue()
{
var instance = LogManager.GetLogger("a", typeof(ImNotALogger));
Assert.NotNull(instance);
}
/// <summary>
/// ImNotALogger inherits not from Logger , but should not throw an exception
/// </summary>
[Fact]
public void GetLogger_wrong_loggertype_should_continue_even_if_class_is_static()
{
var instance = LogManager.GetLogger("a", typeof(ImAStaticClass));
Assert.NotNull(instance);
}
#if NET4_0 || NET4_5
[Fact]
public void GivenLazyClass_WhenGetCurrentClassLogger_ThenLoggerNameShouldBeCurrentClass()
{
var logger = new Lazy<ILogger>(LogManager.GetCurrentClassLogger);
Assert.Equal(this.GetType().FullName, logger.Value.Name);
}
#endif
#if NET4_5
/// <summary>
/// target for <see cref="ThreadSafe_getCurrentClassLogger_test"/>
/// </summary>
private static MemoryQueueTarget mTarget = new MemoryQueueTarget(500);
/// <summary>
/// target for <see cref="ThreadSafe_getCurrentClassLogger_test"/>
/// </summary>
private static MemoryQueueTarget mTarget2 = new MemoryQueueTarget(500);
/// <summary>
/// Note: THe problem can be reproduced when: debugging the unittest + "break when exception is thrown" checked in visual studio.
///
/// https://github.com/NLog/NLog/issues/500
/// </summary>
[Fact]
public void ThreadSafe_getCurrentClassLogger_test()
{
using (var c = new UnityContainer())
{
var r = Enumerable.Range(1, 100); //reported with 10.
Task.Run(() =>
{
//need for init
LogManager.Configuration = new LoggingConfiguration();
LogManager.Configuration.AddTarget("memory", mTarget);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, mTarget));
LogManager.Configuration.AddTarget("memory2", mTarget2);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, mTarget2));
LogManager.ReconfigExistingLoggers();
});
Parallel.ForEach(r, a =>
{
var res = c.Resolve<ClassA>();
});
mTarget.Layout = @"${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message} ${exception:format=tostring}";
mTarget2.Layout = @"${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message} ${exception:format=tostring}";
}
}
/// <summary>
/// target for <see cref="ThreadSafe_getCurrentClassLogger_test"/>
/// </summary>
[Target("Memory")]
public sealed class MemoryQueueTarget : TargetWithLayout
{
private int maxSize;
public MemoryQueueTarget(int size)
{
this.Logs = new Queue<string>();
this.maxSize = size;
}
public Queue<string> Logs { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
string msg = this.Layout.Render(logEvent);
if (msg.Length > 100)
msg = msg.Substring(0, 100) + "...";
this.Logs.Enqueue(msg);
while (this.Logs.Count > maxSize)
{
Logs.Dequeue();
}
}
}
/// <summary>
/// class for <see cref="ThreadSafe_getCurrentClassLogger_test"/>
/// </summary>
public class ClassA
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public ClassA(ClassB dd)
{
logger.Info("Hi there A");
}
}
/// <summary>
/// class for <see cref="ThreadSafe_getCurrentClassLogger_test"/>
/// </summary>
public class ClassB
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public ClassB(ClassC dd)
{
logger.Info("Hi there B");
}
}
/// <summary>
/// class for <see cref="ThreadSafe_getCurrentClassLogger_test"/>
/// </summary>
public class ClassC
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public ClassC(ClassD dd)
{
logger.Info("Hi there C");
}
}
/// <summary>
/// class for <see cref="ThreadSafe_getCurrentClassLogger_test"/>
/// </summary>
public class ClassD
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public ClassD()
{
logger.Info("Hi there D");
}
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
/// <summary>
/// Context for view execution.
/// </summary>
public class ViewContext : ActionContext
{
private FormContext _formContext = default!;
private DynamicViewData? _viewBag;
private Dictionary<object, object?> _items = default!;
/// <summary>
/// Creates an empty <see cref="ViewContext"/>.
/// </summary>
/// <remarks>
/// The default constructor is provided for unit test purposes only.
/// </remarks>
#nullable disable warnings
// This is a unit-test only constructor where no property is initialized. We'll avoid having to
// using null-forgiveness operator by skipping nullable warnings on this constructor.
public ViewContext()
{
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), ModelState);
}
#nullable enable
/// <summary>
/// Initializes a new instance of <see cref="ViewContext"/>.
/// </summary>
/// <param name="actionContext">The <see cref="ActionContext"/>.</param>
/// <param name="view">The <see cref="IView"/> being rendered.</param>
/// <param name="viewData">The <see cref="ViewDataDictionary"/>.</param>
/// <param name="tempData">The <see cref="ITempDataDictionary"/>.</param>
/// <param name="writer">The <see cref="TextWriter"/> to render output to.</param>
/// <param name="htmlHelperOptions">The <see cref="HtmlHelperOptions"/> to apply to this instance.</param>
public ViewContext(
ActionContext actionContext,
IView view,
ViewDataDictionary viewData,
ITempDataDictionary tempData,
TextWriter writer,
HtmlHelperOptions htmlHelperOptions)
: base(actionContext)
{
if (actionContext == null)
{
throw new ArgumentNullException(nameof(actionContext));
}
if (view == null)
{
throw new ArgumentNullException(nameof(view));
}
if (viewData == null)
{
throw new ArgumentNullException(nameof(viewData));
}
if (tempData == null)
{
throw new ArgumentNullException(nameof(tempData));
}
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (htmlHelperOptions == null)
{
throw new ArgumentNullException(nameof(htmlHelperOptions));
}
View = view;
ViewData = viewData;
TempData = tempData;
Writer = writer;
FormContext = new FormContext();
ClientValidationEnabled = htmlHelperOptions.ClientValidationEnabled;
Html5DateRenderingMode = htmlHelperOptions.Html5DateRenderingMode;
ValidationSummaryMessageElement = htmlHelperOptions.ValidationSummaryMessageElement;
ValidationMessageElement = htmlHelperOptions.ValidationMessageElement;
CheckBoxHiddenInputRenderMode = htmlHelperOptions.CheckBoxHiddenInputRenderMode;
}
/// <summary>
/// Initializes a new instance of <see cref="ViewContext"/>.
/// </summary>
/// <param name="viewContext">The <see cref="ViewContext"/> to copy values from.</param>
/// <param name="view">The <see cref="IView"/> being rendered.</param>
/// <param name="viewData">The <see cref="ViewDataDictionary"/>.</param>
/// <param name="writer">The <see cref="TextWriter"/> to render output to.</param>
public ViewContext(
ViewContext viewContext,
IView view,
ViewDataDictionary viewData,
TextWriter writer)
: base(viewContext)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
if (view == null)
{
throw new ArgumentNullException(nameof(view));
}
if (viewData == null)
{
throw new ArgumentNullException(nameof(viewData));
}
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
FormContext = viewContext.FormContext;
ClientValidationEnabled = viewContext.ClientValidationEnabled;
Html5DateRenderingMode = viewContext.Html5DateRenderingMode;
ValidationSummaryMessageElement = viewContext.ValidationSummaryMessageElement;
ValidationMessageElement = viewContext.ValidationMessageElement;
CheckBoxHiddenInputRenderMode = viewContext.CheckBoxHiddenInputRenderMode;
ExecutingFilePath = viewContext.ExecutingFilePath;
View = view;
ViewData = viewData;
TempData = viewContext.TempData;
Writer = writer;
// The dictionary needs to be initialized at this point so that child viewcontexts share the same underlying storage;
_items = viewContext.Items;
}
/// <summary>
/// Gets or sets the <see cref="FormContext"/> for the form element being rendered.
/// A default context is returned if no form is currently being rendered.
/// </summary>
public virtual FormContext FormContext
{
get => _formContext;
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_formContext = value;
}
}
/// <summary>
/// Gets or sets a value that indicates whether client-side validation is enabled.
/// </summary>
public bool ClientValidationEnabled { get; set; }
/// <summary>
/// Set this property to <see cref="Html5DateRenderingMode.CurrentCulture" /> to have templated helpers such as
/// <see cref="IHtmlHelper.Editor" /> and <see cref="IHtmlHelper{TModel}.EditorFor" /> render date and time
/// values using the current culture. By default, these helpers render dates and times as RFC 3339 compliant strings.
/// </summary>
public Html5DateRenderingMode Html5DateRenderingMode { get; set; }
/// <summary>
/// Element name used to wrap a top-level message generated by <see cref="IHtmlHelper.ValidationSummary"/> and
/// other overloads.
/// </summary>
public string ValidationSummaryMessageElement { get; set; }
/// <summary>
/// Element name used to wrap a top-level message generated by <see cref="IHtmlHelper.ValidationMessage"/> and
/// other overloads.
/// </summary>
public string ValidationMessageElement { get; set; }
/// <summary>
/// Gets or sets the way hidden inputs are rendered for checkbox tag helpers and html helpers.
/// </summary>
public CheckBoxHiddenInputRenderMode CheckBoxHiddenInputRenderMode { get; set; }
/// <summary>
/// Gets the dynamic view bag.
/// </summary>
public dynamic ViewBag
{
get
{
if (_viewBag == null)
{
_viewBag = new DynamicViewData(() => ViewData);
}
return _viewBag;
}
}
/// <summary>
/// Gets or sets the <see cref="IView"/> currently being rendered, if any.
/// </summary>
public IView View { get; set; }
/// <summary>
/// Gets or sets the <see cref="ViewDataDictionary"/>.
/// </summary>
public ViewDataDictionary ViewData { get; set; }
/// <summary>
/// Gets or sets the <see cref="ITempDataDictionary"/> instance.
/// </summary>
public ITempDataDictionary TempData { get; set; }
/// <summary>
/// Gets or sets the <see cref="TextWriter"/> used to write the output.
/// </summary>
public TextWriter Writer { get; set; }
/// <summary>
/// Gets or sets the path of the view file currently being rendered.
/// </summary>
/// <remarks>
/// The rendering of a view may involve one or more files (e.g. _ViewStart, Layouts etc).
/// This property contains the path of the file currently being rendered.
/// </remarks>
public string? ExecutingFilePath { get; set; }
/// <summary>
/// Gets a key/value collection that can be used to share data within the scope of this view execution.
/// </summary>
internal Dictionary<object, object?> Items => _items ??= new Dictionary<object, object?>();
/// <summary>
/// Gets the <see cref="FormContext"/> if <see cref="ClientValidationEnabled"/> is enabled.
/// </summary>
/// <returns></returns>
public FormContext? GetFormContextForClientValidation()
{
return ClientValidationEnabled ? FormContext : null;
}
}
}
| |
using System;
using NUnit.Framework;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Agreement;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Crypto.Tests
{
/// <remarks>Test for ECIES - Elliptic Curve Integrated Encryption Scheme</remarks>
[TestFixture]
public class EcIesTest
: SimpleTest
{
public EcIesTest()
{
}
public override string Name
{
get { return "ECIES"; }
}
private void StaticTest()
{
FpCurve curve = new FpCurve(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G
new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
"ECDH",
new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d
parameters);
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
"ECDH",
curve.DecodePoint(Hex.Decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")), // Q
parameters);
AsymmetricCipherKeyPair p1 = new AsymmetricCipherKeyPair(pubKey, priKey);
AsymmetricCipherKeyPair p2 = new AsymmetricCipherKeyPair(pubKey, priKey);
//
// stream test
//
IesEngine i1 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()));
IesEngine i2 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()));
byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
IesParameters p = new IesParameters(d, e, 64);
i1.Init(true, p1.Private, p2.Public, p);
i2.Init(false, p2.Private, p1.Public, p);
byte[] message = Hex.Decode("1234567890abcdef");
byte[] out1 = i1.ProcessBlock(message, 0, message.Length);
if (!AreEqual(out1, Hex.Decode("468d89877e8238802403ec4cb6b329faeccfa6f3a730f2cdb3c0a8e8")))
{
Fail("stream cipher test failed on enc");
}
byte[] out2 = i2.ProcessBlock(out1, 0, out1.Length);
if (!AreEqual(out2, message))
{
Fail("stream cipher test failed");
}
//
// twofish with CBC
//
BufferedBlockCipher c1 = new PaddedBufferedBlockCipher(
new CbcBlockCipher(new TwofishEngine()));
BufferedBlockCipher c2 = new PaddedBufferedBlockCipher(
new CbcBlockCipher(new TwofishEngine()));
i1 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()),
c1);
i2 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()),
c2);
d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
p = new IesWithCipherParameters(d, e, 64, 128);
i1.Init(true, p1.Private, p2.Public, p);
i2.Init(false, p2.Private, p1.Public, p);
message = Hex.Decode("1234567890abcdef");
out1 = i1.ProcessBlock(message, 0, message.Length);
if (!AreEqual(out1, Hex.Decode("b8a06ea5c2b9df28b58a0a90a734cde8c9c02903e5c220021fe4417410d1e53a32a71696")))
{
Fail("twofish cipher test failed on enc");
}
out2 = i2.ProcessBlock(out1, 0, out1.Length);
if (!AreEqual(out2, message))
{
Fail("twofish cipher test failed");
}
}
private void DoTest(
AsymmetricCipherKeyPair p1,
AsymmetricCipherKeyPair p2)
{
//
// stream test
//
IesEngine i1 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()));
IesEngine i2 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()));
byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
IesParameters p = new IesParameters(d, e, 64);
i1.Init(true, p1.Private, p2.Public, p);
i2.Init(false, p2.Private, p1.Public, p);
byte[] message = Hex.Decode("1234567890abcdef");
byte[] out1 = i1.ProcessBlock(message, 0, message.Length);
byte[] out2 = i2.ProcessBlock(out1, 0, out1.Length);
if (!AreEqual(out2, message))
{
Fail("stream cipher test failed");
}
//
// twofish with CBC
//
BufferedBlockCipher c1 = new PaddedBufferedBlockCipher(
new CbcBlockCipher(new TwofishEngine()));
BufferedBlockCipher c2 = new PaddedBufferedBlockCipher(
new CbcBlockCipher(new TwofishEngine()));
i1 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()),
c1);
i2 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()),
c2);
d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
p = new IesWithCipherParameters(d, e, 64, 128);
i1.Init(true, p1.Private, p2.Public, p);
i2.Init(false, p2.Private, p1.Public, p);
message = Hex.Decode("1234567890abcdef");
out1 = i1.ProcessBlock(message, 0, message.Length);
out2 = i2.ProcessBlock(out1, 0, out1.Length);
if (!AreEqual(out2, message))
{
Fail("twofish cipher test failed");
}
}
public override void PerformTest()
{
StaticTest();
FpCurve curve = new FpCurve(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G
new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n
ECKeyPairGenerator eGen = new ECKeyPairGenerator();
KeyGenerationParameters gParam = new ECKeyGenerationParameters(parameters, new SecureRandom());
eGen.Init(gParam);
AsymmetricCipherKeyPair p1 = eGen.GenerateKeyPair();
AsymmetricCipherKeyPair p2 = eGen.GenerateKeyPair();
DoTest(p1, p2);
}
public static void Main(
string[] args)
{
RunTest(new EcIesTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Security;
using System.Threading.Tasks;
namespace Microsoft.Xml
{
using System;
internal abstract class XmlStreamNodeWriter : XmlNodeWriter
{
private Stream _stream;
private byte[] _buffer;
private int _offset;
private bool _ownsStream;
private const int bufferLength = 512;
private const int maxBytesPerChar = 3;
private Encoding _encoding;
private static UTF8Encoding s_UTF8Encoding = new UTF8Encoding(false, true);
protected XmlStreamNodeWriter()
{
_buffer = new byte[bufferLength];
}
protected void SetOutput(Stream stream, bool ownsStream, Encoding encoding)
{
_stream = stream;
_ownsStream = ownsStream;
_offset = 0;
_encoding = encoding;
}
// Getting/Setting the Stream exists for fragmenting
public Stream Stream
{
get
{
return _stream;
}
set
{
_stream = value;
}
}
// StreamBuffer/BufferOffset exists only for the BinaryWriter to fix up nodes
public byte[] StreamBuffer
{
get
{
return _buffer;
}
}
public int BufferOffset
{
get
{
return _offset;
}
}
public int Position
{
get
{
return (int)_stream.Position + _offset;
}
}
private int GetByteCount(char[] chars)
{
if (_encoding == null)
{
return s_UTF8Encoding.GetByteCount(chars);
}
else
{
return _encoding.GetByteCount(chars);
}
}
protected byte[] GetBuffer(int count, out int offset)
{
DiagnosticUtility.DebugAssert(count >= 0 && count <= bufferLength, "");
int bufferOffset = _offset;
if (bufferOffset + count <= bufferLength)
{
offset = bufferOffset;
}
else
{
FlushBuffer();
offset = 0;
}
#if DEBUG
DiagnosticUtility.DebugAssert(offset + count <= bufferLength, "");
for (int i = 0; i < count; i++)
{
_buffer[offset + i] = (byte)'<';
}
#endif
return _buffer;
}
protected async Task<BytesWithOffset> GetBufferAsync(int count)
{
int offset;
DiagnosticUtility.DebugAssert(count >= 0 && count <= bufferLength, "");
int bufferOffset = _offset;
if (bufferOffset + count <= bufferLength)
{
offset = bufferOffset;
}
else
{
await FlushBufferAsync().ConfigureAwait(false);
offset = 0;
}
#if DEBUG
DiagnosticUtility.DebugAssert(offset + count <= bufferLength, "");
for (int i = 0; i < count; i++)
{
_buffer[offset + i] = (byte)'<';
}
#endif
return new BytesWithOffset(_buffer, offset);
}
protected void Advance(int count)
{
DiagnosticUtility.DebugAssert(_offset + count <= bufferLength, "");
_offset += count;
}
private void EnsureByte()
{
if (_offset >= bufferLength)
{
FlushBuffer();
}
}
protected void WriteByte(byte b)
{
EnsureByte();
_buffer[_offset++] = b;
}
protected Task WriteByteAsync(byte b)
{
if (_offset >= bufferLength)
{
return FlushBufferAndWriteByteAsync(b);
}
else
{
_buffer[_offset++] = b;
return Task.CompletedTask;
}
}
private async Task FlushBufferAndWriteByteAsync(byte b)
{
await FlushBufferAsync().ConfigureAwait(false);
_buffer[_offset++] = b;
}
protected void WriteByte(char ch)
{
DiagnosticUtility.DebugAssert(ch < 0x80, "");
WriteByte((byte)ch);
}
protected Task WriteByteAsync(char ch)
{
DiagnosticUtility.DebugAssert(ch < 0x80, "");
return WriteByteAsync((byte)ch);
}
protected void WriteBytes(byte b1, byte b2)
{
byte[] buffer = _buffer;
int offset = _offset;
if (offset + 1 >= bufferLength)
{
FlushBuffer();
offset = 0;
}
buffer[offset + 0] = b1;
buffer[offset + 1] = b2;
_offset += 2;
}
protected Task WriteBytesAsync(byte b1, byte b2)
{
if (_offset + 1 >= bufferLength)
{
return FlushAndWriteBytesAsync(b1, b2);
}
else
{
_buffer[_offset++] = b1;
_buffer[_offset++] = b2;
return Task.CompletedTask;
}
}
private async Task FlushAndWriteBytesAsync(byte b1, byte b2)
{
await FlushBufferAsync().ConfigureAwait(false);
_buffer[_offset++] = b1;
_buffer[_offset++] = b2;
}
protected void WriteBytes(char ch1, char ch2)
{
DiagnosticUtility.DebugAssert(ch1 < 0x80 && ch2 < 0x80, "");
WriteBytes((byte)ch1, (byte)ch2);
}
protected Task WriteBytesAsync(char ch1, char ch2)
{
DiagnosticUtility.DebugAssert(ch1 < 0x80 && ch2 < 0x80, "");
return WriteBytesAsync((byte)ch1, (byte)ch2);
}
public void WriteBytes(byte[] byteBuffer, int byteOffset, int byteCount)
{
if (byteCount < bufferLength)
{
int offset;
byte[] buffer = GetBuffer(byteCount, out offset);
Buffer.BlockCopy(byteBuffer, byteOffset, buffer, offset, byteCount);
Advance(byteCount);
}
else
{
FlushBuffer();
_stream.Write(byteBuffer, byteOffset, byteCount);
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected void UnsafeWriteBytes(byte* bytes, int byteCount)
{
FlushBuffer();
byte[] buffer = _buffer;
while (byteCount >= bufferLength)
{
for (int i = 0; i < bufferLength; i++)
buffer[i] = bytes[i];
_stream.Write(buffer, 0, bufferLength);
bytes += bufferLength;
byteCount -= bufferLength;
}
{
for (int i = 0; i < byteCount; i++)
buffer[i] = bytes[i];
_stream.Write(buffer, 0, byteCount);
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe protected void WriteUTF8Char(int ch)
{
if (ch < 0x80)
{
WriteByte((byte)ch);
}
else if (ch <= char.MaxValue)
{
char* chars = stackalloc char[1];
chars[0] = (char)ch;
UnsafeWriteUTF8Chars(chars, 1);
}
else
{
SurrogateChar surrogateChar = new SurrogateChar(ch);
char* chars = stackalloc char[2];
chars[0] = surrogateChar.HighChar;
chars[1] = surrogateChar.LowChar;
UnsafeWriteUTF8Chars(chars, 2);
}
}
protected void WriteUTF8Chars(byte[] chars, int charOffset, int charCount)
{
if (charCount < bufferLength)
{
int offset;
byte[] buffer = GetBuffer(charCount, out offset);
Buffer.BlockCopy(chars, charOffset, buffer, offset, charCount);
Advance(charCount);
}
else
{
FlushBuffer();
_stream.Write(chars, charOffset, charCount);
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe protected void WriteUTF8Chars(string value)
{
int count = value.Length;
if (count > 0)
{
fixed (char* chars = value)
{
UnsafeWriteUTF8Chars(chars, count);
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected void UnsafeWriteUTF8Chars(char* chars, int charCount)
{
const int charChunkSize = bufferLength / maxBytesPerChar;
while (charCount > charChunkSize)
{
int offset;
int chunkSize = charChunkSize;
if ((int)(chars[chunkSize - 1] & 0xFC00) == 0xD800) // This is a high surrogate
chunkSize--;
byte[] buffer = GetBuffer(chunkSize * maxBytesPerChar, out offset);
Advance(UnsafeGetUTF8Chars(chars, chunkSize, buffer, offset));
charCount -= chunkSize;
chars += chunkSize;
}
if (charCount > 0)
{
int offset;
byte[] buffer = GetBuffer(charCount * maxBytesPerChar, out offset);
Advance(UnsafeGetUTF8Chars(chars, charCount, buffer, offset));
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected void UnsafeWriteUnicodeChars(char* chars, int charCount)
{
const int charChunkSize = bufferLength / 2;
while (charCount > charChunkSize)
{
int offset;
int chunkSize = charChunkSize;
if ((int)(chars[chunkSize - 1] & 0xFC00) == 0xD800) // This is a high surrogate
chunkSize--;
byte[] buffer = GetBuffer(chunkSize * 2, out offset);
Advance(UnsafeGetUnicodeChars(chars, chunkSize, buffer, offset));
charCount -= chunkSize;
chars += chunkSize;
}
if (charCount > 0)
{
int offset;
byte[] buffer = GetBuffer(charCount * 2, out offset);
Advance(UnsafeGetUnicodeChars(chars, charCount, buffer, offset));
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected int UnsafeGetUnicodeChars(char* chars, int charCount, byte[] buffer, int offset)
{
char* charsMax = chars + charCount;
while (chars < charsMax)
{
char value = *chars++;
buffer[offset++] = (byte)value;
value >>= 8;
buffer[offset++] = (byte)value;
}
return charCount * 2;
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected int UnsafeGetUTF8Length(char* chars, int charCount)
{
char* charsMax = chars + charCount;
while (chars < charsMax)
{
if (*chars >= 0x80)
break;
chars++;
}
if (chars == charsMax)
return charCount;
char[] chArray = new char[charsMax - chars];
for (int i = 0; i < chArray.Length; i++)
{
chArray[i] = chars[i];
}
return (int)(chars - (charsMax - charCount)) + GetByteCount(chArray);
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected int UnsafeGetUTF8Chars(char* chars, int charCount, byte[] buffer, int offset)
{
if (charCount > 0)
{
fixed (byte* _bytes = &buffer[offset])
{
byte* bytes = _bytes;
byte* bytesMax = &bytes[buffer.Length - offset];
char* charsMax = &chars[charCount];
while (true)
{
while (chars < charsMax)
{
char t = *chars;
if (t >= 0x80)
break;
*bytes = (byte)t;
bytes++;
chars++;
}
if (chars >= charsMax)
break;
char* charsStart = chars;
while (chars < charsMax && *chars >= 0x80)
{
chars++;
}
string tmp = new string(charsStart, 0, (int)(chars - charsStart));
byte[] newBytes = _encoding != null ? _encoding.GetBytes(tmp) : s_UTF8Encoding.GetBytes(tmp);
int toCopy = Math.Min(newBytes.Length, (int)(bytesMax - bytes));
Array.Copy(newBytes, 0, buffer, (int)(bytes - _bytes) + offset, toCopy);
bytes += toCopy;
if (chars >= charsMax)
break;
}
return (int)(bytes - _bytes);
}
}
return 0;
}
protected virtual void FlushBuffer()
{
if (_offset != 0)
{
_stream.Write(_buffer, 0, _offset);
_offset = 0;
}
}
protected virtual Task FlushBufferAsync()
{
if (_offset != 0)
{
var task = _stream.WriteAsync(_buffer, 0, _offset);
_offset = 0;
return task;
}
return Task.CompletedTask;
}
public override void Flush()
{
FlushBuffer();
_stream.Flush();
}
public override async Task FlushAsync()
{
await FlushBufferAsync().ConfigureAwait(false);
await _stream.FlushAsync().ConfigureAwait(false);
}
public override void Close()
{
if (_stream != null)
{
if (_ownsStream)
{
_stream.Dispose();
}
_stream = null;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public delegate void InputActionHandler(int value);
public delegate void DpadInputActionHandler(int x, int y);
public class UserInput : MonoBehaviour {
[System.Serializable]
class InputAction {
public event InputActionHandler moveButtonEvent;
public event InputActionHandler confirmButtonEvent;
public event InputActionHandler cancelButtonEvent;
public event InputActionHandler itemMenuButtonEvent;
public event InputActionHandler actionMenuButtonEvent;
public event InputActionHandler statusMenuButtonEvent;
public event InputActionHandler jumpButtonEvent;
public event DpadInputActionHandler dpadButtonEvent;
public bool IsMoveButtonEventValid {
get { return moveButtonEvent != null; }
}
public bool IsConfirmButtonEventValid {
get { return confirmButtonEvent != null; }
}
public bool IsCancelButtonEventValid {
get { return cancelButtonEvent != null; }
}
public bool IsItemMenuButtonEventValid {
get { return itemMenuButtonEvent != null; }
}
public bool IsActionMenuButtonEventValid {
get { return actionMenuButtonEvent != null; }
}
public bool IsDpadButtonEventValid {
get { return dpadButtonEvent != null; }
}
public bool IsStatusMenuButtonEventValid {
get { return statusMenuButtonEvent != null; }
}
public bool IsJumpButtonEventValid {
get { return jumpButtonEvent != null; }
}
public void MoveButtonEvent(int v) { moveButtonEvent(v); }
public void ConfirmButtonEvent(int v) { confirmButtonEvent(v); }
public void CancelButtonEvent(int v) { cancelButtonEvent(v); }
public void ItemMenuButtonEvent(int v) { itemMenuButtonEvent(v); }
public void ActionMenuButtonEvent(int v) { actionMenuButtonEvent(v); }
public void DpadButtonEvent(int x, int y) { dpadButtonEvent(x, y); }
public void StatusMenuButtonEvent(int v) { statusMenuButtonEvent(v); }
public void JumpButtonEvent(int v) { jumpButtonEvent(v); }
}
[SerializeField]
private Stack<InputAction> m_actionStack;
private int m_dpadVLastValue;
private int m_dpadHLastValue;
private static UserInput s_manager;
public void EnsureActionStackReady() {
if(m_actionStack == null) {
m_actionStack = new Stack<InputAction>();
}
if(m_actionStack.Count == 0) {
PushActionEventStack();
}
}
public void PushActionEventStack() {
if(m_actionStack == null) {
m_actionStack = new Stack<InputAction>();
}
m_actionStack.Push (new InputAction());
Debug.Log ("[UserInput] input event stack push: now " + m_actionStack.Count);
}
public void PopActionEventStack() {
if(m_actionStack != null) {
m_actionStack.Pop ();
}
Debug.Log ("[UserInput] input event stack pop: now " + m_actionStack.Count);
}
public void AddToMoveEvent(InputActionHandler h) {
EnsureActionStackReady();
m_actionStack.Peek ().moveButtonEvent += h;
}
public void AddToDpadEvent(DpadInputActionHandler h) {
EnsureActionStackReady();
m_actionStack.Peek ().dpadButtonEvent += h;
}
public void AddToConformCancelEvent(InputActionHandler confirm, InputActionHandler cancel) {
EnsureActionStackReady();
m_actionStack.Peek ().confirmButtonEvent += confirm;
m_actionStack.Peek ().cancelButtonEvent += cancel;
}
public void AddToItemMenuEvent(InputActionHandler h) {
EnsureActionStackReady();
m_actionStack.Peek ().itemMenuButtonEvent += h;
}
public void AddToActionMenuEvent(InputActionHandler h) {
EnsureActionStackReady();
m_actionStack.Peek ().actionMenuButtonEvent += h;
}
public void AddToStatusMenuEvent(InputActionHandler h) {
EnsureActionStackReady();
m_actionStack.Peek ().statusMenuButtonEvent += h;
}
public void AddToJumpEvent(InputActionHandler h) {
EnsureActionStackReady();
m_actionStack.Peek ().jumpButtonEvent += h;
}
public void RemoveFromMoveEvent(InputActionHandler h) {
EnsureActionStackReady();
m_actionStack.Peek ().moveButtonEvent -= h;
}
public void RemoveFromConformCancelEvent(InputActionHandler confirm, InputActionHandler cancel) {
EnsureActionStackReady();
m_actionStack.Peek ().confirmButtonEvent -= confirm;
m_actionStack.Peek ().cancelButtonEvent -= cancel;
}
public void RemoveFromItemMenuEvent(InputActionHandler h) {
EnsureActionStackReady();
m_actionStack.Peek ().itemMenuButtonEvent -= h;
}
public void RemoveFromActionMenuEvent(InputActionHandler h) {
EnsureActionStackReady();
m_actionStack.Peek ().actionMenuButtonEvent -= h;
}
public void RemoveFromDpadEvent(DpadInputActionHandler h) {
EnsureActionStackReady();
m_actionStack.Peek ().dpadButtonEvent -= h;
}
public void RemoveFromStatusMenuEvent(InputActionHandler h) {
EnsureActionStackReady();
m_actionStack.Peek ().statusMenuButtonEvent -= h;
}
public void RemoveFromJumpEvent(InputActionHandler h) {
EnsureActionStackReady();
m_actionStack.Peek ().jumpButtonEvent -= h;
}
public static UserInput GetUserInput() {
if( s_manager == null ) {
UserInput ui = Component.FindObjectOfType(typeof(UserInput)) as UserInput;
if(ui) {
s_manager = ui;
} else {
GameObject go = new GameObject("UserInput");
ui = go.AddComponent<UserInput>() as UserInput;
s_manager = ui;
}
}
return s_manager;
}
void Awake() {
}
// Use this for initialization
void Start () {
UserInput[] uis = Component.FindObjectsOfType(typeof(UserInput)) as UserInput[];
if(uis.Length > 1) {
Debug.LogError("UserInput exists more than one");
foreach(UserInput ui in uis) {
Debug.LogError("UserInput:" + ui.gameObject.name);
}
}
}
// Update is called once per frame
void Update () {
if( m_actionStack != null && m_actionStack.Count > 0 ) {
InputAction a = m_actionStack.Peek();
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
bool ok = Input.GetButtonDown("OK");
bool cancel = Input.GetButtonDown("Cancel");
bool item = Input.GetButtonDown("ItemMenu");
bool action = Input.GetButtonDown("ActionMenu");
bool jumpLeft = Input.GetButtonDown("JumpLeft");
bool jumpRight = Input.GetButtonDown("JumpRight");
bool status = Input.GetButtonDown("StatusMenu");
// FOR Rokete Show - force reset
bool exitGame = Input.GetKeyDown(KeyCode.F8);
if( exitGame ) {
GameManager.GetManager().ExitGame();
}
int intH = 0;
int intDH = 0;
int intDV = 0;
if(h < 0.0f) {
intH = 1;
intDH = -1;
}
else if(h > 0.0f) {
intH = -1;
intDH = 1;
}
if(v < 0.0f) {
intDV = -1;
}
else if(v > 0.0f) {
intDV = 1;
}
//Debug.Log ("[Input] intH:" + intH + " intDH:" + intDH + " intDV:" + intDV + " ok:" + ok + " cancel:" + cancel);
/*
* no event should happen at the same time
*/
if(a.IsMoveButtonEventValid && intH != 0) {
a.MoveButtonEvent(intH);
}
else if(a.IsDpadButtonEventValid &&
( (intDH != 0 && m_dpadHLastValue == 0 ) ||
(intDV != 0 && m_dpadVLastValue == 0) ) )
{
a.DpadButtonEvent(intDH, intDV);
}
else if(cancel) {
if(a.IsCancelButtonEventValid) {
a.CancelButtonEvent(0);
}
}
else if(ok) {
if(a.IsConfirmButtonEventValid) {
a.ConfirmButtonEvent(0);
}
}
else if(item) {
if(a.IsItemMenuButtonEventValid) {
a.ItemMenuButtonEvent(0);
}
}
else if(action) {
if(a.IsActionMenuButtonEventValid) {
a.ActionMenuButtonEvent(0);
}
}
else if(jumpLeft) {
if(a.IsJumpButtonEventValid) {
a.JumpButtonEvent(1);
}
}
else if(jumpRight) {
if(a.IsJumpButtonEventValid) {
a.JumpButtonEvent(-1);
}
}
else if(status) {
if(a.IsStatusMenuButtonEventValid) {
a.StatusMenuButtonEvent(0);
}
}
m_dpadHLastValue = intDH;
m_dpadVLastValue = intDV;
}
}
}
| |
#region Copyright (c) 2004 Ian Davis and James Carlyle
/*------------------------------------------------------------------------------
COPYRIGHT AND PERMISSION NOTICE
Copyright (c) 2004 Ian Davis and James Carlyle
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------*/
#endregion
namespace SemPlan.Spiral.Core {
using System;
using System.Collections;
using System.Text;
/// <summary>
/// Represents group of query patterns
/// </summary>
/// <remarks>
/// $Id: PatternGroup.cs,v 1.4 2006/02/13 23:42:49 ian Exp $
///</remarks>
public class PatternGroup {
protected ArrayList itsPatterns;
protected ArrayList itsAlternateGroups;
protected PatternGroup itsOptionalPatterns;
protected ArrayList itsConstraints;
protected QueryGroupPatterns itsQueryPartPatterns;
protected QueryGroupOr itsQueryPartAlternate;
protected QueryGroupPatterns itsQueryPartOptionalPatterns;
protected QueryGroupOptional itsQueryPartOptional;
protected QueryGroupConstraints itsQueryPartConstraints;
public PatternGroup() {
itsPatterns = new ArrayList();
itsAlternateGroups = new ArrayList();
itsConstraints = new ArrayList();
itsQueryPartAlternate = new QueryGroupOr();
itsQueryPartPatterns = new QueryGroupPatterns();
itsQueryPartOptionalPatterns = new QueryGroupPatterns();
itsQueryPartOptional = new QueryGroupOptional( itsQueryPartOptionalPatterns );
itsQueryPartConstraints = new QueryGroupConstraints( );
}
public virtual void AddPattern( Pattern pattern ) {
itsPatterns.Add( pattern );
itsQueryPartPatterns.Add( pattern );
}
public virtual void AddAlternateGroup( PatternGroup group ) {
itsAlternateGroups.Add( group );
}
public virtual void AddConstraint( Constraint constraint ) {
itsConstraints.Add( constraint );
itsQueryPartConstraints.Add( constraint );
}
public virtual IList Patterns{
get {
ArrayList patternsCopy = new ArrayList();
patternsCopy.AddRange( itsPatterns );
return patternsCopy;
}
}
public virtual IList AlternateGroups {
get {
ArrayList patternsCopy = new ArrayList();
patternsCopy.AddRange( itsAlternateGroups );
return patternsCopy;
}
}
public virtual PatternGroup OptionalGroup {
get {
if ( null == itsOptionalPatterns) {
itsOptionalPatterns = new PatternGroup();
}
return itsOptionalPatterns;
}
set {
itsOptionalPatterns = value;
}
}
public virtual IList Constraints {
get {
ArrayList constraintsCopy = new ArrayList();
constraintsCopy.AddRange( itsConstraints );
return constraintsCopy;
}
}
public virtual bool HasOptionalPatterns {
get {
if ( null != itsOptionalPatterns) {
if( itsOptionalPatterns.HasPatterns ) {
return true;
}
}
return false;
}
}
public virtual bool HasPatterns {
get {
if (itsPatterns.Count > 0) return true;
if ( null != itsOptionalPatterns) {
if( itsOptionalPatterns.HasPatterns ) {
return true;
}
}
foreach (PatternGroup group in itsAlternateGroups) {
if (group.HasPatterns) return true;
}
return false;
}
}
public override string ToString() {
StringBuilder buffer = new StringBuilder();
buffer.Append("{");
if ( itsPatterns.Count > 0 ) {
if ( itsAlternateGroups.Count > 0 ) {
buffer.Append("{");
buffer.Append( Environment.NewLine );
}
buffer.Append( Environment.NewLine );
foreach (Pattern pattern in itsPatterns) {
buffer.Append( " " );
buffer.Append( pattern );
buffer.Append( Environment.NewLine );
}
if ( itsAlternateGroups.Count > 0 ) {
buffer.Append("}");
buffer.Append( Environment.NewLine );
}
}
else {
buffer.Append( " " );
}
if ( itsAlternateGroups.Count > 0 ) {
foreach (PatternGroup group in itsAlternateGroups) {
buffer.Append(" UNION ");
buffer.Append( Environment.NewLine );
buffer.Append( group );
buffer.Append( Environment.NewLine );
}
}
if ( null != itsOptionalPatterns ) {
buffer.Append(" OPTIONAL ");
buffer.Append( Environment.NewLine );
buffer.Append( itsOptionalPatterns );
buffer.Append( Environment.NewLine );
}
if ( itsConstraints.Count > 0 ) {
foreach (Constraint constraint in itsConstraints) {
buffer.Append(" FILTER ");
buffer.Append( constraint );
buffer.Append( Environment.NewLine );
}
}
buffer.Append( "}" );
return buffer.ToString();
}
/// <summary>Determines whether two PatternGroup instances are equal.</summary>
/// <returns>True if the two PatternGroups are equal, False otherwise</returns>
public override bool Equals(object other) {
if (null == other) return false;
if (this == other) return true;
PatternGroup specific = (PatternGroup)other;
if ( itsPatterns.Count != specific.itsPatterns.Count) return false;
if ( itsAlternateGroups.Count != specific.itsAlternateGroups.Count) return false;
if ( itsConstraints.Count != specific.itsConstraints.Count) return false;
if ( null == itsOptionalPatterns ) {
if ( null != specific.itsOptionalPatterns ) return false;
}
else {
if (! itsOptionalPatterns.Equals( specific.itsOptionalPatterns) ) return false;
}
IList otherPatterns = specific.itsPatterns;
foreach (Pattern pattern in itsPatterns) {
if (! otherPatterns.Contains( pattern ) ) {
return false;
}
}
IList otherAlternateGroups = specific.itsAlternateGroups;
foreach (PatternGroup group in itsAlternateGroups) {
if (! otherAlternateGroups.Contains( group ) ) {
return false;
}
}
IList otherConstraints = specific.itsConstraints;
foreach (Constraint constraint in itsConstraints) {
if (! otherConstraints.Contains( constraint ) ) {
return false;
}
}
return true;
}
public override int GetHashCode() {
int hashcode = 12345678;
hashcode = hashcode >> 1;
if ( null != itsOptionalPatterns) {
hashcode = hashcode ^ itsOptionalPatterns.GetHashCode();
}
foreach (Pattern pattern in itsPatterns) {
hashcode = hashcode >> 1;
hashcode = hashcode ^ pattern.GetHashCode();
}
foreach (PatternGroup group in itsAlternateGroups) {
hashcode = hashcode >> 1;
hashcode = hashcode ^ group.GetHashCode();
}
foreach (Constraint constraint in itsConstraints) {
hashcode = hashcode >> 1;
hashcode = hashcode ^ constraint.GetHashCode();
}
return hashcode;
}
public IList GetMentionedVariables() {
ArrayList variables = new ArrayList();
foreach (Pattern pattern in Patterns) {
if (pattern.GetSubject() is Variable) {
variables.Add( pattern.GetSubject() );
}
if (pattern.GetPredicate() is Variable) {
variables.Add( pattern.GetPredicate() );
}
if (pattern.GetObject() is Variable) {
variables.Add( pattern.GetObject() );
}
}
if ( null != itsOptionalPatterns ) {
variables.AddRange( itsOptionalPatterns.GetMentionedVariables() );
}
foreach (PatternGroup group in itsAlternateGroups) {
variables.AddRange( group.GetMentionedVariables() );
}
return variables;
}
public QueryGroup Resolve(TripleStore triples) {
QueryGroupAnd groupAnd = new QueryGroupAnd();
QueryGroupPatterns groupRequired = new QueryGroupPatterns();
foreach (Pattern pattern in itsPatterns) {
groupRequired.Add( pattern.Resolve( triples ) );
}
groupAnd.Add( groupRequired );
if ( null != itsOptionalPatterns) {
try {
QueryGroupPatterns groupOptional = new QueryGroupPatterns();
foreach (Pattern pattern in itsOptionalPatterns.Patterns) {
groupOptional.Add( pattern.Resolve( triples ) );
}
groupAnd.Add( new QueryGroupOptional( groupOptional ) );
}
catch (UnknownGraphMemberException) {
// NOOP
}
}
QueryGroupConstraints groupConstraints = new QueryGroupConstraints();
foreach (Constraint constraint in itsConstraints) {
groupConstraints.Add( constraint );
}
groupAnd.Add( groupConstraints );
QueryGroupOr alternateGroups = new QueryGroupOr();
alternateGroups.Add( groupAnd );
foreach (PatternGroup group in itsAlternateGroups) {
try {
QueryGroupPatterns groupAlternate = new QueryGroupPatterns();
foreach (Pattern pattern in group.Patterns) {
groupAlternate .Add( pattern.Resolve( triples ) );
}
alternateGroups.Add( groupAlternate );
}
catch (UnknownGraphMemberException) {
// NOOP
}
}
return alternateGroups;
}
public Pattern First() {
return (Pattern)itsPatterns[0];
}
public PatternGroup Rest() {
PatternGroup rest = new PatternGroup();
rest.itsPatterns.AddRange( itsPatterns.GetRange(1, itsPatterns.Count - 1) );
rest.OptionalGroup = itsOptionalPatterns;
rest.itsAlternateGroups.AddRange( itsAlternateGroups );
rest.itsConstraints.AddRange(itsConstraints);
return rest;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace FantasyAuctionWebRole.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
namespace Microsoft.Scripting.Actions {
/// <summary>
/// NamespaceTracker represent a CLS namespace.
/// </summary>
public class NamespaceTracker : MemberTracker, IMembersList, IEnumerable<KeyValuePair<string, object>> {
// _dict contains all the currently loaded entries. However, there may be pending types that have
// not yet been loaded in _typeNames
internal Dictionary<string, MemberTracker> _dict = new Dictionary<string, MemberTracker>();
internal readonly List<Assembly> _packageAssemblies = new List<Assembly>();
internal readonly Dictionary<Assembly, TypeNames> _typeNames = new Dictionary<Assembly, TypeNames>();
private readonly string _fullName; // null for the TopReflectedPackage
private TopNamespaceTracker _topPackage;
private int _id;
private static int _masterId;
#region Protected API Surface
protected NamespaceTracker(string name) {
UpdateId();
_fullName = name;
}
public override string ToString() {
return base.ToString() + ":" + _fullName;
}
#endregion
#region Internal API Surface
internal NamespaceTracker GetOrMakeChildPackage(string childName, Assembly assem) {
// lock is held when this is called
Assert.NotNull(childName, assem);
Debug.Assert(childName.IndexOf('.') == -1); // This is the simple name, not the full name
Debug.Assert(_packageAssemblies.Contains(assem)); // Parent namespace must contain all the assemblies of the child
if (_dict.TryGetValue(childName, out MemberTracker ret)) {
// If we have a module, then we add the assembly to the InnerModule
// If it's not a module, we'll wipe it out below, eg "def System(): pass" then
// "import System" will result in the namespace being visible.
if (ret is NamespaceTracker package) {
if (!package._packageAssemblies.Contains(assem)) {
package._packageAssemblies.Add(assem);
package.UpdateSubtreeIds();
}
return package;
}
}
return MakeChildPackage(childName, assem);
}
private NamespaceTracker MakeChildPackage(string childName, Assembly assem) {
// lock is held when this is called
Assert.NotNull(childName, assem);
NamespaceTracker rp = new NamespaceTracker(GetFullChildName(childName));
rp.SetTopPackage(_topPackage);
rp._packageAssemblies.Add(assem);
_dict[childName] = rp;
return rp;
}
private string GetFullChildName(string childName) {
Assert.NotNull(childName);
Debug.Assert(childName.IndexOf('.') == -1); // This is the simple name, not the full name
if (_fullName == null) {
return childName;
}
return _fullName + "." + childName;
}
private static Type LoadType(Assembly assem, string fullTypeName) {
Assert.NotNull(assem, fullTypeName);
Type type = assem.GetType(fullTypeName);
// We should ignore nested types. They will be loaded when the containing type is loaded
Debug.Assert(type == null || !type.IsNested());
return type;
}
internal void AddTypeName(string typeName, Assembly assem) {
// lock is held when this is called
Assert.NotNull(typeName, assem);
Debug.Assert(typeName.IndexOf('.') == -1); // This is the simple name, not the full name
if (!_typeNames.ContainsKey(assem)) {
_typeNames[assem] = new TypeNames(assem, _fullName);
}
_typeNames[assem].AddTypeName(typeName);
string normalizedTypeName = ReflectionUtils.GetNormalizedTypeName(typeName);
if (_dict.ContainsKey(normalizedTypeName)) {
// A similarly named type, namespace, or module already exists.
Type newType = LoadType(assem, GetFullChildName(typeName));
if (newType != null) {
object existingValue = _dict[normalizedTypeName];
TypeTracker existingTypeEntity = existingValue as TypeTracker;
if (existingTypeEntity == null) {
// Replace the existing namespace or module with the new type
Debug.Assert(existingValue is NamespaceTracker);
_dict[normalizedTypeName] = MemberTracker.FromMemberInfo(newType);
} else {
// Unify the new type with the existing type
_dict[normalizedTypeName] = TypeGroup.UpdateTypeEntity(existingTypeEntity, TypeTracker.GetTypeTracker(newType));
}
}
}
}
/// <summary>
/// Loads all the types from all assemblies that contribute to the current namespace (but not child namespaces)
/// </summary>
private void LoadAllTypes() {
foreach (TypeNames typeNameList in _typeNames.Values) {
foreach (string typeName in typeNameList.GetNormalizedTypeNames()) {
if (!TryGetValue(typeName, out object _)) {
Debug.Assert(false, "We should never get here as TryGetMember should raise a TypeLoadException");
throw new TypeLoadException(typeName);
}
}
}
}
#endregion
public override string Name => _fullName;
protected void DiscoverAllTypes(Assembly assem) {
// lock is held when this is called
Assert.NotNull(assem);
NamespaceTracker previousPackage = null;
string previousFullNamespace = string.Empty; // Note that String.Empty is not a valid namespace
foreach (TypeName typeName in AssemblyTypeNames.GetTypeNames(assem, _topPackage.DomainManager.Configuration.PrivateBinding)) {
NamespaceTracker package;
Debug.Assert(typeName.Namespace?.Length != 0);
if (typeName.Namespace == previousFullNamespace) {
// We have a cache hit. We dont need to call GetOrMakePackageHierarchy (which generates
// a fair amount of temporary substrings)
package = previousPackage;
} else {
package = GetOrMakePackageHierarchy(assem, typeName.Namespace);
previousFullNamespace = typeName.Namespace;
previousPackage = package;
}
package.AddTypeName(typeName.Name, assem);
}
}
/// <summary>
/// Populates the tree with nodes for each part of the namespace
/// </summary>
/// <param name="assem"></param>
/// <param name="fullNamespace">Full namespace name. It can be null (for top-level types)</param>
/// <returns></returns>
private NamespaceTracker GetOrMakePackageHierarchy(Assembly assem, string fullNamespace) {
// lock is held when this is called
Assert.NotNull(assem);
if (fullNamespace == null) {
// null is the top-level namespace
return this;
}
NamespaceTracker ret = this;
string[] pieces = fullNamespace.Split('.');
for (int i = 0; i < pieces.Length; i++) {
ret = ret.GetOrMakeChildPackage(pieces[i], assem);
}
return ret;
}
/// <summary>
/// As a fallback, so if the type does exist in any assembly. This would happen if a new type was added
/// that was not in the hardcoded list of types.
/// This code is not accurate because:
/// 1. We dont deal with generic types (TypeCollision).
/// 2. Previous calls to GetCustomMemberNames (eg. "from foo import *" in Python) would not have included this type.
/// 3. This does not deal with new namespaces added to the assembly
/// </summary>
private MemberTracker CheckForUnlistedType(string nameString) {
Assert.NotNull(nameString);
string fullTypeName = GetFullChildName(nameString);
foreach (Assembly assem in _packageAssemblies) {
Type type = assem.GetType(fullTypeName);
if (type == null || type.IsNested()) {
continue;
}
bool publishType = type.IsPublic || _topPackage.DomainManager.Configuration.PrivateBinding;
if (!publishType) {
continue;
}
// We dont use TypeCollision.UpdateTypeEntity here because we do not handle generic type names
return TypeTracker.GetTypeTracker(type);
}
return null;
}
#region IAttributesCollection Members
public bool TryGetValue(string name, out object value) {
bool res = TryGetValue(name, out MemberTracker tmp);
value = tmp;
return res;
}
public bool TryGetValue(string name, out MemberTracker value) {
lock (_topPackage.HierarchyLock) {
LoadNamespaces();
if (_dict.TryGetValue(name, out value)) {
return true;
}
MemberTracker existingTypeEntity = null;
if (name.IndexOf('.') != -1) {
value = null;
return false;
}
// Look up the type names and load the type if its name exists
foreach (KeyValuePair<Assembly, TypeNames> kvp in _typeNames) {
if (!kvp.Value.Contains(name)) {
continue;
}
existingTypeEntity = kvp.Value.UpdateTypeEntity((TypeTracker)existingTypeEntity, name);
}
if (existingTypeEntity == null) {
existingTypeEntity = CheckForUnlistedType(name);
}
if (existingTypeEntity != null) {
_dict[name] = existingTypeEntity;
value = existingTypeEntity;
return true;
}
return false;
}
}
public bool ContainsKey(string name) {
object dummy;
return TryGetValue(name, out dummy);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public object this[string name] {
get {
if (TryGetValue(name, out object res)) {
return res;
}
throw new KeyNotFoundException();
}
}
public int Count => _dict.Count;
public ICollection<string> Keys {
get {
LoadNamespaces();
lock (_topPackage.HierarchyLock) {
var res = new List<string>();
return (ICollection<string>)AddKeys(res);
}
}
}
private IList AddKeys(IList res) {
foreach (string s in _dict.Keys) {
res.Add(s);
}
foreach (KeyValuePair<Assembly, TypeNames> kvp in _typeNames) {
foreach (string typeName in kvp.Value.GetNormalizedTypeNames()) {
if (!res.Contains(typeName)) {
res.Add(typeName);
}
}
}
return res;
}
#endregion
#region IEnumerable<KeyValuePair<string, object>> Members
public IEnumerator<KeyValuePair<string, object>> GetEnumerator() {
foreach (var key in Keys) {
yield return new KeyValuePair<string, object>(key, this[key]);
}
}
#endregion
IEnumerator IEnumerable.GetEnumerator() {
foreach (var key in Keys) {
yield return new KeyValuePair<string, object>(key, this[key]);
}
}
public IList<Assembly> PackageAssemblies {
get {
LoadNamespaces();
return _packageAssemblies;
}
}
protected virtual void LoadNamespaces() {
_topPackage?.LoadNamespaces();
}
protected void SetTopPackage(TopNamespaceTracker pkg) {
Assert.NotNull(pkg);
_topPackage = pkg;
}
/// <summary>
/// This stores all the public non-nested type names in a single namespace and from a single assembly.
/// This allows inspection of the namespace without eagerly loading all the types. Eagerly loading
/// types slows down startup, increases working set, and is semantically incorrect as it can trigger
/// TypeLoadExceptions sooner than required.
/// </summary>
internal class TypeNames {
List<string> _simpleTypeNames = new List<string>();
Dictionary<string, List<string>> _genericTypeNames = new Dictionary<string, List<string>>();
private readonly Assembly _assembly;
private readonly string _fullNamespace;
internal TypeNames(Assembly assembly, string fullNamespace) {
_assembly = assembly;
_fullNamespace = fullNamespace;
}
internal bool Contains(string normalizedTypeName) {
Debug.Assert(normalizedTypeName.IndexOf('.') == -1); // This is the simple name, not the full name
Debug.Assert(ReflectionUtils.GetNormalizedTypeName(normalizedTypeName) == normalizedTypeName);
return _simpleTypeNames.Contains(normalizedTypeName) || _genericTypeNames.ContainsKey(normalizedTypeName);
}
internal MemberTracker UpdateTypeEntity(TypeTracker existingTypeEntity, string normalizedTypeName) {
Debug.Assert(normalizedTypeName.IndexOf('.') == -1); // This is the simple name, not the full name
Debug.Assert(ReflectionUtils.GetNormalizedTypeName(normalizedTypeName) == normalizedTypeName);
// Look for a non-generic type
if (_simpleTypeNames.Contains(normalizedTypeName)) {
Type newType = LoadType(_assembly, GetFullChildName(normalizedTypeName));
if (newType != null) {
existingTypeEntity = TypeGroup.UpdateTypeEntity(existingTypeEntity, TypeTracker.GetTypeTracker(newType));
}
}
// Look for generic types
if (_genericTypeNames.ContainsKey(normalizedTypeName)) {
List<string> actualNames = _genericTypeNames[normalizedTypeName];
foreach (string actualName in actualNames) {
Type newType = LoadType(_assembly, GetFullChildName(actualName));
if (newType != null) {
existingTypeEntity = TypeGroup.UpdateTypeEntity(existingTypeEntity, TypeTracker.GetTypeTracker(newType));
}
}
}
return existingTypeEntity;
}
internal void AddTypeName(string typeName) {
Debug.Assert(typeName.IndexOf('.') == -1); // This is the simple name, not the full name
string normalizedName = ReflectionUtils.GetNormalizedTypeName(typeName);
if (normalizedName == typeName) {
_simpleTypeNames.Add(typeName);
} else {
List<string> actualNames;
if (_genericTypeNames.ContainsKey(normalizedName)) {
actualNames = _genericTypeNames[normalizedName];
} else {
actualNames = new List<string>();
_genericTypeNames[normalizedName] = actualNames;
}
actualNames.Add(typeName);
}
}
string GetFullChildName(string childName) {
Debug.Assert(childName.IndexOf('.') == -1); // This is the simple name, not the full name
if (_fullNamespace == null) {
return childName;
}
return _fullNamespace + "." + childName;
}
internal ICollection<string> GetNormalizedTypeNames() {
List<string> normalizedTypeNames = new List<string>();
normalizedTypeNames.AddRange(_simpleTypeNames);
normalizedTypeNames.AddRange(_genericTypeNames.Keys);
return normalizedTypeNames;
}
}
public int Id => _id;
#region IMembersList Members
public IList<string> GetMemberNames() {
LoadNamespaces();
lock (_topPackage.HierarchyLock) {
List<string> res = new List<string>();
AddKeys(res);
res.Sort();
return res;
}
}
#endregion
public override TrackerTypes MemberType => TrackerTypes.Namespace;
public override Type DeclaringType => null;
private void UpdateId() {
_id = Interlocked.Increment(ref _masterId);
}
protected void UpdateSubtreeIds() {
// lock is held when this is called
UpdateId();
foreach (KeyValuePair<string, MemberTracker> kvp in _dict) {
NamespaceTracker ns = kvp.Value as NamespaceTracker;
ns?.UpdateSubtreeIds();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Concurrency;
using Orleans.Runtime;
using Orleans.Serialization.Invocation;
using Orleans.Streams;
using UnitTests.GrainInterfaces;
namespace UnitTests.Grains
{
[Reentrant]
public class ReentrantGrain : Grain, IReentrantGrain
{
private IReentrantGrain Self { get; set; }
public Task<string> One()
{
return Task.FromResult("one");
}
public async Task<string> Two()
{
return await Self.One() + " two";
}
public Task SetSelf(IReentrantGrain self)
{
Self = self;
return Task.CompletedTask;
}
}
public class NonRentrantGrain : Grain, INonReentrantGrain
{
private INonReentrantGrain Self { get; set; }
private ILogger logger;
public NonRentrantGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
logger.Info("OnActivateAsync");
return base.OnActivateAsync(cancellationToken);
}
public Task<string> One()
{
logger.Info("Entering One");
string result = "one";
logger.Info("Exiting One");
return Task.FromResult(result);
}
public async Task<string> Two()
{
logger.Info("Entering Two");
string result = await Self.One();
result = result + " two";
logger.Info("Exiting Two");
return result;
}
public Task SetSelf(INonReentrantGrain self)
{
logger.Info("SetSelf {0}", self);
Self = self;
return Task.CompletedTask;
}
}
[MayInterleave(nameof(MayInterleave))]
public class MayInterleavePredicateGrain : Grain, IMayInterleavePredicateGrain
{
private readonly ILogger logger;
public MayInterleavePredicateGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public static bool MayInterleave(IInvokable req)
{
// not interested
if (req.ArgumentCount == 0)
return false;
string arg = null;
// assume single argument message
if (req.ArgumentCount == 1)
arg = (string)UnwrapImmutable(req.GetArgument<object>(0));
// assume stream message
if (req.ArgumentCount == 2)
arg = (string)UnwrapImmutable(req.GetArgument<object>(1));
if (arg == "err")
throw new ApplicationException("boom");
return arg == "reentrant";
}
static object UnwrapImmutable(object item) => item is Immutable<object> ? ((Immutable<object>)item).Value : item;
private IMayInterleavePredicateGrain Self { get; set; }
// this interleaves only when arg == "reentrant"
// and test predicate will throw when arg = "err"
public Task<string> One(string arg)
{
return Task.FromResult("one");
}
public async Task<string> Two()
{
return await Self.One("") + " two";
}
public async Task<string> TwoReentrant()
{
return await Self.One("reentrant") + " two";
}
public Task Exceptional()
{
return Self.One("err");
}
public async Task SubscribeToStream()
{
var stream = GetStream();
await stream.SubscribeAsync((item, _) =>
{
logger.Info("Received stream item:" + item);
return Task.CompletedTask;
});
}
public Task PushToStream(string item)
{
return GetStream().OnNextAsync(item);
}
IAsyncStream<string> GetStream() =>
this.GetStreamProvider("sms").GetStream<string>(Guid.Empty, "test-stream-interleave");
public Task SetSelf(IMayInterleavePredicateGrain self)
{
Self = self;
return Task.CompletedTask;
}
}
public class UnorderedNonRentrantGrain : Grain, IUnorderedNonReentrantGrain
{
private IUnorderedNonReentrantGrain Self { get; set; }
public Task<string> One()
{
return Task.FromResult("one");
}
public async Task<string> Two()
{
return await Self.One() + " two";
}
public Task SetSelf(IUnorderedNonReentrantGrain self)
{
Self = self;
return Task.CompletedTask;
}
}
[Reentrant]
public class ReentrantSelfManagedGrain1 : Grain, IReentrantSelfManagedGrain
{
private long destination;
private ILogger logger;
public ReentrantSelfManagedGrain1(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task<int> GetCounter()
{
return Task.FromResult(1);
}
public Task SetDestination(long id)
{
destination = id;
return Task.CompletedTask;
}
public Task Ping(int seconds)
{
logger.Info("Start Ping({0})", seconds);
var start = DateTime.UtcNow;
var end = start + TimeSpan.FromSeconds(seconds);
int foo = 0;
while (DateTime.UtcNow < end)
{
foo++;
if (foo > 100000)
foo = 0;
}
logger.Info("Before GetCounter - OtherId={0}", destination);
IReentrantSelfManagedGrain otherGrain = GrainFactory.GetGrain<IReentrantSelfManagedGrain>(destination);
var ctr = otherGrain.GetCounter();
logger.Info("After GetCounter() - returning promise");
return ctr;
}
}
public class NonReentrantSelfManagedGrain1 : Grain, INonReentrantSelfManagedGrain
{
private long destination;
private ILogger logger;
public NonReentrantSelfManagedGrain1(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task<int> GetCounter()
{
return Task.FromResult(1);
}
public Task SetDestination(long id)
{
destination = id;
return Task.CompletedTask;
}
public Task Ping(int seconds)
{
logger.Info("Start Ping({0})", seconds);
var start = DateTime.UtcNow;
var end = start + TimeSpan.FromSeconds(seconds);
int foo = 0;
while (DateTime.UtcNow < end)
{
foo++;
if (foo > 100000)
foo = 0;
}
logger.Info("Before GetCounter - OtherId={0}", destination);
INonReentrantSelfManagedGrain otherGrain = GrainFactory.GetGrain<INonReentrantSelfManagedGrain>(destination);
var ctr = otherGrain.GetCounter();
logger.Info("After GetCounter() - returning promise");
return ctr;
}
}
[Reentrant]
public class FanOutGrain : Grain, IFanOutGrain
{
private ILogger logger;
private static readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1);
public FanOutGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public async Task FanOutReentrant(int offset, int num)
{
IReentrantTaskGrain[] fanOutGrains = await InitTaskGrains_Reentrant(offset, num);
logger.Info("Starting fan-out calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
//Task promise = fanOutGrains[i].Ping(OneSecond);
Task promise = fanOutGrains[i].GetCounter();
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains with offset={2}", num, "reentrant", offset);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
public async Task FanOutNonReentrant(int offset, int num)
{
INonReentrantTaskGrain[] fanOutGrains = await InitTaskGrains_NonReentrant(offset, num);
logger.Info("Starting fan-out calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
//Task promise = fanOutGrains[i].Ping(OneSecond);
Task promise = fanOutGrains[i].GetCounter();
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains", num);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
public async Task FanOutReentrant_Chain(int offset, int num)
{
IReentrantTaskGrain[] fanOutGrains = await InitTaskGrains_Reentrant(offset, num);
logger.Info("Starting fan-out chain calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
Task promise = fanOutGrains[i].Ping(OneSecond);
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains with offset={2}", num, "reentrant", offset);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
public async Task FanOutNonReentrant_Chain(int offset, int num)
{
INonReentrantTaskGrain[] fanOutGrains = await InitTaskGrains_NonReentrant(offset, num);
logger.Info("Starting fan-out chain calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
Task promise = fanOutGrains[i].Ping(OneSecond);
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains", num);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
private async Task<IReentrantTaskGrain[]> InitTaskGrains_Reentrant(int offset, int num)
{
IReentrantTaskGrain[] fanOutGrains = new IReentrantTaskGrain[num];
logger.Info("Creating {0} fan-out {1} worker grains", num, "reentrant");
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
int idx = offset + i;
IReentrantTaskGrain grain = GrainFactory.GetGrain<IReentrantTaskGrain>(idx);
fanOutGrains[i] = grain;
int next = offset + ((i + 1) % num);
Task promise = grain.SetDestination(next);
promises.Add(promise);
}
await Task.WhenAll(promises);
return fanOutGrains;
}
private async Task<INonReentrantTaskGrain[]> InitTaskGrains_NonReentrant(int offset, int num)
{
INonReentrantTaskGrain[] fanOutGrains = new INonReentrantTaskGrain[num];
logger.Info("Creating {0} fan-out {1} worker grains", num, "non-reentrant");
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
int idx = offset + i;
INonReentrantTaskGrain grain = GrainFactory.GetGrain<INonReentrantTaskGrain>(idx);
fanOutGrains[i] = grain;
int next = offset + ((i + 1) % num);
Task promise = grain.SetDestination(next);
promises.Add(promise);
}
await Task.WhenAll(promises);
return fanOutGrains;
}
}
[Reentrant]
public class FanOutACGrain : Grain, IFanOutACGrain
{
private ILogger logger;
private static readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1);
public FanOutACGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public async Task FanOutACReentrant(int offset, int num)
{
IReentrantSelfManagedGrain[] fanOutGrains = await InitACGrains_Reentrant(offset, num);
logger.Info("Starting fan-out calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
Task promise = fanOutGrains[i].GetCounter();
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains", num);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
public async Task FanOutACNonReentrant(int offset, int num)
{
INonReentrantSelfManagedGrain[] fanOutGrains = await InitACGrains_NonReentrant(offset, num);
logger.Info("Starting fan-out calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
Task promise = fanOutGrains[i].GetCounter();
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains", num);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
public async Task FanOutACReentrant_Chain(int offset, int num)
{
IReentrantSelfManagedGrain[] fanOutGrains = await InitACGrains_Reentrant(offset, num);
logger.Info("Starting fan-out calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
Task promise = fanOutGrains[i].Ping(OneSecond.Seconds);
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains", num);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
public async Task FanOutACNonReentrant_Chain(int offset, int num)
{
INonReentrantSelfManagedGrain[] fanOutGrains = await InitACGrains_NonReentrant(offset, num);
logger.Info("Starting fan-out calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
Task promise = fanOutGrains[i].Ping(OneSecond.Seconds);
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains", num);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
private async Task<IReentrantSelfManagedGrain[]> InitACGrains_Reentrant(int offset, int num)
{
var fanOutGrains = new IReentrantSelfManagedGrain[num];
List<Task> promises = new List<Task>();
logger.Info("Creating {0} fan-out {1} worker grains with offset={2}", num, "reentrant", offset);
for (int i = 0; i < num; i++)
{
int idx = offset + i;
var grain = GrainFactory.GetGrain<IReentrantSelfManagedGrain>(idx);
fanOutGrains[i] = grain;
int next = offset + ((i + 1) % num);
Task promise = grain.SetDestination(next);
promises.Add(promise);
}
await Task.WhenAll(promises);
return fanOutGrains;
}
private async Task<INonReentrantSelfManagedGrain[]> InitACGrains_NonReentrant(int offset, int num)
{
var fanOutGrains = new INonReentrantSelfManagedGrain[num];
List<Task> promises = new List<Task>();
logger.Info("Creating {0} fan-out {1} worker grains with offset={2}", num, "non-reentrant", offset);
for (int i = 0; i < num; i++)
{
int idx = offset + i;
var grain = GrainFactory.GetGrain<INonReentrantSelfManagedGrain>(idx);
fanOutGrains[i] = grain;
int next = offset + ((i + 1) % num);
Task promise = grain.SetDestination(next);
promises.Add(promise);
}
await Task.WhenAll(promises);
return fanOutGrains;
}
}
[Reentrant]
public class ReentrantTaskGrain : Grain, IReentrantTaskGrain
{
private ILogger logger;
private long otherId;
private int count;
public ReentrantTaskGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task SetDestination(long id)
{
otherId = id;
return Task.CompletedTask;
}
public async Task Ping(TimeSpan wait)
{
logger.Info("Ping Delay={0}", wait);
await Task.Delay(wait);
logger.Info("Before GetCounter - OtherId={0}", otherId);
var otherGrain = GrainFactory.GetGrain<IReentrantTaskGrain>(otherId);
var ctr = await otherGrain.GetCounter();
logger.Info("After GetCounter() - got value={0}", ctr);
}
public Task<int> GetCounter()
{
return Task.FromResult(++count);
}
}
public class NonReentrantTaskGrain : Grain, INonReentrantTaskGrain
{
private ILogger logger;
private long otherId;
private int count;
public NonReentrantTaskGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task SetDestination(long id)
{
otherId = id;
return Task.CompletedTask;
}
public async Task Ping(TimeSpan wait)
{
logger.Info("Ping Delay={0}", wait);
await Task.Delay(wait);
logger.Info("Before GetCounter - OtherId={0}", otherId);
var otherGrain = GrainFactory.GetGrain<INonReentrantTaskGrain>(otherId);
var ctr = await otherGrain.GetCounter();
logger.Info("After GetCounter() - got value={0}", ctr);
}
public Task<int> GetCounter()
{
return Task.FromResult(++count);
}
}
}
| |
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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 Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
namespace Alphaleonis.Win32.Filesystem
{
internal static partial class NativeMethods
{
#region CM_Xxx
/// <summary>The CM_Connect_Machine function creates a connection to a remote machine.</summary>
/// <remarks>
/// <para>Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed.</para>
/// <para>You cannot access remote machines when running on these versions of Windows.</para>
/// <para>Available in Microsoft Windows 2000 and later versions of Windows.</para>
/// </remarks>
/// <param name="uncServerName">Name of the unc server.</param>
/// <param name="phMachine">[out] The ph machine.</param>
/// <returns>
/// <para>If the operation succeeds, the function returns CR_SUCCESS.</para>
/// <para>Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h.</para>
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CM_Connect_MachineW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I4)]
public static extern int CM_Connect_Machine([MarshalAs(UnmanagedType.LPWStr)] string uncServerName, out SafeCmConnectMachineHandle phMachine);
/// <summary>
/// The CM_Get_Device_ID_Ex function retrieves the device instance ID for a specified device instance on a local or a remote machine.
/// </summary>
/// <remarks>
/// <para>Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed.</para>
/// <para>You cannot access remote machines when running on these versions of Windows.</para>
/// <para> </para>
/// <para>Available in Microsoft Windows 2000 and later versions of Windows.</para>
/// </remarks>
/// <param name="dnDevInst">The dn development instance.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="bufferLen">Length of the buffer.</param>
/// <param name="ulFlags">The ul flags.</param>
/// <param name="hMachine">The machine.</param>
/// <returns>
/// <para>If the operation succeeds, the function returns CR_SUCCESS.</para>
/// <para>Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h.</para>
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CM_Get_Device_ID_ExW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I4)]
public static extern int CM_Get_Device_ID_Ex([MarshalAs(UnmanagedType.U4)] uint dnDevInst, SafeGlobalMemoryBufferHandle buffer, [MarshalAs(UnmanagedType.U4)] uint bufferLen, [MarshalAs(UnmanagedType.U4)] uint ulFlags, SafeCmConnectMachineHandle hMachine);
/// <summary>
/// The CM_Disconnect_Machine function removes a connection to a remote machine.
/// </summary>
/// <remarks>
/// <para>Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed.</para>
/// <para>You cannot access remote machines when running on these versions of Windows.</para>
/// <para>SetLastError is set to <c>false</c>.</para>
/// <para>Available in Microsoft Windows 2000 and later versions of Windows.</para>
/// </remarks>
/// <param name="hMachine">The machine.</param>
/// <returns>
/// <para>If the operation succeeds, the function returns CR_SUCCESS.</para>
/// <para>Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h.</para>
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("setupapi.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I4)]
internal static extern int CM_Disconnect_Machine(IntPtr hMachine);
/// <summary>
/// The CM_Get_Parent_Ex function obtains a device instance handle to the parent node of a specified device node (devnode) in a local
/// or a remote machine's device tree.
/// </summary>
/// <remarks>
/// <para>Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed.</para>
/// <para>You cannot access remote machines when running on these versions of Windows.</para>
/// <para>Available in Microsoft Windows 2000 and later versions of Windows.</para>
/// </remarks>
/// <param name="pdnDevInst">[out] The pdn development instance.</param>
/// <param name="dnDevInst">The dn development instance.</param>
/// <param name="ulFlags">The ul flags.</param>
/// <param name="hMachine">The machine.</param>
/// <returns>
/// <para>If the operation succeeds, the function returns CR_SUCCESS.</para>
/// <para>Otherwise, it returns one of the CR_-prefixed error codes defined in Cfgmgr32.h.</para>
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I4)]
internal static extern int CM_Get_Parent_Ex([MarshalAs(UnmanagedType.U4)] out uint pdnDevInst, [MarshalAs(UnmanagedType.U4)] uint dnDevInst, [MarshalAs(UnmanagedType.U4)] uint ulFlags, SafeCmConnectMachineHandle hMachine);
#endregion // CM_Xxx
#region DeviceIoControl
/// <summary>Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.</summary>
/// <returns>
/// <para>If the operation completes successfully, the return value is nonzero.</para>
/// <para>If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError.</para>
/// </returns>
/// <remarks>
/// <para>To retrieve a handle to the device, you must call the <see cref="CreateFile"/> function with either the name of a device or
/// the name of the driver associated with a device.</para>
/// <para>To specify a device name, use the following format: <c>\\.\DeviceName</c></para>
/// <para>Minimum supported client: Windows XP</para>
/// <para>Minimum supported server: Windows Server 2003</para>
/// </remarks>
/// <param name="hDevice">The device.</param>
/// <param name="dwIoControlCode">The i/o control code.</param>
/// <param name="lpInBuffer">Buffer for in data.</param>
/// <param name="nInBufferSize">Size of the in buffer.</param>
/// <param name="lpOutBuffer">Buffer for out data.</param>
/// <param name="nOutBufferSize">Size of the out buffer.</param>
/// <param name="lpBytesReturned">[out] The bytes returned.</param>
/// <param name="lpOverlapped">The overlapped.</param>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeviceIoControl(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] uint dwIoControlCode, IntPtr lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, SafeGlobalMemoryBufferHandle lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped);
/// <summary>Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.</summary>
/// <returns>
/// <para>If the operation completes successfully, the return value is nonzero.</para>
/// <para>If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError.</para>
/// </returns>
/// <remarks>
/// <para>To retrieve a handle to the device, you must call the <see cref="CreateFile"/> function with either the name of a device or
/// the name of the driver associated with a device.</para>
/// <para>To specify a device name, use the following format: <c>\\.\DeviceName</c></para>
/// <para>Minimum supported client: Windows XP</para>
/// <para>Minimum supported server: Windows Server 2003</para>
/// </remarks>
/// <param name="hDevice">The device.</param>
/// <param name="dwIoControlCode">The i/o control code.</param>
/// <param name="lpInBuffer">Buffer for in data.</param>
/// <param name="nInBufferSize">Size of the in buffer.</param>
/// <param name="lpOutBuffer">Buffer for out data.</param>
/// <param name="nOutBufferSize">Size of the out buffer.</param>
/// <param name="lpBytesReturned">[out] The bytes returned.</param>
/// <param name="lpOverlapped">The overlapped.</param>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeviceIoControl2(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] uint dwIoControlCode, SafeGlobalMemoryBufferHandle lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, IntPtr lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped);
/// <summary>Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.</summary>
/// <returns>
/// <para>If the operation completes successfully, the return value is nonzero.</para>
/// <para>If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError.</para>
/// </returns>
/// <remarks>
/// <para>To retrieve a handle to the device, you must call the <see cref="CreateFile"/> function with either the name of a device or
/// the name of the driver associated with a device.</para>
/// <para>To specify a device name, use the following format: <c>\\.\DeviceName</c></para>
/// <para>Minimum supported client: Windows XP</para>
/// <para>Minimum supported server: Windows Server 2003</para>
/// </remarks>
/// <param name="hDevice">The device.</param>
/// <param name="dwIoControlCode">The i/o control code.</param>
/// <param name="lpInBuffer">Buffer for in data.</param>
/// <param name="nInBufferSize">Size of the in buffer.</param>
/// <param name="lpOutBuffer">Buffer for out data.</param>
/// <param name="nOutBufferSize">Size of the out buffer.</param>
/// <param name="lpBytesReturned">[out] The bytes returned.</param>
/// <param name="lpOverlapped">The overlapped.</param>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeviceIoControl"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeviceIoControlUnknownSize(SafeFileHandle hDevice, [MarshalAs(UnmanagedType.U4)] uint dwIoControlCode, [MarshalAs(UnmanagedType.AsAny)] object lpInBuffer, [MarshalAs(UnmanagedType.U4)] uint nInBufferSize, [MarshalAs(UnmanagedType.AsAny)] [Out] object lpOutBuffer, [MarshalAs(UnmanagedType.U4)] uint nOutBufferSize, [MarshalAs(UnmanagedType.U4)] out uint lpBytesReturned, IntPtr lpOverlapped);
#endregion // DeviceIoControl
#region SetupDiXxx
/// <summary>
/// The SetupDiDestroyDeviceInfoList function deletes a device information set and frees all associated memory.
/// </summary>
/// <remarks>
/// <para>SetLastError is set to <c>false</c>.</para>
/// <para>Available in Microsoft Windows 2000 and later versions of Windows.</para>
/// </remarks>
/// <param name="hDevInfo">Information describing the development.</param>
/// <returns>
/// <para>The function returns TRUE if it is successful.</para>
/// <para>Otherwise, it returns FALSE and the logged error can be retrieved with a call to GetLastError.</para>
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("setupapi.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetupDiDestroyDeviceInfoList(IntPtr hDevInfo);
/// <summary>
/// The SetupDiEnumDeviceInterfaces function enumerates the device interfaces that are contained in a device information set.
/// </summary>
/// <remarks>
/// <para>Repeated calls to this function return an <see cref="SP_DEVICE_INTERFACE_DATA"/> structure for a different device
/// interface.</para>
/// <para>This function can be called repeatedly to get information about interfaces in a device information set that are
/// associated</para>
/// <para>with a particular device information element or that are associated with all device information elements.</para>
/// <para>Available in Microsoft Windows 2000 and later versions of Windows.</para>
/// </remarks>
/// <param name="hDevInfo">Information describing the development.</param>
/// <param name="devInfo">Information describing the development.</param>
/// <param name="interfaceClassGuid">[in,out] Unique identifier for the interface class.</param>
/// <param name="memberIndex">Zero-based index of the member.</param>
/// <param name="deviceInterfaceData">[in,out] Information describing the device interface.</param>
/// <returns>
/// <para>SetupDiEnumDeviceInterfaces returns TRUE if the function completed without error.</para>
/// <para>If the function completed with an error, FALSE is returned and the error code for the failure can be retrieved by calling
/// GetLastError.</para>
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetupDiEnumDeviceInterfaces(SafeHandle hDevInfo, IntPtr devInfo, ref Guid interfaceClassGuid, [MarshalAs(UnmanagedType.U4)] uint memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
/// <summary>
/// The SetupDiGetClassDevsEx function returns a handle to a device information set that contains requested device information elements
/// for a local or a remote computer.
/// </summary>
/// <remarks>
/// <para>The caller of SetupDiGetClassDevsEx must delete the returned device information set when it is no longer needed by calling
/// <see cref="SetupDiDestroyDeviceInfoList"/>.</para>
/// <para>Available in Microsoft Windows 2000 and later versions of Windows.</para>
/// </remarks>
/// <param name="classGuid">[in,out] Unique identifier for the class.</param>
/// <param name="enumerator">The enumerator.</param>
/// <param name="hwndParent">The parent.</param>
/// <param name="devsExFlags">The devs ex flags.</param>
/// <param name="deviceInfoSet">Set the device information belongs to.</param>
/// <param name="machineName">Name of the machine.</param>
/// <param name="reserved">The reserved.</param>
/// <returns>
/// <para>If the operation succeeds, SetupDiGetClassDevsEx returns a handle to a device information set that contains all installed
/// devices that matched the supplied parameters.</para>
/// <para>If the operation fails, the function returns INVALID_HANDLE_VALUE. To get extended error information, call
/// GetLastError.</para>
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern SafeSetupDiClassDevsExHandle SetupDiGetClassDevsEx(ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, [MarshalAs(UnmanagedType.U4)] SetupDiGetClassDevsExFlags devsExFlags, IntPtr deviceInfoSet, [MarshalAs(UnmanagedType.LPWStr)] string machineName, IntPtr reserved);
/// <summary>
/// The SetupDiGetDeviceInterfaceDetail function returns details about a device interface.
/// </summary>
/// <remarks>
/// <para>The interface detail returned by this function consists of a device path that can be passed to Win32 functions such as
/// CreateFile.</para>
/// <para>Do not attempt to parse the device path symbolic name. The device path can be reused across system starts.</para>
/// <para>Available in Microsoft Windows 2000 and later versions of Windows.</para>
/// </remarks>
/// <param name="hDevInfo">Information describing the development.</param>
/// <param name="deviceInterfaceData">[in,out] Information describing the device interface.</param>
/// <param name="deviceInterfaceDetailData">[in,out] Information describing the device interface detail.</param>
/// <param name="deviceInterfaceDetailDataSize">Size of the device interface detail data.</param>
/// <param name="requiredSize">Size of the required.</param>
/// <param name="deviceInfoData">[in,out] Information describing the device information.</param>
/// <returns>
/// <para>SetupDiGetDeviceInterfaceDetail returns TRUE if the function completed without error.</para>
/// <para>If the function completed with an error, FALSE is returned and the error code for the failure can be retrieved by calling
/// GetLastError.</para>
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetupDiGetDeviceInterfaceDetail(SafeHandle hDevInfo, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData, [MarshalAs(UnmanagedType.U4)] uint deviceInterfaceDetailDataSize, IntPtr requiredSize, ref SP_DEVINFO_DATA deviceInfoData);
/// <summary>
/// The SetupDiGetDeviceRegistryProperty function retrieves a specified Plug and Play device property.
/// </summary>
/// <remarks><para>Available in Microsoft Windows 2000 and later versions of Windows.</para></remarks>
/// <param name="deviceInfoSet">Set the device information belongs to.</param>
/// <param name="deviceInfoData">[in,out] Information describing the device information.</param>
/// <param name="property">The property.</param>
/// <param name="propertyRegDataType">[out] Type of the property register data.</param>
/// <param name="propertyBuffer">Buffer for property data.</param>
/// <param name="propertyBufferSize">Size of the property buffer.</param>
/// <param name="requiredSize">Size of the required.</param>
/// <returns>
/// <para>SetupDiGetDeviceRegistryProperty returns TRUE if the call was successful.</para>
/// <para>Otherwise, it returns FALSE and the logged error can be retrieved by making a call to GetLastError.</para>
/// <para>SetupDiGetDeviceRegistryProperty returns the ERROR_INVALID_DATA error code if the requested property does not exist for a
/// device or if the property data is not valid.</para>
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetupDiGetDeviceRegistryProperty(SafeHandle deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, SetupDiGetDeviceRegistryPropertyEnum property, IntPtr propertyRegDataType, SafeGlobalMemoryBufferHandle propertyBuffer, [MarshalAs(UnmanagedType.U4)] uint propertyBufferSize, IntPtr requiredSize);
#endregion // SetupDiXxx
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Net.Http;
using Sandboxable.Hyak.Common;
using Sandboxable.Microsoft.Azure.KeyVault.Internal;
namespace Sandboxable.Microsoft.Azure.KeyVault.Internal
{
internal partial class KeyVaultInternalClient : ServiceClient<KeyVaultInternalClient>, IKeyVaultInternalClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private KeyVaultCredential _credentials;
/// <summary>
/// Gets or sets the credential
/// </summary>
public KeyVaultCredential Credentials
{
get { return this._credentials; }
set { this._credentials = value; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IKeyOperations _keys;
/// <summary>
/// Cryptographic and management operations for keys in a vault
/// </summary>
public virtual IKeyOperations Keys
{
get { return this._keys; }
}
private ISecretOperations _secrets;
/// <summary>
/// Operations for secrets in a vault
/// </summary>
public virtual ISecretOperations Secrets
{
get { return this._secrets; }
}
/// <summary>
/// Initializes a new instance of the KeyVaultInternalClient class.
/// </summary>
public KeyVaultInternalClient()
: base()
{
this._keys = new KeyOperations(this);
this._secrets = new SecretOperations(this);
this._apiVersion = "2015-06-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the KeyVaultInternalClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets or sets the credential
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public KeyVaultInternalClient(KeyVaultCredential credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the KeyVaultInternalClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets or sets the credential
/// </param>
public KeyVaultInternalClient(KeyVaultCredential credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = null;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the KeyVaultInternalClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public KeyVaultInternalClient(HttpClient httpClient)
: base(httpClient)
{
this._keys = new KeyOperations(this);
this._secrets = new SecretOperations(this);
this._apiVersion = "2015-06-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the KeyVaultInternalClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets or sets the credential
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public KeyVaultInternalClient(KeyVaultCredential credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the KeyVaultInternalClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets or sets the credential
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public KeyVaultInternalClient(KeyVaultCredential credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = null;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// KeyVaultInternalClient instance
/// </summary>
/// <param name='client'>
/// Instance of KeyVaultInternalClient to clone to
/// </param>
protected override void Clone(ServiceClient<KeyVaultInternalClient> client)
{
base.Clone(client);
if (client is KeyVaultInternalClient)
{
KeyVaultInternalClient clonedClient = ((KeyVaultInternalClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Sqloogle.Libs.Rhino.Etl.Core
{
/// <summary>
/// Represent a virtual row
/// </summary>
[DebuggerDisplay("Count = {items.Count}")]
[DebuggerTypeProxy(typeof(QuackingDictionaryDebugView))]
[Serializable]
public class Row : QuackingDictionary, IEquatable<Row>
{
static readonly Dictionary<Type, List<PropertyInfo>> propertiesCache = new Dictionary<Type, List<PropertyInfo>>();
static readonly Dictionary<Type, List<FieldInfo>> fieldsCache = new Dictionary<Type, List<FieldInfo>>();
/// <summary>
/// Initializes a new instance of the <see cref="Row"/> class.
/// </summary>
public Row()
: base(new Hashtable(StringComparer.InvariantCultureIgnoreCase))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Row"/> class.
/// </summary>
/// <param name="itemsToClone">The items to clone.</param>
protected Row(IDictionary itemsToClone)
: base(new Hashtable(itemsToClone, StringComparer.InvariantCultureIgnoreCase))
{
}
/// <summary>
/// Creates a copy of the given source, erasing whatever is in the row currently.
/// </summary>
/// <param name="source">The source row.</param>
public void Copy(IDictionary source)
{
items = new Hashtable(source, StringComparer.InvariantCultureIgnoreCase);
}
/// <summary>
/// Gets the columns in this row.
/// </summary>
/// <value>The columns.</value>
public IEnumerable<string> Columns
{
get
{
//We likely would want to change the row when iterating on the columns, so we
//want to make sure that we send a copy, to avoid enumeration modified exception
foreach (string column in new ArrayList(items.Keys))
{
yield return column;
}
}
}
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns></returns>
public Row Clone()
{
Row row = new Row(this);
return row;
}
/// <summary>
/// Indicates whether the current <see cref="Row" /> is equal to another <see cref="Row" />.
/// </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(Row other)
{
if(Columns.SequenceEqual(other.Columns, StringComparer.InvariantCultureIgnoreCase) == false)
return false;
foreach (var key in items.Keys)
{
var item = items[key];
var otherItem = other.items[key];
if (item == null | otherItem == null)
return item == null & otherItem == null;
var equalityComparer = CreateComparer(item.GetType(), otherItem.GetType());
if(equalityComparer(item, otherItem) == false)
return false;
}
return true;
}
private static Func<object, object, bool> CreateComparer(Type firstType, Type secondType)
{
if (firstType == secondType)
return Equals;
var firstParameter = Expression.Parameter(typeof (object), "first");
var secondParameter = Expression.Parameter(typeof (object), "second");
var equalExpression = Expression.Equal(Expression.Convert(firstParameter, firstType),
Expression.Convert(Expression.Convert(secondParameter, secondType), firstType));
return Expression.Lambda<Func<object, object, bool>>(equalExpression, firstParameter, secondParameter).Compile();
}
/// <summary>
/// Creates a key from the current row, suitable for use in hashtables
/// </summary>
public ObjectArrayKeys CreateKey()
{
return CreateKey(Columns.ToArray());
}
/// <summary>
/// Creates a key that allow to do full or partial indexing on a row
/// </summary>
/// <param name="columns">The columns.</param>
/// <returns></returns>
public ObjectArrayKeys CreateKey(params string[] columns)
{
object[] array = new object[columns.Length];
for (int i = 0; i < columns.Length; i++)
{
array[i] = items[columns[i]];
}
return new ObjectArrayKeys(array);
}
/// <summary>
/// Copy all the public properties and fields of an object to the row
/// </summary>
/// <param name="obj">The obj.</param>
/// <returns></returns>
public static Row FromObject(object obj)
{
if (obj == null)
throw new ArgumentNullException("obj");
Row row = new Row();
foreach (PropertyInfo property in GetProperties(obj))
{
row[property.Name] = property.GetValue(obj, new object[0]);
}
foreach (FieldInfo field in GetFields(obj))
{
row[field.Name] = field.GetValue(obj);
}
return row;
}
private static List<PropertyInfo> GetProperties(object obj)
{
List<PropertyInfo> properties;
if (propertiesCache.TryGetValue(obj.GetType(), out properties))
return properties;
properties = new List<PropertyInfo>();
foreach (PropertyInfo property in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
{
if (property.CanRead == false || property.GetIndexParameters().Length > 0)
continue;
properties.Add(property);
}
propertiesCache[obj.GetType()] = properties;
return properties;
}
private static List<FieldInfo> GetFields(object obj)
{
List<FieldInfo> fields;
if (fieldsCache.TryGetValue(obj.GetType(), out fields))
return fields;
fields = new List<FieldInfo>();
foreach (FieldInfo fieldInfo in obj.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
{
if (Attribute.IsDefined(fieldInfo, typeof(CompilerGeneratedAttribute)) == false)
{
fields.Add(fieldInfo);
}
}
fieldsCache[obj.GetType()] = fields;
return fields;
}
/// <summary>
/// Generate a row from the reader
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns></returns>
public static Row FromReader(IDataReader reader)
{
Row row = new Row();
for (int i = 0; i < reader.FieldCount; i++)
{
row[reader.GetName(i)] = reader.GetValue(i);
}
return row;
}
/// <summary>
/// Create a new object of <typeparamref name="T"/> and set all
/// the matching fields/properties on it.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T ToObject<T>()
{
return (T)ToObject(typeof(T));
}
/// <summary>
/// Create a new object of <param name="type"/> and set all
/// the matching fields/properties on it.
/// </summary>
public object ToObject(Type type)
{
object instance = Activator.CreateInstance(type);
foreach (PropertyInfo info in GetProperties(instance))
{
if(items.Contains(info.Name) && info.CanWrite)
info.SetValue(instance, items[info.Name],null);
}
foreach (FieldInfo info in GetFields(instance))
{
if(items.Contains(info.Name))
info.SetValue(instance,items[info.Name]);
}
return instance;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Vevo;
using Vevo.Domain;
using Vevo.Domain.Marketing;
using Vevo.Domain.Orders;
using Vevo.Domain.Payments;
using Vevo.Domain.Products;
using Vevo.Domain.Stores;
using Vevo.Shared.Utilities;
using Vevo.WebAppLib;
using Vevo.WebUI;
using Vevo.WebUI.International;
using Vevo.WebUI.Payments;
using Vevo.Deluxe.Domain;
using Vevo.Deluxe.Domain.GiftRegistry;
using Vevo.Shared.DataAccess;
using Vevo.Deluxe.Domain.BundlePromotion;
using Vevo.Deluxe.Domain.Orders;
public partial class ShoppingCartPage : Vevo.Deluxe.WebUI.Base.BaseLicenseLanguagePage
{
private IList<PaymentOption> GetPaymentsWithoutButton()
{
return DataAccessContext.PaymentOptionRepository.GetShownPaymentList(
StoreContext.Culture, BoolFilter.ShowTrue );
}
private IList<PaymentOption> GetPaymentsWithButton()
{
return DataAccessContext.PaymentOptionRepository.GetButtonList(
StoreContext.Culture, BoolFilter.ShowTrue );
}
private void PopulatePaymentButtons()
{
IList<PaymentOption> paymentsWithoutButton = GetPaymentsWithoutButton();
if (paymentsWithoutButton.Count == 0)
{
uxCheckoutImageButton.Visible = false;
}
IList<PaymentOption> paymentsWithButton = GetPaymentsWithButton();
if (paymentsWithButton.Count > 0)
{
if (!StoreContext.ShoppingCart.ContainsSubscriptionProduct())
{
if (!StoreContext.ShoppingCart.ContainsRecurringProduct())
{
uxOrTR.Visible = true;
uxExpressPaymentButtonsTR.Visible = true;
for (int i = 0; i < paymentsWithButton.Count; i++)
{
BaseButtonPaymentMethod control =
(BaseButtonPaymentMethod) LoadControl( "~/" + paymentsWithButton[i].ButtonUserControl );
control.AddConfrimBox();
Panel panel = new Panel();
panel.CssClass = "ExpressPaymentButton";
panel.Controls.Add( control );
uxButtonPlaceHolder.Controls.Add( panel );
}
}
else
{
uxOrTR.Visible = true;
uxRecurringWarning.Visible = true;
}
}
}
}
private decimal ExtractCostFromShippingMethodText( string listItemName )
{
if (String.IsNullOrEmpty( listItemName ))
return 0;
int index = listItemName.LastIndexOf( "(" ) + 2;
int length = listItemName.Length - 1;
string number = listItemName.Substring( index, length - index );
if (index > 0)
return decimal.Parse( number.Trim() );
else
return 0;
}
private string ExtractNameFromListItemText( string listItemName )
{
int index = listItemName.LastIndexOf( "(" );
if (index > 0)
return listItemName.Substring( 0, index ).Trim();
else
return listItemName;
}
private void PopulateControls()
{
decimal shippingTax = 0;
decimal handlingTax = 0;
bool isTaxIncluded = DataAccessContext.Configurations.GetBoolValue( "TaxIncludedInPrice" );
if (StoreContext.ShoppingCart.GetCartItems().Length > 0)
{
uxPanel.Visible = true;
OrderAmount orderAmount = StoreContext.GetOrderAmount();
if (orderAmount.ShippingCost > 0)
{
if (!DataAccessContext.Configurations.GetBoolValue( "IsTaxableShippingCost" ))
{
shippingTax = 0;
}
else
{
shippingTax = orderAmount.ShippingCost * DataAccessContext.Configurations.GetDecimalValue( "TaxPercentageIncludedInPrice" ) / 100;
}
}
if (orderAmount.HandlingFee > 0)
{
if (!DataAccessContext.Configurations.GetBoolValue( "IsTaxableShippingCost" ))
{
handlingTax = 0;
}
else
{
handlingTax = orderAmount.HandlingFee * DataAccessContext.Configurations.GetDecimalValue( "TaxPercentageIncludedInPrice" ) / 100;
}
}
if (isTaxIncluded)
{
uxTotalAmountLabel.Text = StoreContext.Currency.FormatPrice( StoreContext.ShoppingCart.GetSubtotalIncludedTax( StoreContext.WholesaleStatus )
+ (orderAmount.ShippingCost + shippingTax)
+ (orderAmount.HandlingFee + handlingTax)
+ (orderAmount.Discount * -1)
+ (orderAmount.PointDiscount * -1)
+ (orderAmount.GiftCertificate * -1) );
}
else
{
uxTotalAmountLabel.Text = StoreContext.Currency.FormatPrice( orderAmount.Total );
}
if (isTaxIncluded)
{
uxSubTotalLabel.Text = StoreContext.Currency.FormatPrice( StoreContext.ShoppingCart.GetSubtotalIncludedTax( StoreContext.WholesaleStatus ) );
}
else
{
uxSubTotalLabel.Text = StoreContext.Currency.FormatPrice( orderAmount.Subtotal );
}
if (orderAmount.Discount > 0)
{
uxDiscountTR.Visible = true;
uxDiscountAmountLabel.Text = StoreContext.Currency.FormatPrice( orderAmount.Discount * -1 );
}
else
uxDiscountTR.Visible = false;
if (orderAmount.PointDiscount > 0)
{
uxRewardDiscountTR.Visible = true;
uxRewardDiscountLabel.Text = StoreContext.Currency.FormatPrice( orderAmount.PointDiscount * -1 );
}
else
uxRewardDiscountTR.Visible = false;
if (orderAmount.GiftCertificate > 0)
{
uxGiftDiscountTR.Visible = true;
uxGiftDiscountLabel.Text = StoreContext.Currency.FormatPrice( orderAmount.GiftCertificate * -1 );
}
else
uxGiftDiscountTR.Visible = false;
if (orderAmount.Tax > 0 && !isTaxIncluded)
{
uxTaxTR.Visible = true;
uxTaxAmountLabel.Text = StoreContext.Currency.FormatPrice( orderAmount.Tax );
}
else
{
uxTaxTR.Visible = false;
}
if ( orderAmount.ShippingCost > 0 )
{
uxShippingTR.Visible = true;
if (isTaxIncluded)
{
uxShippingAmountLabel.Text = StoreContext.Currency.FormatPrice( orderAmount.ShippingCost + shippingTax );
}
else
{
uxShippingAmountLabel.Text = StoreContext.Currency.FormatPrice( orderAmount.ShippingCost );
}
}
else
uxShippingTR.Visible = false;
if (orderAmount.HandlingFee > 0)
{
uxHandlingFeeTR.Visible = true;
if (isTaxIncluded)
{
uxHandlingFeeLabel.Text = StoreContext.Currency.FormatPrice( orderAmount.HandlingFee + handlingTax );
}
else
{
uxHandlingFeeLabel.Text = StoreContext.Currency.FormatPrice( orderAmount.HandlingFee );
}
}
else
uxHandlingFeeTR.Visible = false;
uxGrid.DataSource = StoreContext.ShoppingCart.GetCartItems();
uxGrid.DataBind();
}
else
{
uxPanel.Visible = false;
uxCartEmptyDiv.Visible = true;
uxCartEmptyLabel.Text = "[$Your shopping cart is empty]";
uxBackHomeLink.Visible = true;
StoreContext.CheckoutDetails.Clear();
}
if (uxTaxIncludePanel.Visible)
{
uxTaxIncludeMessageLabel.Text =
String.Format( "[$TaxIncludeMessage1] {0} [$TaxIncludeMessage2]",
DataAccessContext.Configurations.GetValue( "TaxPercentageIncludedInPrice" ).ToString() );
}
PopulateContinueUrl();
PopulateAddToGiftRegistryButton();
}
private bool VerifyQuantity()
{
string stockMessage = String.Empty;
string giftRegistryMessage = String.Empty;
string minMaxQuantityMessage = String.Empty;
if (!IsEnoughStock( out stockMessage ))
{
uxMessageLiteral.DisplayError(stockMessage);
return false;
}
if (!IsEnoughGiftRegistyWantQuantity( out giftRegistryMessage ))
{
uxMessageLiteral.DisplayError(giftRegistryMessage);
return false;
}
if (!IsAcceptQuantity( out minMaxQuantityMessage ))
{
uxMessageLiteral.DisplayError(minMaxQuantityMessage);
return false;
}
return true;
}
private bool UpdateQuantity()
{
bool result = true;
try
{
if (!VerifyQuantity())
return false;
int rowIndex;
for (rowIndex = 0; rowIndex < uxGrid.Rows.Count; rowIndex++)
{
GridViewRow row = uxGrid.Rows[rowIndex];
if (row.RowType == DataControlRowType.DataRow)
{
string quantityText = ((TextBox) row.FindControl( "uxQuantityText" )).Text;
int quantity = 1;
if (int.TryParse( quantityText, out quantity ))
{
string cartItemID = uxGrid.DataKeys[rowIndex]["CartItemID"].ToString();
StoreContext.ShoppingCart.UpdateQuantity(
cartItemID,
quantity );
}
}
}
}
catch
{
uxMessage.DisplayError( "[$UpdateFailed]" );
result = false;
}
uxCartStatusHidden.Value = "Updated";
return result;
}
private void PopulateContinueUrl()
{
LinkButton link = (LinkButton) uxPanel.FindControl( "uxContinueLink" );
if (!StoreContext.CheckoutDetails.ContainsGiftRegistry())
link.PostBackUrl = "~/Catalog.aspx";
else
link.PostBackUrl = "GiftRegistryItem.aspx?GiftRegistryID=" + StoreContext.CheckoutDetails.GiftRegistryID;
}
private bool HasGiftRegistryByUser( string userName )
{
IList<GiftRegistry> list = DataAccessContextDeluxe.GiftRegistryRepository.GetAllByUserName(
userName, DataAccessContext.StoreRetriever.GetCurrentStoreID() );
return (list.Count > 0);
}
private void PopulateAddToGiftRegistryButton()
{
MembershipUser user = Membership.GetUser();
if (!StoreContext.CheckoutDetails.ContainsGiftRegistry() &&
user != null &&
DataAccessContext.Configurations.GetBoolValue( "GiftRegistryModuleDisplay" )
&& KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName )
)
{
if (Roles.GetRolesForUser( user.UserName )[0].ToLower() == "customers"
&& HasGiftRegistryByUser( user.UserName ))
uxAddToGiftRegistryImageButton.Visible = true;
else
uxAddToGiftRegistryImageButton.Visible = false;
}
else
uxAddToGiftRegistryImageButton.Visible = false;
}
private bool CheckUseInventory( string productID )
{
Product product = DataAccessContext.ProductRepository.GetOne( StoreContext.Culture, productID, new StoreRetriever().GetCurrentStoreID() );
return product.UseInventory;
}
private bool IsEnoughStock( out string message )
{
message = String.Empty;
int rowIndex;
for (rowIndex = 0; rowIndex < uxGrid.Rows.Count; rowIndex++)
{
GridViewRow row = uxGrid.Rows[rowIndex];
if (row.RowType == DataControlRowType.DataRow)
{
ICartItem cartItem = (ICartItem) StoreContext.ShoppingCart.FindCartItemByID( (string) uxGrid.DataKeys[rowIndex]["CartItemID"] );
bool isPromotion = (bool) uxGrid.DataKeys[rowIndex]["IsPromotion"];
bool isProductKit = (bool) uxGrid.DataKeys[rowIndex]["IsProductKit"];
string productID = uxGrid.DataKeys[rowIndex]["ProductID"].ToString();
string productName = ((HyperLink) row.FindControl( "uxItemNameLink" )).Text;
int quantity = ConvertUtilities.ToInt32( ((TextBox) row.FindControl( "uxQuantityText" )).Text );
if (!isPromotion)
{
Product product = DataAccessContext.ProductRepository.GetOne( StoreContext.Culture, productID, new StoreRetriever().GetCurrentStoreID() );
OptionItemValueCollection options = (OptionItemValueCollection) uxGrid.DataKeys[rowIndex]["Options"];
int productStock = product.GetStock( options.GetUseStockOptionItemIDs() );
int currentStock = productStock - quantity;
if (currentStock != DataAccessContext.Configurations.GetIntValue( "OutOfStockValue" ))
{
if (CatalogUtilities.IsOutOfStock( currentStock, CheckUseInventory( productID ) ))
{
message += "<li>" + productName;
if (DataAccessContext.Configurations.GetBoolValue( "ShowQuantity" ))
{
int displayStock = productStock - DataAccessContext.Configurations.GetIntValue( "OutOfStockValue" );
if (displayStock < 0)
{
displayStock = 0;
}
message += " ( available " + displayStock + " items )";
}
else
{
message += "</li>";
}
}
}
if (isProductKit)
{
ProductKitItemValueCollection valueCollection = cartItem.ProductKits;
foreach (ProductKitItemValue value in valueCollection)
{
product = DataAccessContext.ProductRepository.GetOne( StoreContext.Culture, value.ProductID, new StoreRetriever().GetCurrentStoreID() );
productStock = product.GetStock( new string[0] );
currentStock = productStock - quantity;
if (currentStock != DataAccessContext.Configurations.GetIntValue( "OutOfStockValue" ))
{
if (CatalogUtilities.IsOutOfStock( currentStock, CheckUseInventory( product.ProductID ) ))
{
message += "<li>" + product.Name + " of " + productName;
if (DataAccessContext.Configurations.GetBoolValue( "ShowQuantity" ))
{
int displayStock = productStock - DataAccessContext.Configurations.GetIntValue( "OutOfStockValue" );
if (displayStock < 0)
{
displayStock = 0;
}
message += " ( available " + displayStock + " items )";
}
else
{
message += "</li>";
}
}
}
}
}
}
else
{
CartItemPromotion promotionCartItem = (CartItemPromotion) cartItem;
PromotionSelected promotionSelected = promotionCartItem.PromotionSelected;
foreach (PromotionSelectedItem item in promotionSelected.PromotionSelectedItems)
{
Product product = item.Product;
IList<ProductOptionGroup> groups = DataAccessContext.ProductRepository.GetProductOptionGroups( StoreContext.Culture, product.ProductID );
string[] optionsUseStock = item.GetUseStockOptionItems().ToArray( typeof( string ) ) as string[];
int productStock = product.GetStock( optionsUseStock );
int currentStock = productStock - quantity;
if (currentStock != DataAccessContext.Configurations.GetIntValue( "OutOfStockValue" ))
{
if (CatalogUtilities.IsOutOfStock( currentStock, CheckUseInventory( product.ProductID ) ))
{
message += "<li>" + productName;
message += "</li>";
}
}
}
}
}
}
if (!String.IsNullOrEmpty( message ))
{
message =
"<p class=\"ErrorHeader\">[$StockError]</p>" +
"<ul class=\"ErrorBody\">" + message + "</ul>";
return false;
}
else
{
return true;
}
}
private bool CheckBunblePromotionBeforeAddToGiftRegistry( out string message )
{
message = String.Empty;
int rowIndex;
for (rowIndex = 0; rowIndex < uxGrid.Rows.Count; rowIndex++)
{
GridViewRow row = uxGrid.Rows[rowIndex];
if (row.RowType == DataControlRowType.DataRow)
{
string productName = ((HyperLink) row.FindControl( "uxItemNameLink" )).Text;
bool isPromotion = (bool) uxGrid.DataKeys[rowIndex]["IsPromotion"];
if (isPromotion)
{
message += "<li>" + productName + "</li>";
}
}
}
if (!String.IsNullOrEmpty( message ))
{
message =
"<p class=\"ErrorHeader\">[$GiftRegistryErrorBundlePromotion]</p>" +
"<ul class=\"ErrorBody\">" + message + "</ul>";
return false;
}
else
{
return true;
}
}
private bool IsEnoughGiftRegistyWantQuantity( out string message )
{
CheckoutDetails checkout = StoreContext.CheckoutDetails;
message = String.Empty;
if (!String.IsNullOrEmpty( checkout.GiftRegistryID ) && checkout.GiftRegistryID != "0")
{
int rowIndex;
for (rowIndex = 0; rowIndex < uxGrid.Rows.Count; rowIndex++)
{
GridViewRow row = uxGrid.Rows[rowIndex];
if (row.RowType == DataControlRowType.DataRow)
{
string cartItemID = uxGrid.DataKeys[rowIndex]["CartItemID"].ToString();
string giftRegistryItemID =
StoreContext.CheckoutDetails.CartItemIDToGiftRegistryIDMap[cartItemID];
GiftRegistryItem giftRegistryItem = DataAccessContextDeluxe.GiftRegistryItemRepository.GetOne(
giftRegistryItemID );
int wantQuantity = (int) (giftRegistryItem.WantQuantity - giftRegistryItem.HasQuantity);
string productName = ((HyperLink) row.FindControl( "uxItemNameLink" )).Text;
int quantity = ConvertUtilities.ToInt32( ((TextBox) row.FindControl( "uxQuantityText" )).Text );
if (quantity > wantQuantity)
{
message += "<li>" + productName + "</li>";
}
}
}
if (!String.IsNullOrEmpty( message ))
{
message =
"<p class=\"ErrorHeader\">[$GiftRegistryError]</p>" +
"<ul class=\"ErrorBody\">" + message + "</ul>";
return false;
}
else
{
return true;
}
}
else
return true;
}
private bool IsAcceptQuantity( out string message )
{
message = String.Empty;
int rowIndex;
for (rowIndex = 0; rowIndex < uxGrid.Rows.Count; rowIndex++)
{
GridViewRow row = uxGrid.Rows[rowIndex];
if (row.RowType == DataControlRowType.DataRow)
{
if ((bool) uxGrid.DataKeys[rowIndex]["IsPromotion"])
continue;
string productID = uxGrid.DataKeys[rowIndex]["ProductID"].ToString();
string productName = ((HyperLink) row.FindControl( "uxItemNameLink" )).Text;
int quantity = ConvertUtilities.ToInt32( ((TextBox) row.FindControl( "uxQuantityText" )).Text );
Product product = DataAccessContext.ProductRepository.GetOne( StoreContext.Culture, productID, new StoreRetriever().GetCurrentStoreID() );
int minQuantity = product.MinQuantity;
int maxQuantity = product.MaxQuantity;
if (quantity < minQuantity)
{
message += "<li>" + productName;
message += " ( minimum quantity " + minQuantity + " items )";
message += "</li>";
}
if (maxQuantity != 0 && quantity > maxQuantity)
{
message += "<li>" + productName;
message += " ( maximum quantity " + maxQuantity + " items )";
message += "</li>";
}
}
}
if (!String.IsNullOrEmpty( message ))
{
message =
"<p class=\"ErrorHeader\">[$QuantityError]</p>" +
"<ul class=\"ErrorBody\">" + message + "</ul>";
return false;
}
else
{
return true;
}
}
private bool TaxIncludeVisibility()
{
return DataAccessContext.Configurations.GetBoolValue( "TaxIncludedInPrice" );
}
private void SignOut()
{
if (Page.User.Identity.IsAuthenticated &&
(!Roles.IsUserInRole( Page.User.Identity.Name, "Customers" )))
FormsAuthentication.SignOut();
}
protected void Page_Load( object sender, EventArgs e )
{
PopulatePaymentButtons();
if (CatalogUtilities.IsCatalogMode())
{
//************ do something *****************
}
}
protected void Page_PreRender( object sender, EventArgs e )
{
uxTaxIncludePanel.Visible = TaxIncludeVisibility();
PopulateControls();
}
protected void uxGrid_RowDeleting( object sender, GridViewDeleteEventArgs e )
{
StoreContext.ShoppingCart.DeleteItem(
uxGrid.DataKeys[e.RowIndex]["CartItemID"].ToString() );
uxCartStatusHidden.Value = "Deleted";
}
protected void uxUpdateQuantityImageButton_Click( object sender, EventArgs e )
{
UpdateQuantity();
}
protected void uxClearCartButton_Click( object sender, EventArgs e )
{
StoreContext.ClearCheckoutSession();
}
protected void uxCheckoutImageButton_Click( object sender, EventArgs e )
{
if (UpdateQuantity())
{
SignOut();
Response.Redirect( "Checkout.aspx" );
}
}
protected void uxAddToGiftRegistryImageButton_Click( object sender, EventArgs e )
{
if (UpdateQuantity())
{
string errorMessage;
if (CheckBunblePromotionBeforeAddToGiftRegistry( out errorMessage ))
{
SignOut();
Response.Redirect( "GiftRegistrySelect.aspx" );
}
else
{
uxMessageLiteral.DisplayError( errorMessage );
}
}
}
protected void uxGrid_RowDataBound( object sender, GridViewRowEventArgs e )
{
TextBox quantity = (TextBox) e.Row.FindControl( "uxQuantityText" );
WebUtilities.TieButton( this.Page, quantity, uxUpdateQuantityImageButton );
}
protected string GetName( object cartItem )
{
return ((ICartItem) cartItem).GetName( StoreContext.Culture, StoreContext.Currency );
}
protected string GetMainText( object cartItem )
{
string mainText;
((ICartItem) cartItem).GetPreCheckoutTooltip(
StoreContext.Currency,
StoreContext.WholesaleStatus,
out mainText );
return mainText;
}
protected string GetTaxTooltipText()
{
return String.Format( "[$TaxIncludeMessage1] {0} [$TaxIncludeMessage2]",
DataAccessContext.Configurations.GetValue( "TaxPercentageIncludedInPrice" ).ToString() );
}
protected string GetTooltipText( object cartItem )
{
string mainText;
return ((ICartItem) cartItem).GetPreCheckoutTooltip(
StoreContext.Currency,
StoreContext.WholesaleStatus,
out mainText );
}
protected string GetUnitPriceText( object cartItem )
{
return StoreContext.Currency.FormatPrice( ((ICartItem) cartItem).GetShoppingCartUnitPrice(
StoreContext.WholesaleStatus ) );
}
protected string GetSubtotalText( object cartItem )
{
ICartItem item = ((ICartItem) cartItem);
return StoreContext.Currency.FormatPrice(
item.GetShoppingCartUnitPrice( StoreContext.WholesaleStatus )
* item.Quantity );
}
protected string GetItemImage( object cartItem )
{
ICartItem baseCartItem = (ICartItem) cartItem;
if (baseCartItem.IsPromotion)
{
CartItemPromotion cartItemPromotion = (CartItemPromotion) baseCartItem;
PromotionGroup promotion = cartItemPromotion.PromotionSelected.GetPromotionGroup();
if (String.IsNullOrEmpty( promotion.ImageFile ))
{
return "~/Images/Products/Thumbnail/DefaultNoImage.gif";
}
else
{
return "~/" + promotion.ImageFile;
}
}
else
{
ProductImage details = baseCartItem.Product.GetPrimaryProductImage();
if (String.IsNullOrEmpty( details.ThumbnailImage ))
{
return "~/Images/Products/Thumbnail/DefaultNoImage.gif";
}
else
{
return "~/" + details.ThumbnailImage;
}
}
}
protected string GetLink( object cartItem )
{
ICartItem baseCartItem = (ICartItem) cartItem;
if (baseCartItem.IsPromotion)
{
CartItemPromotion cartItemPromotion = (CartItemPromotion) baseCartItem;
PromotionGroup promotion = cartItemPromotion.PromotionSelected.GetPromotionGroup();
return UrlManager.GetPromotionUrl( promotion.PromotionGroupID, promotion.Locales[StoreContext.Culture].UrlName );
}
else
{
Product product = baseCartItem.Product;
return UrlManager.GetProductUrl( product.ProductID, product.Locales[StoreContext.Culture].UrlName );
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ActorMaterializerImpl.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Akka.Actor;
using Akka.Dispatch;
using Akka.Event;
using Akka.Pattern;
using Akka.Streams.Implementation.Fusing;
using Akka.Streams.Implementation.Stages;
using Akka.Util;
using Akka.Util.Internal;
using Reactive.Streams;
namespace Akka.Streams.Implementation
{
public sealed class ActorMaterializerImpl : ActorMaterializer
{
#region Materializer session implementation
private sealed class ActorMaterializerSession : MaterializerSession
{
private static readonly MethodInfo ProcessorForMethod =
typeof(ActorMaterializerSession).GetMethod("ProcessorFor",
BindingFlags.NonPublic | BindingFlags.Instance);
private readonly ActorMaterializerImpl _materializer;
private readonly Func<GraphInterpreterShell, IActorRef> _subflowFuser;
private readonly string _flowName;
private int _nextId;
public ActorMaterializerSession(ActorMaterializerImpl materializer, IModule topLevel, Attributes initialAttributes, Func<GraphInterpreterShell, IActorRef> subflowFuser)
: base(topLevel, initialAttributes)
{
_materializer = materializer;
_subflowFuser = subflowFuser;
_flowName = _materializer.CreateFlowName();
}
protected override object MaterializeAtomic(IModule atomic, Attributes effectiveAttributes,
IDictionary<IModule, object> materializedValues)
{
if (atomic is ISinkModule)
{
var sink = (ISinkModule) atomic;
object materialized;
var subscriber = sink.Create(CreateMaterializationContext(effectiveAttributes), out materialized);
AssignPort(sink.Shape.Inlets.First(), subscriber);
materializedValues.Add(atomic, materialized);
}
else if (atomic is ISourceModule)
{
var source = (ISourceModule) atomic;
object materialized;
var publisher = source.Create(CreateMaterializationContext(effectiveAttributes), out materialized);
AssignPort(source.Shape.Outlets.First(), publisher);
materializedValues.Add(atomic, materialized);
}
else if (atomic is IStageModule)
{
// FIXME: Remove this, only stream-of-stream ops need it
var stage = (IStageModule) atomic;
// assumes BaseType is StageModule<>
var methodInfo = ProcessorForMethod.MakeGenericMethod(atomic.GetType().BaseType.GenericTypeArguments);
var parameters = new object[]
{stage, effectiveAttributes, _materializer.EffectiveSettings(effectiveAttributes), null};
var processor = methodInfo.Invoke(this, parameters);
object materialized = parameters[3];
AssignPort(stage.In, UntypedSubscriber.FromTyped(processor));
AssignPort(stage.Out, UntypedPublisher.FromTyped(processor));
materializedValues.Add(atomic, materialized);
}
//else if (atomic is TlsModule)
//{
//})
else if (atomic is GraphModule)
{
var graph = (GraphModule) atomic;
MaterializeGraph(graph, effectiveAttributes, materializedValues);
}
else if (atomic is GraphStageModule)
{
var stage = (GraphStageModule) atomic;
var graph =
new GraphModule(
GraphAssembly.Create(stage.Shape.Inlets, stage.Shape.Outlets, new[] {stage.Stage}),
stage.Shape, stage.Attributes, new IModule[] {stage});
MaterializeGraph(graph, effectiveAttributes, materializedValues);
}
return NotUsed.Instance;
}
private string StageName(Attributes attr) => $"{_flowName}-{_nextId++}-{attr.GetNameOrDefault()}";
private MaterializationContext CreateMaterializationContext(Attributes effectiveAttributes)
=> new MaterializationContext(_materializer, effectiveAttributes, StageName(effectiveAttributes));
private void MaterializeGraph(GraphModule graph, Attributes effectiveAttributes, IDictionary<IModule, object> materializedValues)
{
var calculatedSettings = _materializer.EffectiveSettings(effectiveAttributes);
var t = graph.Assembly.Materialize(effectiveAttributes, graph.MaterializedValueIds, materializedValues, RegisterSource);
var inHandlers = t.Item1;
var outHandlers = t.Item2;
var logics = t.Item3;
var shell = new GraphInterpreterShell(graph.Assembly, inHandlers, outHandlers, logics, graph.Shape, calculatedSettings, _materializer);
var impl = _subflowFuser != null && !effectiveAttributes.Contains(Attributes.AsyncBoundary.Instance)
? _subflowFuser(shell)
: _materializer.ActorOf(ActorGraphInterpreter.Props(shell), StageName(effectiveAttributes), calculatedSettings.Dispatcher);
var i = 0;
var inletsEnumerator = graph.Shape.Inlets.GetEnumerator();
while (inletsEnumerator.MoveNext())
{
var inlet = inletsEnumerator.Current;
var elementType = inlet.GetType().GetGenericArguments().First();
var subscriber = typeof(ActorGraphInterpreter.BoundarySubscriber<>).Instantiate(elementType, impl, shell, i);
AssignPort(inlet, UntypedSubscriber.FromTyped(subscriber));
i++;
}
i = 0;
var outletsEnumerator = graph.Shape.Outlets.GetEnumerator();
while (outletsEnumerator.MoveNext())
{
var outlet = outletsEnumerator.Current;
var elementType = outlet.GetType().GetGenericArguments().First();
var publisher = typeof(ActorGraphInterpreter.BoundaryPublisher<>).Instantiate(elementType, impl, shell, i);
var message = new ActorGraphInterpreter.ExposedPublisher(shell, i, (IActorPublisher)publisher);
impl.Tell(message);
AssignPort(outletsEnumerator.Current, (IUntypedPublisher) publisher);
i++;
}
}
// ReSharper disable once UnusedMember.Local
private IProcessor<TIn, TOut> ProcessorFor<TIn, TOut>(StageModule<TIn, TOut> op, Attributes effectiveAttributes, ActorMaterializerSettings settings, out object materialized)
{
DirectProcessor<TIn, TOut> processor;
if ((processor = op as DirectProcessor<TIn, TOut>) != null)
{
var t = processor.ProcessorFactory();
materialized = t.Item2;
return t.Item1;
}
var props = ActorProcessorFactory.Props(_materializer, op, effectiveAttributes, out materialized);
return ActorProcessorFactory.Create<TIn, TOut>(_materializer.ActorOf(props, StageName(effectiveAttributes), settings.Dispatcher));
}
}
#endregion
private readonly ActorSystem _system;
private readonly ActorMaterializerSettings _settings;
private readonly Dispatchers _dispatchers;
private readonly IActorRef _supervisor;
private readonly AtomicBoolean _haveShutDown;
private readonly EnumerableActorName _flowNames;
private ILoggingAdapter _logger;
public ActorMaterializerImpl(ActorSystem system, ActorMaterializerSettings settings, Dispatchers dispatchers, IActorRef supervisor, AtomicBoolean haveShutDown, EnumerableActorName flowNames)
{
_system = system;
_settings = settings;
_dispatchers = dispatchers;
_supervisor = supervisor;
_haveShutDown = haveShutDown;
_flowNames = flowNames;
_executionContext = new Lazy<MessageDispatcher>(() => _dispatchers.Lookup(_settings.Dispatcher == Deploy.NoDispatcherGiven
? Dispatchers.DefaultDispatcherId
: _settings.Dispatcher));
if (_settings.IsFuzzingMode && !_system.Settings.Config.HasPath("akka.stream.secret-test-fuzzing-warning-disable"))
Logger.Warning("Fuzzing mode is enabled on this system. If you see this warning on your production system then set 'akka.materializer.debug.fuzzing-mode' to off.");
}
public override bool IsShutdown => _haveShutDown.Value;
public override ActorMaterializerSettings Settings => _settings;
public override ActorSystem System => _system;
public override IActorRef Supervisor => _supervisor;
public override ILoggingAdapter Logger => _logger ?? (_logger = GetLogger());
public override IMaterializer WithNamePrefix(string name)
=> new ActorMaterializerImpl(_system, _settings, _dispatchers, _supervisor, _haveShutDown, _flowNames.Copy(name));
private string CreateFlowName() => _flowNames.Next();
private Attributes InitialAttributes =>
Attributes.CreateInputBuffer(_settings.InitialInputBufferSize, _settings.MaxInputBufferSize)
.And(ActorAttributes.CreateDispatcher(_settings.Dispatcher))
.And(ActorAttributes.CreateSupervisionStrategy(_settings.SupervisionDecider));
public override ActorMaterializerSettings EffectiveSettings(Attributes attributes)
{
return attributes.AttributeList.Aggregate(Settings, (settings, attribute) =>
{
if (attribute is Attributes.InputBuffer)
{
var inputBuffer = (Attributes.InputBuffer)attribute;
return settings.WithInputBuffer(inputBuffer.Initial, inputBuffer.Max);
}
if (attribute is ActorAttributes.Dispatcher)
return settings.WithDispatcher(((ActorAttributes.Dispatcher)attribute).Name);
if (attribute is ActorAttributes.SupervisionStrategy)
return settings.WithSupervisionStrategy(((ActorAttributes.SupervisionStrategy)attribute).Decider);
return settings;
});
}
public override ICancelable ScheduleOnce(TimeSpan delay, Action action)
=> _system.Scheduler.Advanced.ScheduleOnceCancelable(delay, action);
public override ICancelable ScheduleRepeatedly(TimeSpan initialDelay, TimeSpan interval, Action action)
=> _system.Scheduler.Advanced.ScheduleRepeatedlyCancelable(initialDelay, interval, action);
public override TMat Materialize<TMat>(IGraph<ClosedShape, TMat> runnable) => Materialize(runnable, null);
internal TMat Materialize<TMat>(IGraph<ClosedShape, TMat> runnable, Func<GraphInterpreterShell, IActorRef> subFlowFuser)
{
var runnableGraph = _settings.IsAutoFusing
? Fusing.Fusing.Aggressive(runnable)
: runnable;
if (_haveShutDown.Value)
throw new IllegalStateException("Attempted to call Materialize() after the ActorMaterializer has been shut down.");
if (StreamLayout.IsDebug)
StreamLayout.Validate(runnableGraph.Module);
var session = new ActorMaterializerSession(this, runnableGraph.Module, InitialAttributes, subFlowFuser);
var matVal = session.Materialize();
return (TMat) matVal;
}
private readonly Lazy<MessageDispatcher> _executionContext;
public override MessageDispatcher ExecutionContext => _executionContext.Value;
public override void Shutdown()
{
if (_haveShutDown.CompareAndSet(false, true))
Supervisor.Tell(PoisonPill.Instance);
}
protected internal override IActorRef ActorOf(MaterializationContext context, Props props)
{
var dispatcher = props.Deploy.Dispatcher == Deploy.NoDispatcherGiven
? EffectiveSettings(context.EffectiveAttributes).Dispatcher
: props.Dispatcher;
return ActorOf(props, context.StageName, dispatcher);
}
private IActorRef ActorOf(Props props, string name, string dispatcher)
{
if (Supervisor is LocalActorRef)
{
var aref = (LocalActorRef)Supervisor;
return ((ActorCell)aref.Underlying).AttachChild(props.WithDispatcher(dispatcher), isSystemService: false, name: name);
}
if (Supervisor is RepointableActorRef)
{
var aref = (RepointableActorRef)Supervisor;
if (aref.IsStarted)
return ((ActorCell)aref.Underlying).AttachChild(props.WithDispatcher(dispatcher), isSystemService: false, name: name);
var timeout = aref.Underlying.System.Settings.CreationTimeout;
var f = Supervisor.Ask<IActorRef>(new StreamSupervisor.Materialize(props.WithDispatcher(dispatcher), name), timeout);
return f.Result;
}
throw new IllegalStateException($"Stream supervisor must be a local actor, was [{Supervisor.GetType()}]");
}
private ILoggingAdapter GetLogger() => _system.Log;
}
internal class SubFusingActorMaterializerImpl : IMaterializer
{
private readonly ActorMaterializerImpl _delegateMaterializer;
private readonly Func<GraphInterpreterShell, IActorRef> _registerShell;
public SubFusingActorMaterializerImpl(ActorMaterializerImpl delegateMaterializer, Func<GraphInterpreterShell, IActorRef> registerShell)
{
_delegateMaterializer = delegateMaterializer;
_registerShell = registerShell;
}
public IMaterializer WithNamePrefix(string namePrefix)
=> new SubFusingActorMaterializerImpl((ActorMaterializerImpl) _delegateMaterializer.WithNamePrefix(namePrefix), _registerShell);
public TMat Materialize<TMat>(IGraph<ClosedShape, TMat> runnable)
=> _delegateMaterializer.Materialize(runnable, _registerShell);
public ICancelable ScheduleOnce(TimeSpan delay, Action action)
=> _delegateMaterializer.ScheduleOnce(delay, action);
public ICancelable ScheduleRepeatedly(TimeSpan initialDelay, TimeSpan interval, Action action)
=> _delegateMaterializer.ScheduleRepeatedly(initialDelay, interval, action);
public MessageDispatcher ExecutionContext => _delegateMaterializer.ExecutionContext;
}
internal class FlowNameCounter : ExtensionIdProvider<FlowNameCounter>, IExtension
{
public static FlowNameCounter Instance(ActorSystem system)
=> system.WithExtension<FlowNameCounter, FlowNameCounter>();
public readonly AtomicCounterLong Counter = new AtomicCounterLong(0);
public override FlowNameCounter CreateExtension(ExtendedActorSystem system) => new FlowNameCounter();
}
public class StreamSupervisor : ActorBase
{
#region Messages
public sealed class Materialize : INoSerializationVerificationNeeded
{
public readonly Props Props;
public readonly string Name;
public Materialize(Props props, string name)
{
Props = props;
Name = name;
}
}
public sealed class GetChildren
{
public static readonly GetChildren Instance = new GetChildren();
private GetChildren() { }
}
public sealed class StopChildren
{
public static readonly StopChildren Instance = new StopChildren();
private StopChildren() { }
}
public sealed class StoppedChildren
{
public static readonly StoppedChildren Instance = new StoppedChildren();
private StoppedChildren() { }
}
public sealed class PrintDebugDump
{
public static readonly PrintDebugDump Instance = new PrintDebugDump();
private PrintDebugDump() { }
}
public sealed class Children
{
public readonly IImmutableSet<IActorRef> Refs;
public Children(IImmutableSet<IActorRef> refs)
{
Refs = refs;
}
}
#endregion
public static Props Props(ActorMaterializerSettings settings, AtomicBoolean haveShutdown)
=> Actor.Props.Create(() => new StreamSupervisor(settings, haveShutdown)).WithDeploy(Deploy.Local);
public static string NextName() => ActorName.Next();
private static readonly EnumerableActorName ActorName = new EnumerableActorNameImpl("StreamSupervisor", new AtomicCounterLong(0L));
public readonly ActorMaterializerSettings Settings;
public readonly AtomicBoolean HaveShutdown;
public StreamSupervisor(ActorMaterializerSettings settings, AtomicBoolean haveShutdown)
{
Settings = settings;
HaveShutdown = haveShutdown;
}
protected override SupervisorStrategy SupervisorStrategy() => Actor.SupervisorStrategy.StoppingStrategy;
protected override bool Receive(object message)
{
if (message is Materialize)
{
var materialize = (Materialize) message;
Sender.Tell(Context.ActorOf(materialize.Props, materialize.Name));
}
else if (message is GetChildren)
Sender.Tell(new Children(Context.GetChildren().ToImmutableHashSet()));
else if (message is StopChildren)
{
foreach (var child in Context.GetChildren())
Context.Stop(child);
Sender.Tell(StoppedChildren.Instance);
}
else
return false;
return true;
}
protected override void PostStop() => HaveShutdown.Value = true;
}
internal static class ActorProcessorFactory
{
public static Props Props<TIn, TOut>(ActorMaterializer materializer, StageModule<TIn, TOut> op, Attributes parentAttributes, out object materialized)
{
var attr = parentAttributes.And(op.Attributes);
// USE THIS TO AVOID CLOSING OVER THE MATERIALIZER BELOW
// Also, otherwise the attributes will not affect the settings properly!
var settings = materializer.EffectiveSettings(attr);
Props result;
materialized = null;
if (op is IGroupBy)
{
var groupBy = (IGroupBy) op;
result = GroupByProcessorImpl<TIn>.Props(settings, groupBy.MaxSubstreams, groupBy.Extractor);
}
else if (op.GetType().IsGenericType && op.GetType().GetGenericTypeDefinition() == typeof(DirectProcessor<,>))
throw new ArgumentException("DirectProcessor cannot end up in ActorProcessorFactory");
else
throw new ArgumentException($"StageModule type {op.GetType()} is not supported");
return result;
}
public static ActorProcessor<TIn, TOut> Create<TIn, TOut>(IActorRef impl)
{
var p = new ActorProcessor<TIn,TOut>(impl);
// Resolve cyclic dependency with actor. This MUST be the first message no matter what.
impl.Tell(new ExposedPublisher(p));
return p;
}
}
}
| |
namespace RecordPlay
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.tsMain = new System.Windows.Forms.ToolStrip();
this.tsbNew = new System.Windows.Forms.ToolStripButton();
this.tsbOpen = new System.Windows.Forms.ToolStripButton();
this.tsbRecord = new System.Windows.Forms.ToolStripButton();
this.tsbPlay = new System.Windows.Forms.ToolStripButton();
this.tsbPause = new System.Windows.Forms.ToolStripButton();
this.tsbStop = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.tsbBackward = new System.Windows.Forms.ToolStripButton();
this.tstStep = new System.Windows.Forms.ToolStripTextBox();
this.tsbForward = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.tsbRecordFrom = new System.Windows.Forms.ToolStripButton();
this.tstTime = new System.Windows.Forms.ToolStripTextBox();
this.tsbPlayFrom = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.tsbClose = new System.Windows.Forms.ToolStripButton();
this.ssMain = new System.Windows.Forms.StatusStrip();
this.tspProgress = new System.Windows.Forms.ToolStripProgressBar();
this.tsslPosition = new System.Windows.Forms.ToolStripStatusLabel();
this.tsslStatus = new System.Windows.Forms.ToolStripStatusLabel();
this.ofdAudio = new System.Windows.Forms.OpenFileDialog();
this.gbPlayer = new System.Windows.Forms.GroupBox();
this.cbPlayer = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.cbMute = new System.Windows.Forms.CheckBox();
this.tbPlayer = new System.Windows.Forms.TrackBar();
this.tbRecorder = new System.Windows.Forms.TrackBar();
this.cbRecorderLine = new System.Windows.Forms.ComboBox();
this.gbRecorder = new System.Windows.Forms.GroupBox();
this.cbRecorder = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.gbDictophone = new System.Windows.Forms.GroupBox();
this.nudVolumeLevelScale = new System.Windows.Forms.NumericUpDown();
this.label5 = new System.Windows.Forms.Label();
this.nudSilentLevel = new System.Windows.Forms.NumericUpDown();
this.label4 = new System.Windows.Forms.Label();
this.cbSkipSilent = new System.Windows.Forms.CheckBox();
this.nudBufferSizeInMs = new System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.sfdAudio = new System.Windows.Forms.SaveFileDialog();
this.tbTimeline = new System.Windows.Forms.TrackBar();
this.tsMain.SuspendLayout();
this.ssMain.SuspendLayout();
this.gbPlayer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.tbPlayer)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tbRecorder)).BeginInit();
this.gbRecorder.SuspendLayout();
this.gbDictophone.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudVolumeLevelScale)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudSilentLevel)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudBufferSizeInMs)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tbTimeline)).BeginInit();
this.SuspendLayout();
//
// tsMain
//
this.tsMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsbNew,
this.tsbOpen,
this.tsbRecord,
this.tsbPlay,
this.tsbPause,
this.tsbStop,
this.toolStripSeparator1,
this.tsbBackward,
this.tstStep,
this.tsbForward,
this.toolStripSeparator2,
this.tsbRecordFrom,
this.tstTime,
this.tsbPlayFrom,
this.toolStripSeparator3,
this.tsbClose});
this.tsMain.Location = new System.Drawing.Point(0, 0);
this.tsMain.Name = "tsMain";
this.tsMain.Size = new System.Drawing.Size(347, 25);
this.tsMain.TabIndex = 2;
//
// tsbNew
//
this.tsbNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbNew.Image = ((System.Drawing.Image)(resources.GetObject("tsbNew.Image")));
this.tsbNew.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbNew.Name = "tsbNew";
this.tsbNew.Size = new System.Drawing.Size(23, 22);
this.tsbNew.Text = "New";
this.tsbNew.Click += new System.EventHandler(this.tsbNew_Click);
//
// tsbOpen
//
this.tsbOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbOpen.Image = ((System.Drawing.Image)(resources.GetObject("tsbOpen.Image")));
this.tsbOpen.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbOpen.Name = "tsbOpen";
this.tsbOpen.Size = new System.Drawing.Size(23, 22);
this.tsbOpen.Text = "Open";
this.tsbOpen.Click += new System.EventHandler(this.tsbOpen_Click);
//
// tsbRecord
//
this.tsbRecord.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbRecord.Image = ((System.Drawing.Image)(resources.GetObject("tsbRecord.Image")));
this.tsbRecord.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbRecord.Name = "tsbRecord";
this.tsbRecord.Size = new System.Drawing.Size(23, 22);
this.tsbRecord.Text = "Record";
this.tsbRecord.Click += new System.EventHandler(this.tsbRecord_Click);
//
// tsbPlay
//
this.tsbPlay.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbPlay.Image = ((System.Drawing.Image)(resources.GetObject("tsbPlay.Image")));
this.tsbPlay.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbPlay.Name = "tsbPlay";
this.tsbPlay.Size = new System.Drawing.Size(23, 22);
this.tsbPlay.Text = "Play";
this.tsbPlay.Click += new System.EventHandler(this.tsbPlay_Click);
//
// tsbPause
//
this.tsbPause.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbPause.Image = ((System.Drawing.Image)(resources.GetObject("tsbPause.Image")));
this.tsbPause.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbPause.Name = "tsbPause";
this.tsbPause.Size = new System.Drawing.Size(23, 22);
this.tsbPause.Text = "Pause";
this.tsbPause.Click += new System.EventHandler(this.tsbPause_Click);
//
// tsbStop
//
this.tsbStop.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbStop.Image = ((System.Drawing.Image)(resources.GetObject("tsbStop.Image")));
this.tsbStop.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbStop.Name = "tsbStop";
this.tsbStop.Size = new System.Drawing.Size(23, 22);
this.tsbStop.Text = "Stop";
this.tsbStop.Click += new System.EventHandler(this.tsbStop_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// tsbBackward
//
this.tsbBackward.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbBackward.Image = ((System.Drawing.Image)(resources.GetObject("tsbBackward.Image")));
this.tsbBackward.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbBackward.Name = "tsbBackward";
this.tsbBackward.Size = new System.Drawing.Size(23, 22);
this.tsbBackward.Text = "Backward";
this.tsbBackward.Click += new System.EventHandler(this.tsbBackward_Click);
//
// tstStep
//
this.tstStep.Name = "tstStep";
this.tstStep.Size = new System.Drawing.Size(25, 25);
this.tstStep.Text = "10";
this.tstStep.TextBoxTextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// tsbForward
//
this.tsbForward.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbForward.Image = ((System.Drawing.Image)(resources.GetObject("tsbForward.Image")));
this.tsbForward.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbForward.Name = "tsbForward";
this.tsbForward.Size = new System.Drawing.Size(23, 22);
this.tsbForward.Text = "Forward";
this.tsbForward.Click += new System.EventHandler(this.tsbForward_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
//
// tsbRecordFrom
//
this.tsbRecordFrom.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbRecordFrom.Image = ((System.Drawing.Image)(resources.GetObject("tsbRecordFrom.Image")));
this.tsbRecordFrom.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbRecordFrom.Name = "tsbRecordFrom";
this.tsbRecordFrom.Size = new System.Drawing.Size(23, 22);
this.tsbRecordFrom.Text = "Record";
this.tsbRecordFrom.Click += new System.EventHandler(this.tsbRecordFrom_Click);
//
// tstTime
//
this.tstTime.Name = "tstTime";
this.tstTime.Size = new System.Drawing.Size(30, 25);
this.tstTime.Text = "10";
this.tstTime.TextBoxTextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// tsbPlayFrom
//
this.tsbPlayFrom.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbPlayFrom.Image = ((System.Drawing.Image)(resources.GetObject("tsbPlayFrom.Image")));
this.tsbPlayFrom.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbPlayFrom.Name = "tsbPlayFrom";
this.tsbPlayFrom.Size = new System.Drawing.Size(23, 22);
this.tsbPlayFrom.Text = "Play";
this.tsbPlayFrom.Click += new System.EventHandler(this.tsbPlayFrom_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25);
//
// tsbClose
//
this.tsbClose.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbClose.Image = ((System.Drawing.Image)(resources.GetObject("tsbClose.Image")));
this.tsbClose.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbClose.Name = "tsbClose";
this.tsbClose.Size = new System.Drawing.Size(23, 22);
this.tsbClose.Text = "Close";
this.tsbClose.Click += new System.EventHandler(this.tsbClose_Click);
//
// ssMain
//
this.ssMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tspProgress,
this.tsslPosition,
this.tsslStatus});
this.ssMain.Location = new System.Drawing.Point(0, 302);
this.ssMain.Name = "ssMain";
this.ssMain.Size = new System.Drawing.Size(347, 22);
this.ssMain.TabIndex = 3;
this.ssMain.Text = "statusStrip1";
//
// tspProgress
//
this.tspProgress.Name = "tspProgress";
this.tspProgress.Size = new System.Drawing.Size(150, 16);
//
// tsslPosition
//
this.tsslPosition.Name = "tsslPosition";
this.tsslPosition.Size = new System.Drawing.Size(44, 17);
this.tsslPosition.Text = "Position";
//
// tsslStatus
//
this.tsslStatus.Name = "tsslStatus";
this.tsslStatus.Size = new System.Drawing.Size(38, 17);
this.tsslStatus.Text = "Status";
//
// ofdAudio
//
this.ofdAudio.DefaultExt = "wav";
//
// gbPlayer
//
this.gbPlayer.Controls.Add(this.cbPlayer);
this.gbPlayer.Controls.Add(this.label3);
this.gbPlayer.Controls.Add(this.cbMute);
this.gbPlayer.Controls.Add(this.tbPlayer);
this.gbPlayer.Location = new System.Drawing.Point(6, 111);
this.gbPlayer.Name = "gbPlayer";
this.gbPlayer.Size = new System.Drawing.Size(164, 140);
this.gbPlayer.TabIndex = 43;
this.gbPlayer.TabStop = false;
this.gbPlayer.Text = "Player";
//
// cbPlayer
//
this.cbPlayer.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbPlayer.Location = new System.Drawing.Point(6, 36);
this.cbPlayer.Name = "cbPlayer";
this.cbPlayer.Size = new System.Drawing.Size(152, 21);
this.cbPlayer.TabIndex = 12;
this.cbPlayer.SelectedIndexChanged += new System.EventHandler(this.cbPlayer_SelectedIndexChanged);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 20);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(71, 13);
this.label3.TabIndex = 20;
this.label3.Text = "Select player:";
//
// cbMute
//
this.cbMute.AutoSize = true;
this.cbMute.Location = new System.Drawing.Point(6, 63);
this.cbMute.Name = "cbMute";
this.cbMute.Size = new System.Drawing.Size(50, 17);
this.cbMute.TabIndex = 49;
this.cbMute.Text = "Mute";
this.cbMute.UseVisualStyleBackColor = true;
//
// tbPlayer
//
this.tbPlayer.Location = new System.Drawing.Point(6, 90);
this.tbPlayer.Maximum = 65535;
this.tbPlayer.Name = "tbPlayer";
this.tbPlayer.Size = new System.Drawing.Size(155, 42);
this.tbPlayer.TabIndex = 47;
this.tbPlayer.TickStyle = System.Windows.Forms.TickStyle.None;
//
// tbRecorder
//
this.tbRecorder.Location = new System.Drawing.Point(6, 90);
this.tbRecorder.Maximum = 65535;
this.tbRecorder.Name = "tbRecorder";
this.tbRecorder.Size = new System.Drawing.Size(155, 42);
this.tbRecorder.TabIndex = 50;
this.tbRecorder.TickStyle = System.Windows.Forms.TickStyle.None;
//
// cbRecorderLine
//
this.cbRecorderLine.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbRecorderLine.Location = new System.Drawing.Point(6, 63);
this.cbRecorderLine.Name = "cbRecorderLine";
this.cbRecorderLine.Size = new System.Drawing.Size(152, 21);
this.cbRecorderLine.TabIndex = 52;
//
// gbRecorder
//
this.gbRecorder.Controls.Add(this.cbRecorder);
this.gbRecorder.Controls.Add(this.cbRecorderLine);
this.gbRecorder.Controls.Add(this.label2);
this.gbRecorder.Controls.Add(this.tbRecorder);
this.gbRecorder.Location = new System.Drawing.Point(176, 111);
this.gbRecorder.Name = "gbRecorder";
this.gbRecorder.Size = new System.Drawing.Size(164, 140);
this.gbRecorder.TabIndex = 53;
this.gbRecorder.TabStop = false;
this.gbRecorder.Text = "Recorder";
//
// cbRecorder
//
this.cbRecorder.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbRecorder.Location = new System.Drawing.Point(6, 36);
this.cbRecorder.Name = "cbRecorder";
this.cbRecorder.Size = new System.Drawing.Size(152, 21);
this.cbRecorder.TabIndex = 11;
this.cbRecorder.SelectedIndexChanged += new System.EventHandler(this.cbRecorder_SelectedIndexChanged);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(3, 20);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(82, 13);
this.label2.TabIndex = 19;
this.label2.Text = "Select recorder:";
//
// gbDictophone
//
this.gbDictophone.Controls.Add(this.nudVolumeLevelScale);
this.gbDictophone.Controls.Add(this.label5);
this.gbDictophone.Controls.Add(this.nudSilentLevel);
this.gbDictophone.Controls.Add(this.label4);
this.gbDictophone.Controls.Add(this.cbSkipSilent);
this.gbDictophone.Controls.Add(this.nudBufferSizeInMs);
this.gbDictophone.Controls.Add(this.label1);
this.gbDictophone.Location = new System.Drawing.Point(6, 28);
this.gbDictophone.Name = "gbDictophone";
this.gbDictophone.Size = new System.Drawing.Size(334, 77);
this.gbDictophone.TabIndex = 54;
this.gbDictophone.TabStop = false;
this.gbDictophone.Text = "General";
//
// nudVolumeLevelScale
//
this.nudVolumeLevelScale.Location = new System.Drawing.Point(273, 49);
this.nudVolumeLevelScale.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.nudVolumeLevelScale.Name = "nudVolumeLevelScale";
this.nudVolumeLevelScale.Size = new System.Drawing.Size(52, 20);
this.nudVolumeLevelScale.TabIndex = 54;
this.nudVolumeLevelScale.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.nudVolumeLevelScale.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(173, 51);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(92, 13);
this.label5.TabIndex = 53;
this.label5.Text = "Volume scale in %";
//
// nudSilentLevel
//
this.nudSilentLevel.Increment = new decimal(new int[] {
100,
0,
0,
0});
this.nudSilentLevel.Location = new System.Drawing.Point(96, 23);
this.nudSilentLevel.Maximum = new decimal(new int[] {
32000,
0,
0,
0});
this.nudSilentLevel.Name = "nudSilentLevel";
this.nudSilentLevel.Size = new System.Drawing.Size(59, 20);
this.nudSilentLevel.TabIndex = 52;
this.nudSilentLevel.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.nudSilentLevel.Value = new decimal(new int[] {
10000,
0,
0,
0});
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(3, 25);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(58, 13);
this.label4.TabIndex = 51;
this.label4.Text = "Silent level";
//
// cbSkipSilent
//
this.cbSkipSilent.AutoSize = true;
this.cbSkipSilent.Location = new System.Drawing.Point(3, 46);
this.cbSkipSilent.Name = "cbSkipSilent";
this.cbSkipSilent.Size = new System.Drawing.Size(74, 17);
this.cbSkipSilent.TabIndex = 50;
this.cbSkipSilent.Text = "Skip silent";
this.cbSkipSilent.UseVisualStyleBackColor = true;
//
// nudBufferSizeInMs
//
this.nudBufferSizeInMs.Increment = new decimal(new int[] {
10,
0,
0,
0});
this.nudBufferSizeInMs.Location = new System.Drawing.Point(273, 23);
this.nudBufferSizeInMs.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.nudBufferSizeInMs.Minimum = new decimal(new int[] {
50,
0,
0,
0});
this.nudBufferSizeInMs.Name = "nudBufferSizeInMs";
this.nudBufferSizeInMs.Size = new System.Drawing.Size(52, 20);
this.nudBufferSizeInMs.TabIndex = 1;
this.nudBufferSizeInMs.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.nudBufferSizeInMs.Value = new decimal(new int[] {
500,
0,
0,
0});
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(173, 25);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(83, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Buffer size in ms";
//
// sfdAudio
//
this.sfdAudio.DefaultExt = "wav";
this.sfdAudio.Filter = "*.wav|*.wav|*.mp3|*.mp3";
//
// tbTimeline
//
this.tbTimeline.Location = new System.Drawing.Point(0, 257);
this.tbTimeline.Maximum = 65535;
this.tbTimeline.Name = "tbTimeline";
this.tbTimeline.Size = new System.Drawing.Size(347, 42);
this.tbTimeline.TabIndex = 55;
this.tbTimeline.TickStyle = System.Windows.Forms.TickStyle.None;
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(347, 324);
this.Controls.Add(this.tbTimeline);
this.Controls.Add(this.gbDictophone);
this.Controls.Add(this.gbRecorder);
this.Controls.Add(this.gbPlayer);
this.Controls.Add(this.ssMain);
this.Controls.Add(this.tsMain);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MainForm";
this.Text = "Dictophone";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainForm_FormClosed);
this.tsMain.ResumeLayout(false);
this.tsMain.PerformLayout();
this.ssMain.ResumeLayout(false);
this.ssMain.PerformLayout();
this.gbPlayer.ResumeLayout(false);
this.gbPlayer.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.tbPlayer)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tbRecorder)).EndInit();
this.gbRecorder.ResumeLayout(false);
this.gbRecorder.PerformLayout();
this.gbDictophone.ResumeLayout(false);
this.gbDictophone.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nudVolumeLevelScale)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudSilentLevel)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudBufferSizeInMs)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tbTimeline)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStrip tsMain;
private System.Windows.Forms.ToolStripButton tsbOpen;
private System.Windows.Forms.ToolStripButton tsbRecord;
private System.Windows.Forms.ToolStripButton tsbPlay;
private System.Windows.Forms.ToolStripButton tsbNew;
private System.Windows.Forms.ToolStripButton tsbPause;
private System.Windows.Forms.StatusStrip ssMain;
private System.Windows.Forms.ToolStripStatusLabel tsslStatus;
private System.Windows.Forms.ToolStripProgressBar tspProgress;
private System.Windows.Forms.ToolStripButton tsbStop;
private System.Windows.Forms.ToolStripButton tsbForward;
private System.Windows.Forms.ToolStripButton tsbBackward;
private System.Windows.Forms.ToolStripButton tsbPlayFrom;
private System.Windows.Forms.ToolStripTextBox tstStep;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripTextBox tstTime;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripButton tsbClose;
private System.Windows.Forms.OpenFileDialog ofdAudio;
private System.Windows.Forms.ToolStripStatusLabel tsslPosition;
private System.Windows.Forms.GroupBox gbPlayer;
private System.Windows.Forms.ComboBox cbPlayer;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TrackBar tbPlayer;
private System.Windows.Forms.CheckBox cbMute;
private System.Windows.Forms.TrackBar tbRecorder;
private System.Windows.Forms.ComboBox cbRecorderLine;
private System.Windows.Forms.GroupBox gbRecorder;
private System.Windows.Forms.ComboBox cbRecorder;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.GroupBox gbDictophone;
private System.Windows.Forms.NumericUpDown nudBufferSizeInMs;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.CheckBox cbSkipSilent;
private System.Windows.Forms.NumericUpDown nudSilentLevel;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.NumericUpDown nudVolumeLevelScale;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.ToolStripButton tsbRecordFrom;
private System.Windows.Forms.SaveFileDialog sfdAudio;
private System.Windows.Forms.TrackBar tbTimeline;
}
}
| |
#region MIT license
//
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq.Expressions;
using System.Linq;
using System.Collections.ObjectModel;
using DbLinq.Data.Linq.Sugar;
using DbLinq.Data.Linq.Sugar.ExpressionMutator;
using DbLinq.Data.Linq.Sugar.Expressions;
namespace DbLinq.Data.Linq.Sugar.Expressions
{
/// <summary>
/// Holds new expression types (sql related), all well as their operands
/// </summary>
[DebuggerDisplay("SpecialExpression {SpecialNodeType}")]
#if !MONO_STRICT
public
#endif
class SpecialExpression : OperandsMutableExpression, IExecutableExpression
{
public SpecialExpressionType SpecialNodeType { get { return (SpecialExpressionType)NodeType; } }
protected static Type GetSpecialExpressionTypeType(SpecialExpressionType specialExpressionType, IList<Expression> operands)
{
Type defaultType;
if (operands.Count > 0)
defaultType = operands[0].Type;
else
defaultType = null;
switch (specialExpressionType) // SETuse
{
case SpecialExpressionType.IsNull:
case SpecialExpressionType.IsNotNull:
return typeof(bool);
case SpecialExpressionType.Concat:
return typeof(string);
case SpecialExpressionType.Count:
return typeof(int);
case SpecialExpressionType.Exists:
return typeof(bool);
case SpecialExpressionType.Like:
return typeof(bool);
case SpecialExpressionType.Min:
case SpecialExpressionType.Max:
case SpecialExpressionType.Sum:
return defaultType; // for such methods, the type is related to the operands type
case SpecialExpressionType.Average:
return typeof(double);
case SpecialExpressionType.StringLength:
return typeof(int);
case SpecialExpressionType.ToUpper:
case SpecialExpressionType.ToLower:
return typeof(string);
case SpecialExpressionType.In:
return typeof(bool);
case SpecialExpressionType.Substring:
return defaultType;
case SpecialExpressionType.Trim:
case SpecialExpressionType.LTrim:
case SpecialExpressionType.RTrim:
return typeof(string);
case SpecialExpressionType.StringInsert:
return typeof(string);
case SpecialExpressionType.Replace:
return typeof(string);
case SpecialExpressionType.Remove:
return typeof(string);
case SpecialExpressionType.IndexOf:
return typeof(int);
case SpecialExpressionType.Year:
case SpecialExpressionType.Month:
case SpecialExpressionType.Day:
case SpecialExpressionType.Hour:
case SpecialExpressionType.Second:
case SpecialExpressionType.Minute:
case SpecialExpressionType.Millisecond:
return typeof(int);
case SpecialExpressionType.Now:
case SpecialExpressionType.Date:
return typeof(DateTime);
case SpecialExpressionType.DateDiffInMilliseconds:
return typeof(long);
case SpecialExpressionType.Abs:
case SpecialExpressionType.Exp:
case SpecialExpressionType.Floor:
case SpecialExpressionType.Ln:
case SpecialExpressionType.Log:
case SpecialExpressionType.Pow:
case SpecialExpressionType.Round:
case SpecialExpressionType.Sign:
case SpecialExpressionType.Sqrt:
return defaultType;
default:
throw Error.BadArgument("S0058: Unknown SpecialExpressionType value {0}", specialExpressionType);
}
}
public SpecialExpression(SpecialExpressionType expressionType, params Expression[] operands)
: base((ExpressionType)expressionType, GetSpecialExpressionTypeType(expressionType, operands), operands)
{
}
public SpecialExpression(SpecialExpressionType expressionType, IList<Expression> operands)
: base((ExpressionType)expressionType, GetSpecialExpressionTypeType(expressionType, operands), operands)
{
}
protected override Expression Mutate2(IList<Expression> newOperands)
{
return new SpecialExpression((SpecialExpressionType)NodeType, newOperands);
}
public object Execute()
{
switch (SpecialNodeType) // SETuse
{
case SpecialExpressionType.IsNull:
return operands[0].Evaluate() == null;
case SpecialExpressionType.IsNotNull:
return operands[0].Evaluate() != null;
case SpecialExpressionType.Concat:
{
var values = new List<string>();
foreach (var operand in operands)
{
var value = operand.Evaluate();
if (value != null)
values.Add(System.Convert.ToString(value, CultureInfo.InvariantCulture));
else
values.Add(null);
}
return string.Concat(values.ToArray());
}
case SpecialExpressionType.Count:
{
var value = operands[0].Evaluate();
// TODO: string is IEnumerable. See what we do here
if (value is IEnumerable)
{
int count = 0;
foreach (var dontCare in (IEnumerable)value)
count++;
return count;
}
// TODO: by default, shall we answer 1 or throw an exception?
return 1;
}
case SpecialExpressionType.Exists:
{
var value = operands[0].Evaluate();
// TODO: string is IEnumerable. See what we do here
if (value is IEnumerable)
{
return true;
}
// TODO: by default, shall we answer 1 or throw an exception?
return false;
}
case SpecialExpressionType.Min:
{
decimal? min = null;
foreach (var operand in operands)
{
var value = System.Convert.ToDecimal(operand.Evaluate());
if (!min.HasValue || value < min.Value)
min = value;
}
return System.Convert.ChangeType(min.Value, operands[0].Type);
}
case SpecialExpressionType.Max:
{
decimal? max = null;
foreach (var operand in operands)
{
var value = System.Convert.ToDecimal(operand.Evaluate());
if (!max.HasValue || value > max.Value)
max = value;
}
return System.Convert.ChangeType(max.Value, operands[0].Type);
}
case SpecialExpressionType.Sum:
{
decimal sum = operands.Select(op => System.Convert.ToDecimal(op.Evaluate())).Sum();
return System.Convert.ChangeType(sum, operands.First().Type);
}
case SpecialExpressionType.Average:
{
decimal sum = 0;
foreach (var operand in operands)
sum += System.Convert.ToDecimal(operand.Evaluate());
return sum / operands.Count;
}
case SpecialExpressionType.StringLength:
return operands[0].Evaluate().ToString().Length;
case SpecialExpressionType.ToUpper:
return operands[0].Evaluate().ToString().ToUpper();
case SpecialExpressionType.ToLower:
return operands[0].Evaluate().ToString().ToLower();
case SpecialExpressionType.Substring:
return EvaluateStandardCallInvoke("SubString", operands);
case SpecialExpressionType.In:
throw new NotImplementedException();
case SpecialExpressionType.Replace:
return EvaluateStandardCallInvoke("Replace", operands);
case SpecialExpressionType.Remove:
return EvaluateStandardCallInvoke("Remove", operands);
case SpecialExpressionType.IndexOf:
return EvaluateStandardCallInvoke("IndexOf", operands);
case SpecialExpressionType.Year:
return ((DateTime)operands[0].Evaluate()).Year;
case SpecialExpressionType.Month:
return ((DateTime)operands[0].Evaluate()).Month;
case SpecialExpressionType.Day:
return ((DateTime)operands[0].Evaluate()).Day;
case SpecialExpressionType.Hour:
return ((DateTime)operands[0].Evaluate()).Hour;
case SpecialExpressionType.Minute:
return ((DateTime)operands[0].Evaluate()).Minute;
case SpecialExpressionType.Second:
return ((DateTime)operands[0].Evaluate()).Second;
case SpecialExpressionType.Millisecond:
return ((DateTime)operands[0].Evaluate()).Millisecond;
case SpecialExpressionType.Now:
return DateTime.Now;
case SpecialExpressionType.Date:
return ((DateTime)operands[0].Evaluate());
case SpecialExpressionType.DateDiffInMilliseconds:
return ((DateTime)operands[0].Evaluate()) - ((DateTime)operands[1].Evaluate());
case SpecialExpressionType.Abs:
case SpecialExpressionType.Exp:
case SpecialExpressionType.Floor:
case SpecialExpressionType.Ln:
case SpecialExpressionType.Log:
case SpecialExpressionType.Pow:
case SpecialExpressionType.Round:
case SpecialExpressionType.Sign:
case SpecialExpressionType.Sqrt:
return EvaluateMathCallInvoke(SpecialNodeType, operands);
default:
throw Error.BadArgument("S0116: Unknown SpecialExpressionType ({0})", SpecialNodeType);
}
}
private object EvaluateMathCallInvoke(SpecialExpressionType SpecialNodeType, ReadOnlyCollection<Expression> operands)
{
return typeof(Math).GetMethod(SpecialNodeType.ToString(), operands.Skip(1).Select(op => op.Type).ToArray())
.Invoke(null, operands.Skip(1).Select(op => op.Evaluate()).ToArray());
}
protected object EvaluateStatardMemberAccess(string propertyName, ReadOnlyCollection<Expression> operands)
{
return operands[0].Type.GetProperty(propertyName).GetValue(operands.First().Evaluate(), null);
}
protected object EvaluateStandardCallInvoke(string methodName, ReadOnlyCollection<Expression> operands)
{
return operands[0].Type.GetMethod(methodName,
operands.Skip(1).Select(op => op.Type).ToArray())
.Invoke(operands[0].Evaluate(),
operands.Skip(1).Select(op => op.Evaluate()).ToArray());
}
}
}
| |
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 SiaqodbCloudService.Areas.HelpPage.ModelDescriptions;
using SiaqodbCloudService.Areas.HelpPage.Models;
namespace SiaqodbCloudService.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);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using Xunit;
namespace System.Reflection.Tests
{
public static partial class ModuleTests
{
[Fact]
public static void ModuleAssembly()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage);
Module m = a.ManifestModule;
Assert.Equal(a, m.Assembly);
}
}
[Fact]
public static void ModuleMvid()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage);
Module m = a.ManifestModule;
Guid mvid = m.ModuleVersionId;
Assert.Equal(TestData.s_SimpleAssemblyMvid, mvid);
}
}
[Fact]
public static void ModuleMetadataToken()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage);
Module m = a.ManifestModule;
Assert.Equal(0x00000001, m.MetadataToken);
}
}
[Fact]
public static void ModuleIsResource()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage);
Module m = a.ManifestModule;
Assert.False(m.IsResource());
}
}
[Fact]
public static void ModuleFullyQualifiedNameFromPath()
{
using (TempFile tf = TempFile.Create(TestData.s_SimpleAssemblyImage))
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
string path = tf.Path;
Assembly a = lc.LoadFromAssemblyPath(path);
Module m = a.ManifestModule;
Assert.Equal(path, m.FullyQualifiedName);
}
}
[Fact]
public static void ModuleFullyQualifiedNameFromByteArray()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage);
Module m = a.ManifestModule;
Assert.Equal(string.Empty, m.FullyQualifiedName);
}
}
[Fact]
public static void ModuleGetNameFromPath()
{
using (TempFile tf = TempFile.Create(TestData.s_SimpleAssemblyImage))
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
string path = tf.Path;
Assembly a = lc.LoadFromAssemblyPath(path);
Module m = a.ManifestModule;
string name = Path.GetFileName(path);
Assert.Equal(name, m.Name);
}
}
[Fact]
public static void ModuleGetNameFromByteArray()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage);
Module m = a.ManifestModule;
Assert.Equal(string.Empty, m.Name);
}
}
[Fact]
public static void ModuleScopeNameFromPath()
{
using (TempFile tf = TempFile.Create(TestData.s_SimpleAssemblyImage))
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
string path = tf.Path;
Assembly a = lc.LoadFromAssemblyPath(path);
Module m = a.ManifestModule;
Assert.Equal("SimpleAssembly.dll", m.ScopeName);
}
}
[Fact]
public static void ModuleScopeNameFromByteArray()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage);
Module m = a.ManifestModule;
Assert.Equal("SimpleAssembly.dll", m.ScopeName);
}
}
[Fact]
public static void GetPEKindAnyCpu()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_PlatformAnyCpu);
Module m = a.ManifestModule;
m.GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine);
Assert.Equal(PortableExecutableKinds.ILOnly, peKind);
Assert.Equal(ImageFileMachine.I386, machine);
AssemblyName an = a.GetName(copiedName: false);
ProcessorArchitecture pa = an.ProcessorArchitecture;
Assert.Equal(ProcessorArchitecture.MSIL, pa);
}
}
[Fact]
public static void GetPEKindAnyCpu32BitPreferred()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_PlatformAnyCpu32BitPreferred);
Module m = a.ManifestModule;
m.GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine);
Assert.Equal(PortableExecutableKinds.ILOnly | PortableExecutableKinds.Preferred32Bit, peKind);
Assert.Equal(ImageFileMachine.I386, machine);
AssemblyName an = a.GetName(copiedName: false);
ProcessorArchitecture pa = an.ProcessorArchitecture;
Assert.Equal(ProcessorArchitecture.MSIL, pa);
}
}
[Fact]
public static void GetPEKindX86()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_PlatformX86);
Module m = a.ManifestModule;
m.GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine);
Assert.Equal(PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit, peKind);
Assert.Equal(ImageFileMachine.I386, machine);
AssemblyName an = a.GetName(copiedName: false);
ProcessorArchitecture pa = an.ProcessorArchitecture;
Assert.Equal(ProcessorArchitecture.X86, pa);
}
}
[Fact]
public static void GetPEKindX64()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_PlatformX64);
Module m = a.ManifestModule;
m.GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine);
Assert.Equal(PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus, peKind);
Assert.Equal(ImageFileMachine.AMD64, machine);
AssemblyName an = a.GetName(copiedName: false);
ProcessorArchitecture pa = an.ProcessorArchitecture;
Assert.Equal(ProcessorArchitecture.Amd64, pa);
}
}
[Fact]
public static void GetPEKindItanium()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_PlatformItanium);
Module m = a.ManifestModule;
m.GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine);
Assert.Equal(PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus, peKind);
Assert.Equal(ImageFileMachine.IA64, machine);
AssemblyName an = a.GetName(copiedName: false);
ProcessorArchitecture pa = an.ProcessorArchitecture;
Assert.Equal(ProcessorArchitecture.IA64, pa);
}
}
[Fact]
public static void GetPEKindArm()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly a = lc.LoadFromByteArray(TestData.s_PlatformArm);
Module m = a.ManifestModule;
m.GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine);
Assert.Equal(PortableExecutableKinds.ILOnly, peKind);
Assert.Equal(ImageFileMachine.ARM, machine);
AssemblyName an = a.GetName(copiedName: false);
ProcessorArchitecture pa = an.ProcessorArchitecture;
Assert.Equal(ProcessorArchitecture.Arm, pa);
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/8/2010 10:01:52 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Drawing;
namespace DotSpatial.Data
{
/// <summary>
/// TiledImage is a special kind of image coverage where the images specifically form tiles that
/// are adjacent and perfectly aligned to represent a larger image.
/// </summary>
public class TiledImage : RasterBoundDataSet, ITiledImage, IImageData
{
#region Private Variables
private string _fileName;
private int _numBands;
private int _stride;
private TileCollection _tiles;
private WorldFile _worldFile;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of the TiledImage where the fileName is specified.
/// This doesn't actually open the file until the Open method is called.
/// </summary>
/// <param name="fileName"></param>
public TiledImage(string fileName)
{
_fileName = fileName;
}
/// <summary>
/// Creates a new instance of TiledImage
/// </summary>
public TiledImage(int width, int height)
{
Init(width, height);
}
#endregion
#region Methods
/// <summary>
/// Gets or sets the array of tiles used for this
/// </summary>
public virtual IImageData[,] Tiles
{
get { return _tiles.Tiles; }
set { _tiles.Tiles = value; }
}
/// <summary>
///
/// </summary>
protected TileCollection TileCollection
{
get { return _tiles; }
set { _tiles = value; }
}
#region IImageData Members
/// <summary>
/// This should be overridden with custom file handling
/// </summary>
public virtual void Open()
{
}
#endregion
#region ITiledImage Members
/// <inheritdoc />
public virtual Bitmap GetBitmap(Extent envelope, Size pixelSize)
{
Bitmap result = new Bitmap(pixelSize.Width, pixelSize.Height);
Graphics g = Graphics.FromImage(result);
foreach (var image in GetImages())
{
Extent bounds = envelope.Intersection(image.Extent);
Size ps = new Size((int)(pixelSize.Width * bounds.Width / envelope.Width),
(int)(pixelSize.Height * bounds.Height / envelope.Height));
int x = pixelSize.Width * (int)((bounds.X - envelope.X) / envelope.Width);
int y = pixelSize.Height * (int)((envelope.Y - bounds.Y) / envelope.Height);
if (ps.Width > 0 && ps.Height > 0)
{
Bitmap tile = image.GetBitmap(bounds, ps);
g.DrawImageUnscaled(tile, x, y);
}
}
return result;
}
/// <inheritdoc />
public override void Close()
{
if (Tiles == null) return;
foreach (IImageData image in Tiles)
{
if (image != null) image.Close();
}
base.Close();
}
#endregion
/// <summary>
/// Even if this TiledImage has already been constructed, we can initialize the tile collection later.
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
public void Init(int width, int height)
{
_tiles = new TileCollection(width, height);
TypeName = "TileImage";
SpaceTimeSupport = SpaceTimeSupport.Spatial;
}
/// <summary>
/// Calls a method that calculates the proper image bounds for each of the extents of the tiles,
/// given the affine coefficients for the whole image.
/// </summary>
/// <param name="affine"> x' = A + Bx + Cy; y' = D + Ex + Fy</param>
public void SetTileBounds(double[] affine)
{
_tiles.SetTileBounds(affine);
}
#endregion
#region Properties
/// <inheritdoc />
public string Filename
{
get { return _fileName; }
set { _fileName = value; }
}
/// <inheritdoc />
public int Height
{
get
{
return _tiles.Height;
}
set
{
}
}
/// <inheritdoc />
public int Stride
{
get { return _stride; }
set { _stride = value; }
}
/// <inheritdoc />
public int Width
{
get
{
return _tiles.Width;
}
set
{
}
}
#endregion
#region IImageData Members
/// <summary>
/// Gets or sets the number of bands
/// </summary>
public int NumBands
{
get { return _numBands; }
set { _numBands = value; }
}
/// <inheritdoc />
public int BytesPerPixel
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
/// <inheritdoc />
public void CopyValues(IImageData source)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public Bitmap GetBitmap()
{
throw new NotImplementedException();
}
/// <inheritdoc />
public Bitmap GetBitmap(Extent envelope, Rectangle window)
{
return GetBitmap(envelope, new Size(window.Width, window.Height));
}
/// <inheritdoc />
public Color GetColor(int row, int column)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void CopyBitmapToValues()
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void Save()
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void SaveAs(string fileName)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void SetColor(int row, int column, Color col)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void CopyValuesToBitmap()
{
throw new NotImplementedException();
}
/// <inheritdoc />
public byte[] Values
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
/// <summary>
/// Not Implemented
/// </summary>
/// <param name="image"></param>
public void SetBitmap(Bitmap image)
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented.
/// </summary>
/// <returns></returns>
public IEnumerable<Color> GetColorPalette()
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
/// <param name="value"></param>
public void SetColorPalette(IEnumerable<Color> value)
{
throw new NotImplementedException();
}
/// <summary>
/// Not implemented
/// </summary>
/// <param name="xOffset"></param>
/// <param name="yOffset"></param>
/// <param name="xSize"></param>
/// <param name="ySize"></param>
/// <returns></returns>
public Bitmap ReadBlock(int xOffset, int yOffset, int xSize, int ySize)
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
/// <param name="value"></param>
/// <param name="xOffset"></param>
/// <param name="yOffset"></param>
public void WriteBlock(Bitmap value, int xOffset, int yOffset)
{
throw new NotImplementedException();
}
/// <summary>
/// Not implemented
/// </summary>
public void UpdateOverviews()
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
public ImageBandType BandType
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
#region ITiledImage Members
/// <inheritdoc />
public int TileWidth
{
get { return _tiles.TileWidth; }
}
/// <inheritdoc />
public int TileHeight
{
get { return _tiles.TileHeight; }
}
/// <inheritdoc />
public int Count
{
get { return _tiles.NumTiles; }
}
/// <inheritdoc />
public override Extent Extent
{
get
{
Extent ext = new Extent();
foreach (IImageData image in _tiles)
{
ext.ExpandToInclude(image.Extent);
}
return ext;
}
}
/// <inheritdoc />
public IEnumerable<IImageData> GetImages()
{
return _tiles;
}
/// <summary>
/// Gets or sets the WorldFile for this set of tiles.
/// </summary>
public WorldFile WorldFile
{
get { return _worldFile; }
set { _worldFile = value; }
}
#endregion
/// <inheritdoc />
protected override void Dispose(bool disposeManagedResources)
{
foreach (IImageData tile in _tiles)
{
tile.Dispose();
}
base.Dispose(disposeManagedResources);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Security
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security.Tokens;
using System.Text;
using System.Xml;
using HexBinary = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary;
using KeyIdentifierClauseEntry = WSSecurityTokenSerializer.KeyIdentifierClauseEntry;
using StrEntry = WSSecurityTokenSerializer.StrEntry;
using TokenEntry = WSSecurityTokenSerializer.TokenEntry;
class WSSecurityJan2004 : WSSecurityTokenSerializer.SerializerEntries
{
WSSecurityTokenSerializer tokenSerializer;
SamlSerializer samlSerializer;
public WSSecurityJan2004(WSSecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
{
this.tokenSerializer = tokenSerializer;
this.samlSerializer = samlSerializer;
}
public WSSecurityTokenSerializer WSSecurityTokenSerializer
{
get { return this.tokenSerializer; }
}
public SamlSerializer SamlSerializer
{
get { return this.samlSerializer; }
}
protected void PopulateJan2004TokenEntries(IList<TokenEntry> tokenEntryList)
{
tokenEntryList.Add(new GenericXmlTokenEntry());
tokenEntryList.Add(new UserNamePasswordTokenEntry(this.tokenSerializer));
tokenEntryList.Add(new KerberosTokenEntry(this.tokenSerializer));
tokenEntryList.Add(new X509TokenEntry(this.tokenSerializer));
}
public override void PopulateTokenEntries(IList<TokenEntry> tokenEntryList)
{
PopulateJan2004TokenEntries(tokenEntryList);
tokenEntryList.Add(new SamlTokenEntry(this.tokenSerializer, this.samlSerializer));
tokenEntryList.Add(new WrappedKeyTokenEntry(this.tokenSerializer));
}
internal abstract class BinaryTokenEntry : TokenEntry
{
internal static readonly XmlDictionaryString ElementName = XD.SecurityJan2004Dictionary.BinarySecurityToken;
internal static readonly XmlDictionaryString EncodingTypeAttribute = XD.SecurityJan2004Dictionary.EncodingType;
internal const string EncodingTypeAttributeString = SecurityJan2004Strings.EncodingType;
internal const string EncodingTypeValueBase64Binary = SecurityJan2004Strings.EncodingTypeValueBase64Binary;
internal const string EncodingTypeValueHexBinary = SecurityJan2004Strings.EncodingTypeValueHexBinary;
internal static readonly XmlDictionaryString ValueTypeAttribute = XD.SecurityJan2004Dictionary.ValueType;
WSSecurityTokenSerializer tokenSerializer;
string[] valueTypeUris = null;
protected BinaryTokenEntry(WSSecurityTokenSerializer tokenSerializer, string valueTypeUri)
{
this.tokenSerializer = tokenSerializer;
this.valueTypeUris = new string[1];
this.valueTypeUris[0] = valueTypeUri;
}
protected BinaryTokenEntry(WSSecurityTokenSerializer tokenSerializer, string[] valueTypeUris)
{
if (valueTypeUris == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("valueTypeUris");
this.tokenSerializer = tokenSerializer;
this.valueTypeUris = new string[valueTypeUris.GetLength(0)];
for (int i = 0; i < this.valueTypeUris.GetLength(0); ++i)
this.valueTypeUris[i] = valueTypeUris[i];
}
protected override XmlDictionaryString LocalName { get { return ElementName; } }
protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.Namespace; } }
public override string TokenTypeUri { get { return this.valueTypeUris[0]; } }
protected override string ValueTypeUri { get { return this.valueTypeUris[0]; } }
public override bool SupportsTokenTypeUri(string tokenTypeUri)
{
for (int i = 0; i < this.valueTypeUris.GetLength(0); ++i)
{
if (this.valueTypeUris[i] == tokenTypeUri)
return true;
}
return false;
}
public abstract SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromBinaryCore(byte[] rawData);
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml,
SecurityTokenReferenceStyle tokenReferenceStyle)
{
TokenReferenceStyleHelper.Validate(tokenReferenceStyle);
switch (tokenReferenceStyle)
{
case SecurityTokenReferenceStyle.Internal:
return CreateDirectReference(issuedTokenXml, UtilityStrings.IdAttribute, UtilityStrings.Namespace, this.TokenType);
case SecurityTokenReferenceStyle.External:
string encoding = issuedTokenXml.GetAttribute(EncodingTypeAttributeString, null);
string encodedData = issuedTokenXml.InnerText;
byte[] binaryData;
if (encoding == null || encoding == EncodingTypeValueBase64Binary)
{
binaryData = Convert.FromBase64String(encodedData);
}
else if (encoding == EncodingTypeValueHexBinary)
{
binaryData = HexBinary.Parse(encodedData).Value;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.UnknownEncodingInBinarySecurityToken)));
}
return CreateKeyIdentifierClauseFromBinaryCore(binaryData);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenReferenceStyle"));
}
}
public abstract SecurityToken ReadBinaryCore(string id, string valueTypeUri, byte[] rawData);
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
{
string wsuId = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
string valueTypeUri = reader.GetAttribute(ValueTypeAttribute, null);
string encoding = reader.GetAttribute(EncodingTypeAttribute, null);
byte[] binaryData;
if (encoding == null || encoding == EncodingTypeValueBase64Binary)
{
binaryData = reader.ReadElementContentAsBase64();
}
else if (encoding == EncodingTypeValueHexBinary)
{
binaryData = HexBinary.Parse(reader.ReadElementContentAsString()).Value;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.UnknownEncodingInBinarySecurityToken)));
}
return ReadBinaryCore(wsuId, valueTypeUri, binaryData);
}
public abstract void WriteBinaryCore(SecurityToken token, out string id, out byte[] rawData);
public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
{
string id;
byte[] rawData;
WriteBinaryCore(token, out id, out rawData);
if (rawData == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rawData");
}
writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, ElementName, XD.SecurityJan2004Dictionary.Namespace);
if (id != null)
{
writer.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace, id);
}
if (valueTypeUris != null)
{
writer.WriteAttributeString(ValueTypeAttribute, null, this.valueTypeUris[0]);
}
if (this.tokenSerializer.EmitBspRequiredAttributes)
{
writer.WriteAttributeString(EncodingTypeAttribute, null, EncodingTypeValueBase64Binary);
}
writer.WriteBase64(rawData, 0, rawData.Length);
writer.WriteEndElement(); // BinarySecurityToken
}
}
class GenericXmlTokenEntry : TokenEntry
{
protected override XmlDictionaryString LocalName { get { return null; } }
protected override XmlDictionaryString NamespaceUri { get { return null; } }
protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(GenericXmlSecurityToken) }; }
public override string TokenTypeUri { get { return null; } }
protected override string ValueTypeUri { get { return null; } }
public GenericXmlTokenEntry()
{
}
public override bool CanReadTokenCore(XmlElement element)
{
return false;
}
public override bool CanReadTokenCore(XmlDictionaryReader reader)
{
return false;
}
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml,
SecurityTokenReferenceStyle tokenReferenceStyle)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
{
BufferedGenericXmlSecurityToken bufferedXmlToken = token as BufferedGenericXmlSecurityToken;
if (bufferedXmlToken != null && bufferedXmlToken.TokenXmlBuffer != null)
{
using (XmlDictionaryReader reader = bufferedXmlToken.TokenXmlBuffer.GetReader(0))
{
writer.WriteNode(reader, false);
}
}
else
{
GenericXmlSecurityToken xmlToken = (GenericXmlSecurityToken)token;
xmlToken.TokenXml.WriteTo(writer);
}
}
}
class KerberosTokenEntry : BinaryTokenEntry
{
public KerberosTokenEntry(WSSecurityTokenSerializer tokenSerializer)
: base(tokenSerializer, new string[] { SecurityJan2004Strings.KerberosTokenTypeGSS, SecurityJan2004Strings.KerberosTokenType1510 })
{
}
protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(KerberosReceiverSecurityToken), typeof(KerberosRequestorSecurityToken) }; }
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromBinaryCore(byte[] rawData)
{
byte[] tokenHash;
using (HashAlgorithm hasher = CryptoHelper.NewSha1HashAlgorithm())
{
tokenHash = hasher.ComputeHash(rawData, 0, rawData.Length);
}
return new KerberosTicketHashKeyIdentifierClause(tokenHash);
}
public override SecurityToken ReadBinaryCore(string id, string valueTypeUri, byte[] rawData)
{
return new KerberosReceiverSecurityToken(rawData, id, false, valueTypeUri);
}
public override void WriteBinaryCore(SecurityToken token, out string id, out byte[] rawData)
{
KerberosRequestorSecurityToken kerbToken = (KerberosRequestorSecurityToken)token;
id = token.Id;
rawData = kerbToken.GetRequest();
}
}
protected class SamlTokenEntry : TokenEntry
{
const string samlAssertionId = "AssertionID";
SamlSerializer samlSerializer;
SecurityTokenSerializer tokenSerializer;
public SamlTokenEntry(SecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
{
this.tokenSerializer = tokenSerializer;
if (samlSerializer != null)
{
this.samlSerializer = samlSerializer;
}
else
{
this.samlSerializer = new SamlSerializer();
}
this.samlSerializer.PopulateDictionary(BinaryMessageEncoderFactory.XmlDictionary);
}
protected override XmlDictionaryString LocalName { get { return XD.SecurityJan2004Dictionary.SamlAssertion; } }
protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.SamlUri; } }
protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(SamlSecurityToken) }; }
public override string TokenTypeUri { get { return null; } }
protected override string ValueTypeUri { get { return null; } }
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml,
SecurityTokenReferenceStyle tokenReferenceStyle)
{
TokenReferenceStyleHelper.Validate(tokenReferenceStyle);
switch (tokenReferenceStyle)
{
// SAML uses same reference for internal and external
case SecurityTokenReferenceStyle.Internal:
case SecurityTokenReferenceStyle.External:
string assertionId = issuedTokenXml.GetAttribute(samlAssertionId);
return new SamlAssertionKeyIdentifierClause(assertionId);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenReferenceStyle"));
}
}
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
{
SamlSecurityToken samlToken = this.samlSerializer.ReadToken(reader, this.tokenSerializer, tokenResolver);
return samlToken;
}
public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
{
SamlSecurityToken samlToken = token as SamlSecurityToken;
this.samlSerializer.WriteToken(samlToken, writer, this.tokenSerializer);
}
}
class UserNamePasswordTokenEntry : TokenEntry
{
WSSecurityTokenSerializer tokenSerializer;
public UserNamePasswordTokenEntry(WSSecurityTokenSerializer tokenSerializer)
{
this.tokenSerializer = tokenSerializer;
}
protected override XmlDictionaryString LocalName { get { return XD.SecurityJan2004Dictionary.UserNameTokenElement; } }
protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.Namespace; } }
protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(UserNameSecurityToken) }; }
public override string TokenTypeUri { get { return SecurityJan2004Strings.UPTokenType; } }
protected override string ValueTypeUri { get { return null; } }
public override IAsyncResult BeginReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver, AsyncCallback callback, object state)
{
string id;
string userName;
string password;
ParseToken(reader, out id, out userName, out password);
SecurityToken token = new UserNameSecurityToken(userName, password, id);
return new CompletedAsyncResult<SecurityToken>(token, callback, state);
}
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml,
SecurityTokenReferenceStyle tokenReferenceStyle)
{
TokenReferenceStyleHelper.Validate(tokenReferenceStyle);
switch (tokenReferenceStyle)
{
case SecurityTokenReferenceStyle.Internal:
return CreateDirectReference(issuedTokenXml, UtilityStrings.IdAttribute, UtilityStrings.Namespace, typeof(UserNameSecurityToken));
case SecurityTokenReferenceStyle.External:
// UP tokens aren't referred to externally
return null;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenReferenceStyle"));
}
}
public override SecurityToken EndReadTokenCore(IAsyncResult result)
{
return CompletedAsyncResult<SecurityToken>.End(result);
}
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
{
string id;
string userName;
string password;
ParseToken(reader, out id, out userName, out password);
if (id == null)
id = SecurityUniqueId.Create().Value;
return new UserNameSecurityToken(userName, password, id);
}
public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
{
UserNameSecurityToken upToken = (UserNameSecurityToken)token;
WriteUserNamePassword(writer, upToken.Id, upToken.UserName, upToken.Password);
}
void WriteUserNamePassword(XmlDictionaryWriter writer, string id, string userName, string password)
{
writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.UserNameTokenElement,
XD.SecurityJan2004Dictionary.Namespace); // <wsse:UsernameToken
writer.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute,
XD.UtilityDictionary.Namespace, id); // wsu:Id="..."
writer.WriteElementString(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.UserNameElement,
XD.SecurityJan2004Dictionary.Namespace, userName); // ><wsse:Username>...</wsse:Username>
if (password != null)
{
writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.PasswordElement,
XD.SecurityJan2004Dictionary.Namespace);
if (this.tokenSerializer.EmitBspRequiredAttributes)
{
writer.WriteAttributeString(XD.SecurityJan2004Dictionary.TypeAttribute, null, SecurityJan2004Strings.UPTokenPasswordTextValue);
}
writer.WriteString(password); // <wsse:Password>...</wsse:Password>
writer.WriteEndElement();
}
writer.WriteEndElement(); // </wsse:UsernameToken>
}
static string ParsePassword(XmlDictionaryReader reader)
{
string type = reader.GetAttribute(XD.SecurityJan2004Dictionary.TypeAttribute, null);
if (type != null && type.Length > 0 && type != SecurityJan2004Strings.UPTokenPasswordTextValue)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedPasswordType, type)));
}
return reader.ReadElementString();
}
static void ParseToken(XmlDictionaryReader reader, out string id, out string userName, out string password)
{
id = null;
userName = null;
password = null;
reader.MoveToContent();
id = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
reader.ReadStartElement(XD.SecurityJan2004Dictionary.UserNameTokenElement, XD.SecurityJan2004Dictionary.Namespace);
while (reader.IsStartElement())
{
if (reader.IsStartElement(XD.SecurityJan2004Dictionary.UserNameElement, XD.SecurityJan2004Dictionary.Namespace))
{
userName = reader.ReadElementString();
}
else if (reader.IsStartElement(XD.SecurityJan2004Dictionary.PasswordElement, XD.SecurityJan2004Dictionary.Namespace))
{
password = ParsePassword(reader);
}
else if (reader.IsStartElement(XD.SecurityJan2004Dictionary.NonceElement, XD.SecurityJan2004Dictionary.Namespace))
{
// Nonce can be safely ignored
reader.Skip();
}
else if (reader.IsStartElement(XD.UtilityDictionary.CreatedElement, XD.UtilityDictionary.Namespace))
{
// wsu:Created can be safely ignored
reader.Skip();
}
else
{
XmlHelper.OnUnexpectedChildNodeError(SecurityJan2004Strings.UserNameTokenElement, reader);
}
}
reader.ReadEndElement();
if (userName == null)
XmlHelper.OnRequiredElementMissing(SecurityJan2004Strings.UserNameElement, SecurityJan2004Strings.Namespace);
}
}
protected class WrappedKeyTokenEntry : TokenEntry
{
WSSecurityTokenSerializer tokenSerializer;
public WrappedKeyTokenEntry(WSSecurityTokenSerializer tokenSerializer)
{
this.tokenSerializer = tokenSerializer;
}
protected override XmlDictionaryString LocalName { get { return EncryptedKey.ElementName; } }
protected override XmlDictionaryString NamespaceUri { get { return XD.XmlEncryptionDictionary.Namespace; } }
protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(WrappedKeySecurityToken) }; }
public override string TokenTypeUri { get { return null; } }
protected override string ValueTypeUri { get { return null; } }
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml,
SecurityTokenReferenceStyle tokenReferenceStyle)
{
TokenReferenceStyleHelper.Validate(tokenReferenceStyle);
switch (tokenReferenceStyle)
{
case SecurityTokenReferenceStyle.Internal:
return CreateDirectReference(issuedTokenXml, XmlEncryptionStrings.Id, null, null);
case SecurityTokenReferenceStyle.External:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.CantInferReferenceForToken, EncryptedKey.ElementName.Value)));
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenReferenceStyle"));
}
}
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
{
EncryptedKey encryptedKey = new EncryptedKey();
encryptedKey.SecurityTokenSerializer = this.tokenSerializer;
encryptedKey.ReadFrom(reader);
SecurityKeyIdentifier unwrappingTokenIdentifier = encryptedKey.KeyIdentifier;
byte[] wrappedKey = encryptedKey.GetWrappedKey();
WrappedKeySecurityToken wrappedKeyToken = CreateWrappedKeyToken(encryptedKey.Id, encryptedKey.EncryptionMethod,
encryptedKey.CarriedKeyName, unwrappingTokenIdentifier, wrappedKey, tokenResolver);
wrappedKeyToken.EncryptedKey = encryptedKey;
return wrappedKeyToken;
}
WrappedKeySecurityToken CreateWrappedKeyToken(string id, string encryptionMethod, string carriedKeyName,
SecurityKeyIdentifier unwrappingTokenIdentifier, byte[] wrappedKey, SecurityTokenResolver tokenResolver)
{
ISspiNegotiationInfo sspiResolver = tokenResolver as ISspiNegotiationInfo;
if (sspiResolver != null)
{
ISspiNegotiation unwrappingSspiContext = sspiResolver.SspiNegotiation;
// ensure that the encryption algorithm is compatible
if (encryptionMethod != unwrappingSspiContext.KeyEncryptionAlgorithm)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.BadKeyEncryptionAlgorithm, encryptionMethod)));
}
byte[] unwrappedKey = unwrappingSspiContext.Decrypt(wrappedKey);
return new WrappedKeySecurityToken(id, unwrappedKey, encryptionMethod, unwrappingSspiContext, unwrappedKey);
}
else
{
if (tokenResolver == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("tokenResolver"));
}
if (unwrappingTokenIdentifier == null || unwrappingTokenIdentifier.Count == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.MissingKeyInfoInEncryptedKey)));
}
SecurityToken unwrappingToken;
SecurityHeaderTokenResolver resolver = tokenResolver as SecurityHeaderTokenResolver;
if (resolver != null)
{
unwrappingToken = resolver.ExpectedWrapper;
if (unwrappingToken != null)
{
if (!resolver.CheckExternalWrapperMatch(unwrappingTokenIdentifier))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.EncryptedKeyWasNotEncryptedWithTheRequiredEncryptingToken, unwrappingToken)));
}
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToResolveKeyInfoForUnwrappingToken, unwrappingTokenIdentifier, resolver)));
}
}
else
{
try
{
unwrappingToken = tokenResolver.ResolveToken(unwrappingTokenIdentifier);
}
catch (Exception exception)
{
if (exception is MessageSecurityException)
throw;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToResolveKeyInfoForUnwrappingToken, unwrappingTokenIdentifier, tokenResolver), exception));
}
}
SecurityKey unwrappingSecurityKey;
byte[] unwrappedKey = SecurityUtils.DecryptKey(unwrappingToken, encryptionMethod, wrappedKey, out unwrappingSecurityKey);
return new WrappedKeySecurityToken(id, unwrappedKey, encryptionMethod, unwrappingToken, unwrappingTokenIdentifier, wrappedKey, unwrappingSecurityKey);
}
}
public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
{
WrappedKeySecurityToken wrappedKeyToken = token as WrappedKeySecurityToken;
wrappedKeyToken.EnsureEncryptedKeySetUp();
wrappedKeyToken.EncryptedKey.SecurityTokenSerializer = this.tokenSerializer;
wrappedKeyToken.EncryptedKey.WriteTo(writer, ServiceModelDictionaryManager.Instance);
}
}
protected class X509TokenEntry : BinaryTokenEntry
{
internal const string ValueTypeAbsoluteUri = SecurityJan2004Strings.X509TokenType;
public X509TokenEntry(WSSecurityTokenSerializer tokenSerializer)
: base(tokenSerializer, ValueTypeAbsoluteUri)
{
}
protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(X509SecurityToken), typeof(X509WindowsSecurityToken) }; }
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromBinaryCore(byte[] rawData)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.CantInferReferenceForToken, ValueTypeAbsoluteUri)));
}
public override SecurityToken ReadBinaryCore(string id, string valueTypeUri, byte[] rawData)
{
X509Certificate2 certificate;
if (!SecurityUtils.TryCreateX509CertificateFromRawData(rawData, out certificate))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.InvalidX509RawData)));
}
return new X509SecurityToken(certificate, id, false);
}
public override void WriteBinaryCore(SecurityToken token, out string id, out byte[] rawData)
{
id = token.Id;
X509SecurityToken x509Token = token as X509SecurityToken;
if (x509Token != null)
{
rawData = x509Token.Certificate.GetRawCertData();
}
else
{
rawData = ((X509WindowsSecurityToken)token).Certificate.GetRawCertData();
}
}
}
public class IdManager : SignatureTargetIdManager
{
static readonly IdManager instance = new IdManager();
IdManager()
{
}
public override string DefaultIdNamespacePrefix
{
get { return UtilityStrings.Prefix; }
}
public override string DefaultIdNamespaceUri
{
get { return UtilityStrings.Namespace; }
}
internal static IdManager Instance
{
get { return instance; }
}
public override string ExtractId(XmlDictionaryReader reader)
{
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
if (reader.IsStartElement(EncryptedData.ElementName, XD.XmlEncryptionDictionary.Namespace))
{
return reader.GetAttribute(XD.XmlEncryptionDictionary.Id, null);
}
else
{
return reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
}
}
public override void WriteIdAttribute(XmlDictionaryWriter writer, string id)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
writer.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace, id);
}
}
}
}
| |
// Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Ogc;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using UIKit;
namespace ArcGISRuntime.Samples.WmsServiceCatalog
{
[Register("WmsServiceCatalog")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "WMS service catalog",
category: "Layers",
description: "Connect to a WMS service and show the available layers and sublayers. ",
instructions: "",
tags: new[] { "OGC", "WMS", "catalog", "web map service" })]
public class WmsServiceCatalog : UIViewController
{
// Hold references to UI controls.
private MapView _myMapView;
private UITableView _layerList;
private NSLayoutConstraint[] _portraitConstraints;
private NSLayoutConstraint[] _landscapeConstraints;
// Hold the URL to the WMS service providing the US NOAA National Weather Service forecast weather chart.
private readonly Uri _wmsUrl = new Uri("https://idpgis.ncep.noaa.gov/arcgis/services/NWS_Forecasts_Guidance_Warnings/natl_fcst_wx_chart/MapServer/WMSServer?request=GetCapabilities&service=WMS");
// Hold a source for the UITableView that shows the available WMS layers.
private LayerListSource _layerListSource;
public WmsServiceCatalog()
{
Title = "WMS service catalog";
}
private async void Initialize()
{
// Show dark gray canvas basemap.
_myMapView.Map = new Map(BasemapStyle.ArcGISDarkGray);
// Create the WMS Service.
WmsService service = new WmsService(_wmsUrl);
try
{
// Load the WMS Service.
await service.LoadAsync();
// Get the service info (metadata) from the service.
WmsServiceInfo info = service.ServiceInfo;
List<LayerDisplayVM> viewModelList = new List<LayerDisplayVM>();
// Get the list of layer infos.
foreach (var layerInfo in info.LayerInfos)
{
LayerDisplayVM.BuildLayerInfoList(new LayerDisplayVM(layerInfo, null), viewModelList);
}
// Construct the layer list source.
_layerListSource = new LayerListSource(viewModelList, this);
// Set the source for the table view (layer list).
_layerList.Source = _layerListSource;
// Force an update of the list display.
_layerList.ReloadData();
}
catch (Exception e)
{
new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show();
}
}
/// <summary>
/// Updates the map with the latest layer selection.
/// </summary>
private async void UpdateMapDisplay(List<LayerDisplayVM> displayList)
{
// Remove all existing layers.
_myMapView.Map.OperationalLayers.Clear();
// Get a list of selected LayerInfos.
IEnumerable<WmsLayerInfo> selectedLayers = displayList.Where(vm => vm.IsEnabled).Select(vm => vm.Info);
// Create a new WmsLayer from the selected layers.
WmsLayer myLayer = new WmsLayer(selectedLayers);
try
{
// Wait for the layer to load.
await myLayer.LoadAsync();
// Zoom to the extent of the layer.
await _myMapView.SetViewpointAsync(new Viewpoint(myLayer.FullExtent));
// Add the layer to the map.
_myMapView.Map.OperationalLayers.Add(myLayer);
}
catch (Exception e)
{
new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show();
}
}
/// <summary>
/// Takes action once a new layer selection is made.
/// </summary>
public void LayerSelectionChanged(int selectedIndex)
{
// Clear existing selection.
foreach (LayerDisplayVM item in _layerListSource.ViewModelList)
{
item.Select(false);
}
// Update the selection.
_layerListSource.ViewModelList[selectedIndex].Select();
// Update the map.
UpdateMapDisplay(_layerListSource.ViewModelList);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Initialize();
}
public override void LoadView()
{
// Create the views.
View = new UIView {BackgroundColor = ApplicationTheme.BackgroundColor};
_myMapView = new MapView();
_myMapView.TranslatesAutoresizingMaskIntoConstraints = false;
_layerList = new UITableView();
_layerList.TranslatesAutoresizingMaskIntoConstraints = false;
_layerList.RowHeight = 40;
UILabel helpLabel = new UILabel
{
Text = "Select layers for display.",
AdjustsFontSizeToFitWidth = true,
TextAlignment = UITextAlignment.Center,
BackgroundColor = UIColor.FromWhiteAlpha(0, .6f),
TextColor = UIColor.White,
Lines = 1,
TranslatesAutoresizingMaskIntoConstraints = false
};
// Add the views.
View.AddSubviews(_myMapView, _layerList, helpLabel);
// Lay out the views.
NSLayoutConstraint.ActivateConstraints(new[]
{
helpLabel.LeadingAnchor.ConstraintEqualTo(_myMapView.LeadingAnchor),
helpLabel.TrailingAnchor.ConstraintEqualTo(_myMapView.TrailingAnchor),
helpLabel.TopAnchor.ConstraintEqualTo(_myMapView.TopAnchor),
helpLabel.HeightAnchor.ConstraintEqualTo(40),
});
_portraitConstraints = new[]
{
_layerList.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_layerList.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_layerList.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_layerList.HeightAnchor.ConstraintEqualTo(_layerList.RowHeight * 4),
_myMapView.TopAnchor.ConstraintEqualTo(_layerList.BottomAnchor),
_myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_myMapView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor)
};
_landscapeConstraints = new[]
{
_layerList.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_layerList.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_layerList.BottomAnchor.ConstraintEqualTo(View.BottomAnchor),
_layerList.TrailingAnchor.ConstraintEqualTo(View.CenterXAnchor),
_myMapView.LeadingAnchor.ConstraintEqualTo(_layerList.TrailingAnchor),
_myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_myMapView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor),
_myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor)
};
SetLayoutOrientation();
}
public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection)
{
base.TraitCollectionDidChange(previousTraitCollection);
// Reset constraints.
NSLayoutConstraint.DeactivateConstraints(_portraitConstraints);
NSLayoutConstraint.DeactivateConstraints(_landscapeConstraints);
SetLayoutOrientation();
}
private void SetLayoutOrientation()
{
if (View.TraitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Compact)
{
NSLayoutConstraint.ActivateConstraints(_landscapeConstraints);
}
else
{
NSLayoutConstraint.ActivateConstraints(_portraitConstraints);
}
}
}
/// <summary>
/// This is a ViewModel class for maintaining the state of a layer selection.
/// Typically, this would go in a separate file, but it is included here for clarity.
/// </summary>
public class LayerDisplayVM
{
public WmsLayerInfo Info { get; }
// True if layer is selected for display.
public bool IsEnabled { get; private set; }
// Keeps track of how much indentation should be added (to simulate a tree view in a list).
private int NestLevel
{
get
{
if (Parent == null)
{
return 0;
}
return Parent.NestLevel + 1;
}
}
private List<LayerDisplayVM> Children { get; set; }
private LayerDisplayVM Parent { get; }
public LayerDisplayVM(WmsLayerInfo info, LayerDisplayVM parent)
{
Info = info;
Parent = parent;
}
// Select this layer and all child layers.
public void Select(bool isSelected = true)
{
IsEnabled = isSelected;
if (Children == null)
{
return;
}
foreach (var child in Children)
{
child.Select(isSelected);
}
}
// Name with formatting to simulate treeview.
public string Name => $"{new string(' ', NestLevel * 8)} {Info.Title}";
public static void BuildLayerInfoList(LayerDisplayVM root, IList<LayerDisplayVM> result)
{
// Add the root node to the result list.
result.Add(root);
// Initialize the child collection for the root.
root.Children = new List<LayerDisplayVM>();
// Recursively add sublayers.
foreach (WmsLayerInfo layer in root.Info.LayerInfos)
{
// Create the view model for the sublayer.
LayerDisplayVM layerVM = new LayerDisplayVM(layer, root);
// Add the sublayer to the root's sublayer collection.
root.Children.Add(layerVM);
// Recursively add children.
BuildLayerInfoList(layerVM, result);
}
}
}
/// <summary>
/// Class defines how a UITableView renders its contents.
/// This implements the list of WMS sublayers.
/// </summary>
public class LayerListSource : UITableViewSource
{
public readonly List<LayerDisplayVM> ViewModelList = new List<LayerDisplayVM>();
// Used when re-using cells to ensure that a cell of the right type is used
private const string CellId = "TableCell";
// Hold a reference to the owning view controller; this will be the active instance of WmsServiceCatalog.
[Weak] public WmsServiceCatalog Owner;
public LayerListSource(List<LayerDisplayVM> items, WmsServiceCatalog owner)
{
// Set the items.
if (items != null)
{
ViewModelList = items;
}
// Set the owner.
Owner = owner;
}
/// <summary>
/// This method gets a table view cell for the suggestion at the specified index.
/// </summary>
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
// Try to get a re-usable cell (this is for performance).
UITableViewCell cell = tableView.DequeueReusableCell(CellId);
// If there are no cells, create a new one.
if (cell == null)
{
cell = new UITableViewCell(UITableViewCellStyle.Default, CellId)
{
BackgroundColor = UIColor.FromWhiteAlpha(0, 0f)
};
cell.TextLabel.TextColor = Owner.View.TintColor;
}
// Get the specific item to display.
LayerDisplayVM item = ViewModelList[indexPath.Row];
// Set the text on the cell.
cell.TextLabel.Text = item.Name;
// Return the cell.
return cell;
}
/// <summary>
/// This method allows the UITableView to know how many rows to render.
/// </summary>
public override nint RowsInSection(UITableView tableview, nint section)
{
return ViewModelList.Count;
}
/// <summary>
/// Method called when a row is selected; notifies the primary view.
/// </summary>
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
// Deselect the row.
tableView.DeselectRow(indexPath, true);
// Select the layer.
Owner.LayerSelectionChanged(indexPath.Row);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Web;
using Vevo;
using Vevo.Domain;
using Vevo.Domain.Configurations;
using Vevo.Domain.Products;
using Vevo.Domain.Stores;
using Vevo.WebUI;
using Vevo.WebUI.International;
using Vevo.WebUI.Products;
public partial class DepartmentPage : Vevo.Deluxe.WebUI.Base.BaseLicenseLanguagePage
{
private string DepartmentID
{
get
{
if (ViewState["DepartmentID"] == null)
return "0";
else
return (string) ViewState["DepartmentID"];
}
set
{
ViewState["DepartmentID"] = value;
}
}
private string CurrentDepartmentID
{
get
{
string id = Request.QueryString["DepartmentID"];
if (!String.IsNullOrEmpty( id ))
{
return id;
}
else
{
Department department = DataAccessContext.DepartmentRepository.GetOneByUrlName(
StoreContext.Culture, CurrentDepartmentName );
return department.DepartmentID;
}
}
}
private string CurrentDepartmentName
{
get
{
if (Request.QueryString["DepartmentName"] == null)
return String.Empty;
else
return Request.QueryString["DepartmentName"];
}
}
private bool IsParentOfOtherDepartments()
{
if (!String.IsNullOrEmpty( CurrentDepartmentName ))
{
return DataAccessContext.DepartmentRepository.IsUrlNameNotLeaf( CurrentDepartmentName );
}
else if (!String.IsNullOrEmpty( CurrentDepartmentID ))
{
return DataAccessContext.DepartmentRepository.IsDepartmentIDNotLeaf( CurrentDepartmentID );
}
else
{
return false;
}
}
private void PopulateTitleAndMeta( DynamicPageElement element )
{
Department department = DataAccessContext.DepartmentRepository.GetOne(
StoreContext.Culture, CurrentDepartmentID );
string title = SeoVariable.ReplaceDepartmentVariable(
department,
StoreContext.Culture,
DataAccessContext.Configurations.GetValue( StoreContext.Culture.CultureID, "DefaultDepartmentPageTitle", StoreContext.CurrentStore ) );
element.SetUpTitleAndMetaTags(
department.GetPageTitle( StoreContext.Culture, title ),
department.GetMetaDescription( StoreContext.Culture ),
department.GetMetaKeyword( StoreContext.Culture ) );
}
private void PopulateControls()
{
DynamicPageElement element = new DynamicPageElement( this );
if (CurrentDepartmentID == "0")
{
if (CurrentDepartmentName == "")
element.SetUpTitleAndMetaTags( "[$Title] - " + NamedConfig.SiteName, NamedConfig.SiteDescription );
else
Response.Redirect( "~/Error404.aspx" );
}
else
{
Department department = DataAccessContext.DepartmentRepository.GetOne(
StoreContext.Culture, CurrentDepartmentID );
if (department.IsCategoryAvailableStore( StoreContext.CurrentStore.StoreID ) && (department.IsParentsEnable()))
PopulateTitleAndMeta( element );
else
Response.Redirect( "~/Error404.aspx" );
}
}
private void PopulateUserControl()
{
uxProductControlPanel.Visible = false;
uxDepartmentControlPanel.Visible = false;
Department department = DataAccessContext.DepartmentRepository.GetOne(
StoreContext.Culture, CurrentDepartmentID );
uxDepartmentNameLabel.Text = department.Name;
if (IsParentOfOtherDepartments())
{
uxDepartmentControlPanel.Visible = true;
BaseDepartmentListControl departmentControl = new BaseDepartmentListControl();
if (!String.IsNullOrEmpty( department.DepartmentListLayoutPath ))
departmentControl = LoadControl( String.Format( "{0}{1}",
SystemConst.LayoutDepartmentListPath, department.DepartmentListLayoutPath ) )
as BaseDepartmentListControl;
else
departmentControl = LoadControl( String.Format( "{0}{1}",
SystemConst.LayoutDepartmentListPath,
DataAccessContext.Configurations.GetValue( "DefaultDepartmentListLayout" ) ) )
as BaseDepartmentListControl;
uxDepartmentControlPanel.Controls.Add( departmentControl );
}
else
{
uxProductControlPanel.Visible = true;
BaseProductListControl productListControl = new BaseProductListControl();
if (!String.IsNullOrEmpty( department.ProductListLayoutPath ))
productListControl = LoadControl( String.Format(
"{0}{1}",
SystemConst.LayoutProductListPath,
department.ProductListLayoutPath ) ) as BaseProductListControl;
else
productListControl = LoadControl( String.Format(
"{0}{1}",
SystemConst.LayoutProductListPath,
DataAccessContext.Configurations.GetValue( "DefaultProductListLayout" ) ) )
as BaseProductListControl;
productListControl.ID = "uxProductList";
productListControl.DataRetriever = new DataAccessCallbacks.ProductListRetriever( GetProductList );
productListControl.UserDefinedParameters = new object[] { CurrentDepartmentID };
uxProductControlPanel.Controls.Add( productListControl );
}
}
private void SetUpBreadcrumb()
{
if (CurrentDepartmentID == "0" && CurrentDepartmentName == String.Empty)
{
uxCatalogBreadcrumb.Visible = false;
uxDepartmentNameLabel.CssClass = "CatalogName CatalogRoot";
}
else
{
uxCatalogBreadcrumb.SetupDepartmentSitemap( CurrentDepartmentID );
uxCatalogBreadcrumb.Refresh();
}
}
private void Department_StoreCultureChanged( object sender, CultureEventArgs e )
{
if (CurrentDepartmentName == "")
{
Response.Redirect( "~/Department.aspx" );
}
else
{
Department department = DataAccessContext.DepartmentRepository.GetOne(
StoreContext.Culture, DepartmentID );
if (!String.IsNullOrEmpty( department.UrlName ))
{
Response.Redirect( UrlManager.GetDepartmentUrl( DepartmentID, department.UrlName ) );
}
else
{
Response.Redirect( "~/Error404.aspx" );
}
}
}
protected void Page_Load( object sender, EventArgs e )
{
Response.Cache.SetCacheability( HttpCacheability.NoCache );
Response.Expires = 0;
Response.Cache.SetNoStore();
Response.AppendHeader( "Pragma", "no-cache" );
GetStorefrontEvents().StoreCultureChanged +=
new StorefrontEvents.CultureEventHandler( Department_StoreCultureChanged );
if (!IsPostBack)
{
PopulateControls();
DepartmentID = CurrentDepartmentID;
}
PopulateUserControl();
}
protected void Page_PreRender( object sender, EventArgs e )
{
SetUpBreadcrumb();
}
public static IList<Product> GetProductList(
Culture culture,
string sortBy,
int startIndex,
int endIndex,
object[] userDefined,
out int howManyItems )
{
return DataAccessContext.ProductRepository.GetByDepartmentID(
culture,
userDefined[0].ToString(),
sortBy,
startIndex,
endIndex,
BoolFilter.ShowTrue,
out howManyItems,
new StoreRetriever().GetCurrentStoreID()
);
}
}
| |
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using JigLibX.Math;
using JigLibX.Geometry;
#endregion
namespace JigLibX.Geometry
{
/// <summary>
/// An axis aligned Box.
/// </summary>
public class AABox : Primitive
{
private Vector3 minPos = new Vector3(float.MaxValue);
private Vector3 maxPos = new Vector3(float.MinValue);
private static AABox hugeBox = new AABox(
new Vector3(float.MinValue),new Vector3(float.MaxValue));
/// <summary>
/// Position based on one corner. sideLengths are the full side
/// lengths (each element must be >= 0)
/// </summary>
/// <param name="minPos"></param>
/// <param name="maxPos"></param>
public AABox(Vector3 minPos, Vector3 maxPos) :
base((int)PrimitiveType.AABox)
{
this.minPos = minPos;
this.maxPos = maxPos;
}
/// <summary>
/// Constructor
/// </summary>
public AABox() :
base((int)PrimitiveType.AABox)
{
this.Clear();
}
private Vector3 offset = Vector3.Zero;
/// <summary>
/// Gets new Transform or Sets offset to value.Position
/// </summary>
public override Transform Transform
{
get
{
return new Transform(offset, Matrix.Identity);
}
set
{
maxPos = maxPos - offset + value.Position;
minPos = minPos - offset + value.Position;
offset = value.Position;
}
}
/// <summary>
/// Adding points etc.
/// </summary>
public void Clear()
{
minPos.X = minPos.Y = minPos.Z = float.MaxValue;
maxPos.X = maxPos.Y = maxPos.Z = float.MinValue;
}
/// <summary>
/// Adds a point to the AABB.
/// </summary>
/// <remarks>
/// This function is heavily used to calculate the axis
/// aligned bounding boxes arround any object. Calling
/// by reference is unusal but makes it faster.
/// </remarks>
/// <param name="pos"></param>
public void AddPoint(ref Vector3 pos)
{
if (pos.X < minPos.X) minPos.X = pos.X - JiggleMath.Epsilon;
if (pos.X > maxPos.X) maxPos.X = pos.X + JiggleMath.Epsilon;
if (pos.Y < minPos.Y) minPos.Y = pos.Y - JiggleMath.Epsilon;
if (pos.Y > maxPos.Y) maxPos.Y = pos.Y + JiggleMath.Epsilon;
if (pos.Z < minPos.Z) minPos.Z = pos.Z - JiggleMath.Epsilon;
if (pos.Z > maxPos.Z) maxPos.Z = pos.Z + JiggleMath.Epsilon;
}
/// <summary>
/// Adds a point to the AABB
/// </summary>
/// <param name="pos"></param>
public void AddPoint(Vector3 pos)
{
if (pos.X < minPos.X) minPos.X = pos.X - JiggleMath.Epsilon;
if (pos.X > maxPos.X) maxPos.X = pos.X + JiggleMath.Epsilon;
if (pos.Y < minPos.Y) minPos.Y = pos.Y - JiggleMath.Epsilon;
if (pos.Y > maxPos.Y) maxPos.Y = pos.Y + JiggleMath.Epsilon;
if (pos.Z < minPos.Z) minPos.Z = pos.Z - JiggleMath.Epsilon;
if (pos.Z > maxPos.Z) maxPos.Z = pos.Z + JiggleMath.Epsilon;
}
/*
public void AddBox(Box box)
{
Vector3[] pts = new Vector3[8];
box.GetCornerPoints(out pts);
AddPoint(ref pts[0]);
AddPoint(ref pts[1]);
AddPoint(ref pts[2]);
AddPoint(ref pts[3]);
AddPoint(ref pts[4]);
AddPoint(ref pts[5]);
AddPoint(ref pts[6]);
AddPoint(ref pts[7]);
}
public void AddSegment(Segment seg)
{
AddPoint(seg.Origin);
AddPoint(seg.GetEnd());
}
public void AddAABox(AABox aabox)
{
AddPoint(aabox.MaxPos);
AddPoint(aabox.MinPos);
}
public void AddSphere(Sphere sphere)
{
if ((sphere.Position.X - sphere.Radius) < minPos.X)
minPos.X = (sphere.Position.X - sphere.Radius) - JiggleMath.Epsilon;
if ((sphere.Position.X + sphere.Radius) > maxPos.X)
maxPos.X = (sphere.Position.X + sphere.Radius) + JiggleMath.Epsilon;
if ((sphere.Position.Y - sphere.Radius) < minPos.Y)
minPos.Y = (sphere.Position.Y - sphere.Radius) - JiggleMath.Epsilon;
if ((sphere.Position.Y + sphere.Radius) > maxPos.Y)
maxPos.Y = (sphere.Position.Y + sphere.Radius) + JiggleMath.Epsilon;
if ((sphere.Position.Z - sphere.Radius) < minPos.Z)
minPos.Z = (sphere.Position.Z - sphere.Radius) - JiggleMath.Epsilon;
if ((sphere.Position.Z + sphere.Radius) > maxPos.Z)
maxPos.Z = (sphere.Position.Z + sphere.Radius) + JiggleMath.Epsilon;
}
public void AddCapsule(Capsule capsule)
{
AddSphere(new Sphere(capsule.Position, capsule.Radius));
AddSphere(new Sphere(capsule.Position + capsule.Length * capsule.Orientation.Backward, capsule.Radius));
}
public void AddPrimitive(Primitive prim)
{
switch ((PrimitiveType)prim.Type)
{
case PrimitiveType.Box:
AddBox((Box)prim);
break;
case PrimitiveType.Sphere:
AddSphere((Sphere)prim);
break;
case PrimitiveType.Capsule:
AddCapsule((Capsule)prim);
break;
default:
AddAABox(prim.GetBoundingBox());
break;
}
}
*/
/// <summary>
/// Move minPos and maxPos += delta
/// </summary>
/// <param name="delta"></param>
public void Move(Vector3 delta)
{
minPos += delta;
maxPos += delta;
}
/// <summary>
/// IsPointInside
/// </summary>
/// <param name="pos"></param>
/// <returns>bool</returns>
public bool IsPointInside(Vector3 pos)
{
return ((pos.X >= minPos.X) &&
(pos.X <= maxPos.X) &&
(pos.Y >= minPos.Y) &&
(pos.Y <= maxPos.Y) &&
(pos.Z >= minPos.Z) &&
(pos.Z <= maxPos.Z));
}
/// <summary>
/// OverlapTest
/// </summary>
/// <param name="box0"></param>
/// <param name="box1"></param>
/// <returns>bool</returns>
public static bool OverlapTest(AABox box0, AABox box1)
{
return ((box0.minPos.Z >= box1.maxPos.Z) ||
(box0.maxPos.Z <= box1.minPos.Z) ||
(box0.minPos.Y >= box1.maxPos.Y) ||
(box0.maxPos.Y <= box1.minPos.Y) ||
(box0.minPos.X >= box1.maxPos.X) ||
(box0.maxPos.X <= box1.minPos.X)) ? false : true;
}
/// <summary>
/// OverlapTest
/// </summary>
/// <param name="box0"></param>
/// <param name="box1"></param>
/// <param name="tol"></param>
/// <returns>bool</returns>
public static bool OverlapTest(AABox box0, AABox box1, float tol)
{
return ((box0.minPos.Z >= box1.maxPos.Z + tol) ||
(box0.maxPos.Z <= box1.minPos.Z - tol) ||
(box0.minPos.Y >= box1.maxPos.Y + tol) ||
(box0.maxPos.Y <= box1.minPos.Y - tol) ||
(box0.minPos.X >= box1.maxPos.X + tol) ||
(box0.maxPos.X <= box1.minPos.X - tol)) ? false : true;
}
/// <summary>
/// GetCentre
/// </summary>
/// <returns><c>0.5f * (minPos + maxPos)</c></returns>
public Vector3 GetCentre()
{
return 0.5f * (minPos + maxPos);
}
/// <summary>
/// Gets or Sets minPos
/// </summary>
public Vector3 MinPos
{
get { return this.minPos; }
set { this.minPos = value; }
}
/// <summary>
/// Gets or Sets maxPos
/// </summary>
public Vector3 MaxPos
{
get { return this.maxPos; }
set { this.maxPos = value; }
}
/// <summary>
/// GetSideLengths
/// </summary>
/// <returns>maxPos - minPos</returns>
public Vector3 GetSideLengths()
{
return maxPos - minPos;
}
/// <summary>
/// GetRadiusAboutCentre
/// </summary>
/// <returns><c>0.5f * (maxPos - minPos).Length()</c></returns>
public float GetRadiusAboutCentre()
{
return 0.5f * (maxPos - minPos).Length();
}
/// <summary>
/// GetRadiusSqAboutCentre
/// </summary>
/// <returns>float</returns>
public float GetRadiusSqAboutCentre()
{
float result = this.GetRadiusAboutCentre();
return result * result;
}
/// <summary>
/// Gets hugeBox
/// </summary>
public static AABox HugeBox
{
get { return hugeBox; }
}
/// <summary>
/// Clone
/// </summary>
/// <returns>new AABox</returns>
public override Primitive Clone()
{
return new AABox(this.minPos, this.maxPos);
}
/// <summary>
/// SegmentIntersect
/// </summary>
/// <remarks>This is not implemented. It will throw an exception.</remarks>
/// <param name="frac"></param>
/// <param name="pos"></param>
/// <param name="normal"></param>
/// <param name="seg"></param>
/// <returns>bool</returns>
public override bool SegmentIntersect(out float frac, out Vector3 pos, out Vector3 normal, Segment seg)
{
// todo implement
// throw new JigLibXException("Not implemented!");
throw new NotImplementedException();
}
/// <summary>
/// GetVolume
/// </summary>
/// <returns><c>(this.maxPos - this.minPos).LengthSquared()</c></returns>
public override float GetVolume()
{
return (this.maxPos - this.minPos).LengthSquared();
}
/// <summary>
/// GetSurfaceArea
/// </summary>
/// <returns>float</returns>
public override float GetSurfaceArea()
{
Vector3 sl = this.maxPos - this.minPos;
return 2.0f * (sl.X * sl.Y + sl.X * sl.Z + sl.Y * sl.Z);
}
/// <summary>
/// GetMassProperties
/// </summary>
/// <param name="primitiveProperties"></param>
/// <param name="mass"></param>
/// <param name="centerOfMass"></param>
/// <param name="inertiaTensor"></param>
public override void GetMassProperties(PrimitiveProperties primitiveProperties, out float mass, out Vector3 centerOfMass, out Matrix inertiaTensor)
{
mass = 0.0f;
centerOfMass = Vector3.Zero;
inertiaTensor = Matrix.Identity;
}
}
/// <summary>
/// Class BoundingBoxHelper
/// </summary>
public class BoundingBoxHelper
{
/// <summary>
/// InitialBox
/// </summary>
static public BoundingBox InitialBox = new BoundingBox( new Vector3(float.PositiveInfinity),new Vector3(float.NegativeInfinity));
/// <summary>
/// AddPoint
/// </summary>
/// <param name="pos"></param>
/// <param name="bb"></param>
static public void AddPoint(ref Vector3 pos, ref BoundingBox bb)
{
Vector3.Min(ref bb.Min, ref pos, out bb.Min);
Vector3.Max(ref bb.Max, ref pos, out bb.Max);
}
/// <summary>
/// AddPoint
/// </summary>
/// <param name="pos"></param>
/// <param name="bb"></param>
static public void AddPoint(Vector3 pos, ref BoundingBox bb)
{
Vector3.Min(ref bb.Min, ref pos, out bb.Min);
Vector3.Max(ref bb.Max, ref pos, out bb.Max);
}
static Vector3[] pts = new Vector3[8];
/// <summary>
/// AddBox
/// </summary>
/// <remarks>Note: Not thread safe or re-entrant as it uses pts</remarks>
/// <param name="box"></param>
/// <param name="bb"></param>
static public void AddBox(Box box, ref BoundingBox bb)
{
// NOTE Not thread safe or rentrant as its uses pts
box.GetCornerPoints(out pts);
AddPoint(ref pts[0],ref bb);
AddPoint(ref pts[1],ref bb);
AddPoint(ref pts[2],ref bb);
AddPoint(ref pts[3],ref bb);
AddPoint(ref pts[4],ref bb);
AddPoint(ref pts[5],ref bb);
AddPoint(ref pts[6],ref bb);
AddPoint(ref pts[7],ref bb);
}
/// <summary>
/// AddSegment
/// </summary>
/// <param name="seg"></param>
/// <param name="bb"></param>
static public void AddSegment(Segment seg, ref BoundingBox bb)
{
AddPoint(seg.Origin,ref bb);
AddPoint(seg.GetEnd(), ref bb);
}
/// <summary>
/// AddAABox
/// </summary>
/// <param name="aabox"></param>
/// <param name="bb"></param>
static public void AddAABox(AABox aabox, ref BoundingBox bb)
{
bb.Min = Vector3.Min(aabox.MinPos, bb.Min);
bb.Max = Vector3.Max(aabox.MaxPos, bb.Max);
}
/// <summary>
/// AddBBox
/// </summary>
/// <param name="bbox"></param>
/// <param name="bb"></param>
static public void AddBBox(BoundingBox bbox, ref BoundingBox bb)
{
bb.Min = Vector3.Min(bbox.Min, bb.Min);
bb.Max = Vector3.Max(bbox.Max, bb.Max);
}
/// <summary>
/// AddSphere
/// </summary>
/// <param name="sphere"></param>
/// <param name="bb"></param>
static public void AddSphere(Sphere sphere, ref BoundingBox bb)
{
Vector3 radius = new Vector3(sphere.Radius);
Vector3 minSphere = sphere.Position;
Vector3 maxSphere = sphere.Position;
Vector3.Subtract(ref minSphere, ref radius, out minSphere);
Vector3.Add(ref maxSphere, ref radius, out maxSphere);
Vector3.Min(ref bb.Min, ref minSphere, out bb.Min);
Vector3.Max(ref bb.Max, ref maxSphere, out bb.Max);
}
/// <summary>
/// AddSphere
/// </summary>
/// <param name="sphere"></param>
/// <param name="bb"></param>
static public void AddSphere(Microsoft.Xna.Framework.BoundingSphere sphere, ref BoundingBox bb)
{
Vector3 radius = new Vector3(sphere.Radius);
Vector3 minSphere = sphere.Center;
Vector3 maxSphere = sphere.Center;
Vector3.Subtract(ref minSphere, ref radius, out minSphere);
Vector3.Add(ref maxSphere, ref radius, out maxSphere);
Vector3.Min(ref bb.Min, ref minSphere, out bb.Min);
Vector3.Max(ref bb.Max, ref maxSphere, out bb.Max);
}
/// <summary>
/// AddCapsule
/// </summary>
/// <param name="capsule"></param>
/// <param name="bb"></param>
static public void AddCapsule(Capsule capsule, ref BoundingBox bb)
{
AddSphere(new Microsoft.Xna.Framework.BoundingSphere(capsule.Position, capsule.Radius), ref bb);
AddSphere(new Microsoft.Xna.Framework.BoundingSphere(capsule.Position + capsule.Length * capsule.Orientation.Backward, capsule.Radius), ref bb);
}
/// <summary>
/// AddPrimitive
/// </summary>
/// <param name="prim"></param>
/// <param name="bb"></param>
static public void AddPrimitive(Primitive prim, ref BoundingBox bb)
{
switch ((PrimitiveType)prim.Type)
{
case PrimitiveType.Box:
AddBox((Box)prim, ref bb);
break;
case PrimitiveType.Sphere:
AddSphere((Sphere)prim, ref bb);
break;
case PrimitiveType.Capsule:
AddCapsule((Capsule)prim, ref bb);
break;
default:
AddAABox(prim.GetBoundingBox(), ref bb);
break;
}
}
/// <summary>
/// OverlapTest
/// </summary>
/// <param name="box0"></param>
/// <param name="box1"></param>
/// <returns>bool</returns>
public static bool OverlapTest(ref BoundingBox box0, ref BoundingBox box1)
{
return ((box0.Min.Z >= box1.Max.Z) ||
(box0.Max.Z <= box1.Min.Z) ||
(box0.Min.Y >= box1.Max.Y) ||
(box0.Max.Y <= box1.Min.Y) ||
(box0.Min.X >= box1.Max.X) ||
(box0.Max.X <= box1.Min.X)) ? false : true;
}
/// <summary>
/// OverlapTest
/// </summary>
/// <param name="box0"></param>
/// <param name="box1"></param>
/// <param name="tol"></param>
/// <returns>bool</returns>
public static bool OverlapTest(ref BoundingBox box0, ref BoundingBox box1, float tol)
{
return ((box0.Min.Z >= box1.Max.Z + tol) ||
(box0.Max.Z <= box1.Min.Z - tol) ||
(box0.Min.Y >= box1.Max.Y + tol) ||
(box0.Max.Y <= box1.Min.Y - tol) ||
(box0.Min.X >= box1.Max.X + tol) ||
(box0.Max.X <= box1.Min.X - tol)) ? false : true;
}
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Sce.Atf;
using Sce.Atf.Adaptation;
using Sce.Atf.Applications;
using Sce.Atf.Dom;
using Sce.Sled.Shared;
using Sce.Sled.Shared.Services;
namespace Sce.Sled.Lua.Dom
{
public abstract class SledLuaVarBaseListType<T> : DomNodeAdapter, IItemView, ITreeListView, IObservableContext, IHierarchicalInsertionContext, IValidationContext
where T : class, ISledLuaVarBaseType
{
public virtual string Name
{
get { return GetAttribute<string>(NameAttributeInfo); }
set { SetAttribute(NameAttributeInfo, value); }
}
public virtual IList<T> Variables
{
get { return GetChildList<T>(VariablesChildInfo); }
}
#region IItemView Interface
public virtual void GetInfo(object item, ItemInfo info)
{
if (ReferenceEquals(item, this))
{
info.Label = Name;
info.Description = Description;
info.ImageIndex = info.GetImageIndex(Atf.Resources.FolderImage);
return;
}
var itemView = item.As<IItemView>();
if ((itemView == null) || ReferenceEquals(itemView, this))
return;
itemView.GetInfo(item, info);
}
#endregion
#region ITreeListView Interface
public virtual IEnumerable<object> GetChildren(object parent)
{
if (parent == null)
yield break;
var node = parent.As<DomNode>();
if (node == null)
yield break;
foreach (var child in node.Children)
{
if (!child.Is<T>())
continue;
// Respect variable filtering
var converted = child.As<T>();
if (converted.Visible)
yield return converted;
}
}
public virtual IEnumerable<object> Roots
{
get
{
// Respect variable filtering
return Variables.Where(r => r.Visible);
}
}
public virtual string[] ColumnNames
{
get { return TheColumnNames; }
}
#endregion
#region IObservableContext Interface
public virtual event EventHandler<ItemInsertedEventArgs<object>> ItemInserted;
public virtual event EventHandler<ItemRemovedEventArgs<object>> ItemRemoved;
public virtual event EventHandler<ItemChangedEventArgs<object>> ItemChanged;
public virtual event EventHandler Reloaded { add { } remove { } } // Cheap trick to avoid compiler warning
#endregion
#region IHierarchicalInsertionContext Interface
public bool CanInsert(object parent, object child)
{
// Figure out what's being drag-and-drop'd
ISledLuaVarBaseType childVar;
if (!TryGetLuaVar(child.As<IDataObject>(), out childVar))
return false;
// Dropping onto Lua variable...
if (parent.Is<ISledLuaVarBaseType>())
{
// Can't drag-and-drop onto same GUI
var parentVar = parent.As<ISledLuaVarBaseType>();
if (ReferenceEquals(parentVar.DomNode.GetRoot(), childVar.DomNode.GetRoot()))
return false;
// Can only drop onto watch GUI and then
// only if item isn't already watched
return
(parentVar.DomNode.GetRoot().Type == SledLuaSchema.SledLuaVarWatchListType.Type) &&
!m_luaWatchedVariableService.Get.IsLuaVarWatched(childVar);
}
// Dropping onto Lua editor...
var editor = parent.As<SledLuaTreeListViewEditor>();
if (editor == null)
return false;
if (!editor.View.Is<SledLuaVarWatchListType>())
return false;
return !m_luaWatchedVariableService.Get.IsLuaVarWatched(childVar);
}
public void Insert(object parent, object child)
{
// Figure out what's being drag-and-drop'd
ISledLuaVarBaseType childVar;
if (!TryGetLuaVar(child.As<IDataObject>(), out childVar))
return;
m_luaWatchedVariableService.Get.AddWatchedLuaVar(childVar);
}
#endregion
#region IValidationContext Interface
public event EventHandler Beginning;
public event EventHandler Cancelled { add { } remove { } } // Cheap trick to avoid compiler warning
public event EventHandler Ending;
public event EventHandler Ended;
#endregion
public virtual IEnumerable<ExpandedState> ExpandedStates
{
get { return m_lstSaveStates; }
}
public virtual void SaveExpandedStates()
{
ResetExpandedStates();
foreach (var variable in Variables)
{
var state = SaveExpandedStateHelper(variable, m_dictSaveStates);
if (state == null)
continue;
m_lstSaveStates.Add(state);
}
}
public virtual void ResetExpandedStates()
{
m_lstSaveStates.Clear();
m_dictSaveStates.Clear();
}
public virtual bool TryGetVariable(string name, out ISledLuaVarBaseType luaVar)
{
luaVar = null;
foreach (var variable in Variables.Select(v => v.As<T>()))
{
if (TryGetVariableHelper(name, variable, out luaVar))
return true;
}
return false;
}
public void ValidationBeginning()
{
try
{
Beginning.Raise(this, EventArgs.Empty);
}
finally
{
m_validating = true;
}
}
public void ValidationEnded()
{
if (!m_validating)
return;
try
{
Ending.Raise(this, EventArgs.Empty);
Ended.Raise(this, EventArgs.Empty);
}
finally
{
m_validating = false;
}
}
#region ExpandedState Class
public class ExpandedState
{
public ExpandedState(T variable)
{
Variable = variable;
var rootNode = variable.DomNode.GetRoot();
Root = ReferenceEquals(variable.DomNode.Parent, rootNode);
OwnerList = rootNode.As<SledLuaVarBaseListType<T>>();
Context = SledLuaVarLookUpContextType.Normal;
{
var luaVarWatchList = OwnerList.As<SledLuaVarWatchListType>();
if (luaVarWatchList != null)
{
Context = luaVarWatchList.IsCustomWatchedVariable(Variable)
? SledLuaVarLookUpContextType.WatchCustom
: SledLuaVarLookUpContextType.WatchProject;
}
}
LookUp = SledLuaVarLookUpType.FromLuaVar(variable, Context);
Children = new List<ExpandedState>();
}
public bool Root { get; private set; }
public T Variable { get; private set; }
public SledLuaVarLookUpType LookUp { get; private set; }
public SledLuaVarLookUpContextType Context { get; private set; }
public SledLuaVarBaseListType<T> OwnerList { get; private set; }
public ICollection<ExpandedState> Children { get; private set; }
public IEnumerable<ExpandedState> GetFlattenedHierarchy()
{
var flattened = new List<ExpandedState>();
GetFlattenedHierarchyHelper(this, flattened);
return flattened;
}
private static void GetFlattenedHierarchyHelper(ExpandedState state, ICollection<ExpandedState> lstStates)
{
lstStates.Add(state);
foreach (var child in state.Children)
GetFlattenedHierarchyHelper(child, lstStates);
}
}
#endregion
protected override void OnNodeSet()
{
DomNode.AttributeChanged += DomNodeAttributeChanged;
DomNode.ChildInserted += DomNodeChildInserted;
DomNode.ChildRemoving += DomNodeChildRemoving;
base.OnNodeSet();
}
private void DomNodeAttributeChanged(object sender, AttributeEventArgs e)
{
OnDomNodeAttributeChanged(sender, e);
}
private void DomNodeChildInserted(object sender, ChildEventArgs e)
{
OnDomNodeChildInserted(sender, e);
}
private void DomNodeChildRemoving(object sender, ChildEventArgs e)
{
OnDomNodeChildRemoving(sender, e);
}
protected virtual void OnDomNodeAttributeChanged(object sender, AttributeEventArgs e)
{
if (!e.DomNode.Is<T>())
return;
ItemChanged.Raise(
this,
new ItemChangedEventArgs<object>(e.DomNode.As<T>()));
}
protected virtual void OnDomNodeChildInserted(object sender, ChildEventArgs e)
{
if (!e.Child.Is<T>())
return;
var child = e.Child.As<T>();
if (child != null)
{
bool expanded;
if (m_dictSaveStates.TryGetValue(child.UniqueName, out expanded))
child.Expanded = true;
}
// Respect variable filtering
if ((child != null) && !child.Visible)
return;
ItemInserted.Raise(
this,
new ItemInsertedEventArgs<object>(
e.Index,
e.Child.As<T>(),
e.Parent.As<T>()));
}
protected virtual void OnDomNodeChildRemoving(object sender, ChildEventArgs e)
{
if (!e.Child.Is<T>())
return;
ItemRemoved.Raise(
this,
new ItemRemovedEventArgs<object>(
e.Index,
e.Child.As<T>(),
e.Parent.As<T>()));
}
protected static ExpandedState SaveExpandedStateHelper(T variable, IDictionary<string, bool> dictStates)
{
if (!variable.Expanded || !variable.Variables.Any())
return null;
if (string.IsNullOrEmpty(variable.UniqueName))
return null;
if (!dictStates.ContainsKey(variable.UniqueName))
dictStates.Add(variable.UniqueName, true);
var state = new ExpandedState(variable);
foreach (var child in variable.Variables.Select(v => v.As<T>()))
{
var newState = SaveExpandedStateHelper(child, dictStates);
if (newState == null)
continue;
state.Children.Add(newState);
}
return state;
}
protected static bool TryGetVariableHelper(string name, T variable, out ISledLuaVarBaseType luaVar)
{
luaVar = null;
if (string.Compare(variable.Name, name, StringComparison.Ordinal) == 0)
{
luaVar = variable;
return true;
}
// Check if any children
if (!variable.Variables.Any())
return false;
// Enumerate through children
foreach (var var in variable.Variables.Select(v => v.As<T>()))
{
if (TryGetVariableHelper(name, var, out luaVar))
return true;
}
return false;
}
private static bool TryGetLuaVar(IDataObject dataObject, out ISledLuaVarBaseType luaVar)
{
luaVar = null;
if (dataObject == null)
return false;
try
{
if (dataObject.GetDataPresent(typeof(SledLuaVarGlobalType)))
luaVar = (SledLuaVarGlobalType)dataObject.GetData(typeof(SledLuaVarGlobalType));
else if (dataObject.GetDataPresent(typeof(SledLuaVarLocalType)))
luaVar = (SledLuaVarLocalType)dataObject.GetData(typeof(SledLuaVarLocalType));
else if (dataObject.GetDataPresent(typeof(SledLuaVarUpvalueType)))
luaVar = (SledLuaVarUpvalueType)dataObject.GetData(typeof(SledLuaVarUpvalueType));
else if (dataObject.GetDataPresent(typeof(SledLuaVarEnvType)))
luaVar = (SledLuaVarEnvType)dataObject.GetData(typeof(SledLuaVarEnvType));
}
catch (Exception ex)
{
SledOutDevice.OutLine(
SledMessageType.Error,
"[Variable List] Exception with drag-and-drop: {0}",
ex.Message);
}
return luaVar != null;
}
private bool m_validating;
protected abstract string Description { get; }
protected abstract string[] TheColumnNames { get; }
protected abstract AttributeInfo NameAttributeInfo { get; }
protected abstract ChildInfo VariablesChildInfo { get; }
private readonly List<ExpandedState> m_lstSaveStates =
new List<ExpandedState>();
private readonly Dictionary<string, bool> m_dictSaveStates =
new Dictionary<string, bool>();
private readonly SledServiceReference<ISledLuaWatchedVariableService> m_luaWatchedVariableService =
new SledServiceReference<ISledLuaWatchedVariableService>();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Serialization
{
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Schema;
using System.Xml;
using System.Text;
using System.ComponentModel;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Xml.Serialization.Advanced;
using System.Globalization;
using System.Security.Cryptography;
using System.Diagnostics;
using System.Linq;
using System.Xml.Extensions;
// These classes provide a higher level view on reflection specific to
// Xml serialization, for example:
// - allowing one to talk about types w/o having them compiled yet
// - abstracting collections & arrays
// - abstracting classes, structs, interfaces
// - knowing about XSD primitives
// - dealing with Serializable and xmlelement
// and lots of other little details
internal enum TypeKind
{
Root,
Primitive,
Enum,
Struct,
Class,
Array,
Collection,
Enumerable,
Void,
Node,
Attribute,
Serializable
}
internal enum TypeFlags
{
None = 0x0,
Abstract = 0x1,
Reference = 0x2,
Special = 0x4,
CanBeAttributeValue = 0x8,
CanBeTextValue = 0x10,
CanBeElementValue = 0x20,
HasCustomFormatter = 0x40,
AmbiguousDataType = 0x80,
IgnoreDefault = 0x200,
HasIsEmpty = 0x400,
HasDefaultConstructor = 0x800,
XmlEncodingNotRequired = 0x1000,
UseReflection = 0x4000,
CollapseWhitespace = 0x8000,
OptionalValue = 0x10000,
CtorInaccessible = 0x20000,
UsePrivateImplementation = 0x40000,
GenericInterface = 0x80000,
Unsupported = 0x100000,
}
internal class TypeDesc
{
private string _name;
private string _fullName;
private string _cSharpName;
private TypeDesc _arrayElementTypeDesc;
private TypeDesc _arrayTypeDesc;
private TypeDesc _nullableTypeDesc;
private TypeKind _kind;
private XmlSchemaType _dataType;
private Type _type;
private TypeDesc _baseTypeDesc;
private TypeFlags _flags;
private string _formatterName;
private bool _isXsdType;
private bool _isMixed;
private MappedTypeDesc _extendedType;
private int _weight;
private Exception _exception;
internal TypeDesc(string name, string fullName, XmlSchemaType dataType, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, string formatterName)
{
_name = name.Replace('+', '.');
_fullName = fullName.Replace('+', '.');
_kind = kind;
_baseTypeDesc = baseTypeDesc;
_flags = flags;
_isXsdType = kind == TypeKind.Primitive;
if (_isXsdType)
_weight = 1;
else if (kind == TypeKind.Enum)
_weight = 2;
else if (_kind == TypeKind.Root)
_weight = -1;
else
_weight = baseTypeDesc == null ? 0 : baseTypeDesc.Weight + 1;
_dataType = dataType;
_formatterName = formatterName;
}
internal TypeDesc(string name, string fullName, XmlSchemaType dataType, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags)
: this(name, fullName, dataType, kind, baseTypeDesc, flags, null)
{ }
internal TypeDesc(string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags)
: this(name, fullName, (XmlSchemaType)null, kind, baseTypeDesc, flags, null)
{ }
internal TypeDesc(Type type, bool isXsdType, XmlSchemaType dataType, string formatterName, TypeFlags flags)
: this(type.Name, type.FullName, dataType, TypeKind.Primitive, (TypeDesc)null, flags, formatterName)
{
_isXsdType = isXsdType;
_type = type;
}
internal TypeDesc(Type type, string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, TypeDesc arrayElementTypeDesc)
: this(name, fullName, null, kind, baseTypeDesc, flags, null)
{
_arrayElementTypeDesc = arrayElementTypeDesc;
_type = type;
}
public override string ToString()
{
return _fullName;
}
internal TypeFlags Flags
{
get { return _flags; }
}
internal bool IsXsdType
{
get { return _isXsdType; }
}
internal bool IsMappedType
{
get { return _extendedType != null; }
}
internal MappedTypeDesc ExtendedType
{
get { return _extendedType; }
}
internal string Name
{
get { return _name; }
}
internal string FullName
{
get { return _fullName; }
}
internal string CSharpName
{
get
{
if (_cSharpName == null)
{
_cSharpName = _type == null ? CodeIdentifier.GetCSharpName(_fullName) : CodeIdentifier.GetCSharpName(_type);
}
return _cSharpName;
}
}
internal XmlSchemaType DataType
{
get { return _dataType; }
}
internal Type Type
{
get { return _type; }
}
internal string FormatterName
{
get { return _formatterName; }
}
internal TypeKind Kind
{
get { return _kind; }
}
internal bool IsValueType
{
get { return (_flags & TypeFlags.Reference) == 0; }
}
internal bool CanBeAttributeValue
{
get { return (_flags & TypeFlags.CanBeAttributeValue) != 0; }
}
internal bool XmlEncodingNotRequired
{
get { return (_flags & TypeFlags.XmlEncodingNotRequired) != 0; }
}
internal bool CanBeElementValue
{
get { return (_flags & TypeFlags.CanBeElementValue) != 0; }
}
internal bool CanBeTextValue
{
get { return (_flags & TypeFlags.CanBeTextValue) != 0; }
}
internal bool IsMixed
{
get { return _isMixed || CanBeTextValue; }
set { _isMixed = value; }
}
internal bool IsSpecial
{
get { return (_flags & TypeFlags.Special) != 0; }
}
internal bool IsAmbiguousDataType
{
get { return (_flags & TypeFlags.AmbiguousDataType) != 0; }
}
internal bool HasCustomFormatter
{
get { return (_flags & TypeFlags.HasCustomFormatter) != 0; }
}
internal bool HasDefaultSupport
{
get { return (_flags & TypeFlags.IgnoreDefault) == 0; }
}
internal bool HasIsEmpty
{
get { return (_flags & TypeFlags.HasIsEmpty) != 0; }
}
internal bool CollapseWhitespace
{
get { return (_flags & TypeFlags.CollapseWhitespace) != 0; }
}
internal bool HasDefaultConstructor
{
get { return (_flags & TypeFlags.HasDefaultConstructor) != 0; }
}
internal bool IsUnsupported
{
get { return (_flags & TypeFlags.Unsupported) != 0; }
}
internal bool IsGenericInterface
{
get { return (_flags & TypeFlags.GenericInterface) != 0; }
}
internal bool IsPrivateImplementation
{
get { return (_flags & TypeFlags.UsePrivateImplementation) != 0; }
}
internal bool CannotNew
{
get { return !HasDefaultConstructor || ConstructorInaccessible; }
}
internal bool IsAbstract
{
get { return (_flags & TypeFlags.Abstract) != 0; }
}
internal bool IsOptionalValue
{
get { return (_flags & TypeFlags.OptionalValue) != 0; }
}
internal bool UseReflection
{
get { return (_flags & TypeFlags.UseReflection) != 0; }
}
internal bool IsVoid
{
get { return _kind == TypeKind.Void; }
}
internal bool IsClass
{
get { return _kind == TypeKind.Class; }
}
internal bool IsStructLike
{
get { return _kind == TypeKind.Struct || _kind == TypeKind.Class; }
}
internal bool IsArrayLike
{
get { return _kind == TypeKind.Array || _kind == TypeKind.Collection || _kind == TypeKind.Enumerable; }
}
internal bool IsCollection
{
get { return _kind == TypeKind.Collection; }
}
internal bool IsEnumerable
{
get { return _kind == TypeKind.Enumerable; }
}
internal bool IsArray
{
get { return _kind == TypeKind.Array; }
}
internal bool IsPrimitive
{
get { return _kind == TypeKind.Primitive; }
}
internal bool IsEnum
{
get { return _kind == TypeKind.Enum; }
}
internal bool IsNullable
{
get { return !IsValueType; }
}
internal bool IsRoot
{
get { return _kind == TypeKind.Root; }
}
internal bool ConstructorInaccessible
{
get { return (_flags & TypeFlags.CtorInaccessible) != 0; }
}
internal Exception Exception
{
get { return _exception; }
set { _exception = value; }
}
internal TypeDesc GetNullableTypeDesc(Type type)
{
if (IsOptionalValue)
return this;
if (_nullableTypeDesc == null)
{
_nullableTypeDesc = new TypeDesc("NullableOf" + _name, "System.Nullable`1[" + _fullName + "]", null, TypeKind.Struct, this, _flags | TypeFlags.OptionalValue, _formatterName);
_nullableTypeDesc._type = type;
}
return _nullableTypeDesc;
}
internal void CheckSupported()
{
if (IsUnsupported)
{
if (Exception != null)
{
throw Exception;
}
else
{
throw new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, FullName));
}
}
if (_baseTypeDesc != null)
_baseTypeDesc.CheckSupported();
if (_arrayElementTypeDesc != null)
_arrayElementTypeDesc.CheckSupported();
}
internal void CheckNeedConstructor()
{
if (!IsValueType && !IsAbstract && !HasDefaultConstructor)
{
_flags |= TypeFlags.Unsupported;
_exception = new InvalidOperationException(SR.Format(SR.XmlConstructorInaccessible, FullName));
}
}
internal string ArrayLengthName
{
get { return _kind == TypeKind.Array ? "Length" : "Count"; }
}
internal TypeDesc ArrayElementTypeDesc
{
get { return _arrayElementTypeDesc; }
set { _arrayElementTypeDesc = value; }
}
internal int Weight
{
get { return _weight; }
}
internal TypeDesc CreateArrayTypeDesc()
{
if (_arrayTypeDesc == null)
_arrayTypeDesc = new TypeDesc(null, _name + "[]", _fullName + "[]", TypeKind.Array, null, TypeFlags.Reference | (_flags & TypeFlags.UseReflection), this);
return _arrayTypeDesc;
}
internal TypeDesc CreateMappedTypeDesc(MappedTypeDesc extension)
{
TypeDesc newTypeDesc = new TypeDesc(extension.Name, extension.Name, null, _kind, _baseTypeDesc, _flags, null);
newTypeDesc._isXsdType = _isXsdType;
newTypeDesc._isMixed = _isMixed;
newTypeDesc._extendedType = extension;
newTypeDesc._dataType = _dataType;
return newTypeDesc;
}
internal TypeDesc BaseTypeDesc
{
get { return _baseTypeDesc; }
set
{
_baseTypeDesc = value;
_weight = _baseTypeDesc == null ? 0 : _baseTypeDesc.Weight + 1;
}
}
internal bool IsDerivedFrom(TypeDesc baseTypeDesc)
{
TypeDesc typeDesc = this;
while (typeDesc != null)
{
if (typeDesc == baseTypeDesc) return true;
typeDesc = typeDesc.BaseTypeDesc;
}
return baseTypeDesc.IsRoot;
}
internal static TypeDesc FindCommonBaseTypeDesc(TypeDesc[] typeDescs)
{
if (typeDescs.Length == 0) return null;
TypeDesc leastDerivedTypeDesc = null;
int leastDerivedLevel = int.MaxValue;
for (int i = 0; i < typeDescs.Length; i++)
{
int derivationLevel = typeDescs[i].Weight;
if (derivationLevel < leastDerivedLevel)
{
leastDerivedLevel = derivationLevel;
leastDerivedTypeDesc = typeDescs[i];
}
}
while (leastDerivedTypeDesc != null)
{
int i;
for (i = 0; i < typeDescs.Length; i++)
{
if (!typeDescs[i].IsDerivedFrom(leastDerivedTypeDesc)) break;
}
if (i == typeDescs.Length) break;
leastDerivedTypeDesc = leastDerivedTypeDesc.BaseTypeDesc;
}
return leastDerivedTypeDesc;
}
}
internal class TypeScope
{
private Hashtable _typeDescs = new Hashtable();
private Hashtable _arrayTypeDescs = new Hashtable();
private ArrayList _typeMappings = new ArrayList();
private static Hashtable s_primitiveTypes = new Hashtable();
private static Hashtable s_primitiveDataTypes = new Hashtable();
private static NameTable s_primitiveNames = new NameTable();
private static string[] s_unsupportedTypes = new string[] {
"anyURI",
"duration",
"ENTITY",
"ENTITIES",
"gDay",
"gMonth",
"gMonthDay",
"gYear",
"gYearMonth",
"ID",
"IDREF",
"IDREFS",
"integer",
"language",
"negativeInteger",
"nonNegativeInteger",
"nonPositiveInteger",
//"normalizedString",
"NOTATION",
"positiveInteger",
"token"
};
static TypeScope()
{
AddPrimitive(typeof(string), "string", "String", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor);
AddPrimitive(typeof(int), "int", "Int32", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(bool), "boolean", "Boolean", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(short), "short", "Int16", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(long), "long", "Int64", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(float), "float", "Single", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(double), "double", "Double", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(decimal), "decimal", "Decimal", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(DateTime), "dateTime", "DateTime", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(XmlQualifiedName), "QName", "XmlQualifiedName", TypeFlags.CanBeAttributeValue | TypeFlags.HasCustomFormatter | TypeFlags.HasIsEmpty | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.Reference);
AddPrimitive(typeof(byte), "unsignedByte", "Byte", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(SByte), "byte", "SByte", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(UInt16), "unsignedShort", "UInt16", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(UInt32), "unsignedInt", "UInt32", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(UInt64), "unsignedLong", "UInt64", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
// Types without direct mapping (ambiguous)
AddPrimitive(typeof(DateTime), "date", "Date", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(DateTime), "time", "Time", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(string), "Name", "XmlName", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(string), "NCName", "XmlNCName", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(string), "NMTOKEN", "XmlNmToken", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(string), "NMTOKENS", "XmlNmTokens", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(byte[]), "base64Binary", "ByteArrayBase64", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired | TypeFlags.HasDefaultConstructor);
AddPrimitive(typeof(byte[]), "hexBinary", "ByteArrayHex", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired | TypeFlags.HasDefaultConstructor);
// NOTE, Micorosft: byte[] can also be used to mean array of bytes. That datatype is not a primitive, so we
// can't use the AmbiguousDataType mechanism. To get an array of bytes in literal XML, apply [XmlArray] or
// [XmlArrayItem].
XmlSchemaPatternFacet guidPattern = new XmlSchemaPatternFacet();
guidPattern.Value = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
AddNonXsdPrimitive(typeof(Guid), "guid", UrtTypes.Namespace, "Guid", new XmlQualifiedName("string", XmlSchema.Namespace), new XmlSchemaFacet[] { guidPattern }, TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.IgnoreDefault);
AddNonXsdPrimitive(typeof(char), "char", UrtTypes.Namespace, "Char", new XmlQualifiedName("unsignedShort", XmlSchema.Namespace), new XmlSchemaFacet[0], TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.IgnoreDefault);
AddNonXsdPrimitive(typeof(TimeSpan), "TimeSpan", UrtTypes.Namespace, "TimeSpan", new XmlQualifiedName("string", XmlSchema.Namespace), new XmlSchemaFacet[0], TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.IgnoreDefault);
AddSoapEncodedTypes(Soap.Encoding);
// Unsuppoted types that we map to string, if in the future we decide
// to add support for them we would need to create custom formatters for them
// normalizedString is the only one unsuported type that suppose to preserve whitesapce
AddPrimitive(typeof(string), "normalizedString", "String", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor);
for (int i = 0; i < s_unsupportedTypes.Length; i++)
{
AddPrimitive(typeof(string), s_unsupportedTypes[i], "String", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.CollapseWhitespace);
}
}
internal static bool IsKnownType(Type type)
{
if (type == typeof(object))
return true;
if (type.GetTypeInfo().IsEnum)
return false;
switch (type.GetTypeCode())
{
case TypeCode.String: return true;
case TypeCode.Int32: return true;
case TypeCode.Boolean: return true;
case TypeCode.Int16: return true;
case TypeCode.Int64: return true;
case TypeCode.Single: return true;
case TypeCode.Double: return true;
case TypeCode.Decimal: return true;
case TypeCode.DateTime: return true;
case TypeCode.Byte: return true;
case TypeCode.SByte: return true;
case TypeCode.UInt16: return true;
case TypeCode.UInt32: return true;
case TypeCode.UInt64: return true;
case TypeCode.Char: return true;
default:
if (type == typeof(XmlQualifiedName))
return true;
else if (type == typeof(byte[]))
return true;
else if (type == typeof(Guid))
return true;
else if (type == typeof (TimeSpan))
return true;
else if (type == typeof(XmlNode[]))
return true;
break;
}
return false;
}
private static void AddSoapEncodedTypes(string ns)
{
AddSoapEncodedPrimitive(typeof(string), "normalizedString", ns, "String", new XmlQualifiedName("normalizedString", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor);
for (int i = 0; i < s_unsupportedTypes.Length; i++)
{
AddSoapEncodedPrimitive(typeof(string), s_unsupportedTypes[i], ns, "String", new XmlQualifiedName(s_unsupportedTypes[i], XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.Reference | TypeFlags.CollapseWhitespace);
}
AddSoapEncodedPrimitive(typeof(string), "string", ns, "String", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(int), "int", ns, "Int32", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(bool), "boolean", ns, "Boolean", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(short), "short", ns, "Int16", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(long), "long", ns, "Int64", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(float), "float", ns, "Single", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(double), "double", ns, "Double", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(decimal), "decimal", ns, "Decimal", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(DateTime), "dateTime", ns, "DateTime", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(XmlQualifiedName), "QName", ns, "XmlQualifiedName", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.HasCustomFormatter | TypeFlags.HasIsEmpty | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(byte), "unsignedByte", ns, "Byte", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(SByte), "byte", ns, "SByte", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(UInt16), "unsignedShort", ns, "UInt16", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(UInt32), "unsignedInt", ns, "UInt32", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(UInt64), "unsignedLong", ns, "UInt64", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
// Types without direct mapping (ambigous)
AddSoapEncodedPrimitive(typeof(DateTime), "date", ns, "Date", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(DateTime), "time", ns, "Time", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(string), "Name", ns, "XmlName", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(string), "NCName", ns, "XmlNCName", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(string), "NMTOKEN", ns, "XmlNmToken", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(string), "NMTOKENS", ns, "XmlNmTokens", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(byte[]), "base64Binary", ns, "ByteArrayBase64", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(byte[]), "hexBinary", ns, "ByteArrayHex", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(string), "arrayCoordinate", ns, "String", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue);
AddSoapEncodedPrimitive(typeof(byte[]), "base64", ns, "ByteArrayBase64", new XmlQualifiedName("base64Binary", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.IgnoreDefault | TypeFlags.Reference);
}
private static void AddPrimitive(Type type, string dataTypeName, string formatterName, TypeFlags flags)
{
XmlSchemaSimpleType dataType = new XmlSchemaSimpleType();
dataType.Name = dataTypeName;
TypeDesc typeDesc = new TypeDesc(type, true, dataType, formatterName, flags);
if (s_primitiveTypes[type] == null)
s_primitiveTypes.Add(type, typeDesc);
s_primitiveDataTypes.Add(dataType, typeDesc);
s_primitiveNames.Add(dataTypeName, XmlSchema.Namespace, typeDesc);
}
private static void AddNonXsdPrimitive(Type type, string dataTypeName, string ns, string formatterName, XmlQualifiedName baseTypeName, XmlSchemaFacet[] facets, TypeFlags flags)
{
XmlSchemaSimpleType dataType = new XmlSchemaSimpleType();
dataType.Name = dataTypeName;
XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
restriction.BaseTypeName = baseTypeName;
foreach (XmlSchemaFacet facet in facets)
{
restriction.Facets.Add(facet);
}
dataType.Content = restriction;
TypeDesc typeDesc = new TypeDesc(type, false, dataType, formatterName, flags);
if (s_primitiveTypes[type] == null)
s_primitiveTypes.Add(type, typeDesc);
s_primitiveDataTypes.Add(dataType, typeDesc);
s_primitiveNames.Add(dataTypeName, ns, typeDesc);
}
private static void AddSoapEncodedPrimitive(Type type, string dataTypeName, string ns, string formatterName, XmlQualifiedName baseTypeName, TypeFlags flags)
{
AddNonXsdPrimitive(type, dataTypeName, ns, formatterName, baseTypeName, new XmlSchemaFacet[0], flags);
}
internal TypeDesc GetTypeDesc(string name, string ns)
{
return GetTypeDesc(name, ns, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue);
}
internal TypeDesc GetTypeDesc(string name, string ns, TypeFlags flags)
{
TypeDesc typeDesc = (TypeDesc)s_primitiveNames[name, ns];
if (typeDesc != null)
{
if ((typeDesc.Flags & flags) != 0)
{
return typeDesc;
}
}
return null;
}
internal TypeDesc GetTypeDesc(XmlSchemaSimpleType dataType)
{
return (TypeDesc)s_primitiveDataTypes[dataType];
}
internal TypeDesc GetTypeDesc(Type type)
{
return GetTypeDesc(type, null, true, true);
}
internal TypeDesc GetTypeDesc(Type type, MemberInfo source)
{
return GetTypeDesc(type, source, true, true);
}
internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference)
{
return GetTypeDesc(type, source, directReference, true);
}
internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference, bool throwOnError)
{
if (type.GetTypeInfo().ContainsGenericParameters)
{
throw new InvalidOperationException(SR.Format(SR.XmlUnsupportedOpenGenericType, type.ToString()));
}
TypeDesc typeDesc = (TypeDesc)s_primitiveTypes[type];
if (typeDesc == null)
{
typeDesc = (TypeDesc)_typeDescs[type];
if (typeDesc == null)
{
typeDesc = ImportTypeDesc(type, source, directReference);
}
}
if (throwOnError)
typeDesc.CheckSupported();
return typeDesc;
}
internal TypeDesc GetArrayTypeDesc(Type type)
{
TypeDesc typeDesc = (TypeDesc)_arrayTypeDescs[type];
if (typeDesc == null)
{
typeDesc = GetTypeDesc(type);
if (!typeDesc.IsArrayLike)
typeDesc = ImportTypeDesc(type, null, false);
typeDesc.CheckSupported();
_arrayTypeDescs.Add(type, typeDesc);
}
return typeDesc;
}
internal TypeMapping GetTypeMappingFromTypeDesc(TypeDesc typeDesc)
{
foreach (TypeMapping typeMapping in TypeMappings)
{
if (typeMapping.TypeDesc == typeDesc)
return typeMapping;
}
return null;
}
internal Type GetTypeFromTypeDesc(TypeDesc typeDesc)
{
if (typeDesc.Type != null)
return typeDesc.Type;
foreach (DictionaryEntry de in _typeDescs)
{
if (de.Value == typeDesc)
return de.Key as Type;
}
return null;
}
private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directReference)
{
TypeDesc typeDesc = null;
TypeKind kind;
Type arrayElementType = null;
Type baseType = null;
TypeFlags flags = 0;
Exception exception = null;
if (!type.GetTypeInfo().IsVisible)
{
flags |= TypeFlags.Unsupported;
exception = new InvalidOperationException(SR.Format(SR.XmlTypeInaccessible, type.FullName));
}
else if (directReference && (type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed))
{
flags |= TypeFlags.Unsupported;
exception = new InvalidOperationException(SR.Format(SR.XmlTypeStatic, type.FullName));
}
if (DynamicAssemblies.IsTypeDynamic(type))
{
flags |= TypeFlags.UseReflection;
}
if (!type.GetTypeInfo().IsValueType)
flags |= TypeFlags.Reference;
if (type == typeof(object))
{
kind = TypeKind.Root;
flags |= TypeFlags.HasDefaultConstructor;
}
else if (type == typeof(ValueType))
{
kind = TypeKind.Enum;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
}
else if (type == typeof(void))
{
kind = TypeKind.Void;
}
else if (typeof(IXmlSerializable).IsAssignableFrom(type))
{
kind = TypeKind.Serializable;
flags |= TypeFlags.Special | TypeFlags.CanBeElementValue;
flags |= GetConstructorFlags(type, ref exception);
}
else if (type.IsArray)
{
kind = TypeKind.Array;
if (type.GetArrayRank() > 1)
{
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedRank, type.FullName));
}
}
arrayElementType = type.GetElementType();
flags |= TypeFlags.HasDefaultConstructor;
}
else if (typeof(ICollection).IsAssignableFrom(type) && !IsArraySegment(type))
{
kind = TypeKind.Collection;
arrayElementType = GetCollectionElementType(type, memberInfo == null ? null : memberInfo.DeclaringType.FullName + "." + memberInfo.Name);
flags |= GetConstructorFlags(type, ref exception);
}
else if (type == typeof(XmlQualifiedName))
{
kind = TypeKind.Primitive;
}
else if (type.GetTypeInfo().IsPrimitive)
{
kind = TypeKind.Primitive;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
}
else if (type.GetTypeInfo().IsEnum)
{
kind = TypeKind.Enum;
}
else if (type.GetTypeInfo().IsValueType)
{
kind = TypeKind.Struct;
if (IsOptionalValue(type))
{
baseType = type.GetGenericArguments()[0];
flags |= TypeFlags.OptionalValue;
}
else
{
baseType = type.GetTypeInfo().BaseType;
}
if (type.GetTypeInfo().IsAbstract) flags |= TypeFlags.Abstract;
}
else if (type.GetTypeInfo().IsClass)
{
if (type == typeof(XmlAttribute))
{
kind = TypeKind.Attribute;
flags |= TypeFlags.Special | TypeFlags.CanBeAttributeValue;
}
else if (typeof(XmlNode).IsAssignableFrom(type))
{
kind = TypeKind.Node;
baseType = type.GetTypeInfo().BaseType;
flags |= TypeFlags.Special | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue;
if (typeof(XmlText).IsAssignableFrom(type))
flags &= ~TypeFlags.CanBeElementValue;
else if (typeof(XmlElement).IsAssignableFrom(type))
flags &= ~TypeFlags.CanBeTextValue;
else if (type.IsAssignableFrom(typeof(XmlAttribute)))
flags |= TypeFlags.CanBeAttributeValue;
}
else
{
kind = TypeKind.Class;
baseType = type.GetTypeInfo().BaseType;
if (type.GetTypeInfo().IsAbstract)
flags |= TypeFlags.Abstract;
}
}
else if (type.GetTypeInfo().IsInterface)
{
kind = TypeKind.Void;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
if (memberInfo == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterface, type.FullName));
}
else
{
exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterfaceDetails, memberInfo.DeclaringType.FullName + "." + memberInfo.Name, type.FullName));
}
}
}
else
{
kind = TypeKind.Void;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
}
// check to see if the type has public default constructor for classes
if (kind == TypeKind.Class && !type.GetTypeInfo().IsAbstract)
{
flags |= GetConstructorFlags(type, ref exception);
}
// check if a struct-like type is enumerable
if (kind == TypeKind.Struct || kind == TypeKind.Class)
{
if (typeof(IEnumerable).IsAssignableFrom(type) && !IsArraySegment(type))
{
arrayElementType = GetEnumeratorElementType(type, ref flags);
kind = TypeKind.Enumerable;
// GetEnumeratorElementType checks for the security attributes on the GetEnumerator(), Add() methods and Current property,
// we need to check the MoveNext() and ctor methods for the security attribues
flags |= GetConstructorFlags(type, ref exception);
}
}
typeDesc = new TypeDesc(type, CodeIdentifier.MakeValid(TypeName(type)), type.ToString(), kind, null, flags, null);
typeDesc.Exception = exception;
if (directReference && (typeDesc.IsClass || kind == TypeKind.Serializable))
typeDesc.CheckNeedConstructor();
if (typeDesc.IsUnsupported)
{
// return right away, do not check anything else
return typeDesc;
}
_typeDescs.Add(type, typeDesc);
if (arrayElementType != null)
{
TypeDesc td = GetTypeDesc(arrayElementType, memberInfo, true, false);
// explicitly disallow read-only elements, even if they are collections
if (directReference && (td.IsCollection || td.IsEnumerable) && !td.IsPrimitive)
{
td.CheckNeedConstructor();
}
typeDesc.ArrayElementTypeDesc = td;
}
if (baseType != null && baseType != typeof(object) && baseType != typeof(ValueType))
{
typeDesc.BaseTypeDesc = GetTypeDesc(baseType, memberInfo, false, false);
}
if (type.GetTypeInfo().IsNestedPublic)
{
for (Type t = type.DeclaringType; t != null && !t.GetTypeInfo().ContainsGenericParameters && !(t.GetTypeInfo().IsAbstract && t.GetTypeInfo().IsSealed); t = t.DeclaringType)
GetTypeDesc(t, null, false);
}
return typeDesc;
}
private static bool IsArraySegment(Type t)
{
return t.GetTypeInfo().IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
}
internal static bool IsOptionalValue(Type type)
{
if (type.GetTypeInfo().IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition())
return true;
}
return false;
}
/*
static string GetHash(string str) {
MD5 md5 = MD5.Create();
string hash = Convert.ToBase64String(md5.ComputeHash(Encoding.UTF8.GetBytes(str)), 0, 6).Replace("+", "_P").Replace("/", "_S");
return hash;
}
*/
internal static string TypeName(Type t)
{
if (t.IsArray)
{
return "ArrayOf" + TypeName(t.GetElementType());
}
else if (t.GetTypeInfo().IsGenericType)
{
StringBuilder typeName = new StringBuilder();
StringBuilder ns = new StringBuilder();
string name = t.Name;
int arity = name.IndexOf("`", StringComparison.Ordinal);
if (arity >= 0)
{
name = name.Substring(0, arity);
}
typeName.Append(name);
typeName.Append("Of");
Type[] arguments = t.GetGenericArguments();
for (int i = 0; i < arguments.Length; i++)
{
typeName.Append(TypeName(arguments[i]));
ns.Append(arguments[i].Namespace);
}
/*
if (ns.Length > 0) {
typeName.Append("_");
typeName.Append(GetHash(ns.ToString()));
}
*/
return typeName.ToString();
}
return t.Name;
}
internal static Type GetArrayElementType(Type type, string memberInfo)
{
if (type.IsArray)
return type.GetElementType();
else if (IsArraySegment(type))
return null;
else if (typeof(ICollection).IsAssignableFrom(type))
return GetCollectionElementType(type, memberInfo);
else if (typeof(IEnumerable).IsAssignableFrom(type))
{
TypeFlags flags = TypeFlags.None;
return GetEnumeratorElementType(type, ref flags);
}
else
return null;
}
internal static MemberMapping[] GetAllMembers(StructMapping mapping)
{
if (mapping.BaseMapping == null)
return mapping.Members;
ArrayList list = new ArrayList();
GetAllMembers(mapping, list);
return (MemberMapping[])list.ToArray(typeof(MemberMapping));
}
internal static void GetAllMembers(StructMapping mapping, ArrayList list)
{
if (mapping.BaseMapping != null)
{
GetAllMembers(mapping.BaseMapping, list);
}
for (int i = 0; i < mapping.Members.Length; i++)
{
list.Add(mapping.Members[i]);
}
}
internal static MemberMapping[] GetAllMembers(StructMapping mapping, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos)
{
MemberMapping[] mappings = GetAllMembers(mapping);
PopulateMemberInfos(mapping, mappings, memberInfos);
return mappings;
}
internal static MemberMapping[] GetSettableMembers(StructMapping structMapping)
{
ArrayList list = new ArrayList();
GetSettableMembers(structMapping, list);
return (MemberMapping[])list.ToArray(typeof(MemberMapping));
}
private static void GetSettableMembers(StructMapping mapping, ArrayList list)
{
if (mapping.BaseMapping != null)
{
GetSettableMembers(mapping.BaseMapping, list);
}
if (mapping.Members != null)
{
foreach (MemberMapping memberMapping in mapping.Members)
{
MemberInfo memberInfo = memberMapping.MemberInfo;
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null && !CanWriteProperty(propertyInfo, memberMapping.TypeDesc))
{
throw new InvalidOperationException(SR.Format(SR.XmlReadOnlyPropertyError, propertyInfo.DeclaringType, propertyInfo.Name));
}
list.Add(memberMapping);
}
}
}
private static bool CanWriteProperty(PropertyInfo propertyInfo, TypeDesc typeDesc)
{
Debug.Assert(propertyInfo != null);
Debug.Assert(typeDesc != null);
// If the property is a collection, we don't need a setter.
if (typeDesc.Kind == TypeKind.Collection || typeDesc.Kind == TypeKind.Enumerable)
{
return true;
}
// Else the property needs a public setter.
return propertyInfo.SetMethod != null && propertyInfo.SetMethod.IsPublic;
}
internal static MemberMapping[] GetSettableMembers(StructMapping mapping, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos)
{
MemberMapping[] mappings = GetSettableMembers(mapping);
PopulateMemberInfos(mapping, mappings, memberInfos);
return mappings;
}
private static void PopulateMemberInfos(StructMapping structMapping, MemberMapping[] mappings, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos)
{
memberInfos.Clear();
for (int i = 0; i < mappings.Length; ++i)
{
memberInfos[mappings[i].Name] = mappings[i].MemberInfo;
if (mappings[i].ChoiceIdentifier != null)
memberInfos[mappings[i].ChoiceIdentifier.MemberName] = mappings[i].ChoiceIdentifier.MemberInfo;
if (mappings[i].CheckSpecifiedMemberInfo != null)
memberInfos[mappings[i].Name + "Specified"] = mappings[i].CheckSpecifiedMemberInfo;
}
// The scenario here is that user has one base class A and one derived class B and wants to serialize/deserialize an object of B.
// There's one virtual property defined in A and overrided by B. Without the replacing logic below, the code generated will always
// try to access the property defined in A, rather than B.
// The logic here is to:
// 1) Check current members inside memberInfos dictionary and figure out whether there's any override or new properties defined in the derived class.
// If so, replace the one on the base class with the one on the derived class.
// 2) Do the same thing for the memberMapping array. Note that we need to create a new copy of MemberMapping object since the old one could still be referenced
// by the StructMapping of the baseclass, so updating it directly could lead to other issues.
Dictionary<string, MemberInfo> replaceList = null;
MemberInfo replacedInfo = null;
foreach (KeyValuePair<string, MemberInfo> pair in memberInfos)
{
if (ShouldBeReplaced(pair.Value, structMapping.TypeDesc.Type, out replacedInfo))
{
if (replaceList == null)
{
replaceList = new Dictionary<string, MemberInfo>();
}
replaceList.Add(pair.Key, replacedInfo);
}
}
if (replaceList != null)
{
foreach (KeyValuePair<string, MemberInfo> pair in replaceList)
{
memberInfos[pair.Key] = pair.Value;
}
for (int i = 0; i < mappings.Length; i++)
{
MemberInfo mi;
if (replaceList.TryGetValue(mappings[i].Name, out mi))
{
MemberMapping newMapping = mappings[i].Clone();
newMapping.MemberInfo = mi;
mappings[i] = newMapping;
}
}
}
}
private static bool ShouldBeReplaced(MemberInfo memberInfoToBeReplaced, Type derivedType, out MemberInfo replacedInfo)
{
replacedInfo = memberInfoToBeReplaced;
Type currentType = derivedType;
Type typeToBeReplaced = memberInfoToBeReplaced.DeclaringType;
if (typeToBeReplaced.IsAssignableFrom(currentType))
{
while (currentType != typeToBeReplaced)
{
TypeInfo currentInfo = currentType.GetTypeInfo();
foreach (PropertyInfo info in currentInfo.DeclaredProperties)
{
if (info.Name == memberInfoToBeReplaced.Name)
{
// we have a new modifier situation: property names are the same but the declaring types are different
replacedInfo = info;
if (replacedInfo != memberInfoToBeReplaced)
{
return true;
}
}
}
foreach (FieldInfo info in currentInfo.DeclaredFields)
{
if (info.Name == memberInfoToBeReplaced.Name)
{
// we have a new modifier situation: field names are the same but the declaring types are different
replacedInfo = info;
if (replacedInfo != memberInfoToBeReplaced)
{
return true;
}
}
}
// we go one level down and try again
currentType = currentType.GetTypeInfo().BaseType;
}
}
return false;
}
private static TypeFlags GetConstructorFlags(Type type, ref Exception exception)
{
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty<Type>());
if (ctor != null)
{
TypeFlags flags = TypeFlags.HasDefaultConstructor;
if (!ctor.IsPublic)
flags |= TypeFlags.CtorInaccessible;
else
{
IEnumerable<Attribute> attrs = ctor.GetCustomAttributes(typeof(ObsoleteAttribute), false);
if (attrs != null && attrs.Count() > 0)
{
ObsoleteAttribute obsolete = (ObsoleteAttribute)attrs.First();
if (obsolete.IsError)
{
flags |= TypeFlags.CtorInaccessible;
}
}
}
return flags;
}
return 0;
}
private static Type GetEnumeratorElementType(Type type, ref TypeFlags flags)
{
if (typeof(IEnumerable).IsAssignableFrom(type))
{
MethodInfo enumerator = type.GetMethod("GetEnumerator", new Type[0]);
if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
{
// try generic implementation
enumerator = null;
foreach (MemberInfo member in type.GetMember("System.Collections.Generic.IEnumerable<*", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
{
enumerator = member as MethodInfo;
if (enumerator != null && typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
{
// use the first one we find
flags |= TypeFlags.GenericInterface;
break;
}
else
{
enumerator = null;
}
}
if (enumerator == null)
{
// and finally private interface implementation
flags |= TypeFlags.UsePrivateImplementation;
enumerator = type.GetMethod("System.Collections.IEnumerable.GetEnumerator", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty<Type>());
}
}
if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
{
return null;
}
XmlAttributes methodAttrs = new XmlAttributes(enumerator);
if (methodAttrs.XmlIgnore) return null;
PropertyInfo p = enumerator.ReturnType.GetProperty("Current");
Type currentType = (p == null ? typeof(object) : p.PropertyType);
MethodInfo addMethod = type.GetMethod("Add", new Type[] { currentType });
if (addMethod == null && currentType != typeof(object))
{
currentType = typeof(object);
addMethod = type.GetMethod("Add", new Type[] { currentType });
}
if (addMethod == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, currentType, "IEnumerable"));
}
return currentType;
}
else
{
return null;
}
}
internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo)
{
if (typeof(IDictionary).IsAssignableFrom(type))
{
if (memberInfo == null)
{
throw new NotSupportedException(SR.Format(SR.XmlUnsupportedIDictionary, type.FullName));
}
else
{
throw new NotSupportedException(SR.Format(SR.XmlUnsupportedIDictionaryDetails, memberInfo, type.FullName));
}
}
MemberInfo[] defaultMembers = type.GetDefaultMembers();
PropertyInfo indexer = null;
if (defaultMembers != null && defaultMembers.Length > 0)
{
for (Type t = type; t != null; t = t.GetTypeInfo().BaseType)
{
for (int i = 0; i < defaultMembers.Length; i++)
{
if (defaultMembers[i] is PropertyInfo)
{
PropertyInfo defaultProp = (PropertyInfo)defaultMembers[i];
if (defaultProp.DeclaringType != t) continue;
if (!defaultProp.CanRead) continue;
MethodInfo getMethod = defaultProp.GetMethod;
ParameterInfo[] parameters = getMethod.GetParameters();
if (parameters.Length == 1 && parameters[0].ParameterType == typeof(int))
{
indexer = defaultProp;
break;
}
}
}
if (indexer != null) break;
}
}
if (indexer == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlNoDefaultAccessors, type.FullName));
}
MethodInfo addMethod = type.GetMethod("Add", new Type[] { indexer.PropertyType });
if (addMethod == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, indexer.PropertyType, "ICollection"));
}
return indexer;
}
private static Type GetCollectionElementType(Type type, string memberInfo)
{
return GetDefaultIndexer(type, memberInfo).PropertyType;
}
static internal XmlQualifiedName ParseWsdlArrayType(string type, out string dims, XmlSchemaObject parent)
{
string ns;
string name;
int nsLen = type.LastIndexOf(':');
if (nsLen <= 0)
{
ns = "";
}
else
{
ns = type.Substring(0, nsLen);
}
int nameLen = type.IndexOf('[', nsLen + 1);
if (nameLen <= nsLen)
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidArrayTypeSyntax, type));
}
name = type.Substring(nsLen + 1, nameLen - nsLen - 1);
dims = type.Substring(nameLen);
// parent is not null only in the case when we used XmlSchema.Read(),
// in which case we need to fixup the wsdl:arayType attribute value
while (parent != null)
{
if (parent.Namespaces != null)
{
string wsdlNs = (string)parent.Namespaces.Namespaces[ns];
if (wsdlNs != null)
{
ns = wsdlNs;
break;
}
}
parent = parent.Parent;
}
return new XmlQualifiedName(name, ns);
}
internal ICollection Types
{
get { return _typeDescs.Keys; }
}
internal void AddTypeMapping(TypeMapping typeMapping)
{
_typeMappings.Add(typeMapping);
}
internal ICollection TypeMappings
{
get { return _typeMappings; }
}
internal static Hashtable PrimtiveTypes { get { return s_primitiveTypes; } }
}
internal class Soap
{
private Soap() { }
internal const string Encoding = "http://schemas.xmlsoap.org/soap/encoding/";
internal const string UrType = "anyType";
internal const string Array = "Array";
internal const string ArrayType = "arrayType";
}
internal class Soap12
{
private Soap12() { }
internal const string Encoding = "http://www.w3.org/2003/05/soap-encoding";
internal const string RpcNamespace = "http://www.w3.org/2003/05/soap-rpc";
internal const string RpcResult = "result";
}
internal class Wsdl
{
private Wsdl() { }
internal const string Namespace = "http://schemas.xmlsoap.org/wsdl/";
internal const string ArrayType = "arrayType";
}
internal class UrtTypes
{
private UrtTypes() { }
internal const string Namespace = "http://microsoft.com/wsdl/types/";
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
//using System.Diagnostics;
using System.IO.Ports;
public class AndroidInput : MonoBehaviour
{
private const int PACKET_LENGTH = 6; // in bytes
public enum InputMode {WiFi, USB};
//public string ipAdress = "192.168.0.232";
public int port = 5005;
private bool serverError = false;
private bool verticalInputError = false;
private bool horizontalInputError = false;
public float inputDivisorVertical = 45.0f; // 45
public float inputDivisorHorizontal = 60.0f; // 60
public float neutralAreaHorizontal = 10.0f; // 10
public InputMode AndroidInputMode = InputMode.WiFi;
private volatile float firstZ = 0;
private volatile float firstY = 0;
private volatile bool isZset = false;
private volatile bool isYset = false;
private float time = 0;
private float lastTime = 0;
private System.Diagnostics.Stopwatch stopwatch;
private Thread udpThread;
private UdpClient client;
private volatile bool runUdpThread;
private Thread usbThread;
private SerialPort usbPort;
private volatile bool runUsbThread;
private volatile short x, y, z;
void Start ()
{
//stopwatch = new System.Diagnostics.Stopwatch();
//stopwatch.Start();
if(AndroidInputMode == InputMode.WiFi)
{
udpThread = new Thread( new ThreadStart(ReceiveDataUDP) );
udpThread.IsBackground = true;
udpThread.Start();
runUdpThread = true;
}
else
{
usbThread = new Thread( new ThreadStart(ReceiveDataUSB) );
usbThread.IsBackground = true;
usbThread.Start();
runUdpThread = true;
}
}
void Update ()
{
Debug.Log("x: " + x + ", y: " + y + ", z: " + z);
}
void OnDestroy()
{
runUdpThread = false;
runUsbThread = false;
}
private void ReceiveDataUSB()
{
usbPort = new SerialPort();
usbPort.PortName = "COM1"; // change this!
usbPort.Parity = Parity.None;
usbPort.BaudRate = 9600;
usbPort.DataBits = 8 * PACKET_LENGTH;
usbPort.StopBits = StopBits.One;
int bufCount = 0;
byte[] data = new byte[PACKET_LENGTH];
usbPort.Open();
while(runUsbThread)
{
try
{
//IPEndPoint ip = new IPEndPoint(IPAddress.Any, 0);
//byte[] data = client.Receive(ref ip);
bufCount += usbPort.Read(data, bufCount, data.Length - bufCount);
if(bufCount < PACKET_LENGTH) continue;
bufCount = 0;
data = new byte[PACKET_LENGTH];
x = (short) ( (data[1] << 8) | data[0] );
y = (short) ( (data[3] << 8) | data[2] );
z = (short) ( (data[5] << 8) | data[4] );
//Debug.LogError("x: " + x + " y: " + y + " z: " + z);
/*if(y == lastY)
{
Debug.Log("--- SAME ---");
}
else
{
lastY = y;
}*/
if(!isZset)
{
firstZ = z;
isZset = true;
}
if(!isYset)
{
firstY = y;
isYset = true;
}
}
catch (Exception e)
{
Debug.LogError(e.ToString());
//serverError = true;
}
}
usbPort.Close();
}
private void ReceiveDataUDP()
{
client = new UdpClient(port);
//short lastY = 0;
//runUdpThread = true;
while(runUdpThread)
{
/*lastTime = time;
time = stopwatch.ElapsedMilliseconds;
Debug.Log("pre: " + (time - lastTime));*/
try
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref ip);
x = (short) ( (data[1] << 8) | data[0] );
y = (short) ( (data[3] << 8) | data[2] );
z = (short) ( (data[5] << 8) | data[4] );
//Debug.LogError("x: " + x + " y: " + y + " z: " + z);
/*if(y == lastY)
{
Debug.Log("--- SAME ---");
}
else
{
lastY = y;
}*/
if(!isZset)
{
firstZ = z;
isZset = true;
}
if(!isYset)
{
firstY = y;
isYset = true;
}
}
catch (Exception e)
{
Debug.LogError(e.ToString());
//serverError = true;
}
//Thread.Sleep(10);
/*lastTime = time;
time = stopwatch.ElapsedMilliseconds;
Debug.Log("post: " + (time - lastTime));*/
}
}
public float GetAxis(string axis)
{
float inputAxis = 0;
if (axis == "Horizontal")
{
try
{
if(Mathf.Abs((z - firstZ) % 360) > neutralAreaHorizontal) inputAxis = -Mathf.Clamp(((z - firstZ) % 360) / inputDivisorVertical, -1.0f, 1.0f); //TODO
else inputAxis = 0;
horizontalInputError = false;
}
catch (System.Exception e)
{
Debug.Log(e);
horizontalInputError = true;
}
}
else if (axis == "Vertical")
{
try
{
inputAxis = Mathf.Clamp(((y - firstY) % 360) / inputDivisorVertical, -1.0f, 1.0f); //TODO
//Debug.Log(inputAxis);
verticalInputError = false;
}
catch (System.Exception e)
{
Debug.Log(e);
verticalInputError = true;
}
}
return inputAxis;
}
public float getAngleVertical()
{
return (y - firstY) % 360;
}
public float getAngleHorizontal()
{
return (z - firstZ) % 360;
}
// used for any kind of errors, like lost connetion to hardware etc.
public bool HasThrownErrors()
{
return false; //verticalInputError || horizontalInputError || serverError;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using UIKit;
using Xamarin.Forms.Internals;
using PointF = CoreGraphics.CGPoint;
using RectangleF = CoreGraphics.CGRect;
using SizeF = CoreGraphics.CGSize;
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()
{
}
IElementController ElementController => Element as IElementController;
protected CarouselPage Carousel
{
get { return (CarouselPage)Element; }
}
IPageController PageController => (IPageController)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;
PageController.SendAppearing();
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
if (!_appeared || _disposed)
return;
_appeared = false;
PageController.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 < ElementController.LogicalChildren.Count; i++)
{
Element element = ElementController.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;
PageController?.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 >= ElementController.LogicalChildren.Count)
return;
Carousel.CurrentPage = (ContentPage)ElementController.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 < ElementController.LogicalChildren.Count; i++)
{
Element element = ElementController.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);
}
}
public void RegisterEffect(Effect effect)
{
VisualElementRenderer<VisualElement>.RegisterEffect(effect, View);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MapEditor.map
{
class Map
{
SegmentDefinition[] segDef;
MapSegment[,] mapSeg;
int[,] col;
Ledge[] ledge;
public int xSize = 20;
public int ySize = 20;
public String path = "map";
public String[] script = new String[128];
public Map()
{
for (int i = 0; i < script.Length; i++)
script[i] = "";
ledge = new Ledge[16];
for (int l = 0; l < ledge.Length; l++)
ledge[l] = new Ledge();
segDef = new SegmentDefinition[512];
mapSeg = new MapSegment[3, 64];
col = new int[20, 20];
ReadSegmentDefinitions();
}
public void Read()
{
try
{
BinaryReader file = new BinaryReader(File.Open(@"data/" + path + ".zmx",
FileMode.Open));
for (int i = 0; i < ledge.Length; i++)
{
ledge[i].totalNodes = file.ReadInt32();
for (int n = 0; n < ledge[i].totalNodes; n++)
{
ledge[i].SetNode(n, new Vector2(
file.ReadSingle(), file.ReadSingle()));
}
ledge[i].flags = file.ReadInt32();
}
for (int l = 0; l < 3; l++)
{
for (int i = 0; i < 64; i++)
{
int t = file.ReadInt32();
if (t == -1)
mapSeg[l, i] = null;
else
{
mapSeg[l, i] = new MapSegment();
mapSeg[l, i].SetDefIdx(t);
mapSeg[l, i].SetLoc(new Vector2(
file.ReadSingle(),
file.ReadSingle()));
}
}
}
for (int x = 0; x < 20; x++)
{
for (int y = 0; y < 20; y++)
{
col[x, y] = file.ReadInt32();
}
}
for (int i = 0; i < script.Length; i++)
script[i] = file.ReadString();
file.Close();
}
catch { return; }
}
public void Write()
{
Write(false);
}
public void Write(bool backUp)
{
BinaryWriter file;
if (backUp)
{
//file = new BinaryWriter(File.Open(@"../../../../ZombieSmashersXNA/data/maps/" + path + ".zmx", FileMode.Create));
file = new BinaryWriter(File.Open(@"data/" + path + ".zmx", FileMode.Create));
}
else
{
file = new BinaryWriter(File.Open(@"data/" + path + ".zmx",
FileMode.Create));
}
for (int i = 0; i < ledge.Length; i++)
{
file.Write(ledge[i].totalNodes);
for (int n = 0; n < ledge[i].totalNodes; n++)
{
file.Write(ledge[i].GetNode(n).X);
file.Write(ledge[i].GetNode(n).Y);
}
file.Write(ledge[i].flags);
}
for (int l = 0; l < 3; l++)
{
for (int i = 0; i < 64; i++)
{
if (mapSeg[l, i] == null)
file.Write(-1);
else
{
file.Write(mapSeg[l, i].GetDefIdx());
file.Write(mapSeg[l, i].GetLoc().X);
file.Write(mapSeg[l, i].GetLoc().Y);
}
}
}
for (int x = 0; x < 20; x++)
{
for (int y = 0; y < 20; y++)
{
file.Write(col[x, y]);
}
}
for (int i = 0; i < script.Length; i++)
file.Write(script[i]);
file.Close();
}
public void SetLedgeNode(int l, int n, Vector2 v)
{
ledge[l].SetNode(n, v);
}
public void SetLedgeTotalNodes(int l, int t)
{
ledge[l].totalNodes = t;
}
public Vector2 GetLedgeNode(int l, int n)
{
return ledge[l].GetNode(n);
}
public int GetLedgeTotalNodes(int l)
{
return ledge[l].totalNodes;
}
public void SetLedgeFlags(int l, int f)
{
ledge[l].flags = f;
}
public int GetLedgeFlags(int l)
{
return ledge[l].flags;
}
private void ReadSegmentDefinitions()
{
StreamReader s = new StreamReader(@"gfx/maps.zdx");
String t = "";
int n;
int currentTex = 0;
int curDef = -1;
Rectangle tRect = new Rectangle();
String[] split;
t = s.ReadLine();
while (!s.EndOfStream)
{
t = s.ReadLine();
if (t.StartsWith("#"))
{
if (t.StartsWith("#src"))
{
split = t.Split(' ');
if (split.Length > 1)
{
n = Convert.ToInt32(split[1]);
currentTex = n - 1;
}
}
}
else
{
curDef++;
String name = t;
t = s.ReadLine();
split = t.Split(' ');
if (split.Length > 3)
{
tRect.X = Convert.ToInt32(split[0]);
tRect.Y = Convert.ToInt32(split[1]);
tRect.Width = Convert.ToInt32(split[2]) - tRect.X;
tRect.Height = Convert.ToInt32(split[3]) - tRect.Y;
}
else
{
Console.WriteLine("read fail: " + name);
}
int tex = currentTex;
t = s.ReadLine();
int flags = Convert.ToInt32(t);
segDef[curDef] = new SegmentDefinition(name, tex, tRect, flags);
}
}
}
public int GetCol(int x, int y)
{
return col[x, y];
}
public void SetCol(int x, int y, int val)
{
col[x, y] = val;
}
public SegmentDefinition GetSegDef(int idx)
{
return segDef[idx];
}
public Vector2 GetSegLoc(int l, int i)
{
return mapSeg[l, i].GetLoc();
}
public int GetSegIdx(int l, int i)
{
if (mapSeg[l, i] == null)
return -1;
return mapSeg[l, i].GetDefIdx();
}
public void SetSegLoc(int l, int i, Vector2 loc)
{
mapSeg[l, i].SetLoc(loc);
}
public void SwapSegs(int l, int i, int n)
{
MapSegment tSeg = new MapSegment();
if (mapSeg[l, i] != null &&
mapSeg[l, n] != null)
{
tSeg.SetDefIdx(mapSeg[l, i].GetDefIdx());
tSeg.SetLoc(mapSeg[l, i].GetLoc());
tSeg.SetDefIdx(mapSeg[l, i].GetDefIdx());
tSeg.SetLoc(mapSeg[l, i].GetLoc());
mapSeg[l, i].SetDefIdx(mapSeg[l, n].GetDefIdx());
mapSeg[l, i].SetLoc(mapSeg[l, n].GetLoc());
mapSeg[l, n].SetDefIdx(tSeg.GetDefIdx());
mapSeg[l, n].SetLoc(tSeg.GetLoc());
}
}
public int AddSeg(int l, int idx)
{
for (int i = 0; i < 64; i++)
{
if (mapSeg[l, i] == null)
{
mapSeg[l, i] = new MapSegment();
mapSeg[l, i].SetDefIdx(idx);
return i;
}
}
return -1;
}
public int GetHoveredSegment(int x, int y, int l, Vector2 scroll)
{
int r = -1;
float scale = 1.0f;
if (l == 0)
scale = 0.75f;
if (l == 2)
scale = 1.25f;
scale *= 0.5f;
for (int i = 0; i < 64; i++)
{
if (mapSeg[l, i] != null)
{
Rectangle sRect = segDef[mapSeg[l, i].GetDefIdx()].GetSrcRect();
Rectangle dRect = new Rectangle(
(int)(mapSeg[l, i].GetLoc().X - scroll.X * scale),
(int)(mapSeg[l, i].GetLoc().Y - scroll.Y * scale),
dRect.Width = (int)((float)sRect.Width * scale),
dRect.Height = (int)((float)sRect.Height * scale));
if (dRect.Contains(x, y))
r = i;
}
}
return r;
}
public void Draw(SpriteBatch sprite, Texture2D[] mapsTex, Vector2 scroll)
{
Rectangle sRect = new Rectangle();
Rectangle dRect = new Rectangle();
sprite.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
for (int l = 0; l < 3; l++)
{
float scale = 1.0f;
Color color = Color.White;
if (l == 0)
{
color = Color.Gray;
scale = 0.75f;
}
if (l == 2)
{
color = Color.DarkGray;
scale = 1.25f;
}
scale *= 0.5f;
for (int i = 0; i < 64; i++)
{
if (mapSeg[l, i] != null)
{
sRect = segDef[mapSeg[l, i].GetDefIdx()].GetSrcRect();
dRect.X = (int)(mapSeg[l, i].GetLoc().X - scroll.X * scale);
dRect.Y = (int)(mapSeg[l, i].GetLoc().Y - scroll.Y * scale);
dRect.Width = (int)((float)sRect.Width * scale);
dRect.Height = (int)((float)sRect.Height * scale);
sprite.Draw(mapsTex[segDef[mapSeg[l, i].GetDefIdx()].GetSrcIdx()],
dRect,
sRect,
color);
}
}
}
sprite.End();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestNotZAndNotCByte()
{
var test = new BooleanBinaryOpTest__TestNotZAndNotCByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__TestNotZAndNotCByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Byte> _fld1;
public Vector256<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestNotZAndNotCByte testClass)
{
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestNotZAndNotCByte testClass)
{
fixed (Vector256<Byte>* pFld1 = &_fld1)
fixed (Vector256<Byte>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Byte*)(pFld1)),
Avx.LoadVector256((Byte*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector256<Byte> _clsVar1;
private static Vector256<Byte> _clsVar2;
private Vector256<Byte> _fld1;
private Vector256<Byte> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestNotZAndNotCByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
}
public BooleanBinaryOpTest__TestNotZAndNotCByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.TestNotZAndNotC(
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.TestNotZAndNotC(
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector256<Byte>* pClsVar2 = &_clsVar2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Byte*)(pClsVar1)),
Avx.LoadVector256((Byte*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr);
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestNotZAndNotCByte();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestNotZAndNotCByte();
fixed (Vector256<Byte>* pFld1 = &test._fld1)
fixed (Vector256<Byte>* pFld2 = &test._fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Byte*)(pFld1)),
Avx.LoadVector256((Byte*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Byte>* pFld1 = &_fld1)
fixed (Vector256<Byte>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Byte*)(pFld1)),
Avx.LoadVector256((Byte*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Byte*)(&test._fld1)),
Avx.LoadVector256((Byte*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Byte> op1, Vector256<Byte> op2, bool result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Byte>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Byte[] left, Byte[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
succeeded = (((expectedResult1 == false) && (expectedResult2 == false)) == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestNotZAndNotC)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = 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.
/*============================================================
**
**
**
** Implementation details of CLR Contracts.
**
===========================================================*/
#define DEBUG // The behavior of this contract library should be consistent regardless of build type.
#if SILVERLIGHT
#define FEATURE_UNTRUSTED_CALLERS
#elif REDHAWK_RUNTIME
#elif BARTOK_RUNTIME
#else // CLR
#define FEATURE_UNTRUSTED_CALLERS
#define FEATURE_RELIABILITY_CONTRACTS
#define FEATURE_SERIALIZATION
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Reflection;
#if FEATURE_RELIABILITY_CONTRACTS
using System.Runtime.ConstrainedExecution;
#endif
#if FEATURE_UNTRUSTED_CALLERS
using System.Security;
using System.Security.Permissions;
#endif
namespace System.Diagnostics.Contracts {
public static partial class Contract
{
#region Private Methods
[ThreadStatic]
private static bool _assertingMustUseRewriter;
/// <summary>
/// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly.
/// It is NEVER used to indicate failure of actual contracts at runtime.
/// </summary>
[SecuritySafeCritical]
static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind)
{
if (_assertingMustUseRewriter)
System.Diagnostics.Assert.Fail("Asserting that we must use the rewriter went reentrant.", "Didn't rewrite this mscorlib?");
_assertingMustUseRewriter = true;
// For better diagnostics, report which assembly is at fault. Walk up stack and
// find the first non-mscorlib assembly.
Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object.
StackTrace stack = new StackTrace();
Assembly probablyNotRewritten = null;
for (int i = 0; i < stack.FrameCount; i++)
{
Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly;
if (caller != thisAssembly)
{
probablyNotRewritten = caller;
break;
}
}
if (probablyNotRewritten == null)
probablyNotRewritten = thisAssembly;
String simpleName = probablyNotRewritten.GetName().Name;
System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, Environment.GetResourceString("MustUseCCRewrite", contractKind, simpleName), null, null, null);
_assertingMustUseRewriter = false;
}
#endregion Private Methods
#region Failure Behavior
/// <summary>
/// Without contract rewriting, failing Assert/Assumes end up calling this method.
/// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call
/// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by
/// System.Runtime.CompilerServices.ContractHelper.TriggerFailure.
/// </summary>
[SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException)
{
if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), nameof(failureKind));
Contract.EndContractBlock();
// displayMessage == null means: yes we handled it. Otherwise it is the localized failure message
var displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException);
if (displayMessage == null) return;
System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException);
}
/// <summary>
/// Allows a managed application environment such as an interactive interpreter (IronPython)
/// to be notified of contract failures and
/// potentially "handle" them, either by throwing a particular exception type, etc. If any of the
/// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will
/// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires
/// full trust, because it will inform you of bugs in the appdomain and because the event handler
/// could allow you to continue execution.
/// </summary>
public static event EventHandler<ContractFailedEventArgs> ContractFailed {
#if FEATURE_UNTRUSTED_CALLERS
[SecurityCritical]
#if FEATURE_LINK_DEMAND
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
#endif
#endif
add {
System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value;
}
#if FEATURE_UNTRUSTED_CALLERS
[SecurityCritical]
#if FEATURE_LINK_DEMAND
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
#endif
#endif
remove {
System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value;
}
}
#endregion FailureBehavior
}
public sealed class ContractFailedEventArgs : EventArgs
{
private ContractFailureKind _failureKind;
private String _message;
private String _condition;
private Exception _originalException;
private bool _handled;
private bool _unwind;
internal Exception thrownDuringHandler;
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException)
{
Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException);
_failureKind = failureKind;
_message = message;
_condition = condition;
_originalException = originalException;
}
public String Message { get { return _message; } }
public String Condition { get { return _condition; } }
public ContractFailureKind FailureKind { get { return _failureKind; } }
public Exception OriginalException { get { return _originalException; } }
// Whether the event handler "handles" this contract failure, or to fail via escalation policy.
public bool Handled {
get { return _handled; }
}
#if FEATURE_UNTRUSTED_CALLERS
[SecurityCritical]
#if FEATURE_LINK_DEMAND
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
#endif
#endif
public void SetHandled()
{
_handled = true;
}
public bool Unwind {
get { return _unwind; }
}
#if FEATURE_UNTRUSTED_CALLERS
[SecurityCritical]
#if FEATURE_LINK_DEMAND
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
#endif
#endif
public void SetUnwind()
{
_unwind = true;
}
}
[Serializable]
[SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")]
internal sealed class ContractException : Exception
{
readonly ContractFailureKind _Kind;
readonly string _UserMessage;
readonly string _Condition;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public ContractFailureKind Kind { get { return _Kind; } }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string Failure { get { return this.Message; } }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string UserMessage { get { return _UserMessage; } }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string Condition { get { return _Condition; } }
// Called by COM Interop, if we see COR_E_CODECONTRACTFAILED as an HRESULT.
private ContractException()
{
HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED;
}
public ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException)
: base(failure, innerException)
{
HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED;
this._Kind = kind;
this._UserMessage = userMessage;
this._Condition = condition;
}
private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
_Kind = (ContractFailureKind)info.GetInt32("Kind");
_UserMessage = info.GetString("UserMessage");
_Condition = info.GetString("Condition");
}
#if FEATURE_UNTRUSTED_CALLERS && FEATURE_SERIALIZATION
[SecurityCritical]
#if FEATURE_LINK_DEMAND && FEATURE_SERIALIZATION
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
#endif // FEATURE_LINK_DEMAND
#endif // FEATURE_UNTRUSTED_CALLERS
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("Kind", _Kind);
info.AddValue("UserMessage", _UserMessage);
info.AddValue("Condition", _Condition);
}
}
}
namespace System.Runtime.CompilerServices
{
public static partial class ContractHelper
{
#region Private fields
private static volatile EventHandler<ContractFailedEventArgs> contractFailedEvent;
private static readonly Object lockObject = new Object();
internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542);
#endregion
/// <summary>
/// Allows a managed application environment such as an interactive interpreter (IronPython) or a
/// web browser host (Jolt hosting Silverlight in IE) to be notified of contract failures and
/// potentially "handle" them, either by throwing a particular exception type, etc. If any of the
/// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will
/// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires
/// full trust.
/// </summary>
internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed
{
#if FEATURE_UNTRUSTED_CALLERS
[SecurityCritical]
#endif
add {
// Eagerly prepare each event handler _marked with a reliability contract_, to
// attempt to reduce out of memory exceptions while reporting contract violations.
// This only works if the new handler obeys the constraints placed on
// constrained execution regions. Eagerly preparing non-reliable event handlers
// would be a perf hit and wouldn't significantly improve reliability.
// UE: Please mention reliable event handlers should also be marked with the
// PrePrepareMethodAttribute to avoid CER eager preparation work when ngen'ed.
System.Runtime.CompilerServices.RuntimeHelpers.PrepareContractedDelegate(value);
lock (lockObject)
{
contractFailedEvent += value;
}
}
#if FEATURE_UNTRUSTED_CALLERS
[SecurityCritical]
#endif
remove {
lock (lockObject)
{
contractFailedEvent -= value;
}
}
}
/// <summary>
/// Rewriter will call this method on a contract failure to allow listeners to be notified.
/// The method should not perform any failure (assert/throw) itself.
/// This method has 3 functions:
/// 1. Call any contract hooks (such as listeners to Contract failed events)
/// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null)
/// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently.
/// </summary>
/// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough.
/// On exit: null if the event was handled and should not trigger a failure.
/// Otherwise, returns the localized failure message</param>
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
[SecuritySafeCritical]
#endif
static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage)
{
if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), nameof(failureKind));
Contract.EndContractBlock();
string returnValue;
String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup...
ContractFailedEventArgs eventArgs = null; // In case of OOM.
#if FEATURE_RELIABILITY_CONTRACTS
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
displayMessage = GetDisplayMessage(failureKind, userMessage, conditionText);
EventHandler<ContractFailedEventArgs> contractFailedEventLocal = contractFailedEvent;
if (contractFailedEventLocal != null)
{
eventArgs = new ContractFailedEventArgs(failureKind, displayMessage, conditionText, innerException);
foreach (EventHandler<ContractFailedEventArgs> handler in contractFailedEventLocal.GetInvocationList())
{
try
{
handler(null, eventArgs);
}
catch (Exception e)
{
eventArgs.thrownDuringHandler = e;
eventArgs.SetUnwind();
}
}
if (eventArgs.Unwind)
{
#if !FEATURE_CORECLR
if (Environment.IsCLRHosted)
TriggerCodeContractEscalationPolicy(failureKind, displayMessage, conditionText, innerException);
#endif
// unwind
if (innerException == null) { innerException = eventArgs.thrownDuringHandler; }
throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException);
}
}
}
finally
{
if (eventArgs != null && eventArgs.Handled)
{
returnValue = null; // handled
}
else
{
returnValue = displayMessage;
}
}
resultFailureMessage = returnValue;
}
/// <summary>
/// Rewriter calls this method to get the default failure behavior.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "conditionText")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_UNTRUSTED_CALLERS && !FEATURE_CORECLR
[SecuritySafeCritical]
#endif
static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException)
{
// If we're here, our intent is to pop up a dialog box (if we can). For developers
// interacting live with a debugger, this is a good experience. For Silverlight
// hosted in Internet Explorer, the assert window is great. If we cannot
// pop up a dialog box, throw an exception (consider a library compiled with
// "Assert On Failure" but used in a process that can't pop up asserts, like an
// NT Service). For the CLR hosted by server apps like SQL or Exchange, we should
// trigger escalation policy.
#if !FEATURE_CORECLR
if (Environment.IsCLRHosted)
{
TriggerCodeContractEscalationPolicy(kind, displayMessage, conditionText, innerException);
// Hosts like SQL may choose to abort the thread, so we will not get here in all cases.
// But if the host's chosen action was to throw an exception, we should throw an exception
// here (which is easier to do in managed code with the right parameters).
throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException);
}
#endif // !FEATURE_CORECLR
if (!Environment.UserInteractive) {
throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException);
}
// May need to rethink Assert.Fail w/ TaskDialogIndirect as a model. Window title. Main instruction. Content. Expanded info.
// Optional info like string for collapsed text vs. expanded text.
String windowTitle = Environment.GetResourceString(GetResourceNameForFailure(kind));
const int numStackFramesToSkip = 2; // To make stack traces easier to read
System.Diagnostics.Assert.Fail(conditionText, displayMessage, windowTitle, COR_E_CODECONTRACTFAILED, StackTrace.TraceFormat.Normal, numStackFramesToSkip);
// If we got here, the user selected Ignore. Continue.
}
private static String GetResourceNameForFailure(ContractFailureKind failureKind)
{
String resourceName = null;
switch (failureKind)
{
case ContractFailureKind.Assert:
resourceName = "AssertionFailed";
break;
case ContractFailureKind.Assume:
resourceName = "AssumptionFailed";
break;
case ContractFailureKind.Precondition:
resourceName = "PreconditionFailed";
break;
case ContractFailureKind.Postcondition:
resourceName = "PostconditionFailed";
break;
case ContractFailureKind.Invariant:
resourceName = "InvariantFailed";
break;
case ContractFailureKind.PostconditionOnException:
resourceName = "PostconditionOnExceptionFailed";
break;
default:
Contract.Assume(false, "Unreachable code");
resourceName = "AssumptionFailed";
break;
}
return resourceName;
}
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText)
{
String resourceName = GetResourceNameForFailure(failureKind);
// Well-formatted English messages will take one of four forms. A sentence ending in
// either a period or a colon, the condition string, then the message tacked
// on to the end with two spaces in front.
// Note that both the conditionText and userMessage may be null. Also,
// on Silverlight we may not be able to look up a friendly string for the
// error message. Let's leverage Silverlight's default error message there.
String failureMessage;
if (!String.IsNullOrEmpty(conditionText)) {
resourceName += "_Cnd";
failureMessage = Environment.GetResourceString(resourceName, conditionText);
}
else {
failureMessage = Environment.GetResourceString(resourceName);
}
// Now add in the user message, if present.
if (!String.IsNullOrEmpty(userMessage))
{
return failureMessage + " " + userMessage;
}
else
{
return failureMessage;
}
}
#if !FEATURE_CORECLR
// Will trigger escalation policy, if hosted and the host requested us to do something (such as
// abort the thread or exit the process). Starting in Dev11, for hosted apps the default behavior
// is to throw an exception.
// Implementation notes:
// We implement our default behavior of throwing an exception by simply returning from our native
// method inside the runtime and falling through to throw an exception.
// We must call through this method before calling the method on the Environment class
// because our security team does not yet support SecuritySafeCritical on P/Invoke methods.
// Note this can be called in the context of throwing another exception (EnsuresOnThrow).
[SecuritySafeCritical]
[DebuggerNonUserCode]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static void TriggerCodeContractEscalationPolicy(ContractFailureKind failureKind, String message, String conditionText, Exception innerException)
{
String exceptionAsString = null;
if (innerException != null)
exceptionAsString = innerException.ToString();
Environment.TriggerCodeContractFailure(failureKind, message, conditionText, exceptionAsString);
}
#endif // !FEATURE_CORECLR
}
} // namespace System.Runtime.CompilerServices
| |
namespace EIDSS.Reports.Parameterized.Human.AJ.Keepers
{
partial class ExternalComparativeReportKeeper
{
#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(ExternalComparativeReportKeeper));
this.StartYearLabel = new System.Windows.Forms.Label();
this.Year1SpinEdit = new DevExpress.XtraEditors.SpinEdit();
this.Year2SpinEdit = new DevExpress.XtraEditors.SpinEdit();
this.EndYearLabel = new System.Windows.Forms.Label();
this.region1Filter = new EIDSS.Reports.Parameterized.Filters.RegionFilter();
this.rayon1Filter = new EIDSS.Reports.Parameterized.Filters.RayonFilter();
this.EndMonthLookUp = new DevExpress.XtraEditors.LookUpEdit();
this.StartMonthLookUp = new DevExpress.XtraEditors.LookUpEdit();
this.StartMonthLabel = new System.Windows.Forms.Label();
this.EndMonthLabel = new System.Windows.Forms.Label();
this.pnlSettings.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ceUseArchiveData.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Year1SpinEdit.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Year2SpinEdit.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.EndMonthLookUp.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.StartMonthLookUp.Properties)).BeginInit();
this.SuspendLayout();
//
// pnlSettings
//
this.pnlSettings.Controls.Add(this.EndMonthLookUp);
this.pnlSettings.Controls.Add(this.StartMonthLookUp);
this.pnlSettings.Controls.Add(this.StartMonthLabel);
this.pnlSettings.Controls.Add(this.EndMonthLabel);
this.pnlSettings.Controls.Add(this.Year1SpinEdit);
this.pnlSettings.Controls.Add(this.Year2SpinEdit);
this.pnlSettings.Controls.Add(this.region1Filter);
this.pnlSettings.Controls.Add(this.rayon1Filter);
this.pnlSettings.Controls.Add(this.EndYearLabel);
this.pnlSettings.Controls.Add(this.StartYearLabel);
resources.ApplyResources(this.pnlSettings, "pnlSettings");
this.pnlSettings.Controls.SetChildIndex(this.ceUseArchiveData, 0);
this.pnlSettings.Controls.SetChildIndex(this.StartYearLabel, 0);
this.pnlSettings.Controls.SetChildIndex(this.EndYearLabel, 0);
this.pnlSettings.Controls.SetChildIndex(this.rayon1Filter, 0);
this.pnlSettings.Controls.SetChildIndex(this.region1Filter, 0);
this.pnlSettings.Controls.SetChildIndex(this.Year2SpinEdit, 0);
this.pnlSettings.Controls.SetChildIndex(this.Year1SpinEdit, 0);
this.pnlSettings.Controls.SetChildIndex(this.EndMonthLabel, 0);
this.pnlSettings.Controls.SetChildIndex(this.StartMonthLabel, 0);
this.pnlSettings.Controls.SetChildIndex(this.StartMonthLookUp, 0);
this.pnlSettings.Controls.SetChildIndex(this.EndMonthLookUp, 0);
//
// ceUseArchiveData
//
resources.ApplyResources(this.ceUseArchiveData, "ceUseArchiveData");
this.ceUseArchiveData.Properties.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("ceUseArchiveData.Properties.Appearance.Font")));
this.ceUseArchiveData.Properties.Appearance.Options.UseFont = true;
this.ceUseArchiveData.Properties.AppearanceDisabled.Font = ((System.Drawing.Font)(resources.GetObject("ceUseArchiveData.Properties.AppearanceDisabled.Font")));
this.ceUseArchiveData.Properties.AppearanceDisabled.Options.UseFont = true;
this.ceUseArchiveData.Properties.AppearanceFocused.Font = ((System.Drawing.Font)(resources.GetObject("ceUseArchiveData.Properties.AppearanceFocused.Font")));
this.ceUseArchiveData.Properties.AppearanceFocused.Options.UseFont = true;
this.ceUseArchiveData.Properties.AppearanceReadOnly.Font = ((System.Drawing.Font)(resources.GetObject("ceUseArchiveData.Properties.AppearanceReadOnly.Font")));
this.ceUseArchiveData.Properties.AppearanceReadOnly.Options.UseFont = true;
this.ceUseArchiveData.Properties.Caption = resources.GetString("ceUseArchiveData.Properties.Caption");
//
// StartYearLabel
//
resources.ApplyResources(this.StartYearLabel, "StartYearLabel");
this.StartYearLabel.ForeColor = System.Drawing.Color.Black;
this.StartYearLabel.Name = "StartYearLabel";
//
// Year1SpinEdit
//
resources.ApplyResources(this.Year1SpinEdit, "Year1SpinEdit");
this.Year1SpinEdit.Name = "Year1SpinEdit";
this.Year1SpinEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.Year1SpinEdit.Properties.Mask.EditMask = resources.GetString("Year1SpinEdit.Properties.Mask.EditMask");
this.Year1SpinEdit.Properties.Mask.MaskType = ((DevExpress.XtraEditors.Mask.MaskType)(resources.GetObject("Year1SpinEdit.Properties.Mask.MaskType")));
this.Year1SpinEdit.Properties.MaxValue = new decimal(new int[] {
2030,
0,
0,
0});
this.Year1SpinEdit.Properties.MinValue = new decimal(new int[] {
2000,
0,
0,
0});
this.Year1SpinEdit.EditValueChanged += new System.EventHandler(this.seYear1_EditValueChanged);
//
// Year2SpinEdit
//
resources.ApplyResources(this.Year2SpinEdit, "Year2SpinEdit");
this.Year2SpinEdit.Name = "Year2SpinEdit";
this.Year2SpinEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.Year2SpinEdit.Properties.Mask.EditMask = resources.GetString("Year2SpinEdit.Properties.Mask.EditMask");
this.Year2SpinEdit.Properties.Mask.MaskType = ((DevExpress.XtraEditors.Mask.MaskType)(resources.GetObject("Year2SpinEdit.Properties.Mask.MaskType")));
this.Year2SpinEdit.Properties.MaxValue = new decimal(new int[] {
2030,
0,
0,
0});
this.Year2SpinEdit.Properties.MinValue = new decimal(new int[] {
2000,
0,
0,
0});
this.Year2SpinEdit.EditValueChanged += new System.EventHandler(this.seYear2_EditValueChanged);
//
// EndYearLabel
//
resources.ApplyResources(this.EndYearLabel, "EndYearLabel");
this.EndYearLabel.ForeColor = System.Drawing.Color.Black;
this.EndYearLabel.Name = "EndYearLabel";
//
// region1Filter
//
this.region1Filter.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("region1Filter.Appearance.Font")));
this.region1Filter.Appearance.Options.UseFont = true;
resources.ApplyResources(this.region1Filter, "region1Filter");
this.region1Filter.Name = "region1Filter";
this.region1Filter.ValueChanged += new System.EventHandler<EIDSS.Reports.BaseControls.Filters.SingleFilterEventArgs>(this.region1Filter_ValueChanged);
//
// rayon1Filter
//
this.rayon1Filter.Appearance.Options.UseFont = true;
resources.ApplyResources(this.rayon1Filter, "rayon1Filter");
this.rayon1Filter.Name = "rayon1Filter";
this.rayon1Filter.ValueChanged += new System.EventHandler<EIDSS.Reports.BaseControls.Filters.SingleFilterEventArgs>(this.rayon1Filter_ValueChanged);
//
// EndMonthLookUp
//
resources.ApplyResources(this.EndMonthLookUp, "EndMonthLookUp");
this.EndMonthLookUp.Name = "EndMonthLookUp";
this.EndMonthLookUp.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("EndMonthLookUp.Properties.Buttons")))),
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("EndMonthLookUp.Properties.Buttons1"))))});
this.EndMonthLookUp.Properties.DropDownRows = 12;
this.EndMonthLookUp.Properties.NullText = resources.GetString("EndMonthLookUp.Properties.NullText");
this.EndMonthLookUp.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.MonthLookUp_ButtonClick);
this.EndMonthLookUp.EditValueChanged += new System.EventHandler(this.EndMonthLookUp_EditValueChanged);
//
// StartMonthLookUp
//
resources.ApplyResources(this.StartMonthLookUp, "StartMonthLookUp");
this.StartMonthLookUp.Name = "StartMonthLookUp";
this.StartMonthLookUp.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("StartMonthLookUp.Properties.Buttons")))),
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("StartMonthLookUp.Properties.Buttons1"))))});
this.StartMonthLookUp.Properties.DropDownRows = 12;
this.StartMonthLookUp.Properties.NullText = resources.GetString("StartMonthLookUp.Properties.NullText");
this.StartMonthLookUp.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.MonthLookUp_ButtonClick);
this.StartMonthLookUp.EditValueChanged += new System.EventHandler(this.StartMonthLookUp_EditValueChanged);
//
// StartMonthLabel
//
resources.ApplyResources(this.StartMonthLabel, "StartMonthLabel");
this.StartMonthLabel.ForeColor = System.Drawing.Color.Black;
this.StartMonthLabel.Name = "StartMonthLabel";
//
// EndMonthLabel
//
resources.ApplyResources(this.EndMonthLabel, "EndMonthLabel");
this.EndMonthLabel.ForeColor = System.Drawing.Color.Black;
this.EndMonthLabel.Name = "EndMonthLabel";
//
// ExternalComparativeReportKeeper
//
resources.ApplyResources(this, "$this");
this.HeaderHeight = 130;
this.Name = "ExternalComparativeReportKeeper";
this.pnlSettings.ResumeLayout(false);
this.pnlSettings.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.ceUseArchiveData.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.Year1SpinEdit.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.Year2SpinEdit.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.EndMonthLookUp.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.StartMonthLookUp.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label StartYearLabel;
private DevExpress.XtraEditors.SpinEdit Year1SpinEdit;
private DevExpress.XtraEditors.SpinEdit Year2SpinEdit;
private System.Windows.Forms.Label EndYearLabel;
private Parameterized.Filters.RegionFilter region1Filter;
private Parameterized.Filters.RayonFilter rayon1Filter;
protected DevExpress.XtraEditors.LookUpEdit EndMonthLookUp;
protected DevExpress.XtraEditors.LookUpEdit StartMonthLookUp;
protected System.Windows.Forms.Label StartMonthLabel;
protected System.Windows.Forms.Label EndMonthLabel;
}
}
| |
// 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.ComponentModel;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Net;
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.Xml;
namespace System.ServiceModel.Dispatcher
{
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Compat", Justification = "Compat is an accepted abbreviation")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ClientRuntimeCompatBase
{
internal ClientRuntimeCompatBase() { }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
public IList<IClientMessageInspector> MessageInspectors
{
get
{
return this.messageInspectors;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
public KeyedCollection<string, ClientOperation> Operations
{
get
{
return this.compatOperations;
}
}
internal SynchronizedCollection<IClientMessageInspector> messageInspectors;
internal SynchronizedKeyedCollection<string, ClientOperation> operations;
internal KeyedCollection<string, ClientOperation> compatOperations;
}
public sealed class ClientRuntime : ClientRuntimeCompatBase
{
private bool _addTransactionFlowProperties = true;
private Type _callbackProxyType;
private ProxyBehaviorCollection<IChannelInitializer> _channelInitializers;
private string _contractName;
private string _contractNamespace;
private Type _contractProxyType;
private DispatchRuntime _dispatchRuntime;
private IdentityVerifier _identityVerifier;
private ProxyBehaviorCollection<IInteractiveChannelInitializer> _interactiveChannelInitializers;
private IClientOperationSelector _operationSelector;
private ImmutableClientRuntime _runtime;
private ClientOperation _unhandled;
private bool _useSynchronizationContext = true;
private Uri _via;
private SharedRuntimeState _shared;
private int _maxFaultSize;
private bool _messageVersionNoneFaultsEnabled;
internal ClientRuntime(DispatchRuntime dispatchRuntime, SharedRuntimeState shared)
: this(dispatchRuntime.EndpointDispatcher.ContractName,
dispatchRuntime.EndpointDispatcher.ContractNamespace,
shared)
{
if (dispatchRuntime == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dispatchRuntime");
_dispatchRuntime = dispatchRuntime;
_shared = shared;
Fx.Assert(shared.IsOnServer, "Server constructor called on client?");
}
internal ClientRuntime(string contractName, string contractNamespace)
: this(contractName, contractNamespace, new SharedRuntimeState(false))
{
Fx.Assert(!_shared.IsOnServer, "Client constructor called on server?");
}
private ClientRuntime(string contractName, string contractNamespace, SharedRuntimeState shared)
{
_contractName = contractName;
_contractNamespace = contractNamespace;
_shared = shared;
OperationCollection operations = new OperationCollection(this);
this.operations = operations;
this.compatOperations = new OperationCollectionWrapper(operations);
_channelInitializers = new ProxyBehaviorCollection<IChannelInitializer>(this);
this.messageInspectors = new ProxyBehaviorCollection<IClientMessageInspector>(this);
_interactiveChannelInitializers = new ProxyBehaviorCollection<IInteractiveChannelInitializer>(this);
_unhandled = new ClientOperation(this, "*", MessageHeaders.WildcardAction, MessageHeaders.WildcardAction);
_unhandled.InternalFormatter = new MessageOperationFormatter();
_maxFaultSize = TransportDefaults.MaxFaultSize;
}
internal bool AddTransactionFlowProperties
{
get { return _addTransactionFlowProperties; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_addTransactionFlowProperties = value;
}
}
}
public Type CallbackClientType
{
get { return _callbackProxyType; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_callbackProxyType = value;
}
}
}
public SynchronizedCollection<IChannelInitializer> ChannelInitializers
{
get { return _channelInitializers; }
}
public string ContractName
{
get { return _contractName; }
}
public string ContractNamespace
{
get { return _contractNamespace; }
}
public Type ContractClientType
{
get { return _contractProxyType; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_contractProxyType = value;
}
}
}
internal IdentityVerifier IdentityVerifier
{
get
{
if (_identityVerifier == null)
{
_identityVerifier = IdentityVerifier.CreateDefault();
}
return _identityVerifier;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
this.InvalidateRuntime();
_identityVerifier = value;
}
}
public Uri Via
{
get { return _via; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_via = value;
}
}
}
public bool ValidateMustUnderstand
{
get { return _shared.ValidateMustUnderstand; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_shared.ValidateMustUnderstand = value;
}
}
}
public bool MessageVersionNoneFaultsEnabled
{
get
{
return _messageVersionNoneFaultsEnabled;
}
set
{
this.InvalidateRuntime();
_messageVersionNoneFaultsEnabled = value;
}
}
public DispatchRuntime DispatchRuntime
{
get { return _dispatchRuntime; }
}
public DispatchRuntime CallbackDispatchRuntime
{
get
{
if (_dispatchRuntime == null)
_dispatchRuntime = new DispatchRuntime(this, _shared);
return _dispatchRuntime;
}
}
internal bool EnableFaults
{
get
{
if (this.IsOnServer)
{
return _dispatchRuntime.EnableFaults;
}
else
{
return _shared.EnableFaults;
}
}
set
{
lock (this.ThisLock)
{
if (this.IsOnServer)
{
string text = SR.SFxSetEnableFaultsOnChannelDispatcher0;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(text));
}
else
{
this.InvalidateRuntime();
_shared.EnableFaults = value;
}
}
}
}
public SynchronizedCollection<IInteractiveChannelInitializer> InteractiveChannelInitializers
{
get { return _interactiveChannelInitializers; }
}
public int MaxFaultSize
{
get
{
return _maxFaultSize;
}
set
{
this.InvalidateRuntime();
_maxFaultSize = value;
}
}
internal bool IsOnServer
{
get { return _shared.IsOnServer; }
}
public bool ManualAddressing
{
get
{
if (this.IsOnServer)
{
return _dispatchRuntime.ManualAddressing;
}
else
{
return _shared.ManualAddressing;
}
}
set
{
lock (this.ThisLock)
{
if (this.IsOnServer)
{
string text = SR.SFxSetManualAddresssingOnChannelDispatcher0;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(text));
}
else
{
this.InvalidateRuntime();
_shared.ManualAddressing = value;
}
}
}
}
internal int MaxParameterInspectors
{
get
{
lock (this.ThisLock)
{
int max = 0;
for (int i = 0; i < this.operations.Count; i++)
max = System.Math.Max(max, this.operations[i].ParameterInspectors.Count);
return max;
}
}
}
public ICollection<IClientMessageInspector> ClientMessageInspectors
{
get { return this.MessageInspectors; }
}
[EditorBrowsable(EditorBrowsableState.Never)]
public new SynchronizedCollection<IClientMessageInspector> MessageInspectors
{
get { return this.messageInspectors; }
}
public ICollection<ClientOperation> ClientOperations
{
get { return this.Operations; }
}
[EditorBrowsable(EditorBrowsableState.Never)]
public new SynchronizedKeyedCollection<string, ClientOperation> Operations
{
get { return this.operations; }
}
public IClientOperationSelector OperationSelector
{
get { return _operationSelector; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_operationSelector = value;
}
}
}
internal object ThisLock
{
get { return _shared; }
}
public ClientOperation UnhandledClientOperation
{
get { return _unhandled; }
}
internal bool UseSynchronizationContext
{
get { return _useSynchronizationContext; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_useSynchronizationContext = value;
}
}
}
internal T[] GetArray<T>(SynchronizedCollection<T> collection)
{
lock (collection.SyncRoot)
{
if (collection.Count == 0)
{
return Array.Empty<T>();
}
else
{
T[] array = new T[collection.Count];
collection.CopyTo(array, 0);
return array;
}
}
}
internal ImmutableClientRuntime GetRuntime()
{
lock (this.ThisLock)
{
if (_runtime == null)
_runtime = new ImmutableClientRuntime(this);
return _runtime;
}
}
internal void InvalidateRuntime()
{
lock (this.ThisLock)
{
_shared.ThrowIfImmutable();
_runtime = null;
}
}
internal void LockDownProperties()
{
_shared.LockDownProperties();
}
internal SynchronizedCollection<T> NewBehaviorCollection<T>()
{
return new ProxyBehaviorCollection<T>(this);
}
internal bool IsFault(ref Message reply)
{
if (reply == null)
{
return false;
}
if (reply.IsFault)
{
return true;
}
if (this.MessageVersionNoneFaultsEnabled && IsMessageVersionNoneFault(ref reply, this.MaxFaultSize))
{
return true;
}
return false;
}
internal static bool IsMessageVersionNoneFault(ref Message message, int maxFaultSize)
{
if (message.Version != MessageVersion.None || message.IsEmpty)
{
return false;
}
HttpResponseMessageProperty prop = message.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
if (prop == null || prop.StatusCode != HttpStatusCode.InternalServerError)
{
return false;
}
using (MessageBuffer buffer = message.CreateBufferedCopy(maxFaultSize))
{
message.Close();
message = buffer.CreateMessage();
using (Message copy = buffer.CreateMessage())
{
using (XmlDictionaryReader reader = copy.GetReaderAtBodyContents())
{
return reader.IsStartElement(XD.MessageDictionary.Fault, MessageVersion.None.Envelope.DictionaryNamespace);
}
}
}
}
internal class ProxyBehaviorCollection<T> : SynchronizedCollection<T>
{
private ClientRuntime _outer;
internal ProxyBehaviorCollection(ClientRuntime outer)
: base(outer.ThisLock)
{
_outer = outer;
}
protected override void ClearItems()
{
_outer.InvalidateRuntime();
base.ClearItems();
}
protected override void InsertItem(int index, T item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
}
_outer.InvalidateRuntime();
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
_outer.InvalidateRuntime();
base.RemoveItem(index);
}
protected override void SetItem(int index, T item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
}
_outer.InvalidateRuntime();
base.SetItem(index, item);
}
}
internal class OperationCollection : SynchronizedKeyedCollection<string, ClientOperation>
{
private ClientRuntime _outer;
internal OperationCollection(ClientRuntime outer)
: base(outer.ThisLock)
{
_outer = outer;
}
protected override void ClearItems()
{
_outer.InvalidateRuntime();
base.ClearItems();
}
protected override string GetKeyForItem(ClientOperation item)
{
return item.Name;
}
protected override void InsertItem(int index, ClientOperation item)
{
if (item == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
if (item.Parent != _outer)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.SFxMismatchedOperationParent);
_outer.InvalidateRuntime();
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
_outer.InvalidateRuntime();
base.RemoveItem(index);
}
protected override void SetItem(int index, ClientOperation item)
{
if (item == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
if (item.Parent != _outer)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.SFxMismatchedOperationParent);
_outer.InvalidateRuntime();
base.SetItem(index, item);
}
internal void InternalClearItems() { this.ClearItems(); }
internal string InternalGetKeyForItem(ClientOperation item) { return this.GetKeyForItem(item); }
internal void InternalInsertItem(int index, ClientOperation item) { this.InsertItem(index, item); }
internal void InternalRemoveItem(int index) { this.RemoveItem(index); }
internal void InternalSetItem(int index, ClientOperation item) { this.SetItem(index, item); }
}
internal class OperationCollectionWrapper : KeyedCollection<string, ClientOperation>
{
private OperationCollection _inner;
internal OperationCollectionWrapper(OperationCollection inner) { _inner = inner; }
protected override void ClearItems() { _inner.InternalClearItems(); }
protected override string GetKeyForItem(ClientOperation item) { return _inner.InternalGetKeyForItem(item); }
protected override void InsertItem(int index, ClientOperation item) { _inner.InternalInsertItem(index, item); }
protected override void RemoveItem(int index) { _inner.InternalRemoveItem(index); }
protected override void SetItem(int index, ClientOperation item) { _inner.InternalSetItem(index, item); }
}
}
}
| |
using UnityEngine;
using System.Collections;
public class ThirdPersonCharacter : MonoBehaviour {
[SerializeField] float jumpPower = 12; // determines the jump force applied when jumping (and therefore the jump height)
[SerializeField] float airSpeed = 6; // determines the max speed of the character while airborne
[SerializeField] float airControl = 2; // determines the response speed of controlling the character while airborne
[Range(1,4)] [SerializeField] public float gravityMultiplier = 2; // gravity modifier - often higher than natural gravity feels right for game characters
[SerializeField][Range(0.1f,3f)] float moveSpeedMultiplier = 1; // how much the move speed of the character will be multiplied by
[SerializeField][Range(0.1f,3f)] float animSpeedMultiplier = 1; // how much the animation of the character will be multiplied by
[SerializeField] AdvancedSettings advancedSettings; // Container for the advanced settings class , thiss allows the advanced settings to be in a foldout in the inspector
[System.Serializable]
public class AdvancedSettings
{
public float stationaryTurnSpeed = 180; // additional turn speed added when the player is stationary (added to animation root rotation)
public float movingTurnSpeed = 360; // additional turn speed added when the player is moving (added to animation root rotation)
public float headLookResponseSpeed = 2; // speed at which head look follows its target
public float crouchHeightFactor = 0.6f; // collider height is multiplied by this when crouching
public float crouchChangeSpeed = 4; // speed at which capsule changes height when crouching/standing
public float autoTurnThresholdAngle = 100; // character auto turns towards camera direction if facing away by more than this angle
public float autoTurnSpeed = 2; // speed at which character auto-turns towards cam direction
public PhysicMaterial zeroFrictionMaterial; // used when in motion to enable smooth movement
public PhysicMaterial highFrictionMaterial; // used when stationary to avoid sliding down slopes
public float jumpRepeatDelayTime = 0.25f; // amount of time that must elapse between landing and being able to jump again
public float runCycleLegOffset = 0.2f; // animation cycle offset (0-1) used for determining correct leg to jump off
public float groundStickyEffect = 5f; // power of 'stick to ground' effect - prevents bumping down slopes.
}
public Transform lookTarget { get; set; } // The point where the character will be looking at
bool onGround; // Is the character on the ground
Vector3 currentLookPos; // The current position where the character is looking
float originalHeight; // Used for tracking the original height of the characters capsule collider
Animator animator; // The animator for the character
float lastAirTime; // USed for checking when the character was last in the air for controlling jumps
CapsuleCollider capsule; // The collider for the character
const float half = 0.5f; // whats it says, it's a constant for a half
Vector3 moveInput;
bool crouchInput;
bool jumpInput;
float turnAmount;
float forwardAmount;
Vector3 velocity;
IComparer rayHitComparer;
// Use this for initialization
void Start () {
animator = GetComponentInChildren<Animator>();
capsule = GetComponent<Collider>() as CapsuleCollider;
// as can return null so we need to make sure thats its not before assigning to it
if (capsule != null) {
originalHeight = capsule.height;
capsule.center = Vector3.up * originalHeight * half;
} else {
Debug.LogError(" collider cannot be cast to CapsuleCollider");
}
rayHitComparer = new RayHitComparer ();
SetUpAnimator();
}
// The Move function is designed to be called from a separate component
// based on User input, or an AI control script
public void Move (Vector3 move, bool crouch, bool jump, Vector3 lookPos) {
if (move.magnitude > 1) move.Normalize();
// transfer input parameters to member variables.
this.moveInput = move;
this.crouchInput = crouch;
this.jumpInput = jump;
this.currentLookPos = lookPos;
// grab current velocity, we will be changing it.
velocity = GetComponent<Rigidbody>().velocity;
ConvertMoveInput (); // converts the relative move vector into local turn & fwd values
TurnTowardsCameraForward (); // makes the character face the way the camera is looking
PreventStandingInLowHeadroom (); // so the character's head doesn't penetrate a low ceiling
ScaleCapsuleForCrouching (); // so you can fit under low areas when crouching
ApplyExtraTurnRotation(); // this is in addition to root rotation in the animations
GroundCheck (); // detect and stick to ground
SetFriction (); // use low or high friction values depending on the current state
// control and velocity handling is different when grounded and airborne:
if (onGround) {
HandleGroundedVelocities();
} else {
HandleAirborneVelocities();
}
UpdateAnimator (); // send input and other state parameters to the animator
// reassign velocity, since it will have been modified by the above functions.
GetComponent<Rigidbody>().velocity = velocity;
}
void ConvertMoveInput ()
{
// convert the world relative moveInput vector into a local-relative
// turn amount and forward amount required to head in the desired
// direction.
Vector3 localMove = transform.InverseTransformDirection (moveInput);
turnAmount = Mathf.Atan2 (localMove.x, localMove.z);
forwardAmount = localMove.z;
}
void TurnTowardsCameraForward ()
{
// automatically turn to face camera direction,
// when not moving, and beyond the specified angle threshold
if (Mathf.Abs (forwardAmount) < .01f) {
Vector3 lookDelta = transform.InverseTransformDirection (currentLookPos - transform.position);
float lookAngle = Mathf.Atan2 (lookDelta.x, lookDelta.z) * Mathf.Rad2Deg;
// are we beyond the threshold of where need to turn to face the camera?
if (Mathf.Abs (lookAngle) > advancedSettings.autoTurnThresholdAngle) {
turnAmount += lookAngle * advancedSettings.autoTurnSpeed * .001f;
}
}
}
void PreventStandingInLowHeadroom ()
{
// prevent standing up in crouch-only zones
if (!crouchInput) {
Ray crouchRay = new Ray (GetComponent<Rigidbody>().position + Vector3.up * capsule.radius * half, Vector3.up);
float crouchRayLength = originalHeight - capsule.radius * half;
if (Physics.SphereCast (crouchRay, capsule.radius * half, crouchRayLength)) {
crouchInput = true;
}
}
}
void ScaleCapsuleForCrouching ()
{
// scale the capsule collider according to
// if crouching ...
if (onGround && crouchInput && (capsule.height != originalHeight * advancedSettings.crouchHeightFactor)) {
capsule.height = Mathf.MoveTowards (capsule.height, originalHeight * advancedSettings.crouchHeightFactor, Time.deltaTime * 4);
capsule.center = Vector3.MoveTowards (capsule.center, Vector3.up * originalHeight * advancedSettings.crouchHeightFactor * half, Time.deltaTime * 2);
}
// ... everything else
else
if (capsule.height != originalHeight && capsule.center != Vector3.up * originalHeight * half) {
capsule.height = Mathf.MoveTowards (capsule.height, originalHeight, Time.deltaTime * 4);
capsule.center = Vector3.MoveTowards (capsule.center, Vector3.up * originalHeight * half, Time.deltaTime * 2);
}
}
void ApplyExtraTurnRotation ()
{
// help the character turn faster (this is in addition to root rotation in the animation)
float turnSpeed = Mathf.Lerp (advancedSettings.stationaryTurnSpeed, advancedSettings.movingTurnSpeed, forwardAmount);
transform.Rotate (0, turnAmount * turnSpeed * Time.deltaTime, 0);
}
void GroundCheck ()
{
Ray ray = new Ray (transform.position + Vector3.up * .1f, -Vector3.up);
RaycastHit[] hits = Physics.RaycastAll (ray, .5f);
System.Array.Sort (hits, rayHitComparer);
if (velocity.y < jumpPower * .5f) {
onGround = false;
GetComponent<Rigidbody>().useGravity = true;
foreach (var hit in hits) {
// check whether we hit a non-trigger collider (and not the character itself)
if (!hit.collider.isTrigger) {
// this counts as being on ground.
// stick to surface - helps character stick to ground - specially when running down slopes
if (velocity.y <= 0) {
GetComponent<Rigidbody>().position = Vector3.MoveTowards (GetComponent<Rigidbody>().position, hit.point, Time.deltaTime * advancedSettings.groundStickyEffect);
}
onGround = true;
GetComponent<Rigidbody>().useGravity = false;
break;
}
}
}
// remember when we were last in air, for jump delay
if (!onGround) lastAirTime = Time.time;
}
void SetFriction()
{
if (onGround) {
// set friction to low or high, depending on if we're moving
if (moveInput.magnitude == 0) {
// when not moving this helps prevent sliding on slopes:
GetComponent<Collider>().material = advancedSettings.highFrictionMaterial;
} else {
// but when moving, we want no friction:
GetComponent<Collider>().material = advancedSettings.zeroFrictionMaterial;
}
} else {
// while in air, we want no friction against surfaces (walls, ceilings, etc)
GetComponent<Collider>().material = advancedSettings.zeroFrictionMaterial;
}
}
void HandleGroundedVelocities()
{
velocity.y = 0;
if (moveInput.magnitude == 0) {
// when not moving this prevents sliding on slopes:
velocity.x = 0;
velocity.z = 0;
}
// check whether conditions are right to allow a jump:
bool animationGrounded = animator.GetCurrentAnimatorStateInfo (0).IsName ("Grounded");
bool okToRepeatJump = Time.time > lastAirTime + advancedSettings.jumpRepeatDelayTime;
if (jumpInput && !crouchInput && okToRepeatJump && animationGrounded) {
// jump!
onGround = false;
velocity = moveInput * airSpeed;
velocity.y = jumpPower;
}
}
void HandleAirborneVelocities ()
{
// we allow some movement in air, but it's very different to when on ground
// (typically allowing a small change in trajectory)
Vector3 airMove = new Vector3 (moveInput.x * airSpeed, velocity.y, moveInput.z * airSpeed);
velocity = Vector3.Lerp (velocity, airMove, Time.deltaTime * airControl);
GetComponent<Rigidbody>().useGravity = true;
// apply extra gravity from multiplier:
Vector3 extraGravityForce = (Physics.gravity * gravityMultiplier) - Physics.gravity;
GetComponent<Rigidbody>().AddForce(extraGravityForce);
}
void UpdateAnimator ()
{
// Here we tell the animator what to do based on the current states and inputs.
// only use root motion when on ground:
animator.applyRootMotion = onGround;
// update the animator parameters
animator.SetFloat ("Forward", forwardAmount, 0.1f, Time.deltaTime);
animator.SetFloat ("Turn", turnAmount, 0.1f, Time.deltaTime);
animator.SetBool ("Crouch", crouchInput);
animator.SetBool ("OnGround", onGround);
if (!onGround) {
animator.SetFloat ("Jump", velocity.y);
}
// calculate which leg is behind, so as to leave that leg trailing in the jump animation
// (This code is reliant on the specific run cycle offset in our animations,
// and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5)
float runCycle = Mathf.Repeat (animator.GetCurrentAnimatorStateInfo (0).normalizedTime + advancedSettings.runCycleLegOffset, 1);
float jumpLeg = (runCycle < half ? 1 : -1) * forwardAmount;
if (onGround) {
animator.SetFloat ("JumpLeg", jumpLeg);
}
// the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector,
// which affects the movement speed because of the root motion.
if (onGround && moveInput.magnitude > 0) {
animator.speed = animSpeedMultiplier;
} else {
// but we don't want to use that while airborne
animator.speed = 1;
}
}
void OnAnimatorIK(int layerIndex)
{
// we set the weight so most of the look-turn is done with the head, not the body.
animator.SetLookAtWeight(1, 0.2f, 2.5f);
// if a transform is assigned as a look target, it overrides the vector lookPos value
if (lookTarget != null) {
currentLookPos = lookTarget.position;
}
// Used for the head look feature.
animator.SetLookAtPosition( currentLookPos );
}
void SetUpAnimator()
{
// this is a ref to the animator component on the root.
animator = GetComponent<Animator>();
// we use avatar from a child animator component if present
// (this is to enable easy swapping of the character model as a child node)
foreach (var childAnimator in GetComponentsInChildren<Animator>()) {
if (childAnimator != animator) {
animator.avatar = childAnimator.avatar;
Destroy (childAnimator);
break;
}
}
}
public void OnAnimatorMove()
{
// we implement this function to override the default root motion.
// this allows us to modify the positional speed before it's applied.
GetComponent<Rigidbody>().rotation = animator.rootRotation;
if (onGround && Time.deltaTime > 0) {
Vector3 v = (animator.deltaPosition * moveSpeedMultiplier) / Time.deltaTime;
// we preserve the existing y part of the current velocity.
v.y = GetComponent<Rigidbody>().velocity.y;
GetComponent<Rigidbody>().velocity = v;
}
}
//used for comparing distances
class RayHitComparer: IComparer
{
public int Compare(object x, object y)
{
return ((RaycastHit)x).distance.CompareTo(((RaycastHit)y).distance);
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// CarrierRouteResponse
/// </summary>
[DataContract]
public partial class CarrierRouteResponse : IEquatable<CarrierRouteResponse>
{
/// <summary>
/// Initializes a new instance of the <see cref="CarrierRouteResponse" /> class.
/// </summary>
/// <param name="ObjectId">ObjectId.</param>
/// <param name="MatchedAddress">MatchedAddress.</param>
/// <param name="Code">Code.</param>
/// <param name="State">State.</param>
/// <param name="CountyFips">CountyFips.</param>
/// <param name="PostalTown">PostalTown.</param>
/// <param name="PostCode">PostCode.</param>
/// <param name="RouteDelivery">RouteDelivery.</param>
/// <param name="Boundary">Boundary.</param>
/// <param name="BoundaryRef">BoundaryRef.</param>
public CarrierRouteResponse(string ObjectId = null, MatchedAddress MatchedAddress = null, string Code = null, CommonState State = null, string CountyFips = null, string PostalTown = null, string PostCode = null, RouteDelivery RouteDelivery = null, RouteBoundary Boundary = null, string BoundaryRef = null)
{
this.ObjectId = ObjectId;
this.MatchedAddress = MatchedAddress;
this.Code = Code;
this.State = State;
this.CountyFips = CountyFips;
this.PostalTown = PostalTown;
this.PostCode = PostCode;
this.RouteDelivery = RouteDelivery;
this.Boundary = Boundary;
this.BoundaryRef = BoundaryRef;
}
/// <summary>
/// Gets or Sets ObjectId
/// </summary>
[DataMember(Name="objectId", EmitDefaultValue=false)]
public string ObjectId { get; set; }
/// <summary>
/// Gets or Sets MatchedAddress
/// </summary>
[DataMember(Name="matchedAddress", EmitDefaultValue=false)]
public MatchedAddress MatchedAddress { get; set; }
/// <summary>
/// Gets or Sets Code
/// </summary>
[DataMember(Name="code", EmitDefaultValue=false)]
public string Code { get; set; }
/// <summary>
/// Gets or Sets State
/// </summary>
[DataMember(Name="state", EmitDefaultValue=false)]
public CommonState State { get; set; }
/// <summary>
/// Gets or Sets CountyFips
/// </summary>
[DataMember(Name="countyFips", EmitDefaultValue=false)]
public string CountyFips { get; set; }
/// <summary>
/// Gets or Sets PostalTown
/// </summary>
[DataMember(Name="postalTown", EmitDefaultValue=false)]
public string PostalTown { get; set; }
/// <summary>
/// Gets or Sets PostCode
/// </summary>
[DataMember(Name="postCode", EmitDefaultValue=false)]
public string PostCode { get; set; }
/// <summary>
/// Gets or Sets RouteDelivery
/// </summary>
[DataMember(Name="routeDelivery", EmitDefaultValue=false)]
public RouteDelivery RouteDelivery { get; set; }
/// <summary>
/// Gets or Sets Boundary
/// </summary>
[DataMember(Name="boundary", EmitDefaultValue=false)]
public RouteBoundary Boundary { get; set; }
/// <summary>
/// Gets or Sets BoundaryRef
/// </summary>
[DataMember(Name="boundaryRef", EmitDefaultValue=false)]
public string BoundaryRef { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class CarrierRouteResponse {\n");
sb.Append(" ObjectId: ").Append(ObjectId).Append("\n");
sb.Append(" MatchedAddress: ").Append(MatchedAddress).Append("\n");
sb.Append(" Code: ").Append(Code).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" CountyFips: ").Append(CountyFips).Append("\n");
sb.Append(" PostalTown: ").Append(PostalTown).Append("\n");
sb.Append(" PostCode: ").Append(PostCode).Append("\n");
sb.Append(" RouteDelivery: ").Append(RouteDelivery).Append("\n");
sb.Append(" Boundary: ").Append(Boundary).Append("\n");
sb.Append(" BoundaryRef: ").Append(BoundaryRef).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as CarrierRouteResponse);
}
/// <summary>
/// Returns true if CarrierRouteResponse instances are equal
/// </summary>
/// <param name="other">Instance of CarrierRouteResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CarrierRouteResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ObjectId == other.ObjectId ||
this.ObjectId != null &&
this.ObjectId.Equals(other.ObjectId)
) &&
(
this.MatchedAddress == other.MatchedAddress ||
this.MatchedAddress != null &&
this.MatchedAddress.Equals(other.MatchedAddress)
) &&
(
this.Code == other.Code ||
this.Code != null &&
this.Code.Equals(other.Code)
) &&
(
this.State == other.State ||
this.State != null &&
this.State.Equals(other.State)
) &&
(
this.CountyFips == other.CountyFips ||
this.CountyFips != null &&
this.CountyFips.Equals(other.CountyFips)
) &&
(
this.PostalTown == other.PostalTown ||
this.PostalTown != null &&
this.PostalTown.Equals(other.PostalTown)
) &&
(
this.PostCode == other.PostCode ||
this.PostCode != null &&
this.PostCode.Equals(other.PostCode)
) &&
(
this.RouteDelivery == other.RouteDelivery ||
this.RouteDelivery != null &&
this.RouteDelivery.Equals(other.RouteDelivery)
) &&
(
this.Boundary == other.Boundary ||
this.Boundary != null &&
this.Boundary.Equals(other.Boundary)
) &&
(
this.BoundaryRef == other.BoundaryRef ||
this.BoundaryRef != null &&
this.BoundaryRef.Equals(other.BoundaryRef)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ObjectId != null)
hash = hash * 59 + this.ObjectId.GetHashCode();
if (this.MatchedAddress != null)
hash = hash * 59 + this.MatchedAddress.GetHashCode();
if (this.Code != null)
hash = hash * 59 + this.Code.GetHashCode();
if (this.State != null)
hash = hash * 59 + this.State.GetHashCode();
if (this.CountyFips != null)
hash = hash * 59 + this.CountyFips.GetHashCode();
if (this.PostalTown != null)
hash = hash * 59 + this.PostalTown.GetHashCode();
if (this.PostCode != null)
hash = hash * 59 + this.PostCode.GetHashCode();
if (this.RouteDelivery != null)
hash = hash * 59 + this.RouteDelivery.GetHashCode();
if (this.Boundary != null)
hash = hash * 59 + this.Boundary.GetHashCode();
if (this.BoundaryRef != null)
hash = hash * 59 + this.BoundaryRef.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.CodeDom.Compiler;
namespace gView.Framework.Geometry.SpatialRefTranslation
{
internal class IndentedTokenWriter : IndentedTextWriter
{
private bool _start = true, _nl = false;
private char _last = ',', _first = '\0';
public IndentedTokenWriter(TextWriter writer)
: base(writer)
{
}
public IndentedTokenWriter(TextWriter writer, string tabString)
: base(writer, tabString)
{
}
public override void Write(string s)
{
if (_nl) base.WriteLine();
_nl = false;
base.Write(s);
}
public override void WriteLine(string s)
{
if (s != String.Empty)
_first = s[0];
if (!_start)
{
if (_last != ',' && _last != '[' &&
_first != ',' && _first != ']')
{
base.WriteLine(",");
_last = ',';
}
else
{
base.WriteLine();
}
}
else
{
_start = false;
}
if (s != String.Empty)
_last = s[s.Length - 1];
base.Write(s);
_nl = true;
}
}
internal class WktCoordinateSystemWriter
{
private static IFormatProvider _nhi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
public static string Write(object obj)
{
return Write(obj, false);
}
internal static string Write(object obj, bool esri)
{
if (obj == null) return "";
TextWriter textwriter = new StringWriter();
IndentedTextWriter indentedWriter = new IndentedTokenWriter(textwriter);
Write(obj, esri, indentedWriter);
return textwriter.ToString();
}
private static void Write(object obj, bool esri, IndentedTextWriter writer)
{
if (obj is CoordinateSystem)
WriteCoordinateSystem(obj as CoordinateSystem, esri, writer);
else if (obj is Datum)
WriteDatum(obj as Datum, esri, writer);
else if (obj is Ellipsoid)
WriteEllipsoid(obj as Ellipsoid, esri, writer);
else if (obj is AxisInfo)
{
AxisInfo info = (AxisInfo)obj;
WriteAxis(info, esri, writer);
}
else if (obj is WGS84ConversionInfo)
{
WGS84ConversionInfo info = (WGS84ConversionInfo)obj;
WriteWGS84ConversionInfo(info, esri, writer);
}
else if (obj is Unit)
WriteUnit(obj as Unit, esri, writer);
else if (obj is PrimeMeridian)
WritePrimeMeridian(obj as PrimeMeridian, esri, writer);
else throw new NotImplementedException(String.Format("Cannot convert {0} to WKT.", obj.GetType().FullName));
}
private static void WriteCoordinateSystem(CoordinateSystem coordinateSystem, bool esri, IndentedTextWriter writer)
{
if (coordinateSystem is CompoundCoordinateSystem)
WriteCompoundCoordinateSystem(coordinateSystem as CompoundCoordinateSystem, esri, writer);
else if (coordinateSystem is GeographicCoordinateSystem)
WriteGeographicCoordinateSystem(coordinateSystem as GeographicCoordinateSystem, esri, writer);
else if (coordinateSystem is ProjectedCoordinateSystem)
WriteProjectedCoordinateSystem(coordinateSystem as ProjectedCoordinateSystem, esri, writer);
else if (coordinateSystem is LocalCoordinateSystem)
WriteLocalCoordinateSystem(coordinateSystem as LocalCoordinateSystem, esri, writer);
else if (coordinateSystem is FittedCoordinateSystem)
WriteFittedCoordinateSystem(coordinateSystem as FittedCoordinateSystem, esri, writer);
else if (coordinateSystem is GeocentricCoordinateSystem)
WriteGeocentricCoordinateSystem(coordinateSystem as GeocentricCoordinateSystem, esri, writer);
else if (coordinateSystem is VerticalCoordinateSystem)
WriteVerticalCoordinateSystem(coordinateSystem as VerticalCoordinateSystem, esri, writer);
else if (coordinateSystem is HorizontalCoordinateSystem)
WriteHorizontalCoordinateSystem(coordinateSystem as HorizontalCoordinateSystem, esri, writer);
else throw new InvalidOperationException("this coordinate system is recongized");
}
private static void WriteUnit(Unit unit, bool esri, IndentedTextWriter writer)
{
if (unit is AngularUnit)
WriteAngularUnit(unit as AngularUnit,esri, writer);
else if (unit is LinearUnit)
WriteLinearUnit(unit as LinearUnit,esri, writer);
else throw new InvalidOperationException("this unit is not recognized");
}
private static void WriteAuthority(AbstractInformation authority, bool esri, IndentedTextWriter writer)
{
if (esri) return;
if (authority == null ||
(authority.AuthorityCode == String.Empty && authority.Authority == String.Empty)) return;
writer.WriteLine(String.Format("AUTHORITY[\"{0}\",\"{1}\"]", authority.Authority, authority.AuthorityCode));
}
private static void WriteAngularUnit(AngularUnit angularUnit, bool esri, IndentedTextWriter writer)
{
writer.WriteLine("UNIT[");
writer.Indent = writer.Indent + 1;
writer.WriteLine(String.Format("\"{0}\",{1}", angularUnit.Name, angularUnit.RadiansPerUnit.ToString(_nhi)));
//writer.WriteLine(String.Format("AUTHORITY[\"{0}\",\"{1}\"]", angularUnit.Authority, angularUnit.AuthorityCode));
WriteAuthority(angularUnit,esri, writer);
writer.Indent = writer.Indent - 1;
writer.WriteLine("]");
}
private static void WriteCompoundCoordinateSystem(CompoundCoordinateSystem compoundCoordinateSystem, bool esri, IndentedTextWriter writer)
{
writer.WriteLine("COMPD_CS[");
writer.Indent = writer.Indent + 1;
writer.WriteLine(String.Format("\"{0}\",", compoundCoordinateSystem.Name));
WriteCoordinateSystem(compoundCoordinateSystem.HeadCS,esri, writer);
writer.WriteLine(",");
WriteCoordinateSystem(compoundCoordinateSystem.TailCS,esri, writer);
writer.WriteLine(",");
//writer.WriteLine(String.Format("AUTHORITY[\"{0}\",\"{1}\"]", compoundCoordinateSystem.Authority, compoundCoordinateSystem.AuthorityCode));
WriteAuthority(compoundCoordinateSystem,esri, writer);
writer.Indent = writer.Indent - 1;
writer.WriteLine("]");
}
private static void WriteGeographicCoordinateSystem(GeographicCoordinateSystem geographicCoordinateSystem, bool esri, IndentedTextWriter writer)
{
writer.WriteLine("GEOGCS[");
writer.Indent = writer.Indent + 1;
writer.WriteLine(String.Format("\"{0}\",", geographicCoordinateSystem.Name));
WriteHorizontalDatum(geographicCoordinateSystem.HorizontalDatum,esri, writer);
WritePrimeMeridian(geographicCoordinateSystem.PrimeMeridian,esri, writer);
WriteAngularUnit(geographicCoordinateSystem.AngularUnit,esri, writer);
for (int dimension = 0; dimension < geographicCoordinateSystem.Dimension; dimension++)
WriteAxis(geographicCoordinateSystem.GetAxis(dimension), esri, writer);
//writer.WriteLine(String.Format("AUTHORITY[\"{0}\",\"{1}\"]", geographicCoordinateSystem.Authority, geographicCoordinateSystem.AuthorityCode));
WriteAuthority(geographicCoordinateSystem,esri, writer);
writer.Indent = writer.Indent - 1;
writer.Write("]");
}
private static void WriteProjectedCoordinateSystem(ProjectedCoordinateSystem projectedCoordinateSystem, bool esri, IndentedTextWriter writer)
{
writer.WriteLine("PROJCS[");
writer.Indent = writer.Indent + 1;
writer.WriteLine(String.Format("\"{0}\",", projectedCoordinateSystem.Name));
WriteGeographicCoordinateSystem(projectedCoordinateSystem.GeographicCoordinateSystem, esri,writer);
//writer.WriteLine(",");
WriteProjection(projectedCoordinateSystem.Projection, writer);
WriteLinearUnit(projectedCoordinateSystem.LinearUnit,esri, writer);
for (int dimension = 0; dimension < projectedCoordinateSystem.Dimension; dimension++)
WriteAxis(projectedCoordinateSystem.GetAxis(dimension), esri, writer);
//writer.WriteLine(String.Format("AUTHORITY[\"{0}\",\"{1}\"]", projectedCoordinateSystem.Authority, projectedCoordinateSystem.AuthorityCode));
WriteAuthority(projectedCoordinateSystem,esri, writer);
writer.Indent = writer.Indent - 1;
writer.WriteLine("]");
}
private static void WriteDatum(Datum datum, bool esri, IndentedTextWriter writer)
{
if (datum is VerticalDatum)
WriteVerticalDatum(datum as VerticalDatum, esri,writer);
else if (datum is HorizontalDatum)
WriteHorizontalDatum(datum as HorizontalDatum, esri,writer);
else throw new NotImplementedException("This datum is not supported.");
}
private static void WriteHorizontalDatum(HorizontalDatum horizontalDatum, bool esri, IndentedTextWriter writer)
{
writer.WriteLine("DATUM[");
writer.Indent = writer.Indent + 1;
writer.WriteLine(String.Format("\"{0}\",", horizontalDatum.Name));
WriteEllipsoid(horizontalDatum.Ellipsoid, esri, writer);
WriteWGS84ConversionInfo(horizontalDatum.WGS84Parameters,esri, writer);
//writer.WriteLine(String.Format("AUTHORITY[\"{0}\",\"{1}\"]", horizontalDatum.Authority, horizontalDatum.AuthorityCode));
WriteAuthority(horizontalDatum, esri, writer);
writer.Indent = writer.Indent - 1;
writer.WriteLine("]");
}
private static void WriteEllipsoid(Ellipsoid ellipsoid, bool esri, IndentedTextWriter writer)
{
writer.WriteLine("SPHEROID[");
writer.Indent = writer.Indent + 1;
writer.WriteLine(String.Format("\"{0}\",{1},{2}", ellipsoid.Name, ellipsoid.SemiMajorAxis.ToString(_nhi), ellipsoid.InverseFlattening.ToString(_nhi)));
//writer.WriteLine(String.Format("AUTHORITY[\"{0}\",\"{1}\"]", ellipsoid.Authority, ellipsoid.AuthorityCode));
WriteAuthority(ellipsoid, esri, writer);
writer.Indent = writer.Indent - 1;
writer.WriteLine("]");
}
private static void WriteAxis(AxisInfo axis, bool esri, IndentedTextWriter writer)
{
if (esri) return;
if (axis == null) return;
string axisOrientation = String.Empty;
switch (axis.Orientation)
{
case AxisOrientation.Down:
axisOrientation = "DOWN";
break;
case AxisOrientation.East:
axisOrientation = "EAST";
break;
case AxisOrientation.North:
axisOrientation = "NORTH";
break;
case AxisOrientation.Other:
axisOrientation = "OTHER";
break;
case AxisOrientation.South:
axisOrientation = "SOUTH";
break;
case AxisOrientation.Up:
axisOrientation = "UP";
break;
case AxisOrientation.West:
axisOrientation = "WEST";
break;
default:
throw new InvalidOperationException("This should not exist");
}
writer.WriteLine(String.Format("AXIS[\"{0}\",\"{1}\"]", axis.Name, axisOrientation));
}
private static void WriteWGS84ConversionInfo(WGS84ConversionInfo conversionInfo, bool esri, IndentedTextWriter writer)
{
if (esri) return;
writer.WriteLine(String.Format("TOWGS84[{0},{1},{2},{3},{4},{5},{6}]",
conversionInfo.Dx.ToString(_nhi), conversionInfo.Dy.ToString(_nhi), conversionInfo.Dz.ToString(_nhi),
conversionInfo.Ex.ToString(_nhi), conversionInfo.Ey.ToString(_nhi), conversionInfo.Ez.ToString(_nhi),
conversionInfo.Ppm.ToString(_nhi)));
}
private static void WriteLinearUnit(LinearUnit linearUnit, bool esri, IndentedTextWriter writer)
{
writer.WriteLine("UNIT[");
writer.Indent = writer.Indent + 1;
writer.WriteLine(String.Format("\"{0}\",{1}", linearUnit.Name, linearUnit.MetersPerUnit.ToString(_nhi)));
//writer.WriteLine(String.Format("AUTHORITY[\"{0}\",\"{1}\"]", linearUnit.Authority, linearUnit.AuthorityCode));
WriteAuthority(linearUnit, esri, writer);
writer.Indent = writer.Indent - 1;
writer.WriteLine("]");
}
private static void WritePrimeMeridian(PrimeMeridian primeMeridian, bool esri, IndentedTextWriter writer)
{
writer.WriteLine("PRIMEM[");
writer.Indent = writer.Indent + 1;
writer.WriteLine(String.Format("\"{0}\",{1}", primeMeridian.Name, primeMeridian.Longitude.ToString(_nhi)));
//writer.WriteLine(String.Format("AUTHORITY[\"{0}\",\"{1}\"]", primeMeridian.Authority, primeMeridian.AuthorityCode));
WriteAuthority(primeMeridian, esri, writer);
writer.Indent = writer.Indent - 1;
writer.WriteLine("]");
}
private static void WriteProjection(Projection projection, IndentedTextWriter writer)
{
writer.WriteLine(String.Format("PROJECTION[\"{0}\"]", projection.Name));
for (int i = 0; i < projection.NumParameters; i++)
{
string paramName = projection.GetParameter(i).Name;
double paramValue = projection.GetParameter(i).Value;
writer.WriteLine(String.Format("PARAMETER[\"{0}\",{1}]", paramName, paramValue.ToString(_nhi)));
}
}
private static void WriteVerticalCoordinateSystem(VerticalCoordinateSystem verticalCoordinateSystem, bool esri, IndentedTextWriter writer)
{
writer.WriteLine("VERT_CS[");
writer.Indent = writer.Indent + 1;
writer.WriteLine(String.Format("\"{0}\",", verticalCoordinateSystem.Name));
WriteDatum(verticalCoordinateSystem.VerticalDatum, esri, writer);
WriteUnit(verticalCoordinateSystem.VerticalUnit, esri, writer);
//writer.WriteLine(String.Format("AUTHORITY[\"{0}\",\"{1}\"]", verticalCoordinateSystem.Authority, verticalCoordinateSystem.AuthorityCode));
WriteAuthority(verticalCoordinateSystem, esri, writer);
writer.Indent = writer.Indent - 1;
writer.WriteLine("]");
}
private static void WriteVerticalDatum(VerticalDatum verticalDatum, bool esri, IndentedTextWriter writer)
{
writer.WriteLine("VERT_DATUM[");
writer.Indent = writer.Indent + 1;
writer.WriteLine(String.Format("\"{0}\",{1},", verticalDatum.Name, DatumTypeAsCode(verticalDatum.DatumType)));
//writer.WriteLine(String.Format("AUTHORITY[\"{0}\",\"{1}\"]", verticalDatum.Authority, verticalDatum.AuthorityCode));
WriteAuthority(verticalDatum, esri, writer);
writer.Indent = writer.Indent - 1;
writer.WriteLine("]");
}
public static string DatumTypeAsCode(DatumType datumtype)
{
string datumCode = Enum.Format(typeof(DatumType), datumtype, "d");
return datumCode;
}
public static void WriteFittedCoordinateSystem(FittedCoordinateSystem fiitedCoordinateSystem, bool esri, IndentedTextWriter writer)
{
throw new NotImplementedException();
}
public static void WriteGeocentricCoordinateSystem(GeocentricCoordinateSystem geocentricCoordinateSystem, bool esri, IndentedTextWriter writer)
{
throw new NotImplementedException();
}
public static void WriteHorizontalCoordinateSystem(HorizontalCoordinateSystem horizontalCoordinateSystem, bool esri, IndentedTextWriter writer)
{
throw new NotImplementedException();
}
private static void WriteLocalCoordinateSystem(LocalCoordinateSystem localCoordinateSystem, bool esri, IndentedTextWriter writer)
{
throw new NotImplementedException();
}
private static void WriteLocalDatum(LocalDatum localDatum, bool esri, IndentedTextWriter writer)
{
throw new NotImplementedException();
}
}
internal class ESRIWktCoordinateSystemWriter
{
public static string Write(object obj)
{
string ret = WktCoordinateSystemWriter.Write(obj, true);
if (ret == String.Empty) return String.Empty;
StringBuilder sb = new StringBuilder();
StringReader reader = new StringReader(ret);
string l;
while ((l = reader.ReadLine()) != null)
{
sb.Append(l.Trim());
}
return sb.ToString();
}
}
internal class ESRIGeotransWktCoordinateWriter
{
private static IFormatProvider _nhi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
public static string Write(object obj)
{
GeographicCoordinateSystem geocoordsys = null;
WGS84ConversionInfo wgsinfo;
if (obj is ProjectedCoordinateSystem)
{
geocoordsys = ((ProjectedCoordinateSystem)obj).GeographicCoordinateSystem;
}
else if (obj is GeographicCoordinateSystem)
{
geocoordsys = obj as GeographicCoordinateSystem;
}
if (geocoordsys == null) return String.Empty;
wgsinfo = geocoordsys.HorizontalDatum.WGS84Parameters;
string GEOGCS = ESRIWktCoordinateSystemWriter.Write(geocoordsys);
StringBuilder sb = new StringBuilder(@"GEOGTRAN[""");
sb.Append(geocoordsys.Name + "_");
sb.Append(@"To_WGS_1984"",");
sb.Append(GEOGCS + ",");
sb.Append(@"GEOGCS[""GCS_WGS_1984"",");
sb.Append(@"DATUM[""D_WGS_1984"",SPHEROID[""WGS_1984"",6378137.0,298.257223563]],");
sb.Append(@"PRIMEM[""Greenwich"",0.0],UNIT[""Degree"",0.0174532925199433]],");
sb.Append(@"METHOD[""Position_Vector""],");
sb.Append(@"PARAMETER[""X_Axis_Translation""," + wgsinfo.Dx.ToString(_nhi) + "],");
sb.Append(@"PARAMETER[""Y_Axis_Translation""," + wgsinfo.Dy.ToString(_nhi) + "],");
sb.Append(@"PARAMETER[""Z_Axis_Translation""," + wgsinfo.Dz.ToString(_nhi) + "],");
sb.Append(@"PARAMETER[""X_Axis_Rotation""," + wgsinfo.Ex.ToString(_nhi) + "],");
sb.Append(@"PARAMETER[""Y_Axis_Rotation""," + wgsinfo.Ey.ToString(_nhi) + "],");
sb.Append(@"PARAMETER[""Z_Axis_Rotation""," + wgsinfo.Ez.ToString(_nhi) + "],");
sb.Append(@"PARAMETER[""Scale_Difference""," + wgsinfo.Ppm.ToString(_nhi) + "]]");
return sb.ToString();
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// PathDrawingGame.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
namespace PathDrawing
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class PathDrawingGame : Microsoft.Xna.Framework.Game
{
private GraphicsDeviceManager graphics;
// We need a SpriteBatch to do our main drawing
private SpriteBatch spriteBatch;
// We also use the PrimitiveBatch to draw the lines for our path.
private PrimitiveBatch primitiveBatch;
// A font for drawing our instruction text
private SpriteFont font;
// A texture we draw for the ground
private Texture2D groundTexture;
// Sets the number of pixels the ground occupies before repeating. Increase to "zoom in" on
// the ground or decrease to "zoom out".
private const int groundSize = 300;
// The tank that will drive around, following our path.
private Tank tank;
// Whether or not the user is drawing the path for the Tank to follow
private bool drawingWaypoints = false;
public PathDrawingGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
// Frame rate is 30 fps by default for Windows Phone.
TargetElapsedTime = TimeSpan.FromTicks(333333);
graphics.IsFullScreen = true;
// We only care about the FreeDrag gesture for this sample
TouchPanel.EnabledGestures = GestureType.FreeDrag;
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Create the PrimitiveBatch for drawing our path
primitiveBatch = new PrimitiveBatch(GraphicsDevice);
// Load our font and ground
font = Content.Load<SpriteFont>("Font");
groundTexture = Content.Load<Texture2D>("ground");
// Create the tank
tank = new Tank(GraphicsDevice, Content);
tank.Reset(new Vector2(100));
tank.MoveSpeed = 225f;
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// Update the tank
tank.Update(gameTime);
// Get the current state of touch input
TouchCollection touches = TouchPanel.GetState();
// If we have at least one touch...
if (touches.Count > 0)
{
// If the primary touch is pressed and in the tank, we start drawing our path
if (touches[0].State == TouchLocationState.Pressed && tank.HitTest(touches[0].Position))
{
// Clear the waypoints to start a new path
tank.Waypoints.Clear();
// We're now drawing waypoints
drawingWaypoints = true;
// Use the touch location as the first waypoint
tank.Waypoints.Enqueue(touches[0].Position);
}
// Otherwise if the primary touch is released, we stop drawing our path
else if (touches[0].State == TouchLocationState.Released)
{
drawingWaypoints = false;
}
}
// Read all of the gestures
while (TouchPanel.IsGestureAvailable)
{
GestureSample gesture = TouchPanel.ReadGesture();
// If we have a FreeDrag gesture...
if (gesture.GestureType == GestureType.FreeDrag)
{
// If we're drawing waypoints and the drag gesture has moved from the last location,
// enqueue the position of the gesture as the next waypoint.
if (drawingWaypoints && gesture.Delta != Vector2.Zero)
{
tank.Waypoints.Enqueue(gesture.Position);
}
}
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// First draw our ground
DrawGround();
// Next draw the path
DrawPath();
// Draw our instruction text and tank
spriteBatch.Begin();
spriteBatch.DrawString(font, "Drag a path from the tank to have him drive around.", new Vector2(5), Color.White);
tank.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
/// <summary>
/// Helper method to draw our ground texture.
/// </summary>
private void DrawGround()
{
// Draw the ground using a LinearWrap state so we can repeat the texture across the screen
spriteBatch.Begin(0, null, SamplerState.LinearWrap, null, null);
// Compute the source rectangle based on our viewport size and ground scale
Rectangle source = new Rectangle();
source.Width = (GraphicsDevice.Viewport.Width / groundSize) * groundTexture.Width;
source.Height = (GraphicsDevice.Viewport.Height / groundSize) * groundTexture.Height;
// Draw the ground using our source rectangle which will cause it to wrap across the screen
spriteBatch.Draw(groundTexture, GraphicsDevice.Viewport.Bounds, source, Color.White);
spriteBatch.End();
}
/// <summary>
/// Helper method to draw the path using PrimitiveBatch.
/// </summary>
private void DrawPath()
{
// Start drawing lines
primitiveBatch.Begin(PrimitiveType.LineList);
// Add the tank's position as the first vertex
primitiveBatch.AddVertex(tank.Location, Color.White);
for (int i = 1; i < tank.Waypoints.Count; i++)
{
// Add the next waypoint location to our line list
primitiveBatch.AddVertex(tank.Waypoints[i], Color.White);
// If we're not at the end of our waypoint list, add this point again to act as the
// first point for the next line.
if (i < tank.Waypoints.Count - 1)
primitiveBatch.AddVertex(tank.Waypoints[i], Color.White);
}
primitiveBatch.End();
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using GraphQL.Introspection;
using GraphQL.Language.AST;
using GraphQL.Types;
namespace GraphQL.Validation
{
public class TypeInfo : INodeVisitor
{
private readonly ISchema _schema;
private readonly Stack<IGraphType> _typeStack = new Stack<IGraphType>();
private readonly Stack<IGraphType> _inputTypeStack = new Stack<IGraphType>();
private readonly Stack<IGraphType> _parentTypeStack = new Stack<IGraphType>();
private readonly Stack<FieldType> _fieldDefStack = new Stack<FieldType>();
private readonly Stack<INode> _ancestorStack = new Stack<INode>();
private DirectiveGraphType _directive;
private QueryArgument _argument;
public TypeInfo(ISchema schema)
{
_schema = schema;
}
public INode[] GetAncestors()
{
return _ancestorStack.Select(x => x).Skip(1).Reverse().ToArray();
}
public IGraphType GetLastType()
{
return _typeStack.Any() ? _typeStack.Peek() : null;
}
public IGraphType GetInputType()
{
return _inputTypeStack.Any() ? _inputTypeStack.Peek() : null;
}
public IGraphType GetParentType()
{
return _parentTypeStack.Any() ? _parentTypeStack.Peek() : null;
}
public FieldType GetFieldDef()
{
return _fieldDefStack.Any() ? _fieldDefStack.Peek() : null;
}
public DirectiveGraphType GetDirective()
{
return _directive;
}
public QueryArgument GetArgument()
{
return _argument;
}
public void Enter(INode node)
{
_ancestorStack.Push(node);
if (node is SelectionSet)
{
_parentTypeStack.Push(GetLastType());
return;
}
if (node is Field)
{
var field = (Field) node;
var parentType = _parentTypeStack.Peek().GetNamedType();
var fieldType = GetFieldDef(_schema, parentType, field);
_fieldDefStack.Push(fieldType);
var targetType = fieldType?.ResolvedType;
_typeStack.Push(targetType);
return;
}
if (node is Directive)
{
var directive = (Directive) node;
_directive = _schema.Directives.SingleOrDefault(x => x.Name == directive.Name);
}
if (node is Operation)
{
var op = (Operation) node;
IGraphType type = null;
if (op.OperationType == OperationType.Query)
{
type = _schema.Query;
}
else if (op.OperationType == OperationType.Mutation)
{
type = _schema.Mutation;
}
else if (op.OperationType == OperationType.Subscription)
{
type = _schema.Subscription;
}
_typeStack.Push(type);
return;
}
if (node is FragmentDefinition)
{
var def = (FragmentDefinition) node;
var type = _schema.FindType(def.Type.Name);
_typeStack.Push(type);
return;
}
if (node is InlineFragment)
{
var def = (InlineFragment) node;
var type = def.Type != null ? _schema.FindType(def.Type.Name) : GetLastType();
_typeStack.Push(type);
return;
}
if (node is VariableDefinition)
{
var varDef = (VariableDefinition) node;
var inputType = varDef.Type.GraphTypeFromType(_schema);
_inputTypeStack.Push(inputType);
return;
}
if (node is Argument)
{
var argAst = (Argument) node;
QueryArgument argDef = null;
IGraphType argType = null;
var args = GetDirective() != null ? GetDirective()?.Arguments : GetFieldDef()?.Arguments;
if (args != null)
{
argDef = args.Find(argAst.Name);
argType = argDef?.ResolvedType;
}
_argument = argDef;
_inputTypeStack.Push(argType);
}
if (node is ListValue)
{
var type = GetInputType().GetNamedType();
_inputTypeStack.Push(type);
}
if (node is ObjectField)
{
var objectType = GetInputType().GetNamedType();
IGraphType fieldType = null;
if (objectType is InputObjectGraphType)
{
var complexType = objectType as IComplexGraphType;
var inputField = complexType.Fields.FirstOrDefault(x => x.Name == ((ObjectField) node).Name);
fieldType = inputField?.ResolvedType;
}
_inputTypeStack.Push(fieldType);
}
}
public void Leave(INode node)
{
_ancestorStack.Pop();
if (node is SelectionSet)
{
_parentTypeStack.Pop();
return;
}
if (node is Field)
{
_fieldDefStack.Pop();
_typeStack.Pop();
return;
}
if (node is Directive)
{
_directive = null;
return;
}
if (node is Operation
|| node is FragmentDefinition
|| node is InlineFragment)
{
_typeStack.Pop();
return;
}
if (node is VariableDefinition)
{
_inputTypeStack.Pop();
return;
}
if (node is Argument)
{
_argument = null;
_inputTypeStack.Pop();
return;
}
if (node is ListValue || node is ObjectField)
{
_inputTypeStack.Pop();
return;
}
}
private FieldType GetFieldDef(ISchema schema, IGraphType parentType, Field field)
{
var name = field.Name;
if (name == SchemaIntrospection.SchemaMeta.Name
&& Equals(schema.Query, parentType))
{
return SchemaIntrospection.SchemaMeta;
}
if (name == SchemaIntrospection.TypeMeta.Name
&& Equals(schema.Query, parentType))
{
return SchemaIntrospection.TypeMeta;
}
if (name == SchemaIntrospection.TypeNameMeta.Name && parentType.IsCompositeType())
{
return SchemaIntrospection.TypeNameMeta;
}
if (parentType is IObjectGraphType || parentType is IInterfaceGraphType)
{
var complexType = parentType as IComplexGraphType;
return complexType.Fields.FirstOrDefault(x => x.Name == field.Name);
}
return null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace biz.dfch.CS.Examples.Odata.Tests.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);
}
}
}
}
| |
// 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.Collections.Generic;
using System.Text;
using Microsoft.Research.DataStructures;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.Graphs
{
public delegate void EdgeVisitor<Node, Info>(Node source, Info info, Node target);
public static class DepthFirst
{
public static void Visit<Node, EdgeInfo>
(
IGraph<Node, EdgeInfo>/*!*/ graph,
Predicate<Node> nodeStartVisitor,
EdgeVisitor<Node, EdgeInfo> edgeVisitor
)
{
Contract.Requires(graph != null);// Clousot Suggestion
Visitor<Node, EdgeInfo> dfs = new Visitor<Node, EdgeInfo>(graph, nodeStartVisitor, null, edgeVisitor);
dfs.VisitAll();
}
public static void Visit<Node, EdgeInfo>
(
IGraph<Node, EdgeInfo>/*!*/ graph,
Node startNode,
Predicate<Node> nodeStartVisitor,
EdgeVisitor<Node, EdgeInfo> edgeVisitor
)
{
Contract.Requires(graph != null);// Clousot Suggestion
Visitor<Node, EdgeInfo> dfs = new Visitor<Node, EdgeInfo>(graph, nodeStartVisitor, null, edgeVisitor);
dfs.VisitSubGraphNonRecursive(startNode);
}
public class Info<Node>
{
internal Info(Node parent, int starttime)
{
this.Parent = parent;
this.StartTime = starttime;
}
public readonly Node Parent;
public readonly int StartTime;
public int FinishTime;
public bool TargetOfBackEdge;
public bool SourceOfBackEdge;
}
public class Visitor<Node, Edge>
{
struct SearchFrame
{
public readonly Node Node;
public readonly IEnumerator<Pair<Edge, Node>> Edges;
public readonly Info<Node> Info;
public SearchFrame(Node node, IEnumerator<Pair<Edge, Node>> edges, Info<Node> info)
{
this.Node = node;
this.Edges = edges;
this.Info = info;
}
}
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.history != null);
Contract.Invariant(this.graph != null);
Contract.Invariant(this.backEdges != null);
Contract.Invariant(this.todo != null);
}
private int time = 0;
private readonly IGraph<Node, Edge>/*!*/ graph;
private readonly Predicate<Node>/*?*/ nodeStartVisitor;
private readonly Action<Node>/*?*/ nodeFinishVisitor;
private readonly EdgeVisitor<Node, Edge>/*?*/ edgeVisitor;
private readonly Dictionary<Node, Info<Node>/*!*/>/*!*/ history = new Dictionary<Node, Info<Node>/*!*/>();
private readonly Set<STuple<Node, Edge, Node>>/*!*/ backEdges = new Set<STuple<Node, Edge, Node>>();
private readonly Stack<SearchFrame> todo = new Stack<SearchFrame>();
public Visitor(IGraph<Node, Edge>/*!*/ graph)
: this(graph, null, null, null)
{
Contract.Requires(graph != null);// Clousot Suggestion
}
public Visitor(IGraph<Node, Edge>/*!*/ graph,
//^ [Delayed]
Predicate<Node> nodeStartVisitor)
: this(graph, nodeStartVisitor, null, null)
{
Contract.Requires(graph != null);// Clousot Suggestion
}
public Visitor(IGraph<Node, Edge>/*!*/ graph,
//^ [Delayed]
Predicate<Node>/*?*/ nodeStartVisitor,
//^ [Delayed]
Action<Node>/*?*/ nodeFinishVisitor,
//^ [Delayed]
EdgeVisitor<Node, Edge>/*?*/ edgeVisitor)
{
Contract.Requires(graph != null);// Clousot Suggestion
this.graph = graph;
this.nodeStartVisitor = nodeStartVisitor;
this.nodeFinishVisitor = nodeFinishVisitor;
this.edgeVisitor = edgeVisitor;
}
public Visitor(IGraph<Node, Edge>/*!*/ graph,
//^ [Delayed]
IGraphVisitor<Node, Edge>/*!*/ visitor)
: this(graph, visitor.VisitNode, null, visitor.VisitEdge)
{
Contract.Requires(graph != null); // Clousot Suggestion
Contract.Requires(visitor != null);// Clousot Suggestion
}
public virtual void VisitAll()
{
foreach (Node node in graph.Nodes)
{
VisitSubGraphNonRecursive(node);
}
}
[ContractVerification(false)]
internal virtual void VisitEdge(Info<Node> sourceInfo, Node source, Edge info, Node targetNode)
{
Contract.Requires(sourceInfo != null);
if (this.edgeVisitor != null)
{
this.edgeVisitor(source, info, targetNode);
}
Info<Node>/*?*/ targetInfo;
if (history.TryGetValue(targetNode, out targetInfo))
{
Contract.Assume(targetInfo != null);
//^ assume targetInfo != null;
if (targetInfo.FinishTime == 0)
{
// on stack, means it's a back edge
targetInfo.TargetOfBackEdge = true;
sourceInfo.SourceOfBackEdge = true;
this.backEdges.Add(new STuple<Node, Edge, Node>(source, info, targetNode));
}
// no need to visit target node
return;
}
VisitSubGraph(targetNode, source);
}
/// <summary>
/// Non-recursive version
/// </summary>
[ContractVerification(false)]
internal virtual void VisitEdgeNonRecursive(Info<Node> sourceInfo, Node source, Edge info, Node targetNode)
{
Contract.Requires(sourceInfo != null);
if (this.edgeVisitor != null)
{
this.edgeVisitor(source, info, targetNode);
}
Info<Node>/*?*/ targetInfo;
if (history.TryGetValue(targetNode, out targetInfo))
{
Contract.Assume(targetInfo != null);
//^ assume targetInfo != null;
if (targetInfo.FinishTime == 0)
{
// on stack, means it's a back edge
targetInfo.TargetOfBackEdge = true;
sourceInfo.SourceOfBackEdge = true;
this.backEdges.Add(new STuple<Node, Edge, Node>(source, info, targetNode));
}
// no need to visit target node
return;
}
ScheduleNode(targetNode, source);
}
public virtual void VisitSubGraph(Node node)
{
VisitSubGraph(node, default(Node));
}
[ContractVerification(false)]
public virtual void VisitSubGraph(Node node, Node parent)
{
if (history.ContainsKey(node)) return;
var info = new Info<Node>(parent, ++time);
history[node] = info;
if (nodeStartVisitor != null)
{
var cont = nodeStartVisitor(node);
if (!cont) return;
}
this.VisitSuccessors(info, node);
if (nodeFinishVisitor != null) nodeFinishVisitor(node);
info.FinishTime = ++time;
}
public virtual void VisitSubGraphNonRecursive(Node node, Node parent)
{
ScheduleNode(node, parent);
IterativeDFS();
}
public virtual void VisitSubGraphNonRecursive(Node node)
{
ScheduleNode(node, default(Node));
IterativeDFS();
}
/// <summary>
/// Non-recursive version
/// </summary>
[ContractVerification(false)]
public virtual void ScheduleNode(Node node, Node parent)
{
if (history.ContainsKey(node)) return;
var info = new Info<Node>(parent, ++time);
history[node] = info;
if (nodeStartVisitor != null)
{
var cont = nodeStartVisitor(node);
if (!cont) return;
}
todo.Push(new SearchFrame(node, this.graph.Successors(node).GetEnumerator(), info));
}
internal virtual void VisitSuccessors(Info<Node> info, Node node)
{
Contract.Requires(info != null);
foreach (Pair<Edge, Node> edge in graph.Successors(node))
{
this.VisitEdge(info, node, edge.One, edge.Two);
}
}
/// <summary>
/// Drains the todo list
/// </summary>
private void IterativeDFS()
{
while (todo.Count > 0)
{
SearchFrame sf = todo.Peek();
Contract.Assume(sf.Edges != null);
if (sf.Edges.MoveNext())
{
var edgeTarget = sf.Edges.Current;
Contract.Assume(sf.Info != null);
this.VisitEdgeNonRecursive(sf.Info, sf.Node, edgeTarget.One, edgeTarget.Two);
continue; // make sure to visit new edges first.
}
// done with this frame.
if (nodeFinishVisitor != null) nodeFinishVisitor(sf.Node);
Contract.Assume(sf.Info != null);
sf.Info.FinishTime = ++time;
todo.Pop();
}
}
public IEnumerable<Node> Visited
{
get {
Contract.Ensures(Contract.Result<IEnumerable<Node>>() != null);
return this.history.Keys;
}
}
[ContractVerification(false)]
public bool IsVisited(Node node)
{
return this.history.ContainsKey(node);
}
[ContractVerification(false)]
public Info<Node>/*!*/ DepthFirstInfo(Node node)
{
Contract.Ensures(Contract.Result<Info<Node>>() != null);
return this.history[node].AssumeNotNull();
}
public bool IsBackEdge(Node source, Edge info, Node target)
{
return this.backEdges.Contains(new STuple<Node, Edge, Node>(source, info, target));
}
}
}
}
| |
using System.IO;
using System.Linq;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;
using System;
namespace LibGit2Sharp.Tests
{
public class RevertFixture : BaseFixture
{
[Fact]
public void CanRevert()
{
// The branch name to perform the revert on,
// and the file whose contents we expect to be reverted.
const string revertBranchName = "refs/heads/revert";
const string revertedFile = "a.txt";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Checkout the revert branch.
Branch branch = repo.Checkout(revertBranchName);
Assert.NotNull(branch);
// Revert tip commit.
RevertResult result = repo.Revert(repo.Head.Tip, Constants.Signature);
Assert.NotNull(result);
Assert.Equal(RevertStatus.Reverted, result.Status);
// Verify commit was made.
Assert.NotNull(result.Commit);
// Verify the expected commit ID.
Assert.Equal("04746060fa753c9970d88a0b59151d7b212ac903", result.Commit.Id.Sha);
// Verify workspace is clean.
Assert.True(repo.Index.IsFullyMerged);
Assert.False(repo.RetrieveStatus().IsDirty);
// Lookup the blob containing the expected reverted content of a.txt.
Blob expectedBlob = repo.Lookup<Blob>("bc90ea420cf6c5ae3db7dcdffa0d79df567f219b");
Assert.NotNull(expectedBlob);
// Verify contents of Index.
IndexEntry revertedIndexEntry = repo.Index[revertedFile];
Assert.NotNull(revertedIndexEntry);
// Verify the contents of the index.
Assert.Equal(expectedBlob.Id, revertedIndexEntry.Id);
// Verify contents of workspace.
string fullPath = Path.Combine(repo.Info.WorkingDirectory, revertedFile);
Assert.Equal(expectedBlob.GetContentText(new FilteringOptions(revertedFile)), File.ReadAllText(fullPath));
}
}
[Fact]
public void CanRevertAndNotCommit()
{
// The branch name to perform the revert on,
// and the file whose contents we expect to be reverted.
const string revertBranchName = "refs/heads/revert";
const string revertedFile = "a.txt";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
string modifiedFileFullPath = Path.Combine(repo.Info.WorkingDirectory, revertedFile);
// Checkout the revert branch.
Branch branch = repo.Checkout(revertBranchName);
Assert.NotNull(branch);
// Revert tip commit.
RevertResult result = repo.Revert(repo.Head.Tip, Constants.Signature, new RevertOptions() { CommitOnSuccess = false });
Assert.NotNull(result);
Assert.Equal(RevertStatus.Reverted, result.Status);
// Verify the commit was made.
Assert.Null(result.Commit);
// Verify workspace is dirty.
FileStatus fileStatus = repo.RetrieveStatus(revertedFile);
Assert.Equal(FileStatus.Staged, fileStatus);
// This is the ID of the blob containing the expected content.
Blob expectedBlob = repo.Lookup<Blob>("bc90ea420cf6c5ae3db7dcdffa0d79df567f219b");
Assert.NotNull(expectedBlob);
// Verify contents of Index.
IndexEntry revertedIndexEntry = repo.Index[revertedFile];
Assert.NotNull(revertedIndexEntry);
Assert.Equal(expectedBlob.Id, revertedIndexEntry.Id);
// Verify contents of workspace.
string fullPath = Path.Combine(repo.Info.WorkingDirectory, revertedFile);
Assert.Equal(expectedBlob.GetContentText(new FilteringOptions(revertedFile)), File.ReadAllText(fullPath));
}
}
[Fact]
public void RevertWithConflictDoesNotCommit()
{
// The branch name to perform the revert on,
// and the file whose contents we expect to be reverted.
const string revertBranchName = "refs/heads/revert";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Checkout the revert branch.
Branch branch = repo.Checkout(revertBranchName);
Assert.NotNull(branch);
// The commit to revert - we know that reverting this
// specific commit will generate conflicts.
Commit commitToRevert = repo.Lookup<Commit>("cb4f7f0eca7a0114cdafd8537332aa17de36a4e9");
Assert.NotNull(commitToRevert);
// Perform the revert and verify there were conflicts.
RevertResult result = repo.Revert(commitToRevert, Constants.Signature);
Assert.NotNull(result);
Assert.Equal(RevertStatus.Conflicts, result.Status);
Assert.Null(result.Commit);
// Verify there is a conflict on the expected path.
Assert.False(repo.Index.IsFullyMerged);
Assert.NotNull(repo.Index.Conflicts["a.txt"]);
// Verify the non-conflicting paths are staged.
Assert.Equal(FileStatus.Staged, repo.RetrieveStatus("b.txt"));
Assert.Equal(FileStatus.Staged, repo.RetrieveStatus("c.txt"));
}
}
[Theory]
[InlineData(CheckoutFileConflictStrategy.Ours)]
[InlineData(CheckoutFileConflictStrategy.Theirs)]
public void RevertWithFileConflictStrategyOption(CheckoutFileConflictStrategy conflictStrategy)
{
// The branch name to perform the revert on,
// and the file which we expect conflicts as result of the revert.
const string revertBranchName = "refs/heads/revert";
const string conflictedFilePath = "a.txt";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Checkout the revert branch.
Branch branch = repo.Checkout(revertBranchName);
Assert.NotNull(branch);
// Specify FileConflictStrategy.
RevertOptions options = new RevertOptions()
{
FileConflictStrategy = conflictStrategy,
};
RevertResult result = repo.Revert(repo.Head.Tip.Parents.First(), Constants.Signature, options);
// Verify there is a conflict.
Assert.False(repo.Index.IsFullyMerged);
Conflict conflict = repo.Index.Conflicts[conflictedFilePath];
Assert.NotNull(conflict);
Assert.NotNull(conflict);
Assert.NotNull(conflict.Theirs);
Assert.NotNull(conflict.Ours);
// Get the blob containing the expected content.
Blob expectedBlob = null;
switch (conflictStrategy)
{
case CheckoutFileConflictStrategy.Theirs:
expectedBlob = repo.Lookup<Blob>(conflict.Theirs.Id);
break;
case CheckoutFileConflictStrategy.Ours:
expectedBlob = repo.Lookup<Blob>(conflict.Ours.Id);
break;
default:
throw new Exception("Unexpected FileConflictStrategy");
}
Assert.NotNull(expectedBlob);
// Check the content of the file on disk matches what is expected.
string expectedContent = expectedBlob.GetContentText(new FilteringOptions(conflictedFilePath));
Assert.Equal(expectedContent, File.ReadAllText(Path.Combine(repo.Info.WorkingDirectory, conflictedFilePath)));
}
}
[Fact]
public void RevertReportsCheckoutProgress()
{
const string revertBranchName = "refs/heads/revert";
string repoPath = SandboxRevertTestRepo();
using (var repo = new Repository(repoPath))
{
// Checkout the revert branch.
Branch branch = repo.Checkout(revertBranchName);
Assert.NotNull(branch);
bool wasCalled = false;
RevertOptions options = new RevertOptions()
{
OnCheckoutProgress = (path, completed, total) => wasCalled = true
};
repo.Revert(repo.Head.Tip, Constants.Signature, options);
Assert.True(wasCalled);
}
}
[Fact]
public void RevertReportsCheckoutNotification()
{
const string revertBranchName = "refs/heads/revert";
string repoPath = SandboxRevertTestRepo();
using (var repo = new Repository(repoPath))
{
// Checkout the revert branch.
Branch branch = repo.Checkout(revertBranchName);
Assert.NotNull(branch);
bool wasCalled = false;
CheckoutNotifyFlags actualNotifyFlags = CheckoutNotifyFlags.None;
RevertOptions options = new RevertOptions()
{
OnCheckoutNotify = (path, notificationType) => { wasCalled = true; actualNotifyFlags = notificationType; return true; },
CheckoutNotifyFlags = CheckoutNotifyFlags.Updated,
};
repo.Revert(repo.Head.Tip, Constants.Signature, options);
Assert.True(wasCalled);
}
}
[Theory]
[InlineData(null)]
[InlineData(true)]
[InlineData(false)]
public void RevertFindsRenames(bool? findRenames)
{
// The environment is set up such that:
// - file d.txt is edited in the commit that is to be reverted (commit A)
// - file d.txt is renamed to d_renamed.txt
// - commit A is reverted.
// If rename detection is enabled, then the revert is applied
// to d_renamed.txt. If rename detection is not enabled,
// then the revert results in a conflict.
const string revertBranchName = "refs/heads/revert_rename";
const string commitIdToRevert = "ca3e813";
const string expectedBlobId = "0ff3bbb9c8bba2291654cd64067fa417ff54c508";
const string modifiedFilePath = "d_renamed.txt";
string repoPath = SandboxRevertTestRepo();
using (var repo = new Repository(repoPath))
{
Branch currentBranch = repo.Checkout(revertBranchName);
Assert.NotNull(currentBranch);
Commit commitToRevert = repo.Lookup<Commit>(commitIdToRevert);
Assert.NotNull(currentBranch);
RevertOptions options;
if (findRenames.HasValue)
{
options = new RevertOptions()
{
FindRenames = findRenames.Value,
};
}
else
{
options = new RevertOptions();
}
RevertResult result = repo.Revert(commitToRevert, Constants.Signature, options);
Assert.NotNull(result);
if(!findRenames.HasValue ||
findRenames.Value == true)
{
Assert.Equal(RevertStatus.Reverted, result.Status);
Assert.NotNull(result.Commit);
Blob expectedBlob = repo.Lookup<Blob>(expectedBlobId);
Assert.NotNull(expectedBlob);
GitObject blob = result.Commit.Tree[modifiedFilePath].Target as Blob;
Assert.NotNull(blob);
Assert.Equal(blob.Id, expectedBlob.Id);
// Verify contents of workspace
string fullPath = Path.Combine(repo.Info.WorkingDirectory, modifiedFilePath);
Assert.Equal(expectedBlob.GetContentText(new FilteringOptions(modifiedFilePath)), File.ReadAllText(fullPath));
}
else
{
Assert.Equal(RevertStatus.Conflicts, result.Status);
Assert.Null(result.Commit);
}
}
}
[Theory]
[InlineData(1, "a04ef5f22c2413a9743046436c0e5354ed903f78")]
[InlineData(2, "1ae0cd88802bb4f4e6413ba63e41376d235b6fd0")]
public void CanRevertMergeCommit(int mainline, string expectedId)
{
const string revertBranchName = "refs/heads/revert_merge";
const string commitIdToRevert = "2747045";
string repoPath = SandboxRevertTestRepo();
using (var repo = new Repository(repoPath))
{
Branch branch = repo.Checkout(revertBranchName);
Assert.NotNull(branch);
Commit commitToRevert = repo.Lookup<Commit>(commitIdToRevert);
Assert.NotNull(commitToRevert);
RevertOptions options = new RevertOptions()
{
Mainline = mainline,
};
RevertResult result = repo.Revert(commitToRevert, Constants.Signature, options);
Assert.NotNull(result);
Assert.Equal(RevertStatus.Reverted, result.Status);
Assert.Equal(result.Commit.Sha, expectedId);
if(mainline == 1)
{
// In this case, we expect "d_renamed.txt" to be reverted (deleted),
// and a.txt to match the tip of the "revert" branch.
Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus("d_renamed.txt"));
// This is the commit containing the expected contents of a.txt.
Commit commit = repo.Lookup<Commit>("b6fbb29b625aabe0fb5736da6fd61d4147e4405e");
Assert.NotNull(commit);
Assert.Equal(commit["a.txt"].Target.Id, repo.Index["a.txt"].Id);
}
else if(mainline == 2)
{
// In this case, we expect "d_renamed.txt" to be preset,
// and a.txt to match the tip of the master branch.
// In this case, we expect "d_renamed.txt" to be reverted (deleted),
// and a.txt to match the tip of the "revert" branch.
Assert.Equal(FileStatus.Unaltered, repo.RetrieveStatus("d_renamed.txt"));
// This is the commit containing the expected contents of "d_renamed.txt".
Commit commit = repo.Lookup<Commit>("c4b5cea70e4cd5b633ed0f10ae0ed5384e8190d8");
Assert.NotNull(commit);
Assert.Equal(commit["d_renamed.txt"].Target.Id, repo.Index["d_renamed.txt"].Id);
// This is the commit containing the expected contents of a.txt.
commit = repo.Lookup<Commit>("cb4f7f0eca7a0114cdafd8537332aa17de36a4e9");
Assert.NotNull(commit);
Assert.Equal(commit["a.txt"].Target.Id, repo.Index["a.txt"].Id);
}
}
}
[Fact]
public void CanNotRevertAMergeCommitWithoutSpecifyingTheMainlineBranch()
{
const string revertBranchName = "refs/heads/revert_merge";
const string commitIdToRevert = "2747045";
string repoPath = SandboxRevertTestRepo();
using (var repo = new Repository(repoPath))
{
Branch branch = repo.Checkout(revertBranchName);
Assert.NotNull(branch);
var commitToRevert = repo.Lookup<Commit>(commitIdToRevert);
Assert.NotNull(commitToRevert);
Assert.Throws<LibGit2SharpException>(() => repo.Revert(commitToRevert, Constants.Signature));
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void RevertWithNothingToRevert(bool commitOnSuccess)
{
// The branch name to perform the revert on
const string revertBranchName = "refs/heads/revert";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Checkout the revert branch.
Branch branch = repo.Checkout(revertBranchName);
Assert.NotNull(branch);
Commit commitToRevert = repo.Head.Tip;
// Revert tip commit.
RevertResult result = repo.Revert(commitToRevert, Constants.Signature);
Assert.NotNull(result);
Assert.Equal(RevertStatus.Reverted, result.Status);
// Revert the same commit a second time
result = repo.Revert(
commitToRevert,
Constants.Signature,
new RevertOptions() { CommitOnSuccess = commitOnSuccess });
Assert.NotNull(result);
Assert.Equal(null, result.Commit);
Assert.Equal(RevertStatus.NothingToRevert, result.Status);
if (commitOnSuccess)
{
Assert.Equal(CurrentOperation.None, repo.Info.CurrentOperation);
}
else
{
Assert.Equal(CurrentOperation.Revert, repo.Info.CurrentOperation);
}
}
}
[Fact]
public void RevertOrphanedBranchThrows()
{
// The branch name to perform the revert on
const string revertBranchName = "refs/heads/revert";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Checkout the revert branch.
Branch branch = repo.Checkout(revertBranchName);
Assert.NotNull(branch);
Commit commitToRevert = repo.Head.Tip;
// Move the HEAD to an orphaned branch.
repo.Refs.UpdateTarget("HEAD", "refs/heads/orphan");
Assert.True(repo.Info.IsHeadUnborn);
// Revert the tip of the refs/heads/revert branch.
Assert.Throws<UnbornBranchException>(() => repo.Revert(commitToRevert, Constants.Signature));
}
}
}
}
| |
// 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.Runtime.Serialization;
using System.Text;
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Text
{
// An Encoder is used to encode a sequence of blocks of characters into
// a sequence of blocks of bytes. Following instantiation of an encoder,
// sequential blocks of characters are converted into blocks of bytes through
// calls to the GetBytes method. The encoder maintains state between the
// conversions, allowing it to correctly encode character sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Encoder abstract base
// class are typically obtained through calls to the GetEncoder method
// of Encoding objects.
//
[Serializable]
public abstract class Encoder
{
internal EncoderFallback m_fallback = null;
[NonSerialized]
internal EncoderFallbackBuffer m_fallbackBuffer = null;
internal void SerializeEncoder(SerializationInfo info)
{
info.AddValue("m_fallback", this.m_fallback);
}
protected Encoder()
{
// We don't call default reset because default reset probably isn't good if we aren't initialized.
}
public EncoderFallback Fallback
{
get
{
return m_fallback;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Can't change fallback if buffer is wrong
if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0)
throw new ArgumentException(
Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), nameof(value));
m_fallback = value;
m_fallbackBuffer = null;
}
}
// Note: we don't test for threading here because async access to Encoders and Decoders
// doesn't work anyway.
public EncoderFallbackBuffer FallbackBuffer
{
get
{
if (m_fallbackBuffer == null)
{
if (m_fallback != null)
m_fallbackBuffer = m_fallback.CreateFallbackBuffer();
else
m_fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer();
}
return m_fallbackBuffer;
}
}
internal bool InternalHasFallbackBuffer
{
get
{
return m_fallbackBuffer != null;
}
}
// Reset the Encoder
//
// Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder. This
// would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.)
//
// If the caller doesn't want to try again after GetBytes() throws an error, then they need to call Reset().
//
// Virtual implimentation has to call GetBytes with flush and a big enough buffer to clear a 0 char string
// We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big.
public virtual void Reset()
{
char[] charTemp = { };
byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)];
GetBytes(charTemp, 0, 0, byteTemp, 0, true);
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Returns the number of bytes the next call to GetBytes will
// produce if presented with the given range of characters and the given
// value of the flush parameter. The returned value takes into
// account the state in which the encoder was left following the last call
// to GetBytes. The state of the encoder is not affected by a call
// to this method.
//
public abstract int GetByteCount(char[] chars, int index, int count, bool flush);
// We expect this to be the workhorse for NLS encodings
// unfortunately for existing overrides, it has to call the [] version,
// which is really slow, so avoid this method if you might be calling external encodings.
[CLSCompliant(false)]
public virtual unsafe int GetByteCount(char* chars, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
char[] arrChar = new char[count];
int index;
for (index = 0; index < count; index++)
arrChar[index] = chars[index];
return GetByteCount(arrChar, 0, count, flush);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. The method encodes charCount characters from
// chars starting at index charIndex, storing the resulting
// bytes in bytes starting at index byteIndex. The encoding
// takes into account the state in which the encoder was left following the
// last call to this method. The flush parameter indicates whether
// the encoder should flush any shift-states and partial characters at the
// end of the conversion. To ensure correct termination of a sequence of
// blocks of encoded bytes, the last call to GetBytes should specify
// a value of true for the flush parameter.
//
// An exception occurs if the byte array is not large enough to hold the
// complete encoding of the characters. The GetByteCount method can
// be used to determine the exact number of bytes that will be produced for
// a given range of characters. Alternatively, the GetMaxByteCount
// method of the Encoding that produced this encoder can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
//
public abstract int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, bool flush);
// We expect this to be the workhorse for NLS Encodings, but for existing
// ones we need a working (if slow) default implimentation)
//
// WARNING WARNING WARNING
//
// WARNING: If this breaks it could be a security threat. Obviously we
// call this internally, so you need to make sure that your pointers, counts
// and indexes are correct when you call this method.
//
// In addition, we have internal code, which will be marked as "safe" calling
// this code. However this code is dependent upon the implimentation of an
// external GetBytes() method, which could be overridden by a third party and
// the results of which cannot be guaranteed. We use that result to copy
// the byte[] to our byte* output buffer. If the result count was wrong, we
// could easily overflow our output buffer. Therefore we do an extra test
// when we copy the buffer so that we don't overflow byteCount either.
[CLSCompliant(false)]
public virtual unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, bool flush)
{
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Get the char array to convert
char[] arrChar = new char[charCount];
int index;
for (index = 0; index < charCount; index++)
arrChar[index] = chars[index];
// Get the byte array to fill
byte[] arrByte = new byte[byteCount];
// Do the work
int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush);
Debug.Assert(result <= byteCount, "Returned more bytes than we have space for");
// Copy the byte array
// WARNING: We MUST make sure that we don't copy too many bytes. We can't
// rely on result because it could be a 3rd party implimentation. We need
// to make sure we never copy more than byteCount bytes no matter the value
// of result
if (result < byteCount)
byteCount = result;
// Don't copy too many bytes!
for (index = 0; index < byteCount; index++)
bytes[index] = arrByte[index];
return byteCount;
}
// This method is used to avoid running out of output buffer space.
// It will encode until it runs out of chars, and then it will return
// true if it the entire input was converted. In either case it
// will also return the number of converted chars and output bytes used.
// It will only throw a buffer overflow exception if the entire lenght of bytes[] is
// too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings)
// We're done processing this buffer only if completed returns true.
//
// Might consider checking Max...Count to avoid the extra counting step.
//
// Note that if all of the input chars are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many chars as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
public virtual void Convert(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
charsUsed = charCount;
// Its easy to do if it won't overrun our buffer.
// Note: We don't want to call unsafe version because that might be an untrusted version
// which could be really unsafe and we don't want to mix it up.
while (charsUsed > 0)
{
if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount)
{
bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush);
completed = (charsUsed == charCount &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0));
return;
}
// Try again with 1/2 the count, won't flush then 'cause won't read it all
flush = false;
charsUsed /= 2;
}
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow"));
}
// Same thing, but using pointers
//
// Might consider checking Max...Count to avoid the extra counting step.
//
// Note that if all of the input chars are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many chars as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
[CLSCompliant(false)]
public virtual unsafe void Convert(char* chars, int charCount,
byte* bytes, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Get ready to do it
charsUsed = charCount;
// Its easy to do if it won't overrun our buffer.
while (charsUsed > 0)
{
if (GetByteCount(chars, charsUsed, flush) <= byteCount)
{
bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush);
completed = (charsUsed == charCount &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0));
return;
}
// Try again with 1/2 the count, won't flush then 'cause won't read it all
flush = false;
charsUsed /= 2;
}
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow"));
}
}
}
| |
using System;
using System.Reflection;
using UnityEngine;
using Cinemachine.Utility;
using System.Collections.Generic;
namespace Cinemachine.Blackboard
{
/// <summary>
/// Cinemachine Reactor is a decorator of the CinemachineVirtualCamera
/// which modulates its fields based on the input mappings specified here.
/// and the data present in Blackboard.CinemachineBlackboard
/// </summary>
[DocumentationSorting(301, DocumentationSortingAttribute.Level.UserRef)]
[SaveDuringPlay]
public class Reactor : MonoBehaviour
{
/// <summary>
/// Specifies how the entries in the reactor mapping are combined with each other
/// </summary>
public enum CombineMode
{
Set, /// Sets the output value to this value
Add, /// Adds this value to the previous Reactor value
Subtract, /// Subtracts this value from the previous Reactor value
Multiply, /// Multiplies the previous Reactor value by this value
Divide /// Divides the previous Reactor value by this value
};
/// <summary>
/// Wrapper class containing a series of remappings to convert blackboard variables into
/// an input into Reactor
/// </summary>
[Serializable]
public struct BlackboardExpression
{
/// <summary>
/// A single entry in the Reactor input mapper
/// </summary>
[Serializable]
public struct Line
{
/// <summary>
/// Specifies how this remapping is combined with the previous entry in the Input mapper
/// </summary>
[Tooltip("How to modify the resulting value")]
public CombineMode m_Operation;
/// <summary>
/// The key in the Blackboard.CinemachineBlackboard to get the value for
/// </summary>
[Tooltip("Value to look up on the Blackboard. You need to have a script post this value on the blackboard.")]
public string m_BlackboardKey;
/// <summary>
/// Whether to remap the value through a remap curve
/// </summary>
[Tooltip("Whether to remap the value through a remap curve")]
public bool m_Remap;
/// <summary>
/// A remap curve for the value found in the Blackboard.CinemachineBlackboard.
/// The X-axis represents the Blackboard value, and the Y-axis represents the output value from the remapping
/// </summary>
[Tooltip("How to modily the value read from the blackboard before using it. The X-axis represents the Blackboard value, and the Y-axis represents the output value.")]
public AnimationCurve m_RemapCurve;
}
[Tooltip("The inputs from the blackboard to be used in deriving the final value for this input mapper")]
public Line[] m_Lines;
public int GetNumLines() { return m_Lines == null ? 0 : m_Lines.Length; }
/// <summary>
/// Evaluates this BlackboardExpression against the supplied Blackboard.
/// Will attempt find and remap values from the blackboard and combine them as defined in the
/// array of Mapping
/// </summary>
/// <param name="againstBlackboard">The blackboard used to retrieve values from for the
/// remappings</param>
/// <returns>The computed result of the remappings against the blackboard.
internal bool Evaluate(Blackboard againstBlackboard, out float result)
{
result = 0;
for (int i = 0; m_Lines != null && i < m_Lines.Length; ++i)
{
Line line = m_Lines[i];
float blackboardValue;
if (!againstBlackboard.TryGetValue(line.m_BlackboardKey, out blackboardValue))
return false;
if (line.m_Remap && line.m_RemapCurve != null && line.m_RemapCurve.keys.Length > 1)
blackboardValue = line.m_RemapCurve.Evaluate(blackboardValue);
if (i == 0)
result = blackboardValue;
else
{
switch (line.m_Operation)
{
case CombineMode.Set: result = blackboardValue; break;
case CombineMode.Add: result += blackboardValue; break;
case CombineMode.Subtract: result -= blackboardValue; break;
case CombineMode.Multiply: result *= blackboardValue; break;
case CombineMode.Divide: result /= blackboardValue; break;
}
}
}
return true;
}
}
/// <summary>
/// Wrapper class containing a series of remappings to convert blackboard variables into
/// an input into Reactor
/// </summary>
[Serializable]
public struct TargetModifier
{
[Tooltip("Which setting to modify")]
public string m_Field;
[Tooltip("How to apply the expression to the field")]
public CombineMode m_Operation;
[Tooltip("The expression that is used to modify the field")]
public BlackboardExpression m_Expression;
/// This gets set at runtime when mapping is first evaluated.
internal class TargetBinding
{
FieldInfo[] mTargetFieldInfo;
object[] mTargetFieldOwner;
float mInitialValue;
// Use reflection to find the named float field
public static TargetBinding BindTarget(GameObject target, string fieldName)
{
fieldName = fieldName.Trim();
TargetBinding binding = new TargetBinding();
GameObjectFieldScanner scanner = new GameObjectFieldScanner();
scanner.OnLeafField = (fullName, fieldInfo, rootFieldOwner, value) =>
{
//Debug.Log(fullName);
if (fullName == fieldName)
{
binding.mTargetFieldInfo = fieldInfo.ToArray();
binding.mTargetFieldOwner = new object[binding.mTargetFieldInfo.Length];
binding.mTargetFieldOwner[0] = rootFieldOwner;
binding.mInitialValue = Convert.ToSingle(value);
return false; // abort scan, we're done
}
return true;
};
scanner.ScanFields(target);
if (!binding.IsValid)
Debug.Log(string.Format(
GetFullName(target) + " Reactor: can't find " +
((fieldName.Length == 0) ? "(empty)" : fieldName)));
return binding;
}
static string GetFullName(GameObject current)
{
if (current == null)
return "";
if (current.transform.parent == null)
return current.name;
return GetFullName(current.transform.parent.gameObject) + "/" + current.name;
}
public bool IsValid { get { return mTargetFieldInfo != null && mTargetFieldOwner != null; } }
public float Value
{
get
{
int last = mTargetFieldInfo.Length - 1;
object obj = mTargetFieldOwner[0];
for (int i = 0; i < last; ++i)
obj = mTargetFieldInfo[i].GetValue(obj);
return Convert.ToSingle(mTargetFieldInfo[last].GetValue(obj));
}
set
{
int last = mTargetFieldInfo.Length - 1;
for (int i = 0; i < last; ++i)
mTargetFieldOwner[i + 1] = mTargetFieldInfo[i].GetValue(mTargetFieldOwner[i]);
mTargetFieldInfo[last].SetValue(mTargetFieldOwner[last], value);
for (int i = last - 1; i >= 0; --i)
mTargetFieldInfo[i].SetValue(mTargetFieldOwner[i], mTargetFieldOwner[i + 1]);
}
}
// This is the initial value that was saved when the binding was created
public float InitialValue { get { return mInitialValue; } }
}
internal TargetBinding Binding { get; set; }
}
[Tooltip("The Cinemachine fields to modify")]
public TargetModifier[] m_TargetMappings = null;
void OnEnable()
{
InvalidateBindings();
}
void OnDisable()
{
// Restore initial values
InvalidateBindings();
}
/// Call this from the editor when something changes
public void InvalidateBindings()
{
if (m_TargetMappings == null)
return;
for (int i = 0; i < m_TargetMappings.Length; ++i)
{
// Restore initial values
if (m_TargetMappings[i].Binding != null)
m_TargetMappings[i].Binding.Value = m_TargetMappings[i].Binding.InitialValue;
m_TargetMappings[i].Binding = null;
}
}
private void LateUpdate()
{
if (m_TargetMappings == null)
return;
for (int i = 0; i < m_TargetMappings.Length; ++i)
{
if (m_TargetMappings[i].m_Expression.GetNumLines() == 0)
continue;
if (m_TargetMappings[i].Binding == null)
m_TargetMappings[i].Binding = TargetModifier.TargetBinding.BindTarget(
gameObject, m_TargetMappings[i].m_Field);
if (!m_TargetMappings[i].Binding.IsValid)
continue;
float value = m_TargetMappings[i].Binding.InitialValue;
float expr = 0;
if (!m_TargetMappings[i].m_Expression.Evaluate(Blackboard.CinemachineBlackboard, out expr))
continue;
switch (m_TargetMappings[i].m_Operation)
{
case CombineMode.Set: value = expr; break;
case CombineMode.Add: value += expr; break;
case CombineMode.Subtract: value -= expr; break;
case CombineMode.Multiply: value *= expr; break;
case CombineMode.Divide: value /= expr; break;
}
if (!float.IsInfinity(value) && !float.IsNaN(value))
m_TargetMappings[i].Binding.Value = value;
}
}
/// Will return only public float fields
public class GameObjectFieldScanner
{
/// <summary>
/// Called for each leaf field. Return value should be false to abort, true to continue.
/// It will be propagated back to the caller.
/// </summary>
public OnLeafFieldDelegate OnLeafField;
public delegate bool OnLeafFieldDelegate(
string fullName, List<FieldInfo> fieldInfo, object rootFieldOwner, object value);
/// <summary>
/// Which fields will be scanned
/// </summary>
public BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;
bool ScanFields(string fullName, List<FieldInfo> fieldChain, object obj, object rootOwner)
{
FieldInfo fieldInfo = fieldChain[fieldChain.Count - 1];
// Check if it's a complex type
bool isLeaf = true;
if (obj != null
&& !fieldInfo.FieldType.IsSubclassOf(typeof(Component))
&& !fieldInfo.FieldType.IsSubclassOf(typeof(GameObject)))
{
// Check if it's a complex type
FieldInfo[] fields = fieldInfo.FieldType.GetFields(bindingFlags);
if (fields.Length > 0)
{
isLeaf = false;
fieldChain.Add(fields[0]);
for (int i = 0; i < fields.Length; ++i)
{
fieldChain[fieldChain.Count - 1] = fields[i];
string name = fullName + "." + fields[i].Name;
if (!ScanFields(name, fieldChain, fields[i].GetValue(obj), rootOwner))
return false;
}
fieldChain.RemoveAt(fieldChain.Count - 1);
}
}
// If it's a leaf field of the right type then call the leaf handler
if (isLeaf && OnLeafField != null && fieldInfo.FieldType == typeof(float))
if (!OnLeafField(fullName, fieldChain, rootOwner, obj))
return false;
return true;
}
public bool ScanFields(string fullName, MonoBehaviour b)
{
// A little special handling for some known classes
if (b.GetType() == typeof(Reactor) || b.GetType().IsSubclassOf(typeof(Reactor)))
return true;
CinemachineVirtualCameraBase vcam = b as CinemachineVirtualCameraBase;
List<FieldInfo> fieldChain = new List<FieldInfo>();
FieldInfo[] fields = b.GetType().GetFields(bindingFlags);
if (fields.Length > 0)
{
for (int i = 0; i < fields.Length; ++i)
{
if (vcam != null && Array.FindIndex(
vcam.m_ExcludedPropertiesInInspector, match => match == fields[i].Name) >= 0)
{
// Not settable by user, so don't show it
continue;
}
string name = fullName + "." + fields[i].Name;
object fieldValue = fields[i].GetValue(b);
if (fieldValue != null)
{
fieldChain.Clear();
fieldChain.Add(fields[i]);
if (!ScanFields(name, fieldChain, fieldValue, b))
return false;
}
}
}
return true;
}
/// <summary>
/// Recursively scan the MonoBehaviours of a GameObject and its children.
/// For each leaf field found, call the OnLeafField delegate.
/// Returns false if the operation was aborted by the delegate, tru if it went to completion.
/// </summary>
public bool ScanFields(GameObject go, string prefix = null)
{
if (prefix == null)
prefix = "";
else if (prefix.Length > 0)
prefix += ".";
MonoBehaviour[] components = go.GetComponents<MonoBehaviour>();
foreach (MonoBehaviour c in components)
if (c != null && !ScanFields(prefix + c.GetType().FullName, c))
return false;
foreach (Transform child in go.transform)
if (!ScanFields(child.gameObject, prefix + child.gameObject.name))
return false;
return true;
}
};
}
}
| |
using System.Collections.Immutable;
using JetBrains.Annotations;
using JsonApiDotNetCore.Middleware;
using JsonApiDotNetCore.Queries.Expressions;
using JsonApiDotNetCore.Resources.Annotations;
namespace JsonApiDotNetCore.Resources;
/// <summary>
/// Provides an extensibility point to add business logic that is resource-oriented instead of endpoint-oriented.
/// </summary>
/// <typeparam name="TResource">
/// The resource type.
/// </typeparam>
/// <typeparam name="TId">
/// The resource identifier type.
/// </typeparam>
[PublicAPI]
public interface IResourceDefinition<TResource, in TId>
where TResource : class, IIdentifiable<TId>
{
/// <summary>
/// Enables to extend, replace or remove includes that are being applied on this resource type.
/// </summary>
/// <param name="existingIncludes">
/// An optional existing set of includes, coming from query string. Never <c>null</c>, but may be empty.
/// </param>
/// <returns>
/// The new set of includes. Return an empty collection to remove all inclusions (never return <c>null</c>).
/// </returns>
IImmutableSet<IncludeElementExpression> OnApplyIncludes(IImmutableSet<IncludeElementExpression> existingIncludes);
/// <summary>
/// Enables to extend, replace or remove a filter that is being applied on a set of this resource type.
/// </summary>
/// <param name="existingFilter">
/// An optional existing filter, coming from query string. Can be <c>null</c>.
/// </param>
/// <returns>
/// The new filter, or <c>null</c> to disable the existing filter.
/// </returns>
FilterExpression? OnApplyFilter(FilterExpression? existingFilter);
/// <summary>
/// Enables to extend, replace or remove a sort order that is being applied on a set of this resource type. Tip: Use
/// <see cref="JsonApiResourceDefinition{TResource, TId}.CreateSortExpressionFromLambda" /> to build from a lambda expression.
/// </summary>
/// <param name="existingSort">
/// An optional existing sort order, coming from query string. Can be <c>null</c>.
/// </param>
/// <returns>
/// The new sort order, or <c>null</c> to disable the existing sort order and sort by ID.
/// </returns>
SortExpression? OnApplySort(SortExpression? existingSort);
/// <summary>
/// Enables to extend, replace or remove pagination that is being applied on a set of this resource type.
/// </summary>
/// <param name="existingPagination">
/// An optional existing pagination, coming from query string. Can be <c>null</c>.
/// </param>
/// <returns>
/// The changed pagination, or <c>null</c> to use the first page with default size from options. To disable paging, set
/// <see cref="PaginationExpression.PageSize" /> to <c>null</c>.
/// </returns>
PaginationExpression? OnApplyPagination(PaginationExpression? existingPagination);
/// <summary>
/// Enables to extend, replace or remove a sparse fieldset that is being applied on a set of this resource type. Tip: Use
/// <see cref="SparseFieldSetExpressionExtensions.Including{TResource}" /> and <see cref="SparseFieldSetExpressionExtensions.Excluding{TResource}" /> to
/// safely change the fieldset without worrying about nulls.
/// </summary>
/// <remarks>
/// This method executes twice for a single request: first to select which fields to retrieve from the data store and then to select which fields to
/// serialize. Including extra fields from this method will retrieve them, but not include them in the json output. This enables you to expose calculated
/// properties whose value depends on a field that is not in the sparse fieldset.
/// </remarks>
/// <param name="existingSparseFieldSet">
/// The incoming sparse fieldset from query string. At query execution time, this is <c>null</c> if the query string contains no sparse fieldset. At
/// serialization time, this contains all viewable fields if the query string contains no sparse fieldset.
/// </param>
/// <returns>
/// The new sparse fieldset, or <c>null</c> to discard the existing sparse fieldset and select all viewable fields.
/// </returns>
SparseFieldSetExpression? OnApplySparseFieldSet(SparseFieldSetExpression? existingSparseFieldSet);
/// <summary>
/// Enables to adapt the Entity Framework Core <see cref="IQueryable{T}" /> query, based on custom query string parameters. Note this only works on
/// primary resource requests, such as /articles, but not on /blogs/1/articles or /blogs?include=articles.
/// </summary>
/// <example>
/// <code><![CDATA[
/// protected override QueryStringParameterHandlers OnRegisterQueryableHandlersForQueryStringParameters()
/// {
/// return new QueryStringParameterHandlers
/// {
/// ["isActive"] = (source, parameterValue) => source
/// .Include(model => model.Children)
/// .Where(model => model.LastUpdateTime > DateTime.Now.AddMonths(-1)),
/// ["isHighRisk"] = FilterByHighRisk
/// };
/// }
///
/// private static IQueryable<Model> FilterByHighRisk(IQueryable<Model> source, StringValues parameterValue)
/// {
/// bool isFilterOnHighRisk = bool.Parse(parameterValue);
/// return isFilterOnHighRisk ? source.Where(model => model.RiskLevel >= 5) : source.Where(model => model.RiskLevel < 5);
/// }
/// ]]></code>
/// </example>
#pragma warning disable AV1130 // Return type in method signature should be a collection interface instead of a concrete type
QueryStringParameterHandlers<TResource>? OnRegisterQueryableHandlersForQueryStringParameters();
#pragma warning restore AV1130 // Return type in method signature should be a collection interface instead of a concrete type
/// <summary>
/// Enables to add JSON:API meta information, specific to this resource.
/// </summary>
IDictionary<string, object?>? GetMeta(TResource resource);
/// <summary>
/// Executes after the original version of the resource has been retrieved from the underlying data store, as part of a write request.
/// <para>
/// Implementing this method enables to perform validations and make changes to <paramref name="resource" />, before the fields from the request are
/// copied into it.
/// </para>
/// <para>
/// For POST resource requests, this method is typically used to assign property default values or to set required relationships by side-loading the
/// related resources and linking them.
/// </para>
/// </summary>
/// <param name="resource">
/// The original resource retrieved from the underlying data store, or a freshly instantiated resource in case of a POST resource request.
/// </param>
/// <param name="writeOperation">
/// Identifies the logical write operation for which this method was called. Possible values: <see cref="WriteOperationKind.CreateResource" />,
/// <see cref="WriteOperationKind.UpdateResource" /> and <see cref="WriteOperationKind.SetRelationship" />. Note this intentionally excludes
/// <see cref="WriteOperationKind.DeleteResource" />, <see cref="WriteOperationKind.AddToRelationship" /> and
/// <see cref="WriteOperationKind.RemoveFromRelationship" />, because for those endpoints no resource is retrieved upfront.
/// </param>
/// <param name="cancellationToken">
/// Propagates notification that request handling should be canceled.
/// </param>
Task OnPrepareWriteAsync(TResource resource, WriteOperationKind writeOperation, CancellationToken cancellationToken);
/// <summary>
/// Executes before setting (or clearing) the resource at the right side of a to-one relationship.
/// <para>
/// Implementing this method enables to perform validations and change <paramref name="rightResourceId" />, before the relationship is updated.
/// </para>
/// </summary>
/// <param name="leftResource">
/// The original resource as retrieved from the underlying data store. The indication "left" specifies that <paramref name="hasOneRelationship" /> is
/// declared on <typeparamref name="TResource" />.
/// </param>
/// <param name="hasOneRelationship">
/// The to-one relationship being set.
/// </param>
/// <param name="rightResourceId">
/// The new resource identifier (or <c>null</c> to clear the relationship), coming from the request.
/// </param>
/// <param name="writeOperation">
/// Identifies the logical write operation for which this method was called. Possible values: <see cref="WriteOperationKind.CreateResource" />,
/// <see cref="WriteOperationKind.UpdateResource" /> and <see cref="WriteOperationKind.SetRelationship" />.
/// </param>
/// <param name="cancellationToken">
/// Propagates notification that request handling should be canceled.
/// </param>
/// <returns>
/// The replacement resource identifier, or <c>null</c> to clear the relationship. Returns <paramref name="rightResourceId" /> by default.
/// </returns>
Task<IIdentifiable?> OnSetToOneRelationshipAsync(TResource leftResource, HasOneAttribute hasOneRelationship, IIdentifiable? rightResourceId,
WriteOperationKind writeOperation, CancellationToken cancellationToken);
/// <summary>
/// Executes before setting the resources at the right side of a to-many relationship. This replaces on existing set.
/// <para>
/// Implementing this method enables to perform validations and make changes to <paramref name="rightResourceIds" />, before the relationship is updated.
/// </para>
/// </summary>
/// <param name="leftResource">
/// The original resource as retrieved from the underlying data store. The indication "left" specifies that <paramref name="hasManyRelationship" /> is
/// declared on <typeparamref name="TResource" />.
/// </param>
/// <param name="hasManyRelationship">
/// The to-many relationship being set.
/// </param>
/// <param name="rightResourceIds">
/// The set of resource identifiers to replace any existing set with, coming from the request.
/// </param>
/// <param name="writeOperation">
/// Identifies the logical write operation for which this method was called. Possible values: <see cref="WriteOperationKind.CreateResource" />,
/// <see cref="WriteOperationKind.UpdateResource" /> and <see cref="WriteOperationKind.SetRelationship" />.
/// </param>
/// <param name="cancellationToken">
/// Propagates notification that request handling should be canceled.
/// </param>
Task OnSetToManyRelationshipAsync(TResource leftResource, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds,
WriteOperationKind writeOperation, CancellationToken cancellationToken);
/// <summary>
/// Executes before adding resources to the right side of a to-many relationship, as part of a POST relationship request.
/// <para>
/// Implementing this method enables to perform validations and make changes to <paramref name="rightResourceIds" />, before the relationship is updated.
/// </para>
/// </summary>
/// <param name="leftResourceId">
/// Identifier of the left resource. The indication "left" specifies that <paramref name="hasManyRelationship" /> is declared on
/// <typeparamref name="TResource" />.
/// </param>
/// <param name="hasManyRelationship">
/// The to-many relationship being added to.
/// </param>
/// <param name="rightResourceIds">
/// The set of resource identifiers to add to the to-many relationship, coming from the request.
/// </param>
/// <param name="cancellationToken">
/// Propagates notification that request handling should be canceled.
/// </param>
Task OnAddToRelationshipAsync(TId leftResourceId, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds,
CancellationToken cancellationToken);
/// <summary>
/// Executes before removing resources from the right side of a to-many relationship, as part of a DELETE relationship request.
/// <para>
/// Implementing this method enables to perform validations and make changes to <paramref name="rightResourceIds" />, before the relationship is updated.
/// </para>
/// </summary>
/// <param name="leftResource">
/// The original resource as retrieved from the underlying data store. The indication "left" specifies that <paramref name="hasManyRelationship" /> is
/// declared on <typeparamref name="TResource" />. Be aware that for performance reasons, not the full relationship is populated, but only the subset of
/// resources to be removed.
/// </param>
/// <param name="hasManyRelationship">
/// The to-many relationship being removed from.
/// </param>
/// <param name="rightResourceIds">
/// The set of resource identifiers to remove from the to-many relationship, coming from the request.
/// </param>
/// <param name="cancellationToken">
/// Propagates notification that request handling should be canceled.
/// </param>
Task OnRemoveFromRelationshipAsync(TResource leftResource, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds,
CancellationToken cancellationToken);
/// <summary>
/// Executes before writing the changed resource to the underlying data store, as part of a write request.
/// <para>
/// Implementing this method enables to perform validations and make changes to <paramref name="resource" />, after the fields from the request have been
/// copied into it.
/// </para>
/// <para>
/// An example usage is to set the last-modification timestamp, overwriting the value from the incoming request.
/// </para>
/// <para>
/// Another use case is to add a notification message to an outbox table, which gets committed along with the resource write in a single transaction (see
/// https://microservices.io/patterns/data/transactional-outbox.html).
/// </para>
/// </summary>
/// <param name="resource">
/// The original resource retrieved from the underlying data store (or a freshly instantiated resource in case of a POST resource request), updated with
/// the changes from the incoming request. Exception: In case <paramref name="writeOperation" /> is <see cref="WriteOperationKind.DeleteResource" />,
/// <see cref="WriteOperationKind.AddToRelationship" /> or <see cref="WriteOperationKind.RemoveFromRelationship" />, this is an empty object with only
/// the <see cref="Identifiable{T}.Id" /> property set, because for those endpoints no resource is retrieved upfront.
/// </param>
/// <param name="writeOperation">
/// Identifies the logical write operation for which this method was called. Possible values: <see cref="WriteOperationKind.CreateResource" />,
/// <see cref="WriteOperationKind.UpdateResource" />, <see cref="WriteOperationKind.DeleteResource" />, <see cref="WriteOperationKind.SetRelationship" />
/// , <see cref="WriteOperationKind.AddToRelationship" /> and <see cref="WriteOperationKind.RemoveFromRelationship" />.
/// </param>
/// <param name="cancellationToken">
/// Propagates notification that request handling should be canceled.
/// </param>
Task OnWritingAsync(TResource resource, WriteOperationKind writeOperation, CancellationToken cancellationToken);
/// <summary>
/// Executes after successfully writing the changed resource to the underlying data store, as part of a write request.
/// <para>
/// Implementing this method enables to run additional logic, for example enqueue a notification message on a service bus.
/// </para>
/// </summary>
/// <param name="resource">
/// The resource as written to the underlying data store.
/// </param>
/// <param name="writeOperation">
/// Identifies the logical write operation for which this method was called. Possible values: <see cref="WriteOperationKind.CreateResource" />,
/// <see cref="WriteOperationKind.UpdateResource" />, <see cref="WriteOperationKind.DeleteResource" />, <see cref="WriteOperationKind.SetRelationship" />
/// , <see cref="WriteOperationKind.AddToRelationship" /> and <see cref="WriteOperationKind.RemoveFromRelationship" />.
/// </param>
/// <param name="cancellationToken">
/// Propagates notification that request handling should be canceled.
/// </param>
Task OnWriteSucceededAsync(TResource resource, WriteOperationKind writeOperation, CancellationToken cancellationToken);
/// <summary>
/// Executes after a resource has been deserialized from an incoming request body.
/// </summary>
/// <para>
/// Implementing this method enables to change the incoming resource before it enters an ASP.NET Controller Action method.
/// </para>
/// <para>
/// Changing attributes on <paramref name="resource" /> from this method may break detection of side effects on resource POST/PATCH requests, because
/// side effect detection considers any changes done from this method to be part of the incoming request body. So setting additional attributes from this
/// method (that were not sent by the client) are not considered side effects, resulting in incorrectly reporting that there were no side effects.
/// </para>
/// <param name="resource">
/// The deserialized resource.
/// </param>
void OnDeserialize(TResource resource);
/// <summary>
/// Executes before a (primary or included) resource is serialized into an outgoing response body.
/// </summary>
/// <para>
/// Implementing this method enables to change the returned resource, for example scrub sensitive data or transform returned attribute values.
/// </para>
/// <para>
/// Changing attributes on <paramref name="resource" /> from this method may break detection of side effects on resource POST/PATCH requests. What this
/// means is that if side effects were detected before, this is not re-evaluated after running this method, so it may incorrectly report side effects if
/// they were undone by this method.
/// </para>
/// <param name="resource">
/// The serialized resource.
/// </param>
void OnSerialize(TResource resource);
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using Microsoft.SPOT.Platform.Test;
namespace Microsoft.SPOT.Platform.Tests
{
public class SystemMathTests : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests");
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
//SystemMath Test methods
[TestMethod]
public MFTestResults SystemMath1_PI_Test()
{
/// <summary>
/// 1. Tests that the Math.PI constant is accurate to 15 significant digits
/// </summary>
///
Log.Comment("Tests that the Math.PI constant is accurate to 15 significant digits");
bool testResult = true;
double PIFloor = 3.141592653589793;
double PICeil = 3.141592653589794;
testResult &= (PIFloor <= System.Math.PI && System.Math.PI <= PICeil);
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemMath2_E_Test()
{
/// <summary>
/// 1. Tests that the Math.E constant is accurate to 15 significant digits
/// </summary>
///
Log.Comment("Tests that the Math.E constant is accurate to 15 significant digits");
bool testResult = true;
double EFloor = 2.718281828459045;
double ECeil = 2.718281828459046;
testResult &= (EFloor <= System.Math.E && System.Math.E <= ECeil);
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemMath3_Abs_Test()
{
/// <summary>
/// 1. Tests the Math.Abs method
/// </summary>
///
Log.Comment("Tests the Math.Abs method");
bool testResult = true;
int positive = new Random().Next(1000);
Log.Comment("With " + positive);
int negative = -positive;
testResult &= ((positive + negative) == 0);
testResult &= (positive == System.Math.Abs(negative));
testResult &= ((System.Math.Abs(-positive) + negative) == 0);
testResult &= (System.Math.Abs(positive+negative) == 0);
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemMath4_Ceiling_Test()
{
/// <summary>
/// 1. Tests the Math.Ceiling method
/// </summary>
///
Log.Comment("Tests the Math.Ceiling method");
bool testResult = true;
double base1 = new Random().Next(1000);
Log.Comment("With " + base1);
testResult &= (System.Math.Ceiling(base1) == base1);
for (double d = .1; d < 1;d += .1 )
testResult &= (System.Math.Ceiling(base1 + d) == base1 + 1);
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemMath5_Floor_Test()
{
/// <summary>
/// 1. Tests the Math.Floor method
/// </summary>
///
Log.Comment("Tests the Math.Floor method");
bool testResult = true;
double base1 = new Random().Next(1000);
Log.Comment("With " + base1);
for (double d = .0; d < .9; d += .1)
testResult &= (System.Math.Floor(base1 + d) == base1);
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemMath6_Round_Test()
{
/// <summary>
/// 1. Tests the Math.Round method
/// </summary>
///
Log.Comment("Tests the Math.Round method");
bool testResult = true;
double base1 = 334;
Log.Comment("With " + base1);
for (double d = .0; d < .6; d += .1)
{
testResult &= (System.Math.Round(base1 + d) == base1);
Log.Comment(d.ToString() + " " + (System.Math.Round(base1 + d)).ToString());
}
for (double d = .6; d < 1; d += .1)
{
testResult &= (System.Math.Round(base1 + d) == base1 + 1);
Log.Comment(d.ToString() + " " + (System.Math.Round(base1 + d)).ToString());
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemMath7_Max_Test()
{
/// <summary>
/// 1. Tests the Math.Max method
/// </summary>
///
Log.Comment("Tests the Math.Max method");
bool testResult = true;
Random random = new Random();
int big = 51 + random.Next(1000);
Log.Comment("With " + big);
int small = random.Next(50);
Log.Comment("and " + small);
testResult &= (System.Math.Max(big,small) == big);
testResult &= (System.Math.Max(small,big) == big);
testResult &= (System.Math.Max(small, -big) == small);
testResult &= (System.Math.Max(-small, -big) == -small);
testResult &= (System.Math.Max(0, small) == small);
testResult &= (System.Math.Max(-small, 0) == 0);
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemMath8_Min_Test()
{
/// <summary>
/// 1. Tests the Math.Min method
/// </summary>
///
Log.Comment("Tests the Math.Min method");
bool testResult = true;
Random random = new Random();
int big = 51 + random.Next(1000);
Log.Comment("With " + big);
int small = random.Next(50);
Log.Comment("and " + small);
testResult &= (System.Math.Min(big, small) == small);
testResult &= (System.Math.Min(small, big) == small);
testResult &= (System.Math.Min(small, -big) == -big);
testResult &= (System.Math.Min(-small, -big) == -big);
testResult &= (System.Math.Min(0, small) == 0);
testResult &= (System.Math.Min(-small, 0) == -small);
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemMath5_Pow_Test()
{
/// <summary>
/// 1. Tests the Math.Pow method
/// </summary>
///
Log.Comment("Tests that the Math.Pow method");
bool testResult = true;
double base1 = new Random().Next(10);
Log.Comment("with " + base1);
double result = 0;
for (double d = 0; d <= 10; d++)
{
result = 1;
for (int i = 1; i <= d; i++)
result *= base1;
testResult &= (result == System.Math.Pow(base1,d));
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DbConnectionStringBuilder.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
namespace System.Data.Common {
/*
internal sealed class NamedConnectionStringConverter : StringConverter {
public NamedConnectionStringConverter() {
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {
// Although theoretically this could be true, some people may want to just type in a name
return false;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
StandardValuesCollection standardValues = null;
if (null != context) {
DbConnectionStringBuilder instance = (context.Instance as DbConnectionStringBuilder);
if (null != instance) {
string myProviderName = instance.GetType().Namespace;
List<string> myConnectionNames = new List<string>();
foreach(System.Configuration.ConnectionStringSetting setting in System.Configuration.ConfigurationManager.ConnectionStrings) {
if (myProviderName.EndsWith(setting.ProviderName)) {
myConnectionNames.Add(setting.ConnectionName);
}
}
standardValues = new StandardValuesCollection(myConnectionNames);
}
}
return standardValues;
}
}
*/
internal class DbConnectionStringBuilderDescriptor : PropertyDescriptor {
private Type _componentType;
private Type _propertyType;
private bool _isReadOnly;
private bool _refreshOnChange;
internal DbConnectionStringBuilderDescriptor(string propertyName, Type componentType, Type propertyType, bool isReadOnly, Attribute[] attributes) : base(propertyName, attributes) {
//Bid.Trace("<comm.DbConnectionStringBuilderDescriptor|INFO> propertyName='%ls', propertyType='%ls'\n", propertyName, propertyType.Name);
_componentType = componentType;
_propertyType = propertyType;
_isReadOnly = isReadOnly;
}
internal bool RefreshOnChange {
get {
return _refreshOnChange;
}
set {
_refreshOnChange = value;
}
}
public override Type ComponentType {
get {
return _componentType;
}
}
public override bool IsReadOnly {
get {
return _isReadOnly;
}
}
public override Type PropertyType {
get {
return _propertyType;
}
}
public override bool CanResetValue(object component) {
DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder);
return ((null != builder) && builder.ShouldSerialize(DisplayName));
}
public override object GetValue(object component) {
DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder);
if (null != builder) {
object value;
if (builder.TryGetValue(DisplayName, out value)) {
return value;
}
}
return null;
}
public override void ResetValue(object component) {
DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder);
if (null != builder) {
builder.Remove(DisplayName);
if (RefreshOnChange) {
builder.ClearPropertyDescriptors();
}
}
}
public override void SetValue(object component, object value) {
DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder);
if (null != builder) {
// via the editor, empty string does a defacto Reset
if ((typeof(string) == PropertyType) && String.Empty.Equals(value)) {
value = null;
}
builder[DisplayName] = value;
if (RefreshOnChange) {
builder.ClearPropertyDescriptors();
}
}
}
public override bool ShouldSerializeValue(object component) {
DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder);
return ((null != builder) && builder.ShouldSerialize(DisplayName));
}
}
[Serializable()]
internal sealed class ReadOnlyCollection<T> : System.Collections.ICollection, ICollection<T> {
private T[] _items;
internal ReadOnlyCollection(T[] items) {
_items = items;
#if DEBUG
for(int i = 0; i < items.Length; ++i) {
Debug.Assert(null != items[i], "null item");
}
#endif
}
public void CopyTo(T[] array, int arrayIndex) {
Array.Copy(_items, 0, array, arrayIndex, _items.Length);
}
void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) {
Array.Copy(_items, 0, array, arrayIndex, _items.Length);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
return new Enumerator<T>(_items);
}
public System.Collections.IEnumerator GetEnumerator() {
return new Enumerator<T>(_items);
}
bool System.Collections.ICollection.IsSynchronized {
get { return false; }
}
Object System.Collections.ICollection.SyncRoot {
get { return _items; }
}
bool ICollection<T>.IsReadOnly {
get { return true;}
}
void ICollection<T>.Add(T value) {
throw new NotSupportedException();
}
void ICollection<T>.Clear() {
throw new NotSupportedException();
}
bool ICollection<T>.Contains(T value) {
return Array.IndexOf(_items, value) >= 0;
}
bool ICollection<T>.Remove(T value) {
throw new NotSupportedException();
}
public int Count {
get { return _items.Length; }
}
[Serializable()]
internal struct Enumerator<K> : IEnumerator<K>, System.Collections.IEnumerator { // based on List<T>.Enumerator
private K[] _items;
private int _index;
internal Enumerator(K[] items) {
_items = items;
_index = -1;
}
public void Dispose() {
}
public bool MoveNext() {
return (++_index < _items.Length);
}
public K Current {
get {
return _items[_index];
}
}
Object System.Collections.IEnumerator.Current {
get {
return _items[_index];
}
}
void System.Collections.IEnumerator.Reset() {
_index = -1;
}
}
}
internal static class DbConnectionStringBuilderUtil {
internal static bool ConvertToBoolean(object value) {
Debug.Assert(null != value, "ConvertToBoolean(null)");
string svalue = (value as string);
if (null != svalue) {
if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes"))
return true;
else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no"))
return false;
else {
string tmp = svalue.Trim(); // Remove leading & trailing white space.
if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes"))
return true;
else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no"))
return false;
}
return Boolean.Parse(svalue);
}
try {
return ((IConvertible)value).ToBoolean(CultureInfo.InvariantCulture);
}
catch(InvalidCastException e) {
throw ADP.ConvertFailed(value.GetType(), typeof(Boolean), e);
}
}
internal static bool ConvertToIntegratedSecurity(object value) {
Debug.Assert(null != value, "ConvertToIntegratedSecurity(null)");
string svalue = (value as string);
if (null != svalue) {
if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes"))
return true;
else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no"))
return false;
else {
string tmp = svalue.Trim(); // Remove leading & trailing white space.
if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes"))
return true;
else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no"))
return false;
}
return Boolean.Parse(svalue);
}
try {
return ((IConvertible)value).ToBoolean(CultureInfo.InvariantCulture);
}
catch(InvalidCastException e) {
throw ADP.ConvertFailed(value.GetType(), typeof(Boolean), e);
}
}
internal static int ConvertToInt32(object value) {
try {
return ((IConvertible)value).ToInt32(CultureInfo.InvariantCulture);
}
catch(InvalidCastException e) {
throw ADP.ConvertFailed(value.GetType(), typeof(Int32), e);
}
}
internal static string ConvertToString(object value) {
try {
return ((IConvertible)value).ToString(CultureInfo.InvariantCulture);
}
catch(InvalidCastException e) {
throw ADP.ConvertFailed(value.GetType(), typeof(String), e);
}
}
const string ApplicationIntentReadWriteString = "ReadWrite";
const string ApplicationIntentReadOnlyString = "ReadOnly";
internal static bool TryConvertToApplicationIntent(string value, out ApplicationIntent result) {
Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed");
Debug.Assert(null != value, "TryConvertToApplicationIntent(null,...)");
if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadOnlyString)) {
result = ApplicationIntent.ReadOnly;
return true;
}
else if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadWriteString)) {
result = ApplicationIntent.ReadWrite;
return true;
}
else {
result = DbConnectionStringDefaults.ApplicationIntent;
return false;
}
}
internal static bool IsValidApplicationIntentValue(ApplicationIntent value) {
Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed");
return value == ApplicationIntent.ReadOnly || value == ApplicationIntent.ReadWrite;
}
internal static string ApplicationIntentToString(ApplicationIntent value) {
Debug.Assert(IsValidApplicationIntentValue(value));
if (value == ApplicationIntent.ReadOnly) {
return ApplicationIntentReadOnlyString;
}
else {
return ApplicationIntentReadWriteString;
}
}
/// <summary>
/// This method attempts to convert the given value tp ApplicationIntent enum. The algorithm is:
/// * if the value is from type string, it will be matched against ApplicationIntent enum names only, using ordinal, case-insensitive comparer
/// * if the value is from type ApplicationIntent, it will be used as is
/// * if the value is from integral type (SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64), it will be converted to enum
/// * if the value is another enum or any other type, it will be blocked with an appropriate ArgumentException
///
/// in any case above, if the conerted value is out of valid range, the method raises ArgumentOutOfRangeException.
/// </summary>
/// <returns>applicaiton intent value in the valid range</returns>
internal static ApplicationIntent ConvertToApplicationIntent(string keyword, object value) {
Debug.Assert(null != value, "ConvertToApplicationIntent(null)");
string sValue = (value as string);
ApplicationIntent result;
if (null != sValue) {
// We could use Enum.TryParse<ApplicationIntent> here, but it accepts value combinations like
// "ReadOnly, ReadWrite" which are unwelcome here
// Also, Enum.TryParse is 100x slower than plain StringComparer.OrdinalIgnoreCase.Equals method.
if (TryConvertToApplicationIntent(sValue, out result)) {
return result;
}
// try again after remove leading & trailing whitespaces.
sValue = sValue.Trim();
if (TryConvertToApplicationIntent(sValue, out result)) {
return result;
}
// string values must be valid
throw ADP.InvalidConnectionOptionValue(keyword);
}
else {
// the value is not string, try other options
ApplicationIntent eValue;
if (value is ApplicationIntent) {
// quick path for the most common case
eValue = (ApplicationIntent)value;
}
else if (value.GetType().IsEnum) {
// explicitly block scenarios in which user tries to use wrong enum types, like:
// builder["ApplicationIntent"] = EnvironmentVariableTarget.Process;
// workaround: explicitly cast non-ApplicationIntent enums to int
throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), null);
}
else {
try {
// Enum.ToObject allows only integral and enum values (enums are blocked above), rasing ArgumentException for the rest
eValue = (ApplicationIntent)Enum.ToObject(typeof(ApplicationIntent), value);
}
catch (ArgumentException e) {
// to be consistent with the messages we send in case of wrong type usage, replace
// the error with our exception, and keep the original one as inner one for troubleshooting
throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), e);
}
}
// ensure value is in valid range
if (IsValidApplicationIntentValue(eValue)) {
return eValue;
}
else {
throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)eValue);
}
}
}
}
internal static class DbConnectionStringDefaults {
// all
// internal const string NamedConnection = "";
// Odbc
internal const string Driver = "";
internal const string Dsn = "";
// OleDb
internal const bool AdoNetPooler = false;
internal const string FileName = "";
internal const int OleDbServices = ~(/*DBPROPVAL_OS_AGR_AFTERSESSION*/0x00000008 | /*DBPROPVAL_OS_CLIENTCURSOR*/0x00000004); // -13
internal const string Provider = "";
// OracleClient
internal const bool Unicode = false;
internal const bool OmitOracleConnectionName = false;
// SqlClient
internal const ApplicationIntent ApplicationIntent = System.Data.SqlClient.ApplicationIntent.ReadWrite;
internal const string ApplicationName = ".Net SqlClient Data Provider";
internal const bool AsynchronousProcessing = false;
internal const string AttachDBFilename = "";
internal const int ConnectTimeout = 15;
internal const bool ConnectionReset = true;
internal const bool ContextConnection = false;
internal const string CurrentLanguage = "";
internal const string DataSource = "";
internal const bool Encrypt = false;
internal const bool Enlist = true;
internal const string FailoverPartner = "";
internal const string InitialCatalog = "";
internal const bool IntegratedSecurity = false;
internal const int LoadBalanceTimeout = 0; // default of 0 means don't use
internal const bool MultipleActiveResultSets = false;
internal const bool MultiSubnetFailover = false;
internal const int MaxPoolSize = 100;
internal const int MinPoolSize = 0;
internal const string NetworkLibrary = "";
internal const int PacketSize = 8000;
internal const string Password = "";
internal const bool PersistSecurityInfo = false;
internal const bool Pooling = true;
internal const bool TrustServerCertificate = false;
internal const string TypeSystemVersion = "Latest";
internal const string UserID = "";
internal const bool UserInstance = false;
internal const bool Replication = false;
internal const string WorkstationID = "";
internal const string TransactionBinding = "Implicit Unbind";
internal const int ConnectRetryCount = 1;
internal const int ConnectRetryInterval = 10;
}
internal static class DbConnectionOptionKeywords {
// Odbc
internal const string Driver = "driver";
internal const string Pwd = "pwd";
internal const string UID = "uid";
// OleDb
internal const string DataProvider = "data provider";
internal const string ExtendedProperties = "extended properties";
internal const string FileName = "file name";
internal const string Provider = "provider";
internal const string RemoteProvider = "remote provider";
// common keywords (OleDb, OracleClient, SqlClient)
internal const string Password = "password";
internal const string UserID = "user id";
}
internal static class DbConnectionStringKeywords {
// all
// internal const string NamedConnection = "Named Connection";
// Odbc
internal const string Driver = "Driver";
internal const string Dsn = "Dsn";
internal const string FileDsn = "FileDsn";
internal const string SaveFile = "SaveFile";
// OleDb
internal const string FileName = "File Name";
internal const string OleDbServices = "OLE DB Services";
internal const string Provider = "Provider";
// OracleClient
internal const string Unicode = "Unicode";
internal const string OmitOracleConnectionName = "Omit Oracle Connection Name";
// SqlClient
internal const string ApplicationIntent = "ApplicationIntent";
internal const string ApplicationName = "Application Name";
internal const string AsynchronousProcessing = "Asynchronous Processing";
internal const string AttachDBFilename = "AttachDbFilename";
internal const string ConnectTimeout = "Connect Timeout";
internal const string ConnectionReset = "Connection Reset";
internal const string ContextConnection = "Context Connection";
internal const string CurrentLanguage = "Current Language";
internal const string Encrypt = "Encrypt";
internal const string FailoverPartner = "Failover Partner";
internal const string InitialCatalog = "Initial Catalog";
internal const string MultipleActiveResultSets = "MultipleActiveResultSets";
internal const string MultiSubnetFailover = "MultiSubnetFailover";
internal const string NetworkLibrary = "Network Library";
internal const string PacketSize = "Packet Size";
internal const string Replication = "Replication";
internal const string TransactionBinding = "Transaction Binding";
internal const string TrustServerCertificate = "TrustServerCertificate";
internal const string TypeSystemVersion = "Type System Version";
internal const string UserInstance = "User Instance";
internal const string WorkstationID = "Workstation ID";
internal const string ConnectRetryCount = "ConnectRetryCount";
internal const string ConnectRetryInterval = "ConnectRetryInterval";
// common keywords (OleDb, OracleClient, SqlClient)
internal const string DataSource = "Data Source";
internal const string IntegratedSecurity = "Integrated Security";
internal const string Password = "Password";
internal const string PersistSecurityInfo = "Persist Security Info";
internal const string UserID = "User ID";
// managed pooling (OracleClient, SqlClient)
internal const string Enlist = "Enlist";
internal const string LoadBalanceTimeout = "Load Balance Timeout";
internal const string MaxPoolSize = "Max Pool Size";
internal const string Pooling = "Pooling";
internal const string MinPoolSize = "Min Pool Size";
}
internal static class DbConnectionStringSynonyms {
//internal const string AsynchronousProcessing = Async;
internal const string Async = "async";
//internal const string ApplicationName = APP;
internal const string APP = "app";
//internal const string AttachDBFilename = EXTENDEDPROPERTIES+","+INITIALFILENAME;
internal const string EXTENDEDPROPERTIES = "extended properties";
internal const string INITIALFILENAME = "initial file name";
//internal const string ConnectTimeout = CONNECTIONTIMEOUT+","+TIMEOUT;
internal const string CONNECTIONTIMEOUT = "connection timeout";
internal const string TIMEOUT = "timeout";
//internal const string CurrentLanguage = LANGUAGE;
internal const string LANGUAGE = "language";
//internal const string OraDataSource = SERVER;
//internal const string SqlDataSource = ADDR+","+ADDRESS+","+SERVER+","+NETWORKADDRESS;
internal const string ADDR = "addr";
internal const string ADDRESS = "address";
internal const string SERVER = "server";
internal const string NETWORKADDRESS = "network address";
//internal const string InitialCatalog = DATABASE;
internal const string DATABASE = "database";
//internal const string IntegratedSecurity = TRUSTEDCONNECTION;
internal const string TRUSTEDCONNECTION = "trusted_connection"; // underscore introduced in everett
//internal const string LoadBalanceTimeout = ConnectionLifetime;
internal const string ConnectionLifetime = "connection lifetime";
//internal const string NetworkLibrary = NET+","+NETWORK;
internal const string NET = "net";
internal const string NETWORK = "network";
internal const string WorkaroundOracleBug914652 = "Workaround Oracle Bug 914652";
//internal const string Password = Pwd;
internal const string Pwd = "pwd";
//internal const string PersistSecurityInfo = PERSISTSECURITYINFO;
internal const string PERSISTSECURITYINFO = "persistsecurityinfo";
//internal const string UserID = UID+","+User;
internal const string UID = "uid";
internal const string User = "user";
//internal const string WorkstationID = WSID;
internal const string WSID = "wsid";
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//adaptation of included Unity JavaScript component in C# by xadhoom
//reference: http://forum.unity3d.com/threads/64378-CharacterMotor-FPSInputController-PlatformInputController-in-C
// Require a character controller to be attached to the same game object
[RequireComponent(typeof(CharacterController))]
[AddComponentMenu("Character/Character Motor")]
public class CharacterMotor : MonoBehaviour
{
// Does this script currently respond to input?
bool canControl = true;
bool useFixedUpdate = true;
// For the next variables, [System.NonSerialized] tells Unity to not serialize the variable or show it in the inspector view.
// Very handy for organization!
// The current global direction we want the character to move in.
[System.NonSerialized]
public Vector3 inputMoveDirection = Vector3.zero;
// Is the jump button held down? We use this interface instead of checking
// for the jump button directly so this script can also be used by AIs.
[System.NonSerialized]
public bool inputJump = false;
[System.Serializable]
public class CharacterMotorMovement
{
// The maximum horizontal speed when moving
public float maxForwardSpeed = 3.0f;
public float maxSidewaysSpeed = 2.0f;
public float maxBackwardsSpeed = 2.0f;
// Curve for multiplying speed based on slope(negative = downwards)
public AnimationCurve slopeSpeedMultiplier = new AnimationCurve(new Keyframe(-90, 1), new Keyframe(0, 1), new Keyframe(90, 0));
// How fast does the character change speeds? Higher is faster.
public float maxGroundAcceleration = 30.0f;
public float maxAirAcceleration = 20.0f;
// The gravity for the character
public float gravity = 9.81f;
public float maxFallSpeed = 20.0f;
// For the next variables, [System.NonSerialized] tells Unity to not serialize the variable or show it in the inspector view.
// Very handy for organization!
// The last collision flags returned from controller.Move
[System.NonSerialized]
public CollisionFlags collisionFlags;
// We will keep track of the character's current velocity,
[System.NonSerialized]
public Vector3 velocity;
// This keeps track of our current velocity while we're not grounded
[System.NonSerialized]
public Vector3 frameVelocity = Vector3.zero;
[System.NonSerialized]
public Vector3 hitPoint = Vector3.zero;
[System.NonSerialized]
public Vector3 lastHitPoint = new Vector3(Mathf.Infinity, 0, 0);
}
public CharacterMotorMovement movement = new CharacterMotorMovement();
public enum MovementTransferOnJump
{
None, // The jump is not affected by velocity of floor at all.
InitTransfer, // Jump gets its initial velocity from the floor, then gradualy comes to a stop.
PermaTransfer, // Jump gets its initial velocity from the floor, and keeps that velocity until landing.
PermaLocked // Jump is relative to the movement of the last touched floor and will move together with that floor.
}
// We will contain all the jumping related variables in one helper class for clarity.
[System.Serializable]
public class CharacterMotorJumping
{
// Can the character jump?
public bool enabled = true;
// How high do we jump when pressing jump and letting go immediately
public float baseHeight = 1.0f;
// We add extraHeight units(meters) on top when holding the button down longer while jumping
public float extraHeight = 4.1f;
// How much does the character jump out perpendicular to the surface on walkable surfaces?
// 0 means a fully vertical jump and 1 means fully perpendicular.
public float perpAmount = 0.0f;
// How much does the character jump out perpendicular to the surface on too steep surfaces?
// 0 means a fully vertical jump and 1 means fully perpendicular.
public float steepPerpAmount = 0.5f;
// For the next variables, [System.NonSerialized] tells Unity to not serialize the variable or show it in the inspector view.
// Very handy for organization!
// Are we jumping?(Initiated with jump button and not grounded yet)
// To see ifwe are just in the air(initiated by jumping OR falling) see the grounded variable.
[System.NonSerialized]
public bool jumping = false;
[System.NonSerialized]
public bool holdingJumpButton = false;
// the time we jumped at(Used to determine for how long to apply extra jump power after jumping.)
[System.NonSerialized]
public float lastStartTime = 0.0f;
[System.NonSerialized]
public float lastButtonDownTime = -100.0f;
[System.NonSerialized]
public Vector3 jumpDir = Vector3.up;
}
public CharacterMotorJumping jumping = new CharacterMotorJumping();
[System.Serializable]
public class CharacterMotorMovingPlatform
{
public bool enabled = true;
public MovementTransferOnJump movementTransfer = MovementTransferOnJump.PermaTransfer;
[System.NonSerialized]
public Transform hitPlatform;
[System.NonSerialized]
public Transform activePlatform;
[System.NonSerialized]
public Vector3 activeLocalPoint;
[System.NonSerialized]
public Vector3 activeGlobalPoint;
[System.NonSerialized]
public Quaternion activeLocalRotation;
[System.NonSerialized]
public Quaternion activeGlobalRotation;
[System.NonSerialized]
public Matrix4x4 lastMatrix;
[System.NonSerialized]
public Vector3 platformVelocity;
[System.NonSerialized]
public bool newPlatform;
}
public CharacterMotorMovingPlatform movingPlatform = new CharacterMotorMovingPlatform();
[System.Serializable]
public class CharacterMotorSliding
{
// Does the character slide on too steep surfaces?
public bool enabled = true;
// How fast does the character slide on steep surfaces?
public float slidingSpeed = 15.0f;
// How much can the player control the sliding direction?
// ifthe value is 0.5 the player can slide sideways with half the speed of the downwards sliding speed.
public float sidewaysControl = 1.0f;
// How much can the player influence the sliding speed?
// ifthe value is 0.5 the player can speed the sliding up to 150% or slow it down to 50%.
public float speedControl = 0.4f;
}
public CharacterMotorSliding sliding = new CharacterMotorSliding();
[System.NonSerialized]
public bool grounded = true;
[System.NonSerialized]
public Vector3 groundNormal = Vector3.zero;
private Vector3 lastGroundNormal = Vector3.zero;
private Transform tr;
private CharacterController controller;
[System.NonSerialized]
public float maximumYVelocityInAir = 0;
//we use this to determine the maximum velocity the character carried over since the last ground collision
void Awake()
{
controller = GetComponent<CharacterController>();
tr = transform;
}
private void UpdateFunction()
{
// We copy the actual velocity into a temporary variable that we can manipulate.
Vector3 velocity = movement.velocity;
// Update velocity based on input
velocity = ApplyInputVelocityChange(velocity);
// Apply gravity and jumping force
velocity = ApplyGravityAndJumping(velocity);
// Moving platform support
Vector3 moveDistance = Vector3.zero;
if(MoveWithPlatform())
{
Vector3 newGlobalPoint = movingPlatform.activePlatform.TransformPoint(movingPlatform.activeLocalPoint);
moveDistance = (newGlobalPoint - movingPlatform.activeGlobalPoint);
if(moveDistance != Vector3.zero)
controller.Move(moveDistance);
// Support moving platform rotation as well:
Quaternion newGlobalRotation = movingPlatform.activePlatform.rotation * movingPlatform.activeLocalRotation;
Quaternion rotationDiff = newGlobalRotation * Quaternion.Inverse(movingPlatform.activeGlobalRotation);
var yRotation = rotationDiff.eulerAngles.y;
if(yRotation != 0)
{
// Prevent rotation of the local up vector
tr.Rotate(0, yRotation, 0);
}
}
// Save lastPosition for velocity calculation.
Vector3 lastPosition = tr.position;
// We always want the movement to be framerate independent. Multiplying by Time.deltaTime does this.
Vector3 currentMovementOffset = velocity * Time.deltaTime;
// Find out how much we need to push towards the ground to avoid loosing grouning
// when walking down a step or over a sharp change in slope.
float pushDownOffset = Mathf.Max(controller.stepOffset, new Vector3(currentMovementOffset.x, 0, currentMovementOffset.z).magnitude);
if(grounded)
currentMovementOffset -= pushDownOffset * Vector3.up;
// Reset variables that will be set by collision function
movingPlatform.hitPlatform = null;
groundNormal = Vector3.zero;
// Move our character!
movement.collisionFlags = controller.Move(currentMovementOffset);
movement.lastHitPoint = movement.hitPoint;
lastGroundNormal = groundNormal;
if(movingPlatform.enabled && movingPlatform.activePlatform != movingPlatform.hitPlatform)
{
if(movingPlatform.hitPlatform != null)
{
movingPlatform.activePlatform = movingPlatform.hitPlatform;
movingPlatform.lastMatrix = movingPlatform.hitPlatform.localToWorldMatrix;
movingPlatform.newPlatform = true;
}
}
// Calculate the velocity based on the current and previous position.
// This means our velocity will only be the amount the character actually moved as a result of collisions.
Vector3 oldHVelocity = new Vector3(velocity.x, 0, velocity.z);
movement.velocity = (tr.position - lastPosition) / Time.deltaTime;
Vector3 newHVelocity = new Vector3(movement.velocity.x, 0, movement.velocity.z);
// The CharacterController can be moved in unwanted directions when colliding with things.
// We want to prevent this from influencing the recorded velocity.
if(oldHVelocity == Vector3.zero)
{
movement.velocity = new Vector3(0, movement.velocity.y, 0);
}
else
{
float projectedNewVelocity = Vector3.Dot(newHVelocity, oldHVelocity) / oldHVelocity.sqrMagnitude;
movement.velocity = oldHVelocity * Mathf.Clamp01(projectedNewVelocity) + movement.velocity.y * Vector3.up;
}
if(movement.velocity.y < velocity.y - 0.001)
{
if(movement.velocity.y < 0)
{
// Something is forcing the CharacterController down faster than it should.
// Ignore this
movement.velocity.y = velocity.y;
}
else
{
// The upwards movement of the CharacterController has been blocked.
// This is treated like a ceiling collision - stop further jumping here.
jumping.holdingJumpButton = false;
}
}
// We were grounded but just loosed grounding
if(grounded && !IsGroundedTest())
{
grounded = false;
maximumYVelocityInAir = 0;
// Apply inertia from platform
if(movingPlatform.enabled &&
(movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer ||
movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer)
)
{
movement.frameVelocity = movingPlatform.platformVelocity;
movement.velocity += movingPlatform.platformVelocity;
}
SendMessage("OnFall", SendMessageOptions.DontRequireReceiver);
// We pushed the character down to ensure it would stay on the ground ifthere was any.
// But there wasn't so now we cancel the downwards offset to make the fall smoother.
tr.position += pushDownOffset * Vector3.up;
}
// We were not grounded but just landed on something
else if(!grounded && IsGroundedTest())
{
grounded = true;
jumping.jumping = false;
SubtractNewPlatformVelocity();
SendMessage("OnLand", SendMessageOptions.DontRequireReceiver);
}
// Moving platforms support
if(MoveWithPlatform())
{
// Use the center of the lower half sphere of the capsule as reference point.
// This works best when the character is standing on moving tilting platforms.
movingPlatform.activeGlobalPoint = tr.position + Vector3.up * (controller.center.y - controller.height * 0.5f + controller.radius);
movingPlatform.activeLocalPoint = movingPlatform.activePlatform.InverseTransformPoint(movingPlatform.activeGlobalPoint);
// Support moving platform rotation as well:
movingPlatform.activeGlobalRotation = tr.rotation;
movingPlatform.activeLocalRotation = Quaternion.Inverse(movingPlatform.activePlatform.rotation) * movingPlatform.activeGlobalRotation;
}
if (!grounded) //keep track of maximum velocity to account for severity of landing
{
if (movement.velocity.y < maximumYVelocityInAir)
maximumYVelocityInAir = movement.velocity.y;
}
}
void FixedUpdate()
{
if(movingPlatform.enabled)
{
if(movingPlatform.activePlatform != null)
{
if(!movingPlatform.newPlatform)
{
// unused: Vector3 lastVelocity = movingPlatform.platformVelocity;
movingPlatform.platformVelocity = (
movingPlatform.activePlatform.localToWorldMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint)
- movingPlatform.lastMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint)
) / Time.deltaTime;
}
movingPlatform.lastMatrix = movingPlatform.activePlatform.localToWorldMatrix;
movingPlatform.newPlatform = false;
}
else
{
movingPlatform.platformVelocity = Vector3.zero;
}
}
if(useFixedUpdate)
UpdateFunction();
}
void Update()
{
if(!useFixedUpdate)
UpdateFunction();
}
private Vector3 ApplyInputVelocityChange(Vector3 velocity)
{
if(!canControl)
inputMoveDirection = Vector3.zero;
// Find desired velocity
Vector3 desiredVelocity;
if(grounded && TooSteep())
{
// The direction we're sliding in
desiredVelocity = new Vector3(groundNormal.x, 0, groundNormal.z).normalized;
// Find the input movement direction projected onto the sliding direction
var projectedMoveDir = Vector3.Project(inputMoveDirection, desiredVelocity);
// Add the sliding direction, the spped control, and the sideways control vectors
desiredVelocity = desiredVelocity + projectedMoveDir * sliding.speedControl + (inputMoveDirection - projectedMoveDir) * sliding.sidewaysControl;
// Multiply with the sliding speed
desiredVelocity *= sliding.slidingSpeed;
}
else
desiredVelocity = GetDesiredHorizontalVelocity();
if(movingPlatform.enabled && movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer)
{
desiredVelocity += movement.frameVelocity;
desiredVelocity.y = 0;
}
if(grounded)
desiredVelocity = AdjustGroundVelocityToNormal(desiredVelocity, groundNormal);
else
velocity.y = 0;
// Enforce max velocity change
float maxVelocityChange = GetMaxAcceleration(grounded) * Time.deltaTime;
Vector3 velocityChangeVector = (desiredVelocity - velocity);
if(velocityChangeVector.sqrMagnitude > maxVelocityChange * maxVelocityChange)
{
velocityChangeVector = velocityChangeVector.normalized * maxVelocityChange;
}
// ifwe're in the air and don't have control, don't apply any velocity change at all.
// ifwe're on the ground and don't have control we do apply it - it will correspond to friction.
if(grounded || canControl)
velocity += velocityChangeVector;
if(grounded)
{
// When going uphill, the CharacterController will automatically move up by the needed amount.
// Not moving it upwards manually prevent risk of lifting off from the ground.
// When going downhill, DO move down manually, as gravity is not enough on steep hills.
velocity.y = Mathf.Min(velocity.y, 0);
}
return velocity;
}
private Vector3 ApplyGravityAndJumping(Vector3 velocity)
{
if(!inputJump || !canControl)
{
jumping.holdingJumpButton = false;
jumping.lastButtonDownTime = -100;
}
if(inputJump && jumping.lastButtonDownTime < 0 && canControl)
jumping.lastButtonDownTime = Time.time;
if(grounded)
velocity.y = Mathf.Min(0, velocity.y) - movement.gravity * Time.deltaTime;
else
{
velocity.y = movement.velocity.y - movement.gravity * Time.deltaTime;
// When jumping up we don't apply gravity for some time when the user is holding the jump button.
// This gives more control over jump height by pressing the button longer.
if(jumping.jumping && jumping.holdingJumpButton)
{
// Calculate the duration that the extra jump force should have effect.
// ifwe're still less than that duration after the jumping time, apply the force.
if(Time.time < jumping.lastStartTime + jumping.extraHeight / CalculateJumpVerticalSpeed(jumping.baseHeight))
{
// Negate the gravity we just applied, except we push in jumpDir rather than jump upwards.
velocity += jumping.jumpDir * movement.gravity * Time.deltaTime;
}
}
// Make sure we don't fall any faster than maxFallSpeed. This gives our character a terminal velocity.
velocity.y = Mathf.Max(velocity.y, -movement.maxFallSpeed);
}
if(grounded)
{
// Jump only ifthe jump button was pressed down in the last 0.2 seconds.
// We use this check instead of checking ifit's pressed down right now
// because players will often try to jump in the exact moment when hitting the ground after a jump
// and ifthey hit the button a fraction of a second too soon and no new jump happens as a consequence,
// it's confusing and it feels like the game is buggy.
if(jumping.enabled && canControl && (Time.time - jumping.lastButtonDownTime < 0.2))
{
grounded = false;
maximumYVelocityInAir = 0;
jumping.jumping = true;
jumping.lastStartTime = Time.time;
jumping.lastButtonDownTime = -100;
jumping.holdingJumpButton = true;
// Calculate the jumping direction
if(TooSteep())
jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.steepPerpAmount);
else
jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.perpAmount);
// Apply the jumping force to the velocity. Cancel any vertical velocity first.
velocity.y = 0;
velocity += jumping.jumpDir * CalculateJumpVerticalSpeed(jumping.baseHeight);
// Apply inertia from platform
if(movingPlatform.enabled &&
(movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer ||
movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer)
)
{
movement.frameVelocity = movingPlatform.platformVelocity;
velocity += movingPlatform.platformVelocity;
}
SendMessage("OnJump", SendMessageOptions.DontRequireReceiver);
}
else
{
jumping.holdingJumpButton = false;
}
}
return velocity;
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
if(hit.normal.y > 0 && hit.normal.y > groundNormal.y && hit.moveDirection.y < 0)
{
if((hit.point - movement.lastHitPoint).sqrMagnitude > 0.001 || lastGroundNormal == Vector3.zero)
groundNormal = hit.normal;
else
groundNormal = lastGroundNormal;
movingPlatform.hitPlatform = hit.collider.transform;
movement.hitPoint = hit.point;
movement.frameVelocity = Vector3.zero;
}
}
private IEnumerator SubtractNewPlatformVelocity()
{
// When landing, subtract the velocity of the new ground from the character's velocity
// since movement in ground is relative to the movement of the ground.
if(movingPlatform.enabled &&
(movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer ||
movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer))
{
// if we landed on a new platform, we have to wait for two FixedUpdates
// before we know the velocity of the platform under the character
if(movingPlatform.newPlatform)
{
Transform platform = movingPlatform.activePlatform;
yield return new WaitForFixedUpdate();
yield return new WaitForFixedUpdate();
if(grounded && platform == movingPlatform.activePlatform)
yield break;
}
movement.velocity -= movingPlatform.platformVelocity;
}
}
private bool MoveWithPlatform()
{
return (movingPlatform.enabled
&& (grounded || movingPlatform.movementTransfer == MovementTransferOnJump.PermaLocked)
&& movingPlatform.activePlatform != null
);
}
private Vector3 GetDesiredHorizontalVelocity()
{
// Find desired velocity
Vector3 desiredLocalDirection = tr.InverseTransformDirection(inputMoveDirection);
float maxSpeed = MaxSpeedInDirection(desiredLocalDirection);
if(grounded)
{
// Modify max speed on slopes based on slope speed multiplier curve
var movementSlopeAngle = Mathf.Asin(movement.velocity.normalized.y) * Mathf.Rad2Deg;
maxSpeed *= movement.slopeSpeedMultiplier.Evaluate(movementSlopeAngle);
}
return tr.TransformDirection(desiredLocalDirection * maxSpeed);
}
private Vector3 AdjustGroundVelocityToNormal(Vector3 hVelocity, Vector3 groundNormal)
{
Vector3 sideways = Vector3.Cross(Vector3.up, hVelocity);
return Vector3.Cross(sideways, groundNormal).normalized * hVelocity.magnitude;
}
private bool IsGroundedTest()
{
return (groundNormal.y > 0.01);
}
float GetMaxAcceleration(bool grounded)
{
// Maximum acceleration on ground and in air
if(grounded)
return movement.maxGroundAcceleration;
else
return movement.maxAirAcceleration;
}
float CalculateJumpVerticalSpeed(float targetJumpHeight)
{
// From the jump height and gravity we deduce the upwards speed
// for the character to reach at the apex.
return Mathf.Sqrt(2 * targetJumpHeight * movement.gravity);
}
bool IsJumping()
{
return jumping.jumping;
}
bool IsSliding()
{
return (grounded && sliding.enabled && TooSteep());
}
bool IsTouchingCeiling()
{
return (movement.collisionFlags & CollisionFlags.CollidedAbove) != 0;
}
bool IsGrounded()
{
return grounded;
}
bool TooSteep()
{
return (groundNormal.y <= Mathf.Cos(controller.slopeLimit * Mathf.Deg2Rad));
}
Vector3 GetDirection()
{
return inputMoveDirection;
}
void SetControllable(bool controllable)
{
canControl = controllable;
}
// Project a direction onto elliptical quater segments based on forward, sideways, and backwards speed.
// The function returns the length of the resulting vector.
float MaxSpeedInDirection(Vector3 desiredMovementDirection)
{
if(desiredMovementDirection == Vector3.zero)
return 0;
else
{
float zAxisEllipseMultiplier = (desiredMovementDirection.z > 0 ? movement.maxForwardSpeed : movement.maxBackwardsSpeed) / movement.maxSidewaysSpeed;
Vector3 temp = new Vector3(desiredMovementDirection.x, 0, desiredMovementDirection.z / zAxisEllipseMultiplier).normalized;
float length = new Vector3(temp.x, 0, temp.z * zAxisEllipseMultiplier).magnitude * movement.maxSidewaysSpeed;
return length;
}
}
/// <summary>
/// Sets the character velocity manually.
/// </summary>
/// <param name="velocity">Velocity.</param>
void SetVelocity(Vector3 velocity)
{
grounded = false;
movement.velocity = velocity;
movement.frameVelocity = Vector3.zero;
SendMessage("OnExternalVelocity");
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.CompilerServices;
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.integeregererface01.integeregererface01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.integeregererface01.integeregererface01;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Types Rule : Interface Methods (Compiler)
// CLS-compliant language compilers must have syntax for the situation where a single type implements
// two interfaces and each of those interfaces requires the definition of a method with the same name and signature.
// Such methods must be considered distinct and need not have the same implementation.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public interface MyInterface1
{
dynamic Method01(int n);
T Method02<T>(dynamic n);
dynamic Method03(byte b, ref dynamic n);
}
public interface MyInterface2
{
dynamic Method01(int n);
T Method02<T>(dynamic n);
dynamic Method03(byte b, ref dynamic n);
}
public class MyClass : MyInterface1, MyInterface2
{
dynamic MyInterface1.Method01(int n)
{
return default(dynamic);
}
T MyInterface1.Method02<T>(dynamic n)
{
return default(T);
}
dynamic MyInterface1.Method03(byte b, ref dynamic n)
{
return default(dynamic);
}
dynamic MyInterface2.Method01(int n)
{
return default(dynamic);
}
T MyInterface2.Method02<T>(dynamic n)
{
return default(T);
}
dynamic MyInterface2.Method03(byte b, ref dynamic n)
{
return default(dynamic);
}
}
public struct MyStruct : MyInterface1, MyInterface2
{
public dynamic Method01(int n)
{
return default(dynamic);
}
public T Method02<T>(dynamic n)
{
return default(T);
}
public dynamic Method03(byte b, ref dynamic n)
{
return default(dynamic);
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.mixedmode02.mixedmode02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.mixedmode02.mixedmode02;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Naming Rule : Characters and casing
// CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of
// the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers.
// This standard is available from the Web site of the Unicode Consortium.
// For two identifiers to be considered distinct, they must differ by more than just their case.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=warning>\(79,55\).*CS3022</Expects>
//<Expects Status=warning>\(80,55\).*CS3022</Expects>
//<Expects Status=warning>\(47,29\).*CS3026.*vd1</Expects>
//<Expects Status=warning>\(50,23\).*CS3002.*RefMethod01\<T\>\(ref dynamic, T\)</Expects>
//<Expects Status=warning>\(51,23\).*CS3002.*refMethod01\<T\></Expects>
//<Expects Status=warning>\(51,23\).*CS3005</Expects>
//<Expects Status=warning>\(65,13\).*CS3010.*MyInterface\<T,U,V\>.Method01</Expects>
//<Expects Status=warning>\(69,7\).*CS3005.*MyInterface\<T,U,V\>.method02</Expects>
//<Expects Status=warning>\(72,13\).*CS3005.*method03\<X,Y\></Expects>
//<Expects Status=warning>\(75,27\).*CS3010.*MyInterface\<T,U,V\>.MyEvent</Expects>
//<Expects Status=warning>\(75,27\).*CS3010</Expects>
//<Expects Status=warning>\(75,27\).*CS3010</Expects>
//<Expects Status=warning>\(80,22\).*CS3005.*myDelegate01\<T\></Expects>
//<Expects Status=success></Expects>
// <Code>
// <Expects Status=notin>CS3005.*outMethod01\<X\></Expects>
// <Expects Status=notin>CS3005.*method01\<X\></Expects>
// <Expects Status=notin>CS3005.*myDelegate02\<U,V\></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
[type: System.CLSCompliant(false)]
public class MyClass<T>
{
public volatile dynamic vd;
public static T OutMethod01<X>(T t, ref X x, out dynamic d)
{
d = default(object);
return default(T);
}
public static T outMethod01<X>(T t, ref X x, out dynamic d)
{
d = default(object);
return default(T);
}
}
[type: System.CLSCompliant(true)]
public struct MyStruct<U, V>
{
public volatile dynamic vd1;
[method: System.CLSCompliant(true)]
public MyClass<T> RefMethod01<T>(ref dynamic d, T t)
{
d = default(object);
return new MyClass<T>();
}
public MyClass<T> refMethod01<T>(ref dynamic d, T t)
{
d = default(object);
return new MyClass<T>();
}
[property: System.CLSCompliant(false)]
public dynamic Prop
{
get;
set;
}
public dynamic prop
{
get;
set;
}
[field: System.CLSCompliant(false)]
public dynamic field;
public dynamic fielD;
}
public interface MyInterface<T, U, V>
{
[method: System.CLSCompliant(false)]
dynamic Method01<X>(X n);
dynamic method01<X>(X n);
T Method02(dynamic n, U u);
T method02(dynamic n, U u);
[method: System.CLSCompliant(true)]
dynamic Method03<X, Y>(out X x, ref Y y, dynamic n);
dynamic method03<X, Y>(out X x, ref Y y, dynamic n);
[event: System.CLSCompliant(false)]
event MyDelegate01<T> MyEvent;
event MyDelegate01<T> Myevent;
}
public delegate void MyDelegate01<T>(ref T t, [param: System.CLSCompliant(false)]
dynamic d, int n);
public delegate void myDelegate01<T>(ref T t, [param: System.CLSCompliant(true)]
dynamic d, int n);
[System.CLSCompliantAttribute(false)]
public delegate V MyDelegate02<U, V>(U u, params dynamic[] ary);
public delegate V myDelegate02<U, V>(U u, params dynamic[] ary);
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr02.namingchr02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr02.namingchr02;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Naming Rule : Characters and casing
// CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of
// the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers.
// This standard is available from the Web site of the Unicode Consortium.
// For two identifiers to be considered distinct, they must differ by more than just their case.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=warning>\(30,14\).*CS3005.*outMethod01\<X\></Expects>
//<Expects Status=warning>\(36,23\).*CS3005.*refMethod01\<T\></Expects>
//<Expects Status=warning>\(42,13\).*CS3005.*method01\<X\></Expects>
//<Expects Status=warning>\(45,7\).*CS3005.*MyInterface\<T,U,V\>.method02</Expects>
//<Expects Status=warning>\(48,13\).*CS3005.*method03\<X,Y\></Expects>
//<Expects Status=warning>\(52,22\).*CS3005.*myDelegate01\<T\></Expects>
//<Expects Status=warning>\(55,19\).*CS3005.*myDelegate02\<U,V\></Expects>
//<Expects Status=success></Expects>
// <Code>
// <Code>
//[assembly: System.CLSCompliant(true)]
public class MyClass<T>
{
public T OutMethod01<X>(T t, ref X x, out dynamic d)
{
d = default(object);
return default(T);
}
public T outMethod01<X>(T t, ref X x, out dynamic d)
{
d = default(object);
return default(T);
}
}
public struct MyStruct<U, V>
{
public MyClass<T> RefMethod01<T>(ref dynamic d, T t)
{
d = default(object);
return new MyClass<T>();
}
public MyClass<T> refMethod01<T>(ref dynamic d, T t)
{
d = default(object);
return new MyClass<T>();
}
}
public interface MyInterface<T, U, V>
{
dynamic Method01<X>(X n);
dynamic method01<X>(X n);
T Method02(dynamic n, U u);
T method02(dynamic n, U u);
dynamic Method03<X, Y>(out X x, ref Y y, dynamic n);
dynamic method03<X, Y>(out X x, ref Y y, dynamic n);
}
public delegate void MyDelegate01<T>(ref T t, dynamic d, int n);
public delegate void myDelegate01<T>(ref T t, dynamic d, int n);
public delegate V MyDelegate02<U, V>(U u, params dynamic[] ary);
public delegate V myDelegate02<U, V>(U u, params dynamic[] ary);
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr03.namingchr03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr03.namingchr03;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Naming Rule : Characters and casing
// CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of
// the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers.
// This standard is available from the Web site of the Unicode Consortium.
// For two identifiers to be considered distinct, they must differ by more than just their case.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=warning>\(57,24\).*CS0108</Expects>
//<Expects Status=warning>\(41,24\).*CS3005.*method01</Expects>
//<Expects Status=warning>\(42,18\).*CS3005.*method02\<T\></Expects>
//<Expects Status=warning>\(49,24\).*CS3005.*classIdentifier</Expects>
//<Expects Status=warning>\(50,24\).*CS3005.*MEthod01</Expects>
//<Expects Status=warning>\(51,18\).*CS3005.*mEthod02\<T\></Expects>
//<Expects Status=warning>\(52,24\).*CS3005.*method03\<X,Y></Expects>
//<Expects Status=warning>\(57,24\).*CS3005</Expects>
//<Expects Status=warning>\(58,24\).*CS3005.*MyClass3\<U,V\>\.Method01</Expects>
//<Expects Status=warning>\(59,24\).*CS3005.*MyClass3\<U,V\>\.Method03</Expects>
//<Expects Status=success></Expects>
// <Code>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public class MyBase
{
public dynamic Method01(int n, ref dynamic d)
{
return default(object);
}
public T Method02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
}
public class MyClass : MyBase
{
public dynamic ClassIdentifier;
public dynamic method01(int n, ref dynamic d)
{
return default(object);
}
public T method02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
public dynamic Method03<X, Y>(X x, ref Y y, params dynamic[] ary)
{
return default(object);
}
}
public class MyClass2 : MyClass
{
public dynamic classIdentifier;
public dynamic MEthod01(int n, ref dynamic d)
{
return default(object);
}
public T mEthod02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
public dynamic method03<X, Y>(X x, ref Y y, params dynamic[] ary)
{
return default(object);
}
}
public class MyClass3<U, V> : MyClass2
{
public dynamic ClassIdentifier;
public dynamic Method01(long n, ref dynamic d)
{
return default(object);
}
public dynamic Method03(U x, ref V y, params dynamic[] ary)
{
return default(object);
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr04.namingchr04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr04.namingchr04;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Visibility - CLS rules apply only to those parts of a type that are exposed outside the defining assembly.
// Naming Rule : Characters and casing
// CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of
// the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers.
// This standard is available from the Web site of the Unicode Consortium.
// For two identifiers to be considered distinct, they must differ by more than just their case.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=warning>\(31,17\).*CS0169</Expects>
//<Expects Status=warning>\(43,25\).*CS0169</Expects>
//<Expects Status=success></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public class MyBase
{
public dynamic[][][] array; //jagged array
private dynamic Method01(int n, ref dynamic d)
{
return default(object);
}
private T Method02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
}
public class MyClass : MyBase
{
private dynamic _classIdentifier;
internal dynamic method01(int n, ref dynamic d)
{
return default(object);
}
protected T method02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
private dynamic Method03<X, Y>(X x, ref Y y, params dynamic[] ary)
{
return default(object);
}
}
public class MyClass2 : MyClass
{
//static public dynamic[,,,] array1; //cube array
private dynamic _classIdentifier;
private dynamic MEthod01(int n, ref dynamic d)
{
return default(object);
}
private T mEthod02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
protected dynamic method03<X, Y>(X x, ref Y y, params dynamic[] ary)
{
return default(object);
}
}
public class MyClass3<U, V> : MyClass2
{
protected dynamic ClassIdentifier;
private dynamic Method01(long n, ref dynamic d)
{
return default(object);
}
internal protected dynamic method03(U x, ref V y, params dynamic[] ary)
{
return default(object);
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingkeyword01.namingkeyword01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingkeyword01.namingkeyword01;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Naming Rule : Keywords (Compiler)
// CLS-compliant language compilers supply a mechanism for referencing identifiers that coincide with keywords.
// CLS-compliant language compilers provide a mechanism for defining and overriding virtual methods
// with names that are keywords in the language.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public class MyClass
{
public dynamic @dynamic;
public dynamic Method01(ref int @dynamic)
{
return default(dynamic);
}
}
public struct MyStruct
{
public dynamic @dynamic;
public void Method02(out dynamic @dynamic)
{
@dynamic = default(dynamic);
}
}
public interface MyInterface
{
dynamic Method01(int n, dynamic @dynamic);
dynamic @dynamic(string n, dynamic d);
}
public delegate void myDelegate02(params dynamic[] @dynamic);
public delegate int @dynamic(int n);
namespace MyNamespace11
{
public enum @dynamic
{
}
}
}
namespace MyNamespace1
{
public class @dynamic
{
private dynamic Method01(out int n, dynamic d)
{
n = 0;
return default(dynamic);
}
}
namespace MyNamespace2
{
public struct @dynamic
{
private dynamic Method01(int n, ref dynamic d)
{
return default(dynamic);
}
}
namespace MyNamespace3
{
public interface @dynamic
{
dynamic Method01(int n, ref dynamic d);
}
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.typegeneral01.typegeneral01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.typegeneral01.typegeneral01;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Types Rule : Interface Methods (Compiler)
// CLS-compliant language compilers must have syntax for the situation where a single type implements
// two interfaces and each of those interfaces requires the definition of a method with the same name and signature.
// Such methods must be considered distinct and need not have the same implementation.
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public class MyClass
{
public dynamic Method01(int x, int y = 0, int z = 1)
{
return default(dynamic);
}
//
public T Method02<T>(dynamic d = default(dynamic), string s = "QQQ")
{
return default(T);
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MyClass c = new MyClass();
c.Method01(999);
c.Method01(9, 8);
c.Method01(9, 8, 7);
c.Method01(999, z: 888);
c.Method01(999, z: 888, y: 666);
c.Method02<byte>();
c.Method02<int>(default(dynamic));
c.Method02<long>(default(dynamic), "CCC");
var v = new MyStruct<dynamic>();
v.Method11();
v.Method11(default(dynamic));
v.Method11(default(object), default(object), default(object));
v.Method12<int, dynamic>();
v.Method12<int, dynamic>(100);
v.Method12<int, dynamic>(-9999, default(dynamic));
return 0;
}
}
public struct MyStruct<T>
{
public dynamic Method11(T t = default(T), params dynamic[] ary)
{
return default(dynamic);
}
public T Method12<U, V>(U u = default(U), V v = default(V))
{
return default(T);
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.bug89385_a.bug89385_a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.bug89385_a.bug89385_a;
// <Title> regression test</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Foo
{
public static void Method(string s)
{
if (s == "abc")
Test.Result++;
}
public string Prop
{
get;
set;
}
}
public class Test
{
public Foo Foo
{
get;
set;
}
public static void DoExample(dynamic d)
{
Foo.Method(d.Prop);
}
public static int Result = -1;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
try
{
DoExample(new Foo()
{
Prop = "abc"
}
);
}
catch (System.Exception)
{
Test.Result--;
}
return Test.Result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Avx.IsSupported)
{
{
double* inArray = stackalloc double[4];
byte* outBuffer = stackalloc byte[64];
double* outArray = (double*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<double>>(inArray);
Avx.StoreAlignedNonTemporal(outArray, vf);
for (var i = 0; i < 4; i++)
{
if (BitConverter.DoubleToInt64Bits(inArray[i]) != BitConverter.DoubleToInt64Bits(outArray[i]))
{
Console.WriteLine("Avx StoreAlignedNonTemporal failed on double:");
for (var n = 0; n < 4; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
float* inArray = stackalloc float[8];
byte* outBuffer = stackalloc byte[64];
float* outArray = (float*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<float>>(inArray);
Avx.StoreAlignedNonTemporal(outArray, vf);
for (var i = 0; i < 8; i++)
{
if (BitConverter.SingleToInt32Bits(inArray[i]) != BitConverter.SingleToInt32Bits(outArray[i]))
{
Console.WriteLine("Avx StoreAlignedNonTemporal failed on float:");
for (var n = 0; n < 8; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
long* inArray = stackalloc long[4];
byte* outBuffer = stackalloc byte[64];
long* outArray = (long*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<long>>(inArray);
Avx.StoreAlignedNonTemporal(outArray, vf);
for (var i = 0; i < 4; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAlignedNonTemporal failed on long:");
for (var n = 0; n < 4; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
ulong* inArray = stackalloc ulong[4];
byte* outBuffer = stackalloc byte[64];
ulong* outArray = (ulong*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<ulong>>(inArray);
Avx.StoreAlignedNonTemporal(outArray, vf);
for (var i = 0; i < 4; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAlignedNonTemporal failed on ulong:");
for (var n = 0; n < 4; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
int* inArray = stackalloc int[8];
byte* outBuffer = stackalloc byte[64];
int* outArray = (int*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<int>>(inArray);
Avx.StoreAlignedNonTemporal(outArray, vf);
for (var i = 0; i < 8; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAlignedNonTemporal failed on int:");
for (var n = 0; n < 8; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
uint* inArray = stackalloc uint[8];
byte* outBuffer = stackalloc byte[64];
uint* outArray = (uint*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<uint>>(inArray);
Avx.StoreAlignedNonTemporal(outArray, vf);
for (var i = 0; i < 8; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAlignedNonTemporal failed on uint:");
for (var n = 0; n < 8; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
short* inArray = stackalloc short[16];
byte* outBuffer = stackalloc byte[64];
short* outArray = (short*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<short>>(inArray);
Avx.StoreAlignedNonTemporal(outArray, vf);
for (var i = 0; i < 16; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAlignedNonTemporal failed on short:");
for (var n = 0; n < 16; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
ushort* inArray = stackalloc ushort[16];
byte* outBuffer = stackalloc byte[64];
ushort* outArray = (ushort*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<ushort>>(inArray);
Avx.StoreAlignedNonTemporal(outArray, vf);
for (var i = 0; i < 16; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAlignedNonTemporal failed on ushort:");
for (var n = 0; n < 16; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
byte* inArray = stackalloc byte[32];
byte* outBuffer = stackalloc byte[64];
byte* outArray = (byte*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<byte>>(inArray);
Avx.StoreAlignedNonTemporal(outArray, vf);
for (var i = 0; i < 32; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAlignedNonTemporal failed on byte:");
for (var n = 0; n < 32; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
sbyte* inArray = stackalloc sbyte[32];
byte* outBuffer = stackalloc byte[64];
sbyte* outArray = (sbyte*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<sbyte>>(inArray);
Avx.StoreAlignedNonTemporal(outArray, vf);
for (var i = 0; i < 32; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAlignedNonTemporal failed on byte:");
for (var n = 0; n < 32; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
}
return testResult;
}
static unsafe void* Align(byte* buffer, byte expectedAlignment)
{
// Compute how bad the misalignment is, which is at most (expectedAlignment - 1).
// Then subtract that from the expectedAlignment and add it to the original address
// to compute the aligned address.
var misalignment = expectedAlignment - ((ulong)(buffer) % expectedAlignment);
return (void*)(buffer + misalignment);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: money/cards/card_sale_purpose.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Money.Cards {
/// <summary>Holder for reflection information generated from money/cards/card_sale_purpose.proto</summary>
public static partial class CardSalePurposeReflection {
#region Descriptor
/// <summary>File descriptor for money/cards/card_sale_purpose.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CardSalePurposeReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiNtb25leS9jYXJkcy9jYXJkX3NhbGVfcHVycG9zZS5wcm90bxIXaG9sbXMu",
"dHlwZXMubW9uZXkuY2FyZHMilQIKD0NhcmRTYWxlUHVycG9zZRIVCg1mb3Jf",
"Z3VhcmFudGVlGAEgASgIEhkKEWZvcl9wYXltZW50X290aGVyGAIgASgIEhsK",
"E2Zvcl9wYXltZW50X2xvZGdpbmcYAyABKAgSHgoWZm9yX3BheW1lbnRfcmVz",
"dGF1cmFudBgEIAEoCBIdChVmb3JfcGF5bWVudF9naWZ0X3Nob3AYBSABKAgS",
"GwoTZm9yX3BheW1lbnRfbWluaWJhchgGIAEoCBIdChVmb3JfcGF5bWVudF90",
"ZWxlcGhvbmUYByABKAgSGwoTZm9yX3BheW1lbnRfbGF1bmRyeRgIIAEoCBIb",
"ChNmb3JfcGF5bWVudF9wZW5hbHR5GAkgASgIQidaC21vbmV5L2NhcmRzqgIX",
"SE9MTVMuVHlwZXMuTW9uZXkuQ2FyZHNiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Money.Cards.CardSalePurpose), global::HOLMS.Types.Money.Cards.CardSalePurpose.Parser, new[]{ "ForGuarantee", "ForPaymentOther", "ForPaymentLodging", "ForPaymentRestaurant", "ForPaymentGiftShop", "ForPaymentMinibar", "ForPaymentTelephone", "ForPaymentLaundry", "ForPaymentPenalty" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class CardSalePurpose : pb::IMessage<CardSalePurpose> {
private static readonly pb::MessageParser<CardSalePurpose> _parser = new pb::MessageParser<CardSalePurpose>(() => new CardSalePurpose());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CardSalePurpose> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Money.Cards.CardSalePurposeReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CardSalePurpose() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CardSalePurpose(CardSalePurpose other) : this() {
forGuarantee_ = other.forGuarantee_;
forPaymentOther_ = other.forPaymentOther_;
forPaymentLodging_ = other.forPaymentLodging_;
forPaymentRestaurant_ = other.forPaymentRestaurant_;
forPaymentGiftShop_ = other.forPaymentGiftShop_;
forPaymentMinibar_ = other.forPaymentMinibar_;
forPaymentTelephone_ = other.forPaymentTelephone_;
forPaymentLaundry_ = other.forPaymentLaundry_;
forPaymentPenalty_ = other.forPaymentPenalty_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CardSalePurpose Clone() {
return new CardSalePurpose(this);
}
/// <summary>Field number for the "for_guarantee" field.</summary>
public const int ForGuaranteeFieldNumber = 1;
private bool forGuarantee_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ForGuarantee {
get { return forGuarantee_; }
set {
forGuarantee_ = value;
}
}
/// <summary>Field number for the "for_payment_other" field.</summary>
public const int ForPaymentOtherFieldNumber = 2;
private bool forPaymentOther_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ForPaymentOther {
get { return forPaymentOther_; }
set {
forPaymentOther_ = value;
}
}
/// <summary>Field number for the "for_payment_lodging" field.</summary>
public const int ForPaymentLodgingFieldNumber = 3;
private bool forPaymentLodging_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ForPaymentLodging {
get { return forPaymentLodging_; }
set {
forPaymentLodging_ = value;
}
}
/// <summary>Field number for the "for_payment_restaurant" field.</summary>
public const int ForPaymentRestaurantFieldNumber = 4;
private bool forPaymentRestaurant_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ForPaymentRestaurant {
get { return forPaymentRestaurant_; }
set {
forPaymentRestaurant_ = value;
}
}
/// <summary>Field number for the "for_payment_gift_shop" field.</summary>
public const int ForPaymentGiftShopFieldNumber = 5;
private bool forPaymentGiftShop_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ForPaymentGiftShop {
get { return forPaymentGiftShop_; }
set {
forPaymentGiftShop_ = value;
}
}
/// <summary>Field number for the "for_payment_minibar" field.</summary>
public const int ForPaymentMinibarFieldNumber = 6;
private bool forPaymentMinibar_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ForPaymentMinibar {
get { return forPaymentMinibar_; }
set {
forPaymentMinibar_ = value;
}
}
/// <summary>Field number for the "for_payment_telephone" field.</summary>
public const int ForPaymentTelephoneFieldNumber = 7;
private bool forPaymentTelephone_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ForPaymentTelephone {
get { return forPaymentTelephone_; }
set {
forPaymentTelephone_ = value;
}
}
/// <summary>Field number for the "for_payment_laundry" field.</summary>
public const int ForPaymentLaundryFieldNumber = 8;
private bool forPaymentLaundry_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ForPaymentLaundry {
get { return forPaymentLaundry_; }
set {
forPaymentLaundry_ = value;
}
}
/// <summary>Field number for the "for_payment_penalty" field.</summary>
public const int ForPaymentPenaltyFieldNumber = 9;
private bool forPaymentPenalty_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ForPaymentPenalty {
get { return forPaymentPenalty_; }
set {
forPaymentPenalty_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CardSalePurpose);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CardSalePurpose other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ForGuarantee != other.ForGuarantee) return false;
if (ForPaymentOther != other.ForPaymentOther) return false;
if (ForPaymentLodging != other.ForPaymentLodging) return false;
if (ForPaymentRestaurant != other.ForPaymentRestaurant) return false;
if (ForPaymentGiftShop != other.ForPaymentGiftShop) return false;
if (ForPaymentMinibar != other.ForPaymentMinibar) return false;
if (ForPaymentTelephone != other.ForPaymentTelephone) return false;
if (ForPaymentLaundry != other.ForPaymentLaundry) return false;
if (ForPaymentPenalty != other.ForPaymentPenalty) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ForGuarantee != false) hash ^= ForGuarantee.GetHashCode();
if (ForPaymentOther != false) hash ^= ForPaymentOther.GetHashCode();
if (ForPaymentLodging != false) hash ^= ForPaymentLodging.GetHashCode();
if (ForPaymentRestaurant != false) hash ^= ForPaymentRestaurant.GetHashCode();
if (ForPaymentGiftShop != false) hash ^= ForPaymentGiftShop.GetHashCode();
if (ForPaymentMinibar != false) hash ^= ForPaymentMinibar.GetHashCode();
if (ForPaymentTelephone != false) hash ^= ForPaymentTelephone.GetHashCode();
if (ForPaymentLaundry != false) hash ^= ForPaymentLaundry.GetHashCode();
if (ForPaymentPenalty != false) hash ^= ForPaymentPenalty.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ForGuarantee != false) {
output.WriteRawTag(8);
output.WriteBool(ForGuarantee);
}
if (ForPaymentOther != false) {
output.WriteRawTag(16);
output.WriteBool(ForPaymentOther);
}
if (ForPaymentLodging != false) {
output.WriteRawTag(24);
output.WriteBool(ForPaymentLodging);
}
if (ForPaymentRestaurant != false) {
output.WriteRawTag(32);
output.WriteBool(ForPaymentRestaurant);
}
if (ForPaymentGiftShop != false) {
output.WriteRawTag(40);
output.WriteBool(ForPaymentGiftShop);
}
if (ForPaymentMinibar != false) {
output.WriteRawTag(48);
output.WriteBool(ForPaymentMinibar);
}
if (ForPaymentTelephone != false) {
output.WriteRawTag(56);
output.WriteBool(ForPaymentTelephone);
}
if (ForPaymentLaundry != false) {
output.WriteRawTag(64);
output.WriteBool(ForPaymentLaundry);
}
if (ForPaymentPenalty != false) {
output.WriteRawTag(72);
output.WriteBool(ForPaymentPenalty);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ForGuarantee != false) {
size += 1 + 1;
}
if (ForPaymentOther != false) {
size += 1 + 1;
}
if (ForPaymentLodging != false) {
size += 1 + 1;
}
if (ForPaymentRestaurant != false) {
size += 1 + 1;
}
if (ForPaymentGiftShop != false) {
size += 1 + 1;
}
if (ForPaymentMinibar != false) {
size += 1 + 1;
}
if (ForPaymentTelephone != false) {
size += 1 + 1;
}
if (ForPaymentLaundry != false) {
size += 1 + 1;
}
if (ForPaymentPenalty != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CardSalePurpose other) {
if (other == null) {
return;
}
if (other.ForGuarantee != false) {
ForGuarantee = other.ForGuarantee;
}
if (other.ForPaymentOther != false) {
ForPaymentOther = other.ForPaymentOther;
}
if (other.ForPaymentLodging != false) {
ForPaymentLodging = other.ForPaymentLodging;
}
if (other.ForPaymentRestaurant != false) {
ForPaymentRestaurant = other.ForPaymentRestaurant;
}
if (other.ForPaymentGiftShop != false) {
ForPaymentGiftShop = other.ForPaymentGiftShop;
}
if (other.ForPaymentMinibar != false) {
ForPaymentMinibar = other.ForPaymentMinibar;
}
if (other.ForPaymentTelephone != false) {
ForPaymentTelephone = other.ForPaymentTelephone;
}
if (other.ForPaymentLaundry != false) {
ForPaymentLaundry = other.ForPaymentLaundry;
}
if (other.ForPaymentPenalty != false) {
ForPaymentPenalty = other.ForPaymentPenalty;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
ForGuarantee = input.ReadBool();
break;
}
case 16: {
ForPaymentOther = input.ReadBool();
break;
}
case 24: {
ForPaymentLodging = input.ReadBool();
break;
}
case 32: {
ForPaymentRestaurant = input.ReadBool();
break;
}
case 40: {
ForPaymentGiftShop = input.ReadBool();
break;
}
case 48: {
ForPaymentMinibar = input.ReadBool();
break;
}
case 56: {
ForPaymentTelephone = input.ReadBool();
break;
}
case 64: {
ForPaymentLaundry = input.ReadBool();
break;
}
case 72: {
ForPaymentPenalty = input.ReadBool();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.CodeGeneration;
using Orleans.Core;
using Orleans.Hosting;
using Orleans.LogConsistency;
using Orleans.Providers;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Counters;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.LogConsistency;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.MultiClusterNetwork;
using Orleans.Runtime.Providers;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Startup;
using Orleans.Runtime.Storage;
using Orleans.Services;
using Orleans.Storage;
using Orleans.Streams;
using Orleans.Transactions;
using Orleans.Runtime.Versions;
using Orleans.Versions;
using Microsoft.Extensions.Options;
using Orleans.ApplicationParts;
using Orleans.Configuration;
namespace Orleans.Runtime
{
/// <summary>
/// Orleans silo.
/// </summary>
public class Silo
{
/// <summary> Standard name for Primary silo. </summary>
public const string PrimarySiloName = "Primary";
/// <summary> Silo Types. </summary>
public enum SiloType
{
/// <summary> No silo type specified. </summary>
None = 0,
/// <summary> Primary silo. </summary>
Primary,
/// <summary> Secondary silo. </summary>
Secondary,
}
private readonly SiloInitializationParameters initializationParams;
private readonly ISiloMessageCenter messageCenter;
private readonly OrleansTaskScheduler scheduler;
private readonly LocalGrainDirectory localGrainDirectory;
private readonly ActivationDirectory activationDirectory;
private readonly IncomingMessageAgent incomingAgent;
private readonly IncomingMessageAgent incomingSystemAgent;
private readonly IncomingMessageAgent incomingPingAgent;
private readonly Logger logger;
private readonly GrainTypeManager grainTypeManager;
private TypeManager typeManager;
private readonly TaskCompletionSource<int> siloTerminatedTask =
new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly SiloStatisticsManager siloStatistics;
private readonly InsideRuntimeClient runtimeClient;
private StorageProviderManager storageProviderManager;
private LogConsistencyProviderManager logConsistencyProviderManager;
private StatisticsProviderManager statisticsProviderManager;
private BootstrapProviderManager bootstrapProviderManager;
private IReminderService reminderService;
private ProviderManagerSystemTarget providerManagerSystemTarget;
private readonly IMembershipOracle membershipOracle;
private readonly IMultiClusterOracle multiClusterOracle;
private Watchdog platformWatchdog;
private readonly TimeSpan initTimeout;
private readonly TimeSpan stopTimeout = TimeSpan.FromMinutes(1);
private readonly Catalog catalog;
private readonly List<IHealthCheckParticipant> healthCheckParticipants = new List<IHealthCheckParticipant>();
private readonly object lockable = new object();
private readonly GrainFactory grainFactory;
private readonly IGrainRuntime grainRuntime;
private readonly ILoggerFactory loggerFactory;
/// <summary>
/// Gets the type of this
/// </summary>
public SiloType Type => this.initializationParams.Type;
internal string Name => this.initializationParams.Name;
internal ClusterConfiguration OrleansConfig => this.initializationParams.ClusterConfig;
internal GlobalConfiguration GlobalConfig => this.initializationParams.ClusterConfig.Globals;
internal NodeConfiguration LocalConfig => this.initializationParams.NodeConfig;
internal OrleansTaskScheduler LocalScheduler { get { return scheduler; } }
internal GrainTypeManager LocalGrainTypeManager { get { return grainTypeManager; } }
internal ILocalGrainDirectory LocalGrainDirectory { get { return localGrainDirectory; } }
internal IMultiClusterOracle LocalMultiClusterOracle { get { return multiClusterOracle; } }
internal IConsistentRingProvider RingProvider { get; private set; }
internal ILogConsistencyProviderManager LogConsistencyProviderManager { get { return logConsistencyProviderManager; } }
internal IStorageProviderManager StorageProviderManager { get { return storageProviderManager; } }
internal IProviderManager StatisticsProviderManager { get { return statisticsProviderManager; } }
internal IStreamProviderManager StreamProviderManager { get; private set; }
internal IList<IBootstrapProvider> BootstrapProviders { get; private set; }
internal ISiloPerformanceMetrics Metrics { get { return siloStatistics.MetricsTable; } }
internal ICatalog Catalog => catalog;
internal SystemStatus SystemStatus { get; set; }
internal IServiceProvider Services { get; }
/// <summary> SiloAddress for this silo. </summary>
public SiloAddress SiloAddress => this.initializationParams.SiloAddress;
/// <summary>
/// Silo termination event used to signal shutdown of this silo.
/// </summary>
public WaitHandle SiloTerminatedEvent // one event for all types of termination (shutdown, stop and fast kill).
=> ((IAsyncResult)this.siloTerminatedTask.Task).AsyncWaitHandle;
public Task SiloTerminated { get { return this.siloTerminatedTask.Task; } } // one event for all types of termination (shutdown, stop and fast kill).
private SchedulingContext membershipOracleContext;
private SchedulingContext multiClusterOracleContext;
private SchedulingContext reminderServiceContext;
/// <summary>
/// Initializes a new instance of the <see cref="Silo"/> class.
/// </summary>
/// <param name="name">Name of this silo.</param>
/// <param name="siloType">Type of this silo.</param>
/// <param name="config">Silo config data to be used for this silo.</param>
public Silo(string name, SiloType siloType, ClusterConfiguration config)
: this(new SiloInitializationParameters(name, siloType, config), null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Silo"/> class.
/// </summary>
/// <param name="initializationParams">The silo initialization parameters.</param>
/// <param name="services">Dependency Injection container</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "Should not Dispose of messageCenter in this method because it continues to run / exist after this point.")]
internal Silo(SiloInitializationParameters initializationParams, IServiceProvider services)
{
string name = initializationParams.Name;
ClusterConfiguration config = initializationParams.ClusterConfig;
this.initializationParams = initializationParams;
this.SystemStatus = SystemStatus.Creating;
AsynchAgent.IsStarting = true;
var startTime = DateTime.UtcNow;
services?.GetService<TelemetryManager>()?.AddFromConfiguration(services, LocalConfig.TelemetryConfiguration);
StatisticsCollector.Initialize(LocalConfig);
initTimeout = GlobalConfig.MaxJoinAttemptTime;
if (Debugger.IsAttached)
{
initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), GlobalConfig.MaxJoinAttemptTime);
stopTimeout = initTimeout;
}
var localEndpoint = this.initializationParams.SiloAddress.Endpoint;
// Configure DI using Startup type
if (services == null)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<Silo>(this);
serviceCollection.AddSingleton(initializationParams);
serviceCollection.AddLegacyClusterConfigurationSupport(config);
serviceCollection.Configure<SiloIdentityOptions>(options => options.SiloName = name);
var hostContext = new HostBuilderContext(new Dictionary<object, object>());
DefaultSiloServices.AddDefaultServices(hostContext, serviceCollection);
var applicationPartManager = hostContext.GetApplicationPartManager();
applicationPartManager.AddApplicationPartsFromAppDomain();
applicationPartManager.AddApplicationPartsFromBasePath();
services = StartupBuilder.ConfigureStartup(this.LocalConfig.StartupTypeName, serviceCollection);
services.GetService<TelemetryManager>()?.AddFromConfiguration(services, LocalConfig.TelemetryConfiguration);
}
this.Services = services;
//set PropagateActivityId flag from node cofnig
RequestContext.PropagateActivityId = this.initializationParams.NodeConfig.PropagateActivityId;
this.loggerFactory = this.Services.GetRequiredService<ILoggerFactory>();
logger = new LoggerWrapper<Silo>(this.loggerFactory);
logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode));
if (!GCSettings.IsServerGC)
{
logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\">");
logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines).");
}
logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing {0} silo on host {1} MachineName {2} at {3}, gen {4} --------------",
this.initializationParams.Type, LocalConfig.DNSHostName, Environment.MachineName, localEndpoint, this.initializationParams.SiloAddress.Generation);
logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0} with the following configuration= " + Environment.NewLine + "{1}",
name, config.ToString(name));
var siloMessagingOptions = this.Services.GetRequiredService<IOptions<SiloMessagingOptions>>();
BufferPool.InitGlobalBufferPool(siloMessagingOptions);
//init logger for UnobservedExceptionsHandlerClass
UnobservedExceptionsHandlerClass.InitLogger(this.loggerFactory);
if (!UnobservedExceptionsHandlerClass.TrySetUnobservedExceptionHandler(UnobservedExceptionHandler))
{
logger.Warn(ErrorCode.Runtime_Error_100153, "Unable to set unobserved exception handler because it was already set.");
}
AppDomain.CurrentDomain.UnhandledException += this.DomainUnobservedExceptionHandler;
try
{
grainFactory = Services.GetRequiredService<GrainFactory>();
}
catch (InvalidOperationException exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc);
throw;
}
grainTypeManager = Services.GetRequiredService<GrainTypeManager>();
// Performance metrics
siloStatistics = Services.GetRequiredService<SiloStatisticsManager>();
// The scheduler
scheduler = Services.GetRequiredService<OrleansTaskScheduler>();
healthCheckParticipants.Add(scheduler);
runtimeClient = Services.GetRequiredService<InsideRuntimeClient>();
// Initialize the message center
messageCenter = Services.GetRequiredService<MessageCenter>();
var dispatcher = this.Services.GetRequiredService<Dispatcher>();
messageCenter.RerouteHandler = dispatcher.RerouteMessage;
messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage;
// GrainRuntime can be created only here, after messageCenter was created.
grainRuntime = Services.GetRequiredService<IGrainRuntime>();
StreamProviderManager = Services.GetRequiredService<IStreamProviderManager>();
// Now the router/directory service
// This has to come after the message center //; note that it then gets injected back into the message center.;
localGrainDirectory = Services.GetRequiredService<LocalGrainDirectory>();
// Now the activation directory.
activationDirectory = Services.GetRequiredService<ActivationDirectory>();
// Now the consistent ring provider
RingProvider = Services.GetRequiredService<IConsistentRingProvider>();
catalog = Services.GetRequiredService<Catalog>();
siloStatistics.MetricsTable.Scheduler = scheduler;
siloStatistics.MetricsTable.ActivationDirectory = activationDirectory;
siloStatistics.MetricsTable.ActivationCollector = catalog.ActivationCollector;
siloStatistics.MetricsTable.MessageCenter = messageCenter;
// Now the incoming message agents
var messageFactory = this.Services.GetRequiredService<MessageFactory>();
incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, this.loggerFactory);
incomingPingAgent = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, this.loggerFactory);
incomingAgent = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, this.loggerFactory);
membershipOracle = Services.GetRequiredService<IMembershipOracle>();
if (!this.GlobalConfig.HasMultiClusterNetwork)
{
logger.Info("Skip multicluster oracle creation (no multicluster network configured)");
}
else
{
multiClusterOracle = Services.GetRequiredService<IMultiClusterOracle>();
}
this.SystemStatus = SystemStatus.Created;
AsynchAgent.IsStarting = false;
StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME,
() => LogFormatter.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs.
logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
}
private void CreateSystemTargets()
{
logger.Verbose("Creating System Targets for this silo.");
logger.Verbose("Creating {0} System Target", "SiloControl");
var siloControl = ActivatorUtilities.CreateInstance<SiloControl>(Services);
RegisterSystemTarget(siloControl);
logger.Verbose("Creating {0} System Target", "StreamProviderUpdateAgent");
RegisterSystemTarget(new StreamProviderManagerAgent(this, Services.GetRequiredService<IStreamProviderRuntime>(), this.loggerFactory));
logger.Verbose("Creating {0} System Target", "ProtocolGateway");
RegisterSystemTarget(new ProtocolGateway(this.SiloAddress, this.loggerFactory));
logger.Verbose("Creating {0} System Target", "DeploymentLoadPublisher");
RegisterSystemTarget(Services.GetRequiredService<DeploymentLoadPublisher>());
logger.Verbose("Creating {0} System Target", "RemoteGrainDirectory + CacheValidator");
RegisterSystemTarget(LocalGrainDirectory.RemoteGrainDirectory);
RegisterSystemTarget(LocalGrainDirectory.CacheValidator);
logger.Verbose("Creating {0} System Target", "RemoteClusterGrainDirectory");
RegisterSystemTarget(LocalGrainDirectory.RemoteClusterGrainDirectory);
logger.Verbose("Creating {0} System Target", "ClientObserverRegistrar + TypeManager");
this.RegisterSystemTarget(this.Services.GetRequiredService<ClientObserverRegistrar>());
var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>();
var versionDirectorManager = this.Services.GetRequiredService<CachedVersionSelectorManager>();
typeManager = new TypeManager(SiloAddress, this.grainTypeManager, membershipOracle, LocalScheduler, GlobalConfig.TypeMapRefreshInterval, implicitStreamSubscriberTable, this.grainFactory, versionDirectorManager,
this.loggerFactory);
this.RegisterSystemTarget(typeManager);
logger.Verbose("Creating {0} System Target", "MembershipOracle");
if (this.membershipOracle is SystemTarget)
{
RegisterSystemTarget((SystemTarget)membershipOracle);
}
if (multiClusterOracle != null && multiClusterOracle is SystemTarget)
{
logger.Verbose("Creating {0} System Target", "MultiClusterOracle");
RegisterSystemTarget((SystemTarget)multiClusterOracle);
}
var transactionAgent = this.Services.GetRequiredService<ITransactionAgent>() as SystemTarget;
if (transactionAgent != null)
{
logger.Verbose("Creating {0} System Target", "TransactionAgent");
RegisterSystemTarget(transactionAgent);
}
logger.Verbose("Finished creating System Targets for this silo.");
}
private void InjectDependencies()
{
healthCheckParticipants.Add(membershipOracle);
catalog.SiloStatusOracle = this.membershipOracle;
this.membershipOracle.SubscribeToSiloStatusEvents(localGrainDirectory);
messageCenter.SiloDeadOracle = this.membershipOracle.IsDeadSilo;
// consistentRingProvider is not a system target per say, but it behaves like the localGrainDirectory, so it is here
this.membershipOracle.SubscribeToSiloStatusEvents((ISiloStatusListener)RingProvider);
this.membershipOracle.SubscribeToSiloStatusEvents(typeManager);
this.membershipOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<DeploymentLoadPublisher>());
this.membershipOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<ClientObserverRegistrar>());
if (!GlobalConfig.ReminderServiceType.Equals(GlobalConfiguration.ReminderServiceProviderType.Disabled))
{
// start the reminder service system target
reminderService = Services.GetRequiredService<LocalReminderServiceFactory>()
.CreateReminderService(this, initTimeout, this.runtimeClient);
var reminderServiceSystemTarget = this.reminderService as SystemTarget;
if (reminderServiceSystemTarget != null) RegisterSystemTarget(reminderServiceSystemTarget);
}
RegisterSystemTarget(catalog);
scheduler.QueueAction(catalog.Start, catalog.SchedulingContext)
.WaitWithThrow(initTimeout);
// SystemTarget for provider init calls
providerManagerSystemTarget = Services.GetRequiredService<ProviderManagerSystemTarget>();
RegisterSystemTarget(providerManagerSystemTarget);
}
/// <summary> Perform silo startup operations. </summary>
public void Start()
{
try
{
DoStart();
}
catch (Exception exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start", exc);
throw;
}
}
private void DoStart()
{
lock (lockable)
{
if (!this.SystemStatus.Equals(SystemStatus.Created))
throw new InvalidOperationException(String.Format("Calling Silo.Start() on a silo which is not in the Created state. This silo is in the {0} state.", this.SystemStatus));
this.SystemStatus = SystemStatus.Starting;
}
logger.Info(ErrorCode.SiloStarting, "Silo Start()");
// Hook up to receive notification of process exit / Ctrl-C events
AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
if (GlobalConfig.FastKillOnCancelKeyPress)
Console.CancelKeyPress += HandleProcessExit;
ConfigureThreadPoolAndServicePointSettings();
// This has to start first so that the directory system target factory gets loaded before we start the router.
grainTypeManager.Start();
runtimeClient.Start();
// The order of these 4 is pretty much arbitrary.
scheduler.Start();
messageCenter.Start();
incomingPingAgent.Start();
incomingSystemAgent.Start();
incomingAgent.Start();
LocalGrainDirectory.Start();
// Set up an execution context for this thread so that the target creation steps can use asynch values.
RuntimeContext.InitializeMainThread();
// Initialize the implicit stream subscribers table.
var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>();
implicitStreamSubscriberTable.InitImplicitStreamSubscribers(this.grainTypeManager.GrainClassTypeData.Select(t => t.Value.Type).ToArray());
var siloProviderRuntime = Services.GetRequiredService<SiloProviderRuntime>();
runtimeClient.CurrentStreamProviderRuntime = siloProviderRuntime;
statisticsProviderManager = this.Services.GetRequiredService<StatisticsProviderManager>();
string statsProviderName = statisticsProviderManager.LoadProvider(GlobalConfig.ProviderConfigurations)
.WaitForResultWithThrow(initTimeout);
if (statsProviderName != null)
LocalConfig.StatisticsProviderName = statsProviderName;
// can call SetSiloMetricsTableDataManager only after MessageCenter is created (dependency on this.SiloAddress).
siloStatistics.SetSiloStatsTableDataManager(this, LocalConfig).WaitWithThrow(initTimeout);
siloStatistics.SetSiloMetricsTableDataManager(this, LocalConfig).WaitWithThrow(initTimeout);
// This has to follow the above steps that start the runtime components
CreateSystemTargets();
InjectDependencies();
// Validate the configuration.
GlobalConfig.Application.ValidateConfiguration(logger);
// Initialize storage providers once we have a basic silo runtime environment operating
storageProviderManager = this.Services.GetRequiredService<StorageProviderManager>();
scheduler.QueueTask(
() => storageProviderManager.LoadStorageProviders(GlobalConfig.ProviderConfigurations),
providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
ITransactionAgent transactionAgent = this.Services.GetRequiredService<ITransactionAgent>();
ISchedulingContext transactionAgentContext = (transactionAgent as SystemTarget)?.SchedulingContext;
scheduler.QueueTask(transactionAgent.Start, transactionAgentContext)
.WaitWithThrow(initTimeout);
var versionStore = Services.GetService<IVersionStore>() as GrainVersionStore;
versionStore?.SetStorageManager(storageProviderManager);
if (logger.IsVerbose) { logger.Verbose("Storage provider manager created successfully."); }
// Initialize log consistency providers once we have a basic silo runtime environment operating
logConsistencyProviderManager = this.Services.GetRequiredService<LogConsistencyProviderManager>();
scheduler.QueueTask(
() => logConsistencyProviderManager.LoadLogConsistencyProviders(GlobalConfig.ProviderConfigurations),
providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("Log consistency provider manager created successfully."); }
// Load and init stream providers before silo becomes active
var siloStreamProviderManager = (StreamProviderManager) this.Services.GetRequiredService<IStreamProviderManager>();
scheduler.QueueTask(
() => siloStreamProviderManager.LoadStreamProviders(GlobalConfig.ProviderConfigurations, siloProviderRuntime),
providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
runtimeClient.CurrentStreamProviderManager = siloStreamProviderManager;
if (logger.IsVerbose) { logger.Verbose("Stream provider manager created successfully."); }
// Load and init grain services before silo becomes active.
CreateGrainServices(GlobalConfig.GrainServiceConfigurations);
this.membershipOracleContext = (this.membershipOracle as SystemTarget)?.SchedulingContext ??
this.providerManagerSystemTarget.SchedulingContext;
scheduler.QueueTask(() => this.membershipOracle.Start(), this.membershipOracleContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("Local silo status oracle created successfully."); }
scheduler.QueueTask(this.membershipOracle.BecomeActive, this.membershipOracleContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("Local silo status oracle became active successfully."); }
scheduler.QueueTask(() => this.typeManager.Initialize(versionStore), this.typeManager.SchedulingContext)
.WaitWithThrow(this.initTimeout);
//if running in multi cluster scenario, start the MultiClusterNetwork Oracle
if (GlobalConfig.HasMultiClusterNetwork)
{
logger.Info("Starting multicluster oracle with my ServiceId={0} and ClusterId={1}.",
GlobalConfig.ServiceId, GlobalConfig.ClusterId);
this.multiClusterOracleContext = (multiClusterOracle as SystemTarget)?.SchedulingContext ??
this.providerManagerSystemTarget.SchedulingContext;
scheduler.QueueTask(() => multiClusterOracle.Start(), multiClusterOracleContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("multicluster oracle created successfully."); }
}
try
{
this.siloStatistics.Start(this.LocalConfig);
if (this.logger.IsVerbose) { this.logger.Verbose("Silo statistics manager started successfully."); }
// Finally, initialize the deployment load collector, for grains with load-based placement
var deploymentLoadPublisher = Services.GetRequiredService<DeploymentLoadPublisher>();
this.scheduler.QueueTask(deploymentLoadPublisher.Start, deploymentLoadPublisher.SchedulingContext)
.WaitWithThrow(this.initTimeout);
if (this.logger.IsVerbose) { this.logger.Verbose("Silo deployment load publisher started successfully."); }
// Start background timer tick to watch for platform execution stalls, such as when GC kicks in
this.platformWatchdog = new Watchdog(this.LocalConfig.StatisticsLogWriteInterval, this.healthCheckParticipants, this.loggerFactory);
this.platformWatchdog.Start();
if (this.logger.IsVerbose) { this.logger.Verbose("Silo platform watchdog started successfully."); }
if (this.reminderService != null)
{
// so, we have the view of the membership in the consistentRingProvider. We can start the reminder service
this.reminderServiceContext = (this.reminderService as SystemTarget)?.SchedulingContext ??
this.providerManagerSystemTarget.SchedulingContext;
this.scheduler.QueueTask(this.reminderService.Start, this.reminderServiceContext)
.WaitWithThrow(this.initTimeout);
if (this.logger.IsVerbose)
{
this.logger.Verbose("Reminder service started successfully.");
}
}
this.bootstrapProviderManager = this.Services.GetRequiredService<BootstrapProviderManager>();
this.scheduler.QueueTask(
() => this.bootstrapProviderManager.LoadAppBootstrapProviders(siloProviderRuntime, this.GlobalConfig.ProviderConfigurations),
this.providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(this.initTimeout);
this.BootstrapProviders = this.bootstrapProviderManager.GetProviders(); // Data hook for testing & diagnotics
if (this.logger.IsVerbose) { this.logger.Verbose("App bootstrap calls done successfully."); }
// Start stream providers after silo is active (so the pulling agents don't start sending messages before silo is active).
// also after bootstrap provider started so bootstrap provider can initialize everything stream before events from this silo arrive.
this.scheduler.QueueTask(siloStreamProviderManager.StartStreamProviders, this.providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(this.initTimeout);
if (this.logger.IsVerbose) { this.logger.Verbose("Stream providers started successfully."); }
// Now that we're active, we can start the gateway
var mc = this.messageCenter as MessageCenter;
mc?.StartGateway(this.Services.GetRequiredService<ClientObserverRegistrar>());
if (this.logger.IsVerbose) { this.logger.Verbose("Message gateway service started successfully."); }
this.SystemStatus = SystemStatus.Running;
}
catch (Exception exc)
{
this.SafeExecute(() => this.logger.Error(ErrorCode.Runtime_Error_100330, String.Format("Error starting silo {0}. Going to FastKill().", this.SiloAddress), exc));
this.FastKill(); // if failed after Membership became active, mark itself as dead in Membership abale.
throw;
}
if (logger.IsVerbose) { logger.Verbose("Silo.Start complete: System status = {0}", this.SystemStatus); }
}
private void CreateGrainServices(GrainServiceConfigurations grainServiceConfigurations)
{
foreach (var serviceConfig in grainServiceConfigurations.GrainServices)
{
// Construct the Grain Service
var serviceType = System.Type.GetType(serviceConfig.Value.ServiceType);
if (serviceType == null)
{
throw new Exception(String.Format("Cannot find Grain Service type {0} of Grain Service {1}", serviceConfig.Value.ServiceType, serviceConfig.Value.Name));
}
var grainServiceInterfaceType = serviceType.GetInterfaces().FirstOrDefault(x => x.GetInterfaces().Contains(typeof(IGrainService)));
if (grainServiceInterfaceType == null)
{
throw new Exception(String.Format("Cannot find an interface on {0} which implements IGrainService", serviceConfig.Value.ServiceType));
}
var typeCode = GrainInterfaceUtils.GetGrainClassTypeCode(grainServiceInterfaceType);
var grainId = (IGrainIdentity)GrainId.GetGrainServiceGrainId(0, typeCode);
var grainService = (GrainService)ActivatorUtilities.CreateInstance(this.Services, serviceType, grainId, serviceConfig.Value);
RegisterSystemTarget(grainService);
this.scheduler.QueueTask(() => grainService.Init(Services), grainService.SchedulingContext).WaitWithThrow(this.initTimeout);
this.scheduler.QueueTask(grainService.Start, grainService.SchedulingContext).WaitWithThrow(this.initTimeout);
if (this.logger.IsVerbose)
{
this.logger.Verbose(String.Format("{0} Grain Service started successfully.", serviceConfig.Value.Name));
}
}
}
private void ConfigureThreadPoolAndServicePointSettings()
{
if (LocalConfig.MinDotNetThreadPoolSize > 0)
{
int workerThreads;
int completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
if (LocalConfig.MinDotNetThreadPoolSize > workerThreads ||
LocalConfig.MinDotNetThreadPoolSize > completionPortThreads)
{
// if at least one of the new values is larger, set the new min values to be the larger of the prev. and new config value.
int newWorkerThreads = Math.Max(LocalConfig.MinDotNetThreadPoolSize, workerThreads);
int newCompletionPortThreads = Math.Max(LocalConfig.MinDotNetThreadPoolSize, completionPortThreads);
bool ok = ThreadPool.SetMinThreads(newWorkerThreads, newCompletionPortThreads);
if (ok)
{
logger.Info(ErrorCode.SiloConfiguredThreadPool,
"Configured ThreadPool.SetMinThreads() to values: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
else
{
logger.Warn(ErrorCode.SiloFailedToConfigureThreadPool,
"Failed to configure ThreadPool.SetMinThreads(). Tried to set values to: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
}
}
// Set .NET ServicePointManager settings to optimize throughput performance when using Azure storage
// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx
logger.Info(ErrorCode.SiloConfiguredServicePointManager,
"Configured .NET ServicePointManager to Expect100Continue={0}, DefaultConnectionLimit={1}, UseNagleAlgorithm={2} to improve Azure storage performance.",
LocalConfig.Expect100Continue, LocalConfig.DefaultConnectionLimit, LocalConfig.UseNagleAlgorithm);
ServicePointManager.Expect100Continue = LocalConfig.Expect100Continue;
ServicePointManager.DefaultConnectionLimit = LocalConfig.DefaultConnectionLimit;
ServicePointManager.UseNagleAlgorithm = LocalConfig.UseNagleAlgorithm;
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// Grains are not deactivated.
/// </summary>
public void Stop()
{
Terminate(false);
}
/// <summary>
/// Gracefully stop the run time system and the application.
/// All grains will be properly deactivated.
/// All in-flight applications requests would be awaited and finished gracefully.
/// </summary>
public void Shutdown()
{
Terminate(true);
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// </summary>
private void Terminate(bool gracefully)
{
string operation = gracefully ? "Shutdown()" : "Stop()";
bool stopAlreadyInProgress = false;
lock (lockable)
{
if (this.SystemStatus.Equals(SystemStatus.Stopping) ||
this.SystemStatus.Equals(SystemStatus.ShuttingDown) ||
this.SystemStatus.Equals(SystemStatus.Terminated))
{
stopAlreadyInProgress = true;
// Drop through to wait below
}
else if (!this.SystemStatus.Equals(SystemStatus.Running))
{
throw new InvalidOperationException(String.Format("Calling Silo.{0} on a silo which is not in the Running state. This silo is in the {1} state.", operation, this.SystemStatus));
}
else
{
if (gracefully)
this.SystemStatus = SystemStatus.ShuttingDown;
else
this.SystemStatus = SystemStatus.Stopping;
}
}
if (stopAlreadyInProgress)
{
logger.Info(ErrorCode.SiloStopInProgress, "Silo termination is in progress - Will wait for it to finish");
var pause = TimeSpan.FromSeconds(1);
while (!this.SystemStatus.Equals(SystemStatus.Terminated))
{
logger.Info(ErrorCode.WaitingForSiloStop, "Waiting {0} for termination to complete", pause);
Thread.Sleep(pause);
}
return;
}
try
{
try
{
if (gracefully)
{
logger.Info(ErrorCode.SiloShuttingDown, "Silo starting to Shutdown()");
// 1: Write "ShutDown" state in the table + broadcast gossip msgs to re-read the table to everyone
scheduler.QueueTask(this.membershipOracle.ShutDown, this.membershipOracleContext)
.WaitWithThrow(stopTimeout);
}
else
{
logger.Info(ErrorCode.SiloStopping, "Silo starting to Stop()");
// 1: Write "Stopping" state in the table + broadcast gossip msgs to re-read the table to everyone
scheduler.QueueTask(this.membershipOracle.Stop, this.membershipOracleContext)
.WaitWithThrow(stopTimeout);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.SiloFailedToStopMembership, String.Format("Failed to {0} membership oracle. About to FastKill this silo.", operation), exc);
return; // will go to finally
}
if (reminderService != null)
{
// 2: Stop reminder service
scheduler.QueueTask(reminderService.Stop, this.reminderServiceContext)
.WaitWithThrow(stopTimeout);
}
if (gracefully)
{
// 3: Deactivate all grains
SafeExecute(() => catalog.DeactivateAllActivations().WaitWithThrow(stopTimeout));
}
// 3: Stop the gateway
SafeExecute(messageCenter.StopAcceptingClientMessages);
// 4: Start rejecting all silo to silo application messages
SafeExecute(messageCenter.BlockApplicationMessages);
// 5: Stop scheduling/executing application turns
SafeExecute(scheduler.StopApplicationTurns);
// 6: Directory: Speed up directory handoff
// will be started automatically when directory receives SiloStatusChangeNotification(Stopping)
// 7:
SafeExecute(() => LocalGrainDirectory.StopPreparationCompletion.WaitWithThrow(stopTimeout));
// The order of closing providers might be importan: Stats, streams, boostrap, storage.
// Stats first since no one depends on it.
// Storage should definitely be last since other providers ma ybe using it, potentilay indirectly.
// Streams and Bootstrap - the order is less clear. Seems like Bootstrap may indirecly depend on Streams, but not the other way around.
// 8:
SafeExecute(() =>
{
scheduler.QueueTask(() => statisticsProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
});
// 9:
SafeExecute(() =>
{
var siloStreamProviderManager = (StreamProviderManager) StreamProviderManager;
scheduler.QueueTask(() => siloStreamProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
});
// 10:
SafeExecute(() =>
{
scheduler.QueueTask(() => bootstrapProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
});
// 11:
SafeExecute(() =>
{
scheduler.QueueTask(() => storageProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
});
}
finally
{
// 10, 11, 12: Write Dead in the table, Drain scheduler, Stop msg center, ...
logger.Info(ErrorCode.SiloStopped, "Silo is Stopped()");
FastKill();
}
}
/// <summary>
/// Ungracefully stop the run time system and the application running on it.
/// Applications requests would be abruptly terminated, and the internal system state quickly stopped with minimal cleanup.
/// </summary>
private void FastKill()
{
if (!GlobalConfig.LivenessType.Equals(GlobalConfiguration.LivenessProviderType.MembershipTableGrain))
{
// do not execute KillMyself if using MembershipTableGrain, since it will fail, as we've already stopped app scheduler turns.
SafeExecute(() => scheduler.QueueTask( this.membershipOracle.KillMyself, this.membershipOracleContext)
.WaitWithThrow(stopTimeout));
}
// incoming messages
SafeExecute(incomingSystemAgent.Stop);
SafeExecute(incomingPingAgent.Stop);
SafeExecute(incomingAgent.Stop);
// timers
SafeExecute(runtimeClient.Stop);
if (platformWatchdog != null)
SafeExecute(platformWatchdog.Stop); // Silo may be dying before platformWatchdog was set up
SafeExecute(scheduler.Stop);
SafeExecute(scheduler.PrintStatistics);
SafeExecute(activationDirectory.PrintActivationDirectory);
SafeExecute(messageCenter.Stop);
SafeExecute(siloStatistics.Stop);
UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler();
SafeExecute(() => this.SystemStatus = SystemStatus.Terminated);
SafeExecute(() => AppDomain.CurrentDomain.UnhandledException -= this.DomainUnobservedExceptionHandler);
SafeExecute(() => (this.Services as IDisposable)?.Dispose());
// Setting the event should be the last thing we do.
// Do nothing after that!
this.siloTerminatedTask.SetResult(0);
}
private void SafeExecute(Action action)
{
Utils.SafeExecute(action, logger, "Silo.Stop");
}
private void HandleProcessExit(object sender, EventArgs e)
{
// NOTE: We need to minimize the amount of processing occurring on this code path -- we only have under approx 2-3 seconds before process exit will occur
logger.Warn(ErrorCode.Runtime_Error_100220, "Process is exiting");
lock (lockable)
{
if (!this.SystemStatus.Equals(SystemStatus.Running)) return;
this.SystemStatus = SystemStatus.Stopping;
}
logger.Info(ErrorCode.SiloStopping, "Silo.HandleProcessExit() - starting to FastKill()");
FastKill();
}
private void UnobservedExceptionHandler(ISchedulingContext context, Exception exception)
{
var schedulingContext = context as SchedulingContext;
if (schedulingContext == null)
{
if (context == null)
logger.Error(ErrorCode.Runtime_Error_100102, "Silo caught an UnobservedException with context==null.", exception);
else
logger.Error(ErrorCode.Runtime_Error_100103, String.Format("Silo caught an UnobservedException with context of type different than OrleansContext. The type of the context is {0}. The context is {1}",
context.GetType(), context), exception);
}
else
{
logger.Error(ErrorCode.Runtime_Error_100104, String.Format("Silo caught an UnobservedException thrown by {0}.", schedulingContext.Activation), exception);
}
}
private void DomainUnobservedExceptionHandler(object context, UnhandledExceptionEventArgs args)
{
var exception = (Exception)args.ExceptionObject;
if (context is ISchedulingContext)
UnobservedExceptionHandler(context as ISchedulingContext, exception);
else
logger.Error(ErrorCode.Runtime_Error_100324, String.Format("Called DomainUnobservedExceptionHandler with context {0}.", context), exception);
}
internal void RegisterSystemTarget(SystemTarget target)
{
var providerRuntime = this.Services.GetRequiredService<SiloProviderRuntime>();
providerRuntime.RegisterSystemTarget(target);
}
/// <summary> Return dump of diagnostic data from this silo. </summary>
/// <param name="all"></param>
/// <returns>Debug data for this silo.</returns>
public string GetDebugDump(bool all = true)
{
var sb = new StringBuilder();
foreach (var systemTarget in activationDirectory.AllSystemTargets())
sb.AppendFormat("System target {0}:", ((ISystemTargetBase)systemTarget).GrainId.ToString()).AppendLine();
var enumerator = activationDirectory.GetEnumerator();
while(enumerator.MoveNext())
{
Utils.SafeExecute(() =>
{
var activationData = enumerator.Current.Value;
var workItemGroup = scheduler.GetWorkItemGroup(activationData.SchedulingContext);
if (workItemGroup == null)
{
sb.AppendFormat("Activation with no work item group!! Grain {0}, activation {1}.",
activationData.Grain,
activationData.ActivationId);
sb.AppendLine();
return;
}
if (all || activationData.State.Equals(ActivationState.Valid))
{
sb.AppendLine(workItemGroup.DumpStatus());
sb.AppendLine(activationData.DumpStatus());
}
});
}
logger.Info(ErrorCode.SiloDebugDump, sb.ToString());
return sb.ToString();
}
/// <summary> Object.ToString override -- summary info for this silo. </summary>
public override string ToString()
{
return localGrainDirectory.ToString();
}
}
// A dummy system target to use for scheduling context for provider Init calls, to allow them to make grain calls
internal class ProviderManagerSystemTarget : SystemTarget
{
public ProviderManagerSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory)
: base(Constants.ProviderManagerSystemTargetId, localSiloDetails.SiloAddress, loggerFactory)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// The Task-based APIs are currently wrappers over either the APM APIs (e.g. BeginConnect)
// or the SocketAsyncEventArgs APIs (e.g. ReceiveAsync(SocketAsyncEventArgs)). The latter
// are much more efficient when the SocketAsyncEventArg instances can be reused; as such,
// at present we use them for ReceiveAsync and SendAsync, caching an instance for each.
// In the future we could potentially maintain a global cache of instances used for accepts
// and connects, and potentially separate per-socket instances for Receive{Message}FromAsync,
// which would need different instances from ReceiveAsync due to having different results
// and thus different Completed logic. We also currently fall back to APM implementations
// when the single cached instance for each of send/receive is otherwise in use; we could
// potentially also employ a global pool from which to pull in such situations.
public partial class Socket
{
/// <summary>Handler for completed AcceptAsync operations.</summary>
private static readonly EventHandler<SocketAsyncEventArgs> AcceptCompletedHandler = (s, e) => CompleteAccept((Socket)s, (TaskSocketAsyncEventArgs<Socket>)e);
/// <summary>Handler for completed ReceiveAsync operations.</summary>
private static readonly EventHandler<SocketAsyncEventArgs> ReceiveCompletedHandler = (s, e) => CompleteSendReceive((Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive: true);
/// <summary>Handler for completed SendAsync operations.</summary>
private static readonly EventHandler<SocketAsyncEventArgs> SendCompletedHandler = (s, e) => CompleteSendReceive((Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive: false);
/// <summary>
/// Sentinel that can be stored into one of the Socket cached fields to indicate that an instance
/// was previously created but is currently being used by another concurrent operation.
/// </summary>
private static readonly TaskSocketAsyncEventArgs<Socket> s_rentedSocketSentinel = new TaskSocketAsyncEventArgs<Socket>();
/// <summary>
/// Sentinel that can be stored into one of the Int32 fields to indicate that an instance
/// was previously created but is currently being used by another concurrent operation.
/// </summary>
private static readonly Int32TaskSocketAsyncEventArgs s_rentedInt32Sentinel = new Int32TaskSocketAsyncEventArgs();
/// <summary>Cached task with a 0 value.</summary>
private static readonly Task<int> s_zeroTask = Task.FromResult(0);
/// <summary>Cached event args used with Task-based async operations.</summary>
private CachedTaskEventArgs _cachedTaskEventArgs;
internal Task<Socket> AcceptAsync(Socket acceptSocket)
{
// Get any cached SocketAsyncEventArg we may have.
TaskSocketAsyncEventArgs<Socket> saea = Interlocked.Exchange(ref LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs).Accept, s_rentedSocketSentinel);
if (saea == s_rentedSocketSentinel)
{
// An instance was once created (or is currently being created elsewhere), but some other
// concurrent operation is using it. Since we can store at most one, and since an individual
// APM operation is less expensive than creating a new SAEA and using it only once, we simply
// fall back to using an APM implementation.
return AcceptAsyncApm(acceptSocket);
}
else if (saea == null)
{
// No instance has been created yet, so create one.
saea = new TaskSocketAsyncEventArgs<Socket>();
saea.Completed += AcceptCompletedHandler;
}
// Configure the SAEA.
saea.AcceptSocket = acceptSocket;
// Initiate the accept operation.
Task<Socket> t;
if (AcceptAsync(saea))
{
// The operation is completing asynchronously (it may have already completed).
// Get the task for the operation, with appropriate synchronization to coordinate
// with the async callback that'll be completing the task.
bool responsibleForReturningToPool;
t = saea.GetCompletionResponsibility(out responsibleForReturningToPool).Task;
if (responsibleForReturningToPool)
{
// We're responsible for returning it only if the callback has already been invoked
// and gotten what it needs from the SAEA; otherwise, the callback will return it.
ReturnSocketAsyncEventArgs(saea);
}
}
else
{
// The operation completed synchronously. Get a task for it.
t = saea.SocketError == SocketError.Success ?
Task.FromResult(saea.AcceptSocket) :
Task.FromException<Socket>(GetException(saea.SocketError));
// There won't be a callback, and we're done with the SAEA, so return it to the pool.
ReturnSocketAsyncEventArgs(saea);
}
return t;
}
/// <summary>Implements Task-returning AcceptAsync on top of Begin/EndAsync.</summary>
private Task<Socket> AcceptAsyncApm(Socket acceptSocket)
{
var tcs = new TaskCompletionSource<Socket>(this);
BeginAccept(acceptSocket, 0, iar =>
{
var innerTcs = (TaskCompletionSource<Socket>)iar.AsyncState;
try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndAccept(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task ConnectAsync(EndPoint remoteEP)
{
var tcs = new TaskCompletionSource<bool>(this);
BeginConnect(remoteEP, iar =>
{
var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
try
{
((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
innerTcs.TrySetResult(true);
}
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task ConnectAsync(IPAddress address, int port)
{
var tcs = new TaskCompletionSource<bool>(this);
BeginConnect(address, port, iar =>
{
var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
try
{
((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
innerTcs.TrySetResult(true);
}
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task ConnectAsync(IPAddress[] addresses, int port)
{
var tcs = new TaskCompletionSource<bool>(this);
BeginConnect(addresses, port, iar =>
{
var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
try
{
((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
innerTcs.TrySetResult(true);
}
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task ConnectAsync(string host, int port)
{
var tcs = new TaskCompletionSource<bool>(this);
BeginConnect(host, port, iar =>
{
var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
try
{
((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
innerTcs.TrySetResult(true);
}
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task<int> ReceiveAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, bool fromNetworkStream)
{
// Validate the arguments.
ValidateBuffer(buffer);
Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: true);
if (saea != null)
{
// We got a cached instance. Configure the buffer and initate the operation.
ConfigureBuffer(saea, buffer, socketFlags, wrapExceptionsInIOExceptions: fromNetworkStream);
return GetTaskForSendReceive(ReceiveAsync(saea), saea, fromNetworkStream, isReceive: true);
}
else
{
// We couldn't get a cached instance, due to a concurrent receive operation on the socket.
// Fall back to wrapping APM.
return ReceiveAsyncApm(buffer, socketFlags);
}
}
internal ValueTask<int> ReceiveAsync(Memory<byte> buffer, SocketFlags socketFlags, bool fromNetworkStream, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
// TODO https://github.com/dotnet/corefx/issues/24430:
// Fully plumb cancellation down into socket operations.
Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: true);
if (saea != null)
{
// We got a cached instance. Configure the buffer and initate the operation.
ConfigureBuffer(saea, buffer, socketFlags, wrapExceptionsInIOExceptions: fromNetworkStream);
return GetValueTaskForSendReceive(ReceiveAsync(saea), saea, fromNetworkStream, isReceive: true);
}
else
{
// We couldn't get a cached instance, due to a concurrent receive operation on the socket.
// Fall back to wrapping APM.
return new ValueTask<int>(ReceiveAsyncApm(buffer, socketFlags));
}
}
/// <summary>Implements Task-returning ReceiveAsync on top of Begin/EndReceive.</summary>
private Task<int> ReceiveAsyncApm(Memory<byte> buffer, SocketFlags socketFlags)
{
if (buffer.TryGetArray(out ArraySegment<byte> bufferArray))
{
// We were able to extract the underlying byte[] from the Memory<byte>. Use it.
var tcs = new TaskCompletionSource<int>(this);
BeginReceive(bufferArray.Array, bufferArray.Offset, bufferArray.Count, socketFlags, iar =>
{
var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndReceive(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
else
{
// We weren't able to extract an underlying byte[] from the Memory<byte>.
// Instead read into an ArrayPool array, then copy from that into the memory.
byte[] poolArray = ArrayPool<byte>.Shared.Rent(buffer.Length);
var tcs = new TaskCompletionSource<int>(this);
BeginReceive(poolArray, 0, buffer.Length, socketFlags, iar =>
{
var state = (Tuple<TaskCompletionSource<int>, Memory<byte>, byte[]>)iar.AsyncState;
try
{
int bytesCopied = ((Socket)state.Item1.Task.AsyncState).EndReceive(iar);
new ReadOnlyMemory<byte>(state.Item3, 0, bytesCopied).Span.CopyTo(state.Item2.Span);
state.Item1.TrySetResult(bytesCopied);
}
catch (Exception e)
{
state.Item1.TrySetException(e);
}
finally
{
ArrayPool<byte>.Shared.Return(state.Item3);
}
}, Tuple.Create(tcs, buffer, poolArray));
return tcs.Task;
}
}
internal Task<int> ReceiveAsync(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
{
// Validate the arguments.
ValidateBuffersList(buffers);
Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: true);
if (saea != null)
{
// We got a cached instance. Configure the buffer list and initate the operation.
ConfigureBufferList(saea, buffers, socketFlags);
return GetTaskForSendReceive(ReceiveAsync(saea), saea, fromNetworkStream: false, isReceive: true);
}
else
{
// We couldn't get a cached instance, due to a concurrent receive operation on the socket.
// Fall back to wrapping APM.
return ReceiveAsyncApm(buffers, socketFlags);
}
}
/// <summary>Implements Task-returning ReceiveAsync on top of Begin/EndReceive.</summary>
private Task<int> ReceiveAsyncApm(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
{
var tcs = new TaskCompletionSource<int>(this);
BeginReceive(buffers, socketFlags, iar =>
{
var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndReceive(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task<SocketReceiveFromResult> ReceiveFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint)
{
var tcs = new StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>(this) { _field1 = remoteEndPoint };
BeginReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref tcs._field1, iar =>
{
var innerTcs = (StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>)iar.AsyncState;
try
{
int receivedBytes = ((Socket)innerTcs.Task.AsyncState).EndReceiveFrom(iar, ref innerTcs._field1);
innerTcs.TrySetResult(new SocketReceiveFromResult
{
ReceivedBytes = receivedBytes,
RemoteEndPoint = innerTcs._field1
});
}
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task<SocketReceiveMessageFromResult> ReceiveMessageFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint)
{
var tcs = new StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>(this) { _field1 = socketFlags, _field2 = remoteEndPoint };
BeginReceiveMessageFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref tcs._field2, iar =>
{
var innerTcs = (StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>)iar.AsyncState;
try
{
IPPacketInformation ipPacketInformation;
int receivedBytes = ((Socket)innerTcs.Task.AsyncState).EndReceiveMessageFrom(iar, ref innerTcs._field1, ref innerTcs._field2, out ipPacketInformation);
innerTcs.TrySetResult(new SocketReceiveMessageFromResult
{
ReceivedBytes = receivedBytes,
RemoteEndPoint = innerTcs._field2,
SocketFlags = innerTcs._field1,
PacketInformation = ipPacketInformation
});
}
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task<int> SendAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, bool fromNetworkStream)
{
// Validate the arguments.
ValidateBuffer(buffer);
Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: false);
if (saea != null)
{
// We got a cached instance. Configure the buffer and initate the operation.
ConfigureBuffer(saea, buffer, socketFlags, wrapExceptionsInIOExceptions: fromNetworkStream);
return GetTaskForSendReceive(SendAsync(saea), saea, fromNetworkStream, isReceive: false);
}
else
{
// We couldn't get a cached instance, due to a concurrent send operation on the socket.
// Fall back to wrapping APM.
return SendAsyncApm(buffer, socketFlags);
}
}
internal ValueTask<int> SendAsync(ReadOnlyMemory<byte> buffer, SocketFlags socketFlags, bool fromNetworkStream, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
// TODO https://github.com/dotnet/corefx/issues/24430:
// Fully plumb cancellation down into socket operations.
Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: false);
if (saea != null)
{
// We got a cached instance. Configure the buffer and initate the operation.
ConfigureBuffer(saea, MemoryMarshal.AsMemory<byte>(buffer), socketFlags, wrapExceptionsInIOExceptions: fromNetworkStream);
return GetValueTaskForSendReceive(SendAsync(saea), saea, fromNetworkStream, isReceive: false);
}
else
{
// We couldn't get a cached instance, due to a concurrent send operation on the socket.
// Fall back to wrapping APM.
return new ValueTask<int>(SendAsyncApm(buffer, socketFlags));
}
}
/// <summary>Implements Task-returning SendAsync on top of Begin/EndSend.</summary>
private Task<int> SendAsyncApm(ReadOnlyMemory<byte> buffer, SocketFlags socketFlags)
{
if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> bufferArray))
{
var tcs = new TaskCompletionSource<int>(this);
BeginSend(bufferArray.Array, bufferArray.Offset, bufferArray.Count, socketFlags, iar =>
{
var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSend(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
else
{
// We weren't able to extract an underlying byte[] from the Memory<byte>.
// Instead read into an ArrayPool array, then copy from that into the memory.
byte[] poolArray = ArrayPool<byte>.Shared.Rent(buffer.Length);
buffer.Span.CopyTo(poolArray);
var tcs = new TaskCompletionSource<int>(this);
BeginSend(poolArray, 0, buffer.Length, socketFlags, iar =>
{
var state = (Tuple<TaskCompletionSource<int>, byte[]>)iar.AsyncState;
try
{
state.Item1.TrySetResult(((Socket)state.Item1.Task.AsyncState).EndSend(iar));
}
catch (Exception e)
{
state.Item1.TrySetException(e);
}
finally
{
ArrayPool<byte>.Shared.Return(state.Item2);
}
}, Tuple.Create(tcs, poolArray));
return tcs.Task;
}
}
internal Task<int> SendAsync(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
{
// Validate the arguments.
ValidateBuffersList(buffers);
Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: false);
if (saea != null)
{
// We got a cached instance. Configure the buffer list and initate the operation.
ConfigureBufferList(saea, buffers, socketFlags);
return GetTaskForSendReceive(SendAsync(saea), saea, fromNetworkStream: false, isReceive: false);
}
else
{
// We couldn't get a cached instance, due to a concurrent send operation on the socket.
// Fall back to wrapping APM.
return SendAsyncApm(buffers, socketFlags);
}
}
/// <summary>Implements Task-returning SendAsync on top of Begin/EndSend.</summary>
private Task<int> SendAsyncApm(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
{
var tcs = new TaskCompletionSource<int>(this);
BeginSend(buffers, socketFlags, iar =>
{
var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSend(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
internal Task<int> SendToAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEP)
{
var tcs = new TaskCompletionSource<int>(this);
BeginSendTo(buffer.Array, buffer.Offset, buffer.Count, socketFlags, remoteEP, iar =>
{
var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSendTo(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
}
/// <summary>Validates the supplied array segment, throwing if its array or indices are null or out-of-bounds, respectively.</summary>
private static void ValidateBuffer(ArraySegment<byte> buffer)
{
if (buffer.Array == null)
{
throw new ArgumentNullException(nameof(buffer.Array));
}
if (buffer.Offset < 0 || buffer.Offset > buffer.Array.Length)
{
throw new ArgumentOutOfRangeException(nameof(buffer.Offset));
}
if (buffer.Count < 0 || buffer.Count > buffer.Array.Length - buffer.Offset)
{
throw new ArgumentOutOfRangeException(nameof(buffer.Count));
}
}
/// <summary>Validates the supplied buffer list, throwing if it's null or empty.</summary>
private static void ValidateBuffersList(IList<ArraySegment<byte>> buffers)
{
if (buffers == null)
{
throw new ArgumentNullException(nameof(buffers));
}
if (buffers.Count == 0)
{
throw new ArgumentException(SR.Format(SR.net_sockets_zerolist, nameof(buffers)), nameof(buffers));
}
}
private static void ConfigureBuffer(
Int32TaskSocketAsyncEventArgs saea, Memory<byte> buffer, SocketFlags socketFlags, bool wrapExceptionsInIOExceptions)
{
// Configure the buffer. We don't clear the buffers when returning the SAEA to the pool,
// so as to minimize overhead if the same buffer is used for subsequent operations (which is likely).
// But SAEA doesn't support having both a buffer and a buffer list configured, so clear out a buffer list
// if there is one before we set the desired buffer.
if (saea.BufferList != null) saea.BufferList = null;
saea.SetBuffer(buffer);
saea.SocketFlags = socketFlags;
saea._wrapExceptionsInIOExceptions = wrapExceptionsInIOExceptions;
}
private static void ConfigureBufferList(
Int32TaskSocketAsyncEventArgs saea, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
{
// Configure the buffer list. We don't clear the buffers when returning the SAEA to the pool,
// so as to minimize overhead if the same buffers are used for subsequent operations (which is likely).
// But SAEA doesn't support having both a buffer and a buffer list configured, so clear out a buffer
// if there is one before we set the desired buffer list.
if (!saea.MemoryBuffer.Equals(default)) saea.SetBuffer(default);
saea.BufferList = buffers;
saea.SocketFlags = socketFlags;
}
/// <summary>Gets a task to represent the operation.</summary>
/// <param name="pending">true if the operation completes asynchronously; false if it completed synchronously.</param>
/// <param name="saea">The event args instance used with the operation.</param>
/// <param name="fromNetworkStream">
/// true if the request is coming from NetworkStream, which has special semantics for
/// exceptions and cached tasks; otherwise, false.
/// </param>
/// <param name="isReceive">true if this is a receive; false if this is a send.</param>
private Task<int> GetTaskForSendReceive(
bool pending, Int32TaskSocketAsyncEventArgs saea,
bool fromNetworkStream, bool isReceive)
{
Task<int> t;
if (pending)
{
// The operation is completing asynchronously (it may have already completed).
// Get the task for the operation, with appropriate synchronization to coordinate
// with the async callback that'll be completing the task.
bool responsibleForReturningToPool;
t = saea.GetCompletionResponsibility(out responsibleForReturningToPool).Task;
if (responsibleForReturningToPool)
{
// We're responsible for returning it only if the callback has already been invoked
// and gotten what it needs from the SAEA; otherwise, the callback will return it.
ReturnSocketAsyncEventArgs(saea, isReceive);
}
}
else
{
// The operation completed synchronously. Get a task for it.
if (saea.SocketError == SocketError.Success)
{
// Get the number of bytes successfully received/sent.
int bytesTransferred = saea.BytesTransferred;
// For zero bytes transferred, we can return our cached 0 task.
// We can also do so if the request came from network stream and is a send,
// as for that we can return any value because it returns a non-generic Task.
if (bytesTransferred == 0 || (fromNetworkStream & !isReceive))
{
t = s_zeroTask;
}
else
{
// Get any cached, successfully-completed cached task that may exist on this SAEA.
Task<int> lastTask = saea._successfullyCompletedTask;
Debug.Assert(lastTask == null || lastTask.IsCompletedSuccessfully);
// If there is a task and if it has the desired result, simply reuse it.
// Otherwise, create a new one for this result value, and in addition to returning it,
// also store it into the SAEA for potential future reuse.
t = lastTask != null && lastTask.Result == bytesTransferred ?
lastTask :
(saea._successfullyCompletedTask = Task.FromResult(bytesTransferred));
}
}
else
{
t = Task.FromException<int>(GetException(saea.SocketError, wrapExceptionsInIOExceptions: fromNetworkStream));
}
// There won't be a callback, and we're done with the SAEA, so return it to the pool.
ReturnSocketAsyncEventArgs(saea, isReceive);
}
return t;
}
/// <summary>Gets a value task to represent the operation.</summary>
/// <param name="pending">true if the operation completes asynchronously; false if it completed synchronously.</param>
/// <param name="saea">The event args instance used with the operation.</param>
/// <param name="fromNetworkStream">
/// true if the request is coming from NetworkStream, which has special semantics for
/// exceptions and cached tasks; otherwise, false.
/// </param>
/// <param name="isReceive">true if this is a receive; false if this is a send.</param>
private ValueTask<int> GetValueTaskForSendReceive(
bool pending, Int32TaskSocketAsyncEventArgs saea,
bool fromNetworkStream, bool isReceive)
{
ValueTask<int> t;
if (pending)
{
// The operation is completing asynchronously (it may have already completed).
// Get the task for the operation, with appropriate synchronization to coordinate
// with the async callback that'll be completing the task.
bool responsibleForReturningToPool;
t = new ValueTask<int>(saea.GetCompletionResponsibility(out responsibleForReturningToPool).Task);
if (responsibleForReturningToPool)
{
// We're responsible for returning it only if the callback has already been invoked
// and gotten what it needs from the SAEA; otherwise, the callback will return it.
ReturnSocketAsyncEventArgs(saea, isReceive);
}
}
else
{
// The operation completed synchronously. Return a ValueTask for it.
t = saea.SocketError == SocketError.Success ?
new ValueTask<int>(saea.BytesTransferred) :
new ValueTask<int>(Task.FromException<int>(GetException(saea.SocketError, wrapExceptionsInIOExceptions: fromNetworkStream)));
// There won't be a callback, and we're done with the SAEA, so return it to the pool.
ReturnSocketAsyncEventArgs(saea, isReceive);
}
return t;
}
/// <summary>Completes the SocketAsyncEventArg's Task with the result of the send or receive, and returns it to the specified pool.</summary>
private static void CompleteAccept(Socket s, TaskSocketAsyncEventArgs<Socket> saea)
{
// Pull the relevant state off of the SAEA
SocketError error = saea.SocketError;
Socket acceptSocket = saea.AcceptSocket;
// Synchronize with the initiating thread. If the synchronous caller already got what
// it needs from the SAEA, then we can return it to the pool now. Otherwise, it'll be
// responsible for returning it once it's gotten what it needs from it.
bool responsibleForReturningToPool;
AsyncTaskMethodBuilder<Socket> builder = saea.GetCompletionResponsibility(out responsibleForReturningToPool);
if (responsibleForReturningToPool)
{
s.ReturnSocketAsyncEventArgs(saea);
}
// Complete the builder/task with the results.
if (error == SocketError.Success)
{
builder.SetResult(acceptSocket);
}
else
{
builder.SetException(GetException(error));
}
}
/// <summary>Completes the SocketAsyncEventArg's Task with the result of the send or receive, and returns it to the specified pool.</summary>
private static void CompleteSendReceive(Socket s, Int32TaskSocketAsyncEventArgs saea, bool isReceive)
{
// Pull the relevant state off of the SAEA
SocketError error = saea.SocketError;
int bytesTransferred = saea.BytesTransferred;
bool wrapExceptionsInIOExceptions = saea._wrapExceptionsInIOExceptions;
// Synchronize with the initiating thread. If the synchronous caller already got what
// it needs from the SAEA, then we can return it to the pool now. Otherwise, it'll be
// responsible for returning it once it's gotten what it needs from it.
bool responsibleForReturningToPool;
AsyncTaskMethodBuilder<int> builder = saea.GetCompletionResponsibility(out responsibleForReturningToPool);
if (responsibleForReturningToPool)
{
s.ReturnSocketAsyncEventArgs(saea, isReceive);
}
// Complete the builder/task with the results.
if (error == SocketError.Success)
{
builder.SetResult(bytesTransferred);
}
else
{
builder.SetException(GetException(error, wrapExceptionsInIOExceptions));
}
}
/// <summary>Gets a SocketException or an IOException wrapping a SocketException for the specified error.</summary>
private static Exception GetException(SocketError error, bool wrapExceptionsInIOExceptions = false)
{
Exception e = new SocketException((int)error);
return wrapExceptionsInIOExceptions ?
new IOException(SR.Format(SR.net_io_readwritefailure, e.Message), e) :
e;
}
/// <summary>Rents a <see cref="Int32TaskSocketAsyncEventArgs"/> for immediate use.</summary>
/// <param name="isReceive">true if this instance will be used for a receive; false if for sends.</param>
private Int32TaskSocketAsyncEventArgs RentSocketAsyncEventArgs(bool isReceive)
{
// Get any cached SocketAsyncEventArg we may have.
CachedTaskEventArgs cea = LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs);
Int32TaskSocketAsyncEventArgs saea = isReceive ?
Interlocked.Exchange(ref cea.Receive, s_rentedInt32Sentinel) :
Interlocked.Exchange(ref cea.Send, s_rentedInt32Sentinel);
if (saea == s_rentedInt32Sentinel)
{
// An instance was once created (or is currently being created elsewhere), but some other
// concurrent operation is using it. Since we can store at most one, and since an individual
// APM operation is less expensive than creating a new SAEA and using it only once, we simply
// return null, for a caller to fall back to using an APM implementation.
return null;
}
if (saea == null)
{
// No instance has been created yet, so create one.
saea = new Int32TaskSocketAsyncEventArgs();
saea.Completed += isReceive ? ReceiveCompletedHandler : SendCompletedHandler;
}
return saea;
}
/// <summary>Returns a <see cref="Int32TaskSocketAsyncEventArgs"/> instance for reuse.</summary>
/// <param name="saea">The instance to return.</param>
/// <param name="isReceive">true if this instance is used for receives; false if used for sends.</param>
private void ReturnSocketAsyncEventArgs(Int32TaskSocketAsyncEventArgs saea, bool isReceive)
{
Debug.Assert(_cachedTaskEventArgs != null, "Should have been initialized when renting");
Debug.Assert(saea != s_rentedInt32Sentinel);
// Reset state on the SAEA before returning it. But do not reset buffer state. That'll be done
// if necessary by the consumer, but we want to keep the buffers due to likely subsequent reuse
// and the costs associated with changing them.
saea._accessed = false;
saea._builder = default(AsyncTaskMethodBuilder<int>);
saea._wrapExceptionsInIOExceptions = false;
// Write this instance back as a cached instance. It should only ever be overwriting the sentinel,
// never null or another instance.
if (isReceive)
{
Debug.Assert(_cachedTaskEventArgs.Receive == s_rentedInt32Sentinel);
Volatile.Write(ref _cachedTaskEventArgs.Receive, saea);
}
else
{
Debug.Assert(_cachedTaskEventArgs.Send == s_rentedInt32Sentinel);
Volatile.Write(ref _cachedTaskEventArgs.Send, saea);
}
}
/// <summary>Returns a <see cref="Int32TaskSocketAsyncEventArgs"/> instance for reuse.</summary>
/// <param name="saea">The instance to return.</param>
/// <param name="isReceive">true if this instance is used for receives; false if used for sends.</param>
private void ReturnSocketAsyncEventArgs(TaskSocketAsyncEventArgs<Socket> saea)
{
Debug.Assert(_cachedTaskEventArgs != null, "Should have been initialized when renting");
Debug.Assert(saea != s_rentedSocketSentinel);
// Reset state on the SAEA before returning it. But do not reset buffer state. That'll be done
// if necessary by the consumer, but we want to keep the buffers due to likely subsequent reuse
// and the costs associated with changing them.
saea.AcceptSocket = null;
saea._accessed = false;
saea._builder = default(AsyncTaskMethodBuilder<Socket>);
// Write this instance back as a cached instance. It should only ever be overwriting the sentinel,
// never null or another instance.
Debug.Assert(_cachedTaskEventArgs.Accept == s_rentedSocketSentinel);
Volatile.Write(ref _cachedTaskEventArgs.Accept, saea);
}
/// <summary>Dispose of any cached <see cref="Int32TaskSocketAsyncEventArgs"/> instances.</summary>
private void DisposeCachedTaskSocketAsyncEventArgs()
{
CachedTaskEventArgs cea = _cachedTaskEventArgs;
if (cea != null)
{
Interlocked.Exchange(ref cea.Accept, s_rentedSocketSentinel)?.Dispose();
Interlocked.Exchange(ref cea.Receive, s_rentedInt32Sentinel)?.Dispose();
Interlocked.Exchange(ref cea.Send, s_rentedInt32Sentinel)?.Dispose();
}
}
/// <summary>A TaskCompletionSource that carries an extra field of strongly-typed state.</summary>
private class StateTaskCompletionSource<TField1, TResult> : TaskCompletionSource<TResult>
{
internal TField1 _field1;
public StateTaskCompletionSource(object baseState) : base(baseState) { }
}
/// <summary>A TaskCompletionSource that carries several extra fields of strongly-typed state.</summary>
private class StateTaskCompletionSource<TField1, TField2, TResult> : StateTaskCompletionSource<TField1, TResult>
{
internal TField2 _field2;
public StateTaskCompletionSource(object baseState) : base(baseState) { }
}
/// <summary>Cached event args used with Task-based async operations.</summary>
private sealed class CachedTaskEventArgs
{
/// <summary>Cached instance for accept operations.</summary>
public TaskSocketAsyncEventArgs<Socket> Accept;
/// <summary>Cached instance for receive operations.</summary>
public Int32TaskSocketAsyncEventArgs Receive;
/// <summary>Cached instance for send operations.</summary>
public Int32TaskSocketAsyncEventArgs Send;
}
/// <summary>A SocketAsyncEventArgs with an associated async method builder.</summary>
private class TaskSocketAsyncEventArgs<TResult> : SocketAsyncEventArgs
{
/// <summary>
/// The builder used to create the Task representing the result of the async operation.
/// This is a mutable struct.
/// </summary>
internal AsyncTaskMethodBuilder<TResult> _builder;
/// <summary>
/// Whether the instance was already accessed as part of the operation. We expect
/// at most two accesses: one from the synchronous caller to initiate the operation,
/// and one from the callback if the operation completes asynchronously. If it completes
/// synchronously, then it's the initiator's responsbility to return the instance to
/// the pool. If it completes asynchronously, then it's the responsibility of whoever
/// accesses this second, so we track whether it's already been accessed.
/// </summary>
internal bool _accessed = false;
/// <summary>Gets the builder's task with appropriate synchronization.</summary>
internal AsyncTaskMethodBuilder<TResult> GetCompletionResponsibility(out bool responsibleForReturningToPool)
{
lock (this)
{
responsibleForReturningToPool = _accessed;
_accessed = true;
var ignored = _builder.Task; // force initialization under the lock (builder itself lazily initializes w/o synchronization)
return _builder;
}
}
}
/// <summary>A SocketAsyncEventArgs with an associated async method builder.</summary>
private sealed class Int32TaskSocketAsyncEventArgs : TaskSocketAsyncEventArgs<int>
{
/// <summary>A cached, successfully completed task.</summary>
internal Task<int> _successfullyCompletedTask;
/// <summary>Whether exceptions that emerge should be wrapped in IOExceptions.</summary>
internal bool _wrapExceptionsInIOExceptions;
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace PH_App
{
public class ColorMap
{
private int colormapLength = 64;
private int alphaValue = 255;
public ColorMap()
{
}
public ColorMap(int colorLength)
{
colormapLength = colorLength;
}
public ColorMap(int colorLength, int alpha)
{
colormapLength = colorLength;
alphaValue = alpha;
}
public int[,] Spring()
{
int[,] cmap = new int[colormapLength, 4];
float[] spring = new float[colormapLength];
for (int i = 0; i < colormapLength; i++)
{
spring[i] = 1.0f * i / (colormapLength - 1);
cmap[i, 0] = alphaValue;
cmap[i, 1] = 255;
cmap[i, 2] = (int)(255 * spring[i]);
cmap[i, 3] = 255 - cmap[i, 1];
}
return cmap;
}
public int[,] Summer()
{
int[,] cmap = new int[colormapLength, 4];
float[] summer = new float[colormapLength];
for (int i = 0; i < colormapLength; i++)
{
summer[i] = 1.0f * i / (colormapLength - 1);
cmap[i, 0] = alphaValue;
cmap[i, 1] = (int)(255 * summer[i]);
cmap[i, 2] = (int)(255 * 0.5f * (1 + summer[i]));
cmap[i, 3] = (int)(255 * 0.4f);
}
return cmap;
}
public int[,] Autumn()
{
int[,] cmap = new int[colormapLength, 4];
float[] autumn = new float[colormapLength];
for (int i = 0; i < colormapLength; i++)
{
autumn[i] = 1.0f * i / (colormapLength - 1);
cmap[i, 0] = alphaValue;
cmap[i, 1] = 255;
cmap[i, 2] = (int)(255 * autumn[i]);
cmap[i, 3] = 0;
}
return cmap;
}
public int[,] Winter()
{
int[,] cmap = new int[colormapLength, 4];
float[] winter = new float[colormapLength];
for (int i = 0; i < colormapLength; i++)
{
winter[i] = 1.0f * i / (colormapLength - 1);
cmap[i, 0] = alphaValue;
cmap[i, 1] = 0;
cmap[i, 2] = (int)(255 * winter[i]);
cmap[i, 3] = (int)(255 * (1.0f - 0.5f * winter[i]));
}
return cmap;
}
public int[,] Gray()
{
int[,] cmap = new int[colormapLength, 4];
float[] gray = new float[colormapLength];
for (int i = 0; i < colormapLength; i++)
{
gray[i] = 1.0f * i / (colormapLength - 1);
cmap[i, 0] = alphaValue;
cmap[i, 1] = (int)(255 * gray[i]);
cmap[i, 2] = (int)(255 * gray[i]);
cmap[i, 3] = (int)(255 * gray[i]);
}
return cmap;
}
public int[,] Jet()
{
int[,] cmap = new int[colormapLength, 4];
float[,] cMatrix = new float[colormapLength, 3];
int n = (int)Math.Ceiling(colormapLength / 4.0f);
int nMod = 0;
float[] fArray = new float[3 * n - 1];
int[] red = new int[fArray.Length];
int[] green = new int[fArray.Length];
int[] blue = new int[fArray.Length];
if (colormapLength % 4 == 1)
{
nMod = 1;
}
for (int i = 0; i <fArray.Length; i++)
{
if (i < n)
fArray[i] = (float)(i + 1) / n;
else if (i >= n && i < 2 * n - 1)
fArray[i] = 1.0f;
else if (i >= 2 * n - 1)
fArray[i] = (float)(3 * n - 1 - i) / n;
green[i] = (int)Math.Ceiling(n / 2.0f) - nMod + i;
red[i] = green[i] + n;
blue[i] = green[i] - n;
}
int nb = 0;
for (int i = 0; i < blue.Length; i++)
{
if (blue[i] > 0)
nb++;
}
for (int i = 0; i < colormapLength; i++)
{
for (int j = 0; j < red.Length; j++)
{
if (i == red[j] && red[j] < colormapLength)
{
cMatrix[i, 0] = fArray[i - red[0]];
}
}
for (int j = 0; j < green.Length; j++)
{
if (i == green[j] && green[j] < colormapLength)
cMatrix[i, 1] = fArray[i - (int)green[0]];
}
for (int j = 0; j < blue.Length; j++)
{
if (i == blue[j] && blue[j] >= 0)
cMatrix[i, 2] = fArray[fArray.Length - 1 - nb + i];
}
}
for (int i = 0; i < colormapLength; i++)
{
cmap[i, 0] = alphaValue;
for (int j = 0; j < 3; j++)
{
cmap[i, j+1] = (int)(cMatrix[i, j] * 255);
}
}
return cmap;
}
public int[,] Hot()
{
int[,] cmap = new int[colormapLength, 4];
int n = 3 * colormapLength / 8;
float[] red = new float[colormapLength];
float[] green = new float[colormapLength];
float[] blue = new float[colormapLength];
for (int i = 0; i < colormapLength; i++)
{
if (i < n)
red[i] = 1.0f*(i+1) / n;
else
red[i] = 1.0f;
if (i < n)
green[i] = 0f;
else if (i >= n && i < 2 * n)
green[i] = 1.0f * (i+1 - n) / n;
else
green[i] = 1f;
if (i < 2 * n)
blue[i] = 0f;
else
blue[i] = 1.0f * (i + 1 - 2 * n) / (colormapLength - 2 * n);
cmap[i, 0] = alphaValue;
cmap[i, 1] = (int)(255 * red[i]);
cmap[i, 2] = (int)(255 * green[i]);
cmap[i, 3] = (int)(255 * blue[i]);
}
return cmap;
}
public int[,] Cool()
{
int[,] cmap = new int[colormapLength, 4];
float[] cool = new float[colormapLength];
for (int i = 0; i < colormapLength; i++)
{
cool[i] = 1.0f * i / (colormapLength - 1);
cmap[i, 0] = alphaValue;
cmap[i, 1] = (int)(255 * cool[i]);
cmap[i, 2] = (int)(255 * (1 - cool[i]));
cmap[i, 3] = 255;
}
return cmap;
}
}
}
| |
using Volante;
using System;
using System.Collections;
public class Supplier : Persistent
{
public String name;
public String location;
public Relation<Order,Supplier> orders;
}
public class Detail : Persistent
{
public String id;
public float weight;
public Relation<Order,Detail> orders;
}
public class Order : Persistent
{
public Relation<Order,Supplier> supplier;
public Relation<Order,Detail> detail;
public int quantity;
public long price;
public class QuantityComparer : IComparer
{
public int Compare(object a, object b)
{
return ((Order)a).quantity - ((Order)b).quantity;
}
}
public static QuantityComparer quantityComparer = new QuantityComparer();
}
public class TestSOD : Persistent
{
public IFieldIndex<string,Supplier> supplierName;
public IFieldIndex<string,Detail> detailId;
static void skip(String prompt)
{
Console.Write(prompt);
Console.ReadLine();
}
static String input(System.String prompt)
{
while (true)
{
Console.Write(prompt);
String line = Console.ReadLine().Trim();
if (line.Length != 0)
{
return line;
}
}
}
static long inputLong(String prompt)
{
while (true)
{
try
{
return Int32.Parse(input(prompt));
}
catch (FormatException)
{
Console.WriteLine("Invalid integer constant");
}
}
}
static double inputDouble(String prompt)
{
while (true)
{
try
{
return Double.Parse(input(prompt));
}
catch (FormatException)
{
Console.WriteLine("Invalid floating point constant");
}
}
}
static public void Main(String[] args)
{
IDatabase db = DatabaseFactory.CreateDatabase();
Supplier supplier;
Detail detail;
Order order;
Order[] orders;
Projection<Detail,Order> d2o = new Projection<Detail,Order>("orders");
Projection<Supplier,Order> s2o = new Projection<Supplier,Order>("orders");
int i;
db.Open("testsod.dbs");
TestSOD root = (TestSOD)db.Root;
if (root == null)
{
root = new TestSOD();
root.supplierName = db.CreateFieldIndex<string, Supplier>("name", IndexType.Unique);
root.detailId = db.CreateFieldIndex<string, Detail>("id", IndexType.Unique);
db.Root = root;
}
while (true)
{
try
{
switch ((int)inputLong("-------------------------------------\n" +
"Menu:\n" +
"1. Add supplier\n" +
"2. Add detail\n" +
"3. Add Order\n" +
"4. List of suppliers\n" +
"5. List of details\n" +
"6. Suppliers of detail\n" +
"7. Details shipped by supplier\n" +
"8. Orders for detail of supplier\n" +
"9. Exit\n\n>>"))
{
case 1:
supplier = new Supplier();
supplier.name = input("Supplier name: ");
supplier.location = input("Supplier location: ");
supplier.orders = db.CreateRelation<Order,Supplier>(supplier);
root.supplierName.Put(supplier);
db.Commit();
continue;
case 2:
detail = new Detail();
detail.id = input("Detail id: ");
detail.weight = (float)inputDouble("Detail weight: ");
detail.orders = db.CreateRelation<Order,Detail>(detail);
root.detailId.Put(detail);
db.Commit();
continue;
case 3:
supplier = root.supplierName[input("Supplier name: ")];
if (supplier == null)
{
Console.WriteLine("No such supplier!");
break;
}
detail = root.detailId[input("Detail ID: ")];
if (detail == null)
{
Console.WriteLine("No such detail!");
break;
}
order = new Order();
order.quantity = (int)inputLong("Order quantity: ");
order.price = inputLong("Order price: ");
order.detail = detail.orders;
order.supplier = supplier.orders;
detail.orders.Add(order);
supplier.orders.Add(order);
db.Commit();
continue;
case 4:
foreach (Supplier s in root.supplierName)
{
Console.WriteLine("Supplier name: " + s.name + ", supplier.location: " + s.location);
}
break;
case 5:
foreach (Detail d in root.detailId)
{
Console.WriteLine("Detail ID: " + d.id + ", detail.weight: " + d.weight);
}
break;
case 6:
detail = (Detail)root.detailId[input("Detail ID: ")];
if (detail == null)
{
Console.WriteLine("No such detail!");
break;
}
foreach (Order o in detail.orders)
{
supplier = (Supplier)o.supplier.Owner;
Console.WriteLine("Suppplier name: " + supplier.name);
}
break;
case 7:
supplier = root.supplierName[input("Supplier name: ")];
if (supplier == null)
{
Console.WriteLine("No such supplier!");
break;
}
foreach (Order o in supplier.orders)
{
detail = (Detail)o.detail.Owner;
Console.WriteLine("Detail ID: " + detail.id);
}
break;
case 8:
d2o.Reset();
d2o.Project(root.detailId.StartsWith(input("Detail ID prefix: ")));
s2o.Reset();
s2o.Project(root.supplierName.StartsWith(input("Supplier name prefix: ")));
s2o.Join(d2o);
orders = s2o.ToArray();
Array.Sort(orders, 0, orders.Length, Order.quantityComparer);
for (i = 0; i < orders.Length; i++)
{
order = orders[i];
supplier = order.supplier.Owner;
detail = order.detail.Owner;
Console.WriteLine("Detail ID: " + detail.id + ", supplier name: "
+ supplier.name + ", quantity: " + order.quantity);
}
break;
case 9:
db.Close();
return;
}
skip("Press ENTER to continue...");
}
catch (DatabaseException x)
{
Console.WriteLine("Error: " + x.Message);
skip("Press ENTER to continue...");
}
}
}
}
| |
// <copyright file="DriverContext.cs" company="Objectivity Bespoke Software Specialists">
// Copyright (c) Objectivity Bespoke Software Specialists. All rights reserved.
// </copyright>
// <license>
// The MIT License (MIT)
// 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.
// </license>
namespace Ocaramba
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using NLog;
using Ocaramba.Helpers;
using Ocaramba.Logger;
using Ocaramba.Types;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Safari;
/// <summary>
/// Contains handle to driver and methods for web browser.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Driver is disposed on test end")]
public partial class DriverContext
{
#if net47 || net45
private static readonly NLog.Logger Logger = LogManager.GetCurrentClassLogger();
#endif
#if netcoreapp3_1
private static readonly NLog.Logger Logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
#endif
private readonly Collection<ErrorDetail> verifyMessages = new Collection<ErrorDetail>();
/// <summary>
/// Gets or sets the handle to current driver.
/// </summary>
/// <value>
/// The handle to driver.
/// </value>
private IWebDriver driver;
private ChromeDriverService serviceChrome;
private EdgeDriverService serviceEdge;
private TestLogger logTest;
/// <summary>
/// Occurs when [driver options set].
/// </summary>
public event EventHandler<DriverOptionsSetEventArgs> DriverOptionsSet;
/// <summary>
/// Gets instance of Performance PerformanceMeasures class.
/// </summary>
public PerformanceHelper PerformanceMeasures { get; } = new PerformanceHelper();
/// <summary>
/// Gets or sets the test title.
/// </summary>
/// <value>
/// The test title.
/// </value>
public string TestTitle { get; set; }
/// <summary>
/// Gets or sets the Environment Browsers from App.config.
/// </summary>
public string CrossBrowserEnvironment { get; set; }
/// <summary>
/// Gets Sets Folder name for ScreenShot.
/// </summary>
public string ScreenShotFolder
{
get
{
return FilesHelper.GetFolder(BaseConfiguration.ScreenShotFolder, this.CurrentDirectory);
}
}
/// <summary>
/// Gets Sets Folder name for Download.
/// </summary>
public string DownloadFolder
{
get
{
return FilesHelper.GetFolder(BaseConfiguration.DownloadFolder, this.CurrentDirectory);
}
}
/// <summary>
/// Gets Sets Folder name for PageSource.
/// </summary>
public string PageSourceFolder
{
get
{
return FilesHelper.GetFolder(BaseConfiguration.PageSourceFolder, this.CurrentDirectory);
}
}
/// <summary>
/// Gets or sets a value indicating whether [test failed].
/// </summary>
/// <value>
/// <c>true</c> if [test failed]; otherwise, <c>false</c>.
/// </value>
public bool IsTestFailed { get; set; }
/// <summary>
/// Gets or sets test logger.
/// </summary>
public TestLogger LogTest
{
get
{
return this.logTest ?? (this.logTest = new TestLogger());
}
set
{
this.logTest = value;
}
}
/// <summary>
/// Gets driver Handle.
/// </summary>
public IWebDriver Driver
{
get
{
return this.driver;
}
}
/// <summary>
/// Gets all verify messages.
/// </summary>
public Collection<ErrorDetail> VerifyMessages
{
get
{
return this.verifyMessages;
}
}
/// <summary>
/// Gets or sets directory where assembly files are located.
/// </summary>
public string CurrentDirectory { get; set; }
private FirefoxOptions FirefoxOptions
{
get
{
FirefoxOptions options = new FirefoxOptions();
if (!string.IsNullOrEmpty(BaseConfiguration.PathToFirefoxProfile))
{
try
{
var pathToCurrentUserProfiles = BaseConfiguration.PathToFirefoxProfile; // Path to profile
var pathsToProfiles = Directory.GetDirectories(pathToCurrentUserProfiles, "*.default", SearchOption.TopDirectoryOnly);
options.Profile = new FirefoxProfile(pathsToProfiles[0]);
}
catch (DirectoryNotFoundException e)
{
Logger.Error(CultureInfo.CurrentCulture, "problem with loading firefox profile {0}", e.Message);
}
}
options.SetPreference("toolkit.startup.max_resumed_crashes", "999999");
options.SetPreference("network.automatic-ntlm-auth.trusted-uris", BaseConfiguration.Host ?? string.Empty);
// retrieving settings from config file
NameValueCollection firefoxPreferences = new NameValueCollection();
NameValueCollection firefoxExtensions = new NameValueCollection();
#if net47 || net45
firefoxPreferences = ConfigurationManager.GetSection("FirefoxPreferences") as NameValueCollection;
firefoxExtensions = ConfigurationManager.GetSection("FirefoxExtensions") as NameValueCollection;
#endif
#if netcoreapp3_1
firefoxPreferences = BaseConfiguration.GetNameValueCollectionFromAppsettings("FirefoxPreferences");
firefoxExtensions = BaseConfiguration.GetNameValueCollectionFromAppsettings("FirefoxExtensions");
#endif
// preference for downloading files
options.SetPreference("browser.download.dir", this.DownloadFolder);
options.SetPreference("browser.download.folderList", 2);
options.SetPreference("browser.download.managershowWhenStarting", false);
options.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.ms-excel, application/x-msexcel, application/pdf, text/csv, text/html, application/octet-stream");
// disable Firefox's built-in PDF viewer
options.SetPreference("pdfjs.disabled", true);
// disable Adobe Acrobat PDF preview plugin
options.SetPreference("plugin.scan.Acrobat", "99.0");
options.SetPreference("plugin.scan.plid.all", false);
// set browser proxy for Firefox
if (!string.IsNullOrEmpty(BaseConfiguration.Proxy))
{
options.Proxy = this.CurrentProxy();
}
// if there are any extensions
if (firefoxExtensions != null)
{
// loop through all of them
for (var i = 0; i < firefoxExtensions.Count; i++)
{
Logger.Trace(CultureInfo.CurrentCulture, "Installing extension {0}", firefoxExtensions.GetKey(i));
try
{
options.Profile.AddExtension(firefoxExtensions.GetKey(i));
}
catch (FileNotFoundException)
{
Logger.Trace(CultureInfo.CurrentCulture, "Installing extension {0}", this.CurrentDirectory + FilesHelper.Separator + firefoxExtensions.GetKey(i));
options.Profile.AddExtension(this.CurrentDirectory + FilesHelper.Separator + firefoxExtensions.GetKey(i));
}
}
}
options = this.AddFirefoxArguments(options);
// custom preferences
// if there are any settings
if (firefoxPreferences == null)
{
return options;
}
// loop through all of them
for (var i = 0; i < firefoxPreferences.Count; i++)
{
Logger.Trace(CultureInfo.CurrentCulture, "Set custom preference '{0},{1}'", firefoxPreferences.GetKey(i), firefoxPreferences[i]);
// and verify all of them
switch (firefoxPreferences[i])
{
// if current settings value is "true"
case "true":
options.SetPreference(firefoxPreferences.GetKey(i), true);
break;
// if "false"
case "false":
options.SetPreference(firefoxPreferences.GetKey(i), false);
break;
// otherwise
default:
int temp;
// an attempt to parse current settings value to an integer. Method TryParse returns True if the attempt is successful (the string is integer) or return False (if the string is just a string and cannot be cast to a number)
if (int.TryParse(firefoxPreferences.Get(i), out temp))
{
options.SetPreference(firefoxPreferences.GetKey(i), temp);
}
else
{
options.SetPreference(firefoxPreferences.GetKey(i), firefoxPreferences[i]);
}
break;
}
}
return options;
}
}
private ChromeOptions ChromeOptions
{
get
{
ChromeOptions options = new ChromeOptions();
// retrieving settings from config file
NameValueCollection chromePreferences = null;
NameValueCollection chromeExtensions = null;
NameValueCollection chromeArguments = null;
#if net47 || net45
chromePreferences = ConfigurationManager.GetSection("ChromePreferences") as NameValueCollection;
chromeExtensions = ConfigurationManager.GetSection("ChromeExtensions") as NameValueCollection;
chromeArguments = ConfigurationManager.GetSection("ChromeArguments") as NameValueCollection;
#endif
#if netcoreapp3_1
chromePreferences = BaseConfiguration.GetNameValueCollectionFromAppsettings("ChromePreferences");
chromeExtensions = BaseConfiguration.GetNameValueCollectionFromAppsettings("ChromeExtensions");
chromeArguments = BaseConfiguration.GetNameValueCollectionFromAppsettings("chromeArguments");
#endif
options.AddUserProfilePreference("profile.default_content_settings.popups", 0);
options.AddUserProfilePreference("download.default_directory", this.DownloadFolder);
options.AddUserProfilePreference("download.prompt_for_download", false);
// set browser proxy for chrome
if (!string.IsNullOrEmpty(BaseConfiguration.Proxy))
{
options.Proxy = this.CurrentProxy();
}
// if there are any extensions
if (chromeExtensions != null)
{
// loop through all of them
for (var i = 0; i < chromeExtensions.Count; i++)
{
Logger.Trace(CultureInfo.CurrentCulture, "Installing extension {0}", chromeExtensions.GetKey(i));
try
{
options.AddExtension(chromeExtensions.GetKey(i));
}
catch (FileNotFoundException)
{
Logger.Trace(CultureInfo.CurrentCulture, "Installing extension {0}", this.CurrentDirectory + FilesHelper.Separator + chromeExtensions.GetKey(i));
options.AddExtension(this.CurrentDirectory + FilesHelper.Separator + chromeExtensions.GetKey(i));
}
}
}
// if there are any arguments
if (chromeArguments != null)
{
// loop through all of them
for (var i = 0; i < chromeArguments.Count; i++)
{
Logger.Trace(CultureInfo.CurrentCulture, "Setting Chrome Arguments {0}", chromeArguments.GetKey(i));
options.AddArgument(chromeArguments.GetKey(i));
}
}
// custom preferences
// if there are any settings
if (chromePreferences == null)
{
return options;
}
// loop through all of them
for (var i = 0; i < chromePreferences.Count; i++)
{
Logger.Trace(CultureInfo.CurrentCulture, "Set custom preference '{0},{1}'", chromePreferences.GetKey(i), chromePreferences[i]);
// and verify all of them
switch (chromePreferences[i])
{
// if current settings value is "true"
case "true":
options.AddUserProfilePreference(chromePreferences.GetKey(i), true);
break;
// if "false"
case "false":
options.AddUserProfilePreference(chromePreferences.GetKey(i), false);
break;
// otherwise
default:
int temp;
// an attempt to parse current settings value to an integer. Method TryParse returns True if the attempt is successful (the string is integer) or return False (if the string is just a string and cannot be cast to a number)
if (int.TryParse(chromePreferences.Get(i), out temp))
{
options.AddUserProfilePreference(chromePreferences.GetKey(i), temp);
}
else
{
options.AddUserProfilePreference(chromePreferences.GetKey(i), chromePreferences[i]);
}
break;
}
}
return options;
}
}
private InternetExplorerOptions InternetExplorerOptions
{
get
{
// retrieving settings from config file
NameValueCollection internetExplorerPreferences = null;
#if net47 || net45
internetExplorerPreferences = ConfigurationManager.GetSection("InternetExplorerPreferences") as NameValueCollection;
#endif
#if netcoreapp3_1
internetExplorerPreferences = BaseConfiguration.GetNameValueCollectionFromAppsettings("InternetExplorerPreferences");
#endif
var options = new InternetExplorerOptions
{
EnsureCleanSession = true,
IgnoreZoomLevel = true,
};
// set browser proxy for IE
if (!string.IsNullOrEmpty(BaseConfiguration.Proxy))
{
options.Proxy = this.CurrentProxy();
}
// custom preferences
// if there are any settings
if (internetExplorerPreferences == null)
{
return options;
}
this.GetInternetExplorerPreferences(internetExplorerPreferences, options);
return options;
}
}
private OpenQA.Selenium.Edge.EdgeOptions EdgeOptions
{
get
{
var options = new OpenQA.Selenium.Edge.EdgeOptions();
// retrieving settings from config file
NameValueCollection edgeChromiumPreferences = null;
NameValueCollection edgeChromiumExtensions = null;
NameValueCollection edgeChromiumArguments = null;
#if net47 || net45
edgeChromiumPreferences = ConfigurationManager.GetSection("EdgeChromiumPreferences") as NameValueCollection;
edgeChromiumExtensions = ConfigurationManager.GetSection("EdgeChromiumExtensions") as NameValueCollection;
edgeChromiumArguments = ConfigurationManager.GetSection("EdgeChromiumArguments") as NameValueCollection;
#endif
#if netcoreapp3_1
edgeChromiumPreferences = BaseConfiguration.GetNameValueCollectionFromAppsettings("EdgeChromiumPreferences");
edgeChromiumExtensions = BaseConfiguration.GetNameValueCollectionFromAppsettings("EdgeChromiumExtensions");
edgeChromiumArguments = BaseConfiguration.GetNameValueCollectionFromAppsettings("EdgeChromiumArguments");
#endif
// set browser proxy for Edge
if (!string.IsNullOrEmpty(BaseConfiguration.Proxy))
{
options.Proxy = this.CurrentProxy();
}
options.AddAdditionalOption("useAutomationExtension", false);
options.AddExcludedArgument("enable-automation");
// if there are any extensions
if (edgeChromiumExtensions != null)
{
// loop through all of them
for (var i = 0; i < edgeChromiumExtensions.Count; i++)
{
Logger.Trace(CultureInfo.CurrentCulture, "Installing extension {0}", edgeChromiumExtensions.GetKey(i));
try
{
options.AddExtension(edgeChromiumExtensions.GetKey(i));
}
catch (FileNotFoundException)
{
Logger.Trace(CultureInfo.CurrentCulture, "Installing extension {0}", this.CurrentDirectory + FilesHelper.Separator + edgeChromiumExtensions.GetKey(i));
options.AddExtension(this.CurrentDirectory + FilesHelper.Separator + edgeChromiumExtensions.GetKey(i));
}
}
}
// if there are any arguments
if (edgeChromiumArguments != null)
{
// loop through all of them
for (var i = 0; i < edgeChromiumArguments.Count; i++)
{
Logger.Trace(CultureInfo.CurrentCulture, "Setting Chrome Arguments {0}", edgeChromiumArguments.GetKey(i));
options.AddArgument(edgeChromiumArguments.GetKey(i));
}
}
// custom preferences
// if there are any settings
if (edgeChromiumPreferences == null)
{
return options;
}
// loop through all of them
for (var i = 0; i < edgeChromiumPreferences.Count; i++)
{
Logger.Trace(CultureInfo.CurrentCulture, "Set custom preference '{0},{1}'", edgeChromiumPreferences.GetKey(i), edgeChromiumPreferences[i]);
// and verify all of them
switch (edgeChromiumPreferences[i])
{
// if current settings value is "true"
case "true":
options.AddUserProfilePreference(edgeChromiumPreferences.GetKey(i), true);
break;
// if "false"
case "false":
options.AddUserProfilePreference(edgeChromiumPreferences.GetKey(i), false);
break;
// otherwise
default:
int temp;
// an attempt to parse current settings value to an integer. Method TryParse returns True if the attempt is successful (the string is integer) or return False (if the string is just a string and cannot be cast to a number)
if (int.TryParse(edgeChromiumPreferences.Get(i), out temp))
{
options.AddUserProfilePreference(edgeChromiumPreferences.GetKey(i), temp);
}
else
{
options.AddUserProfilePreference(edgeChromiumPreferences.GetKey(i), edgeChromiumPreferences[i]);
}
break;
}
}
return options;
}
}
private SafariOptions SafariOptions
{
get
{
var options = new SafariOptions();
options.AddAdditionalOption("cleanSession", true);
return options;
}
}
/// <summary>
/// Takes the screenshot.
/// </summary>
/// <returns>An image of the page currently loaded in the browser.</returns>
public Screenshot TakeScreenshot()
{
try
{
var screenshotDriver = (ITakesScreenshot)this.driver;
var screenshot = screenshotDriver.GetScreenshot();
return screenshot;
}
catch (NullReferenceException)
{
Logger.Error("Test failed but was unable to get webdriver screenshot.");
}
catch (UnhandledAlertException)
{
Logger.Error("Test failed but was unable to get webdriver screenshot.");
}
return null;
}
/// <summary>
/// Starts the specified Driver.
/// </summary>
/// <exception cref="NotSupportedException">When driver not supported.</exception>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Driver disposed later in stop method")]
public void Start()
{
switch (BaseConfiguration.TestBrowser)
{
case BrowserType.Firefox:
if (!string.IsNullOrEmpty(BaseConfiguration.FirefoxBrowserExecutableLocation))
{
this.FirefoxOptions.BrowserExecutableLocation = BaseConfiguration.FirefoxBrowserExecutableLocation;
}
#if netcoreapp3_1
FirefoxDriverService serviceFirefox = FirefoxDriverService.CreateDefaultService();
serviceFirefox.Host = "::1";
this.driver = string.IsNullOrEmpty(BaseConfiguration.PathToFirefoxDriverDirectory) ? new FirefoxDriver(serviceFirefox, this.SetDriverOptions(this.FirefoxOptions)) : new FirefoxDriver(BaseConfiguration.PathToFirefoxDriverDirectory, this.SetDriverOptions(this.FirefoxOptions));
#endif
#if net47 || net45
this.driver = string.IsNullOrEmpty(BaseConfiguration.PathToFirefoxDriverDirectory) ? new FirefoxDriver(this.SetDriverOptions(this.FirefoxOptions)) : new FirefoxDriver(BaseConfiguration.PathToFirefoxDriverDirectory, this.SetDriverOptions(this.FirefoxOptions));
#endif
break;
case BrowserType.InternetExplorer:
case BrowserType.IE:
this.driver = string.IsNullOrEmpty(BaseConfiguration.PathToInternetExplorerDriverDirectory) ? new InternetExplorerDriver(this.SetDriverOptions(this.InternetExplorerOptions)) : new InternetExplorerDriver(BaseConfiguration.PathToInternetExplorerDriverDirectory, this.SetDriverOptions(this.InternetExplorerOptions));
break;
case BrowserType.Chrome:
if (!string.IsNullOrEmpty(BaseConfiguration.ChromeBrowserExecutableLocation))
{
this.ChromeOptions.BinaryLocation = BaseConfiguration.ChromeBrowserExecutableLocation;
}
this.serviceChrome = ChromeDriverService.CreateDefaultService();
this.serviceChrome.LogPath = BaseConfiguration.PathToChromeDriverLog;
this.serviceChrome.EnableVerboseLogging = BaseConfiguration.EnableVerboseLoggingChrome;
this.driver = string.IsNullOrEmpty(BaseConfiguration.PathToChromeDriverDirectory) ? new ChromeDriver(this.serviceChrome, this.SetDriverOptions(this.ChromeOptions)) : new ChromeDriver(BaseConfiguration.PathToChromeDriverDirectory, this.SetDriverOptions(this.ChromeOptions));
break;
case BrowserType.Safari:
this.driver = new SafariDriver(this.SetDriverOptions(this.SafariOptions));
this.CheckIfProxySetForSafari();
break;
case BrowserType.RemoteWebDriver:
this.SetupRemoteWebDriver();
break;
case BrowserType.Edge:
case BrowserType.EdgeChromium:
if (!string.IsNullOrEmpty(BaseConfiguration.EdgeChromiumBrowserExecutableLocation))
{
this.EdgeOptions.BinaryLocation = BaseConfiguration.EdgeChromiumBrowserExecutableLocation;
}
this.serviceEdge = EdgeDriverService.CreateDefaultService();
this.driver = string.IsNullOrEmpty(BaseConfiguration.PathToEdgeChromiumDriverDirectory) ? new EdgeDriver(this.serviceEdge, this.SetDriverOptions(this.EdgeOptions)) : new EdgeDriver(EdgeDriverService.CreateDefaultService(BaseConfiguration.PathToEdgeChromiumDriverDirectory, @"msedgedriver.exe"), this.SetDriverOptions(this.EdgeOptions));
break;
default:
throw new NotSupportedException(
string.Format(CultureInfo.CurrentCulture, "Driver {0} is not supported", BaseConfiguration.TestBrowser));
}
if (BaseConfiguration.EnableEventFiringWebDriver)
{
this.driver = new MyEventFiringWebDriver(this.driver);
}
}
/// <summary>
/// Maximizes the current window if it is not already maximized.
/// </summary>
public void WindowMaximize()
{
this.driver.Manage().Window.Maximize();
}
/// <summary>
/// Deletes all cookies from the page.
/// </summary>
public void DeleteAllCookies()
{
this.driver.Manage().Cookies.DeleteAllCookies();
}
/// <summary>
/// Stop browser instance.
/// </summary>
public void Stop()
{
if (this.serviceChrome != null)
{
this.serviceChrome.Dispose();
}
if (this.serviceEdge != null)
{
this.serviceEdge.Dispose();
}
if (this.driver != null)
{
this.driver.Quit();
}
}
private void SetupRemoteWebDriver()
{
NameValueCollection driverCapabilitiesConf = new NameValueCollection();
NameValueCollection settings = new NameValueCollection();
#if net47 || net45
driverCapabilitiesConf = ConfigurationManager.GetSection("DriverCapabilities") as NameValueCollection;
settings = ConfigurationManager.GetSection("environments/" + this.CrossBrowserEnvironment) as NameValueCollection;
#endif
#if netcoreapp3_1
driverCapabilitiesConf = BaseConfiguration.GetNameValueCollectionFromAppsettings("DriverCapabilities");
settings = BaseConfiguration.GetNameValueCollectionFromAppsettings("environments:" + this.CrossBrowserEnvironment);
#endif
var browserType = this.GetBrowserTypeForRemoteDriver(settings);
switch (browserType)
{
case BrowserType.Firefox:
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.Proxy = this.CurrentProxy();
this.SetRemoteDriverBrowserOptions(driverCapabilitiesConf, settings, firefoxOptions);
firefoxOptions.BrowserVersion = "latest";
this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(firefoxOptions).ToCapabilities());
break;
case BrowserType.Android:
case BrowserType.Chrome:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.Proxy = this.CurrentProxy();
this.SetRemoteDriverBrowserOptions(driverCapabilitiesConf, settings, chromeOptions);
chromeOptions.BrowserVersion = "latest";
this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(chromeOptions).ToCapabilities());
break;
case BrowserType.Iphone:
case BrowserType.Safari:
SafariOptions safariOptions = new SafariOptions();
this.SetRemoteDriverOptions(driverCapabilitiesConf, settings, safariOptions);
this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(safariOptions).ToCapabilities());
break;
case BrowserType.Edge:
case BrowserType.EdgeChromium:
EdgeOptions egEdgeOptions = new EdgeOptions();
egEdgeOptions.BrowserVersion = "latest";
egEdgeOptions.Proxy = this.CurrentProxy();
this.SetRemoteDriverOptions(driverCapabilitiesConf, settings, egEdgeOptions);
this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(egEdgeOptions).ToCapabilities());
break;
case BrowserType.IE:
case BrowserType.InternetExplorer:
InternetExplorerOptions internetExplorerOptions = new InternetExplorerOptions();
internetExplorerOptions.Proxy = this.CurrentProxy();
this.SetRemoteDriverBrowserOptions(driverCapabilitiesConf, settings, internetExplorerOptions);
this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(internetExplorerOptions).ToCapabilities());
break;
default:
throw new NotSupportedException(
string.Format(CultureInfo.CurrentCulture, "Driver {0} is not supported", this.CrossBrowserEnvironment));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System
{
using System;
using System.Reflection;
using System.Runtime;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics;
[ClassInterface(ClassInterfaceType.AutoDual)]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Delegate : ICloneable, ISerializable
{
// _target is the object we will invoke on
internal Object _target;
// MethodBase, either cached after first request or assigned from a DynamicMethod
// For open delegates to collectible types, this may be a LoaderAllocator object
internal Object _methodBase;
// _methodPtr is a pointer to the method we will invoke
// It could be a small thunk if this is a static or UM call
internal IntPtr _methodPtr;
// In the case of a static method passed to a delegate, this field stores
// whatever _methodPtr would have stored: and _methodPtr points to a
// small thunk which removes the "this" pointer before going on
// to _methodPtrAux.
internal IntPtr _methodPtrAux;
// This constructor is called from the class generated by the
// compiler generated code
protected Delegate(Object target, String method)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodName to
// such and don't allow relaxed signature matching (which could make
// the choice of target method ambiguous) for backwards
// compatibility. The name matching was case sensitive and we
// preserve that as well.
if (!BindToMethodName(target, (RuntimeType)target.GetType(), method,
DelegateBindingFlags.InstanceMethodOnly |
DelegateBindingFlags.ClosedDelegateOnly))
throw new ArgumentException(SR.Arg_DlgtTargMeth);
}
// This constructor is called from a class to generate a
// delegate based upon a static method name and the Type object
// for the class defining the method.
protected unsafe Delegate(Type target, String method)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
if (target.ContainsGenericParameters)
throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeType rtTarget = target as RuntimeType;
if (rtTarget == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target));
// This API existed in v1/v1.1 and only expected to create open
// static delegates. Constrain the call to BindToMethodName to such
// and don't allow relaxed signature matching (which could make the
// choice of target method ambiguous) for backwards compatibility.
// The name matching was case insensitive (no idea why this is
// different from the constructor above) and we preserve that as
// well.
BindToMethodName(null, rtTarget, method,
DelegateBindingFlags.StaticMethodOnly |
DelegateBindingFlags.OpenDelegateOnly |
DelegateBindingFlags.CaselessMatching);
}
// Protect the default constructor so you can't build a delegate
private Delegate()
{
}
public Object DynamicInvoke(params Object[] args)
{
// Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
// But to maintain backward compatibility we can't switch to calling an
// internal overload of DynamicInvokeImpl that takes a stack mark.
// Fortunately the stack walker skips all the reflection invocation frames including this one.
// So this method will never be returned by the stack walker as the caller.
// See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
return DynamicInvokeImpl(args);
}
protected virtual object DynamicInvokeImpl(object[] args)
{
RuntimeMethodHandleInternal method = new RuntimeMethodHandleInternal(GetInvokeMethod());
RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase((RuntimeType)this.GetType(), method);
return invoke.UnsafeInvoke(this, BindingFlags.Default, null, args, null);
}
public override bool Equals(Object obj)
{
if (obj == null || !InternalEqualTypes(this, obj))
return false;
Delegate d = (Delegate)obj;
// do an optimistic check first. This is hopefully cheap enough to be worth
if (_target == d._target && _methodPtr == d._methodPtr && _methodPtrAux == d._methodPtrAux)
return true;
// even though the fields were not all equals the delegates may still match
// When target carries the delegate itself the 2 targets (delegates) may be different instances
// but the delegates are logically the same
// It may also happen that the method pointer was not jitted when creating one delegate and jitted in the other
// if that's the case the delegates may still be equals but we need to make a more complicated check
if (_methodPtrAux == IntPtr.Zero)
{
if (d._methodPtrAux != IntPtr.Zero)
return false; // different delegate kind
// they are both closed over the first arg
if (_target != d._target)
return false;
// fall through method handle check
}
else
{
if (d._methodPtrAux == IntPtr.Zero)
return false; // different delegate kind
// Ignore the target as it will be the delegate instance, though it may be a different one
/*
if (_methodPtr != d._methodPtr)
return false;
*/
if (_methodPtrAux == d._methodPtrAux)
return true;
// fall through method handle check
}
// method ptrs don't match, go down long path
//
if (_methodBase == null || d._methodBase == null || !(_methodBase is MethodInfo) || !(d._methodBase is MethodInfo))
return Delegate.InternalEqualMethodHandles(this, d);
else
return _methodBase.Equals(d._methodBase);
}
public override int GetHashCode()
{
//
// this is not right in the face of a method being jitted in one delegate and not in another
// in that case the delegate is the same and Equals will return true but GetHashCode returns a
// different hashcode which is not true.
/*
if (_methodPtrAux == IntPtr.Zero)
return unchecked((int)((long)this._methodPtr));
else
return unchecked((int)((long)this._methodPtrAux));
*/
if (_methodPtrAux == IntPtr.Zero)
return ( _target != null ? RuntimeHelpers.GetHashCode(_target) * 33 : 0) + GetType().GetHashCode();
else
return GetType().GetHashCode();
}
public static Delegate Combine(Delegate a, Delegate b)
{
if ((Object)a == null) // cast to object for a more efficient test
return b;
return a.CombineImpl(b);
}
public static Delegate Combine(params Delegate[] delegates)
{
if (delegates == null || delegates.Length == 0)
return null;
Delegate d = delegates[0];
for (int i = 1; i < delegates.Length; i++)
d = Combine(d, delegates[i]);
return d;
}
public virtual Delegate[] GetInvocationList()
{
Delegate[] d = new Delegate[1];
d[0] = this;
return d;
}
// This routine will return the method
public MethodInfo Method
{
get
{
return GetMethodImpl();
}
}
protected virtual MethodInfo GetMethodImpl()
{
if ((_methodBase == null) || !(_methodBase is MethodInfo))
{
IRuntimeMethodInfo method = FindMethodHandle();
RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(method);
// need a proper declaring type instance method on a generic type
if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType))
{
bool isStatic = (RuntimeMethodHandle.GetAttributes(method) & MethodAttributes.Static) != (MethodAttributes)0;
if (!isStatic)
{
if (_methodPtrAux == IntPtr.Zero)
{
// The target may be of a derived type that doesn't have visibility onto the
// target method. We don't want to call RuntimeType.GetMethodBase below with that
// or reflection can end up generating a MethodInfo where the ReflectedType cannot
// see the MethodInfo itself and that breaks an important invariant. But the
// target type could include important generic type information we need in order
// to work out what the exact instantiation of the method's declaring type is. So
// we'll walk up the inheritance chain (which will yield exactly instantiated
// types at each step) until we find the declaring type. Since the declaring type
// we get from the method is probably shared and those in the hierarchy we're
// walking won't be we compare using the generic type definition forms instead.
Type currentType = _target.GetType();
Type targetType = declaringType.GetGenericTypeDefinition();
while (currentType != null)
{
if (currentType.IsGenericType &&
currentType.GetGenericTypeDefinition() == targetType)
{
declaringType = currentType as RuntimeType;
break;
}
currentType = currentType.BaseType;
}
// RCWs don't need to be "strongly-typed" in which case we don't find a base type
// that matches the declaring type of the method. This is fine because interop needs
// to work with exact methods anyway so declaringType is never shared at this point.
Debug.Assert(currentType != null || _target.GetType().IsCOMObject, "The class hierarchy should declare the method");
}
else
{
// it's an open one, need to fetch the first arg of the instantiation
MethodInfo invoke = this.GetType().GetMethod("Invoke");
declaringType = (RuntimeType)invoke.GetParameters()[0].ParameterType;
}
}
}
_methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method);
}
return (MethodInfo)_methodBase;
}
public Object Target
{
get
{
return GetTarget();
}
}
public static Delegate Remove(Delegate source, Delegate value)
{
if (source == null)
return null;
if (value == null)
return source;
if (!InternalEqualTypes(source, value))
throw new ArgumentException(SR.Arg_DlgtTypeMis);
return source.RemoveImpl(value);
}
public static Delegate RemoveAll(Delegate source, Delegate value)
{
Delegate newDelegate = null;
do
{
newDelegate = source;
source = Remove(source, value);
}
while (newDelegate != source);
return newDelegate;
}
protected virtual Delegate CombineImpl(Delegate d)
{
throw new MulticastNotSupportedException(SR.Multicast_Combine);
}
protected virtual Delegate RemoveImpl(Delegate d)
{
return (d.Equals(this)) ? null : this;
}
public virtual Object Clone()
{
return MemberwiseClone();
}
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method)
{
return CreateDelegate(type, target, method, false, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase)
{
return CreateDelegate(type, target, method, ignoreCase, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (target == null)
throw new ArgumentNullException(nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodName to such
// and don't allow relaxed signature matching (which could make the
// choice of target method ambiguous) for backwards compatibility.
// We never generate a closed over null delegate and this is
// actually enforced via the check on target above, but we pass
// NeverCloseOverNull anyway just for clarity.
if (!d.BindToMethodName(target, (RuntimeType)target.GetType(), method,
DelegateBindingFlags.InstanceMethodOnly |
DelegateBindingFlags.ClosedDelegateOnly |
DelegateBindingFlags.NeverCloseOverNull |
(ignoreCase ? DelegateBindingFlags.CaselessMatching : 0)))
{
if (throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
d = null;
}
return d;
}
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method)
{
return CreateDelegate(type, target, method, false, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase)
{
return CreateDelegate(type, target, method, ignoreCase, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (target == null)
throw new ArgumentNullException(nameof(target));
if (target.ContainsGenericParameters)
throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
RuntimeType rtTarget = target as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (rtTarget == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create open
// static delegates. Constrain the call to BindToMethodName to such
// and don't allow relaxed signature matching (which could make the
// choice of target method ambiguous) for backwards compatibility.
if (!d.BindToMethodName(null, rtTarget, method,
DelegateBindingFlags.StaticMethodOnly |
DelegateBindingFlags.OpenDelegateOnly |
(ignoreCase ? DelegateBindingFlags.CaselessMatching : 0)))
{
if (throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
d = null;
}
return d;
}
// V1 API.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
if (rmi == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodInfo to
// open delegates only for backwards compatibility. But we'll allow
// relaxed signature checking and open static delegates because
// there's no ambiguity there (the caller would have to explicitly
// pass us a static method or a method with a non-exact signature
// and the only change in behavior from v1.1 there is that we won't
// fail the call).
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Delegate d = CreateDelegateInternal(
rtType,
rmi,
null,
DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature,
ref stackMark);
if (d == null && throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
// V2 API.
public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method)
{
return CreateDelegate(type, firstArgument, method, true);
}
// V2 API.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method, bool throwOnBindFailure)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
if (rmi == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// This API is new in Whidbey and allows the full range of delegate
// flexability (open or closed delegates binding to static or
// instance methods with relaxed signature checking. The delegate
// can also be closed over null. There's no ambiguity with all these
// options since the caller is providing us a specific MethodInfo.
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Delegate d = CreateDelegateInternal(
rtType,
rmi,
firstArgument,
DelegateBindingFlags.RelaxedSignature,
ref stackMark);
if (d == null && throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
public static bool operator ==(Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 == null;
return d1.Equals(d2);
}
public static bool operator !=(Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 != null;
return !d1.Equals(d2);
}
//
// Implementation of ISerializable
//
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
//
// internal implementation details (FCALLS and utilities)
//
// V2 internal API.
// This is Critical because it skips the security check when creating the delegate.
internal unsafe static Delegate CreateDelegateNoSecurityCheck(Type type, Object target, RuntimeMethodHandle method)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method.IsNullHandle())
throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// Initialize the method...
Delegate d = InternalAlloc(rtType);
// This is a new internal API added in Whidbey. Currently it's only
// used by the dynamic method code to generate a wrapper delegate.
// Allow flexible binding options since the target method is
// unambiguously provided to us.
if (!d.BindToMethodInfo(target,
method.GetMethodInfo(),
RuntimeMethodHandle.GetDeclaringType(method.GetMethodInfo()),
DelegateBindingFlags.RelaxedSignature | DelegateBindingFlags.SkipSecurityChecks))
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
// Caution: this method is intended for deserialization only, no security checks are performed.
internal static Delegate CreateDelegateNoSecurityCheck(RuntimeType type, Object firstArgument, MethodInfo method)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeMethodInfo rtMethod = method as RuntimeMethodInfo;
if (rtMethod == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!type.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// This API is used by the formatters when deserializing a delegate.
// They pass us the specific target method (that was already the
// target in a valid delegate) so we should bind with the most
// relaxed rules available (the result will never be ambiguous, it
// just increases the chance of success with minor (compatible)
// signature changes). We explicitly skip security checks here --
// we're not really constructing a delegate, we're cloning an
// existing instance which already passed its checks.
Delegate d = UnsafeCreateDelegate(type, rtMethod, firstArgument,
DelegateBindingFlags.SkipSecurityChecks |
DelegateBindingFlags.RelaxedSignature);
if (d == null)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
// V1 API.
public static Delegate CreateDelegate(Type type, MethodInfo method)
{
return CreateDelegate(type, method, true);
}
internal static Delegate CreateDelegateInternal(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags, ref StackCrawlMark stackMark)
{
Debug.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0);
return UnsafeCreateDelegate(rtType, rtMethod, firstArgument, flags);
}
internal static Delegate UnsafeCreateDelegate(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags)
{
Delegate d = InternalAlloc(rtType);
if (d.BindToMethodInfo(firstArgument, rtMethod, rtMethod.GetDeclaringTypeInternal(), flags))
return d;
else
return null;
}
//
// internal implementation details (FCALLS and utilities)
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool BindToMethodName(Object target, RuntimeType methodType, String method, DelegateBindingFlags flags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool BindToMethodInfo(Object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static MulticastDelegate InternalAlloc(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static MulticastDelegate InternalAllocLike(Delegate d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool InternalEqualTypes(object a, object b);
// Used by the ctor. Do not call directly.
// The name of this function will appear in managed stacktraces as delegate constructor.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void DelegateConstruct(Object target, IntPtr slot);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetMulticastInvoke();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetInvokeMethod();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IRuntimeMethodInfo FindMethodHandle();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool InternalEqualMethodHandles(Delegate left, Delegate right);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr AdjustTarget(Object target, IntPtr methodPtr);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetCallStub(IntPtr methodPtr);
internal virtual Object GetTarget()
{
return (_methodPtrAux == IntPtr.Zero) ? _target : null;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CompareUnmanagedFunctionPtrs(Delegate d1, Delegate d2);
}
// These flags effect the way BindToMethodInfo and BindToMethodName are allowed to bind a delegate to a target method. Their
// values must be kept in sync with the definition in vm\comdelegate.h.
internal enum DelegateBindingFlags
{
StaticMethodOnly = 0x00000001, // Can only bind to static target methods
InstanceMethodOnly = 0x00000002, // Can only bind to instance (including virtual) methods
OpenDelegateOnly = 0x00000004, // Only allow the creation of delegates open over the 1st argument
ClosedDelegateOnly = 0x00000008, // Only allow the creation of delegates closed over the 1st argument
NeverCloseOverNull = 0x00000010, // A null target will never been considered as a possible null 1st argument
CaselessMatching = 0x00000020, // Use case insensitive lookup for methods matched by name
SkipSecurityChecks = 0x00000040, // Skip security checks (visibility, link demand etc.)
RelaxedSignature = 0x00000080, // Allow relaxed signature matching (co/contra variance)
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Controls.dll
// Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 4/4/2009 11:52:50 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DotSpatial.Data;
using DotSpatial.Serialization;
using DotSpatial.Symbology;
namespace DotSpatial.Controls
{
public class MapGroup : Group, IMapGroup
{
/// <summary>
/// Overrides the base CreateGroup method to ensure that new groups are GeoGroups.
/// </summary>
protected override void OnCreateGroup()
{
new MapGroup(Layers, ParentMapFrame, ProgressHandler) {LegendText = "New Group"};
}
#region Nested type: MapLayerEnumerator
/// <summary>
/// Transforms an IMapLayer enumerator into an ILayer Enumerator
/// </summary>
public class MapLayerEnumerator : IEnumerator<ILayer>
{
private readonly IEnumerator<IMapLayer> _enumerator;
/// <summary>
/// Creates a new instance of the MapLayerEnumerator
/// </summary>
/// <param name="subEnumerator"></param>
public MapLayerEnumerator(IEnumerator<IMapLayer> subEnumerator)
{
_enumerator = subEnumerator;
}
#region IEnumerator<ILayer> Members
/// <inheritdoc />
public ILayer Current
{
get { return _enumerator.Current; }
}
/// <inheritdoc />
public void Dispose()
{
_enumerator.Dispose();
}
object IEnumerator.Current
{
get { return _enumerator.Current; }
}
/// <inheritdoc />
public bool MoveNext()
{
return _enumerator.MoveNext();
}
/// <inheritdoc />
public void Reset()
{
_enumerator.Reset();
}
#endregion
}
#endregion
#region Private Variables
private IMapLayerCollection _layers;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of GeoGroup
/// </summary>
public MapGroup()
{
Layers = new MapLayerCollection();
}
/// <summary>
/// Creates a new group for the specified map. This will place the group at the root level on the MapFrame.
/// </summary>
/// <param name="map">The map to add this group to.</param>
/// <param name="name">The name to appear in the legend text.</param>
public MapGroup(IMap map, string name)
: base(map.MapFrame, map.ProgressHandler)
{
Layers = new MapLayerCollection(map.MapFrame, this, map.ProgressHandler);
base.LegendText = name;
map.Layers.Add(this);
}
/// <summary>
/// Creates a group that sits in a layer list and uses the specified progress handler
/// </summary>
/// <param name="container">the layer list</param>
/// <param name="frame"></param>
/// <param name="progressHandler">the progress handler</param>
public MapGroup(ICollection<IMapLayer> container, IMapFrame frame, IProgressHandler progressHandler)
: base(frame, progressHandler)
{
Layers = new MapLayerCollection(frame, this, progressHandler);
container.Add(this);
}
#endregion
#region Methods
/// <inheritdoc />
public override int IndexOf(ILayer item)
{
IMapLayer ml = item as IMapLayer;
if (ml != null)
{
return _layers.IndexOf(ml);
}
return -1;
}
/// <inheritdoc />
public override void Add(ILayer layer)
{
IMapLayer ml = layer as IMapLayer;
if (ml != null)
{
_layers.Add(ml);
}
}
/// <inheritdoc />
public override bool Remove(ILayer layer)
{
IMapLayer ml = layer as IMapLayer;
return ml != null && _layers.Remove(ml);
}
/// <inheritdoc />
public override void RemoveAt(int index)
{
_layers.RemoveAt(index);
}
/// <inheritdoc />
public override void Insert(int index, ILayer layer)
{
IMapLayer ml = layer as IMapLayer;
if (ml != null)
{
_layers.Insert(index, ml);
}
}
/// <inheritdoc />
public override ILayer this[int index]
{
get
{
return _layers[index];
}
set
{
IMapLayer ml = value as IMapLayer;
_layers[index] = ml;
}
}
/// <inheritdoc />
public override void Clear()
{
_layers.Clear();
}
/// <inheritdoc />
public override bool Contains(ILayer item)
{
IMapLayer ml = item as IMapLayer;
return ml != null && _layers.Contains(ml);
}
/// <inheritdoc />
public override void CopyTo(ILayer[] array, int arrayIndex)
{
for (int i = 0; i < Layers.Count; i++)
{
array[i + arrayIndex] = _layers[i];
}
}
/// <inheritdoc />
public override int Count
{
get { return _layers.Count; }
}
/// <inheritdoc />
public override bool IsReadOnly
{
get { return _layers.IsReadOnly; }
}
/// <inheritdoc />
public override void SuspendEvents()
{
_layers.SuspendEvents();
}
/// <inheritdoc />
public override void ResumeEvents()
{
_layers.ResumeEvents();
}
/// <inheritdoc />
public override bool EventsSuspended
{
get { return _layers.EventsSuspended; }
}
/// <inheritdoc />
public override IEnumerator<ILayer> GetEnumerator()
{
return new MapLayerEnumerator(_layers.GetEnumerator());
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return _layers.GetEnumerator();
}
/// <summary>
/// This draws content from the specified geographic regions onto the specified graphics
/// object specified by MapArgs.
/// </summary>
public void DrawRegions(MapArgs args, List<Extent> regions)
{
if (Layers == null) return;
foreach (IMapLayer layer in Layers)
{
if (!layer.IsVisible) continue;
if (layer.UseDynamicVisibility)
{
if (layer.DynamicVisibilityMode == DynamicVisibilityMode.ZoomedIn)
{
if (MapFrame.ViewExtents.Width > layer.DynamicVisibilityWidth)
{
continue; // skip the geoLayer if we are zoomed out too far.
}
}
else
{
if (MapFrame.ViewExtents.Width < layer.DynamicVisibilityWidth)
{
continue; // skip the geoLayer if we are zoomed in too far.
}
}
}
layer.DrawRegions(args, regions);
}
}
#endregion
#region Properties
/// <summary>
/// Gets the collection of Geographic drawing layers.
/// </summary>
/// <summary>
/// Gets or sets the layers
/// </summary>
[Serialize("Layers")]
public new IMapLayerCollection Layers
{
get { return _layers; }
set
{
if (Layers != null)
{
Ignore_Layer_Events(_layers);
}
Handle_Layer_Events(value);
_layers = value;
//set the MapFrame property
if (ParentMapFrame != null)
{
_layers.MapFrame = ParentMapFrame;
}
}
}
/// <inheritdoc />
public override IFrame MapFrame
{
get { return base.MapFrame; }
set
{
base.MapFrame = value;
if (_layers != null)
{
IMapFrame newValue = value as IMapFrame;
if (newValue != null && _layers.MapFrame == null)
{
_layers.MapFrame = newValue;
}
}
}
}
/// <summary>
/// Gets the layers cast as ILayer without any information about the actual drawing methods.
/// This is useful for handling methods that my come from various types of maps.
/// </summary>
/// <returns>An enumerable collection of ILayer</returns>
public override IList<ILayer> GetLayers()
{
return _layers.Cast<ILayer>().ToList();
}
/// <summary>
/// Gets the MapFrame that this group ultimately belongs to. This may not
/// be the immediate parent of this group.
/// </summary>
public IMapFrame ParentMapFrame
{
get { return MapFrame as IMapFrame; }
set { MapFrame = value; }
}
/// <summary>
/// This is a different view of the layers cast as legend items. This allows
/// easier cycling in recursive legend code.
/// </summary>
public override IEnumerable<ILegendItem> LegendItems
{
get
{
// Keep cast for 3.5 framework
return _layers.Cast<ILegendItem>();
}
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: operations/rpc/room_svc.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Operations.RPC {
/// <summary>Holder for reflection information generated from operations/rpc/room_svc.proto</summary>
public static partial class RoomSvcReflection {
#region Descriptor
/// <summary>File descriptor for operations/rpc/room_svc.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static RoomSvcReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch1vcGVyYXRpb25zL3JwYy9yb29tX3N2Yy5wcm90bxIaaG9sbXMudHlwZXMu",
"b3BlcmF0aW9ucy5ycGMaLmJvb2tpbmcvaW5kaWNhdG9ycy9yZXNlcnZhdGlv",
"bl9pbmRpY2F0b3IucHJvdG8aG2dvb2dsZS9wcm90b2J1Zi9lbXB0eS5wcm90",
"bxofZ29vZ2xlL3Byb3RvYnVmL3RpbWVzdGFtcC5wcm90bxo2b3BlcmF0aW9u",
"cy9ob3VzZWtlZXBpbmcvaG91c2VrZWVwaW5nX3Jvb21fc3RhdHVzLnByb3Rv",
"GhtvcGVyYXRpb25zL3Jvb21zL3Jvb20ucHJvdG8aJW9wZXJhdGlvbnMvcm9v",
"bXMvcm9vbV9pbmRpY2F0b3IucHJvdG8aKnByaW1pdGl2ZS9zZXJ2ZXJfYWN0",
"aW9uX2NvbmZpcm1hdGlvbi5wcm90bxoydGVuYW5jeV9jb25maWcvaW5kaWNh",
"dG9ycy9wcm9wZXJ0eV9pbmRpY2F0b3IucHJvdG8iRwoSUm9vbVN2Y0FsbFJl",
"c3BvbnNlEjEKBXJvb21zGAEgAygLMiIuaG9sbXMudHlwZXMub3BlcmF0aW9u",
"cy5yb29tcy5Sb29tIosBChNSb29tU3ZjQ1JVRFJlc3BvbnNlEkIKC2NydWRf",
"cmVzdWx0GAEgASgOMi0uaG9sbXMudHlwZXMub3BlcmF0aW9ucy5ycGMuUm9v",
"bVN2Y0NSVURSZXN1bHQSMAoEcm9vbRgCIAEoCzIiLmhvbG1zLnR5cGVzLm9w",
"ZXJhdGlvbnMucm9vbXMuUm9vbSKfAQoXUm9vbVN2Y09jY3VwYW5jeVJlcXVl",
"c3QSOQoEcm9vbRgBIAEoCzIrLmhvbG1zLnR5cGVzLm9wZXJhdGlvbnMucm9v",
"bXMuUm9vbUluZGljYXRvchJJCgtyZXNlcnZhdGlvbhgCIAEoCzI0LmhvbG1z",
"LnR5cGVzLmJvb2tpbmcuaW5kaWNhdG9ycy5SZXNlcnZhdGlvbkluZGljYXRv",
"ciJoCh1Sb29tU3ZjQ2xhaW1PY2N1cGFuY3lSZXNwb25zZRJHCgZyZXN1bHQY",
"ASABKA4yNy5ob2xtcy50eXBlcy5vcGVyYXRpb25zLnJwYy5Sb29tU3ZjT2Nj",
"dXBhbmN5Q2xhaW1SZXN1bHQibAofUm9vbVN2Y1JlbGVhc2VPY2N1cGFuY3lS",
"ZXNwb25zZRJJCgZyZXN1bHQYASABKA4yOS5ob2xtcy50eXBlcy5vcGVyYXRp",
"b25zLnJwYy5Sb29tU3ZjT2NjdXBhbmN5UmVsZWFzZVJlc3VsdCKIAQooUm9v",
"bVN2Y0dldEJ5T2NjdXB5aW5nUmVzZXJ2YXRpb25SZXNwb25zZRIiChpyZXNl",
"cnZhdGlvbl9oYXNfcm9vbV9jbGFpbRgBIAEoCBI4CgxjbGFpbWVkX3Jvb20Y",
"AiABKAsyIi5ob2xtcy50eXBlcy5vcGVyYXRpb25zLnJvb21zLlJvb20i3QEK",
"GlJvb21TdmNJc3N1ZVJvb21LZXlSZXF1ZXN0EkkKC3Jlc2VydmF0aW9uGAEg",
"ASgLMjQuaG9sbXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3JzLlJlc2VydmF0",
"aW9uSW5kaWNhdG9yEi8KC2V4cGlyeV90aW1lGAIgASgLMhouZ29vZ2xlLnBy",
"b3RvYnVmLlRpbWVzdGFtcBIWCg5udW1iZXJfb2Zfa2V5cxgDIAEoBRISCgpp",
"c19uZXdfa2V5GAQgASgIEhcKD3Rlcm1pbmFsX251bWJlchgFIAEoDSJpChtS",
"b29tU3ZjSXNzdWVSb29tS2V5UmVzcG9uc2USSgoGcmVzdWx0GAEgASgOMjou",
"aG9sbXMudHlwZXMub3BlcmF0aW9ucy5ycGMuUk9PTV9TVkNfSVNTVUVfUk9P",
"TV9LRVlfUkVTVUxUInkKKFJvb21TdmNHZXRIb3VzZWtlZXBpbmdSb29tU3Rh",
"dHVzUmVzcG9uc2USTQoIc3RhdHVzZXMYASADKAsyOy5ob2xtcy50eXBlcy5v",
"cGVyYXRpb25zLmhvdXNla2VlcGluZy5Ib3VzZWtlZXBpbmdSb29tU3RhdHVz",
"KlAKEVJvb21TdmNDUlVEUmVzdWx0EhAKDENSVURfU1VDQ0VTUxAAEhEKDVVO",
"S05PV05fRVJST1IQARIWChJEVVBMSUNBVEVfVFJVTktfSUQQAirDAQobUm9v",
"bVN2Y09jY3VwYW5jeUNsYWltUmVzdWx0EhsKF09DQ1VQQU5DWV9DTEFJTV9T",
"VUNDRVNTEAASHgoaRkFJTF9ST09NX0FMUkVBRFlfT0NDVVBJRUQQARInCiNG",
"QUlMX1JFU0VSVkFUSU9OX0hBU19FWElTVElOR19DTEFJTRACEiwKKE9DQ1VQ",
"QU5DWV9DTEFJTV9SRVNVTFRfUk9PTV9OT1RfQVNTSUdORUQQAxIQCgxGQUlM",
"X1VOS05PV04QBCqkAQodUm9vbVN2Y09jY3VwYW5jeVJlbGVhc2VSZXN1bHQS",
"HQoZT0NDVVBBTkNZX1JFTEVBU0VfU1VDQ0VTUxAAEiQKIEZBSUxfTk9fRVhJ",
"U1RJTkdfT0NDVVBBTkNZX0NMQUlNEAESLQopRkFJTF9SRVNFUlZBVElPTl9P",
"Q0NVUFlJTkdfRElGRkVSRU5UX1JPT00QAhIPCgtGQUlMX1VOTk9XThAEKlsK",
"HlJPT01fU1ZDX0lTU1VFX1JPT01fS0VZX1JFU1VMVBILCgdTVUNDRVNTEAAS",
"CwoHVElNRU9VVBABEhIKDklOVkFMSURfQ09ORklHEAISCwoHRkFJTFVSRRAD",
"MpwJCgdSb29tU3ZjEk0KA0FsbBIWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eRou",
"LmhvbG1zLnR5cGVzLm9wZXJhdGlvbnMucnBjLlJvb21TdmNBbGxSZXNwb25z",
"ZRJdCgZDcmVhdGUSIi5ob2xtcy50eXBlcy5vcGVyYXRpb25zLnJvb21zLlJv",
"b20aLy5ob2xtcy50eXBlcy5vcGVyYXRpb25zLnJwYy5Sb29tU3ZjQ1JVRFJl",
"c3BvbnNlEl0KBlVwZGF0ZRIiLmhvbG1zLnR5cGVzLm9wZXJhdGlvbnMucm9v",
"bXMuUm9vbRovLmhvbG1zLnR5cGVzLm9wZXJhdGlvbnMucnBjLlJvb21TdmND",
"UlVEUmVzcG9uc2USXQoGRGVsZXRlEiIuaG9sbXMudHlwZXMub3BlcmF0aW9u",
"cy5yb29tcy5Sb29tGi8uaG9sbXMudHlwZXMucHJpbWl0aXZlLlNlcnZlckFj",
"dGlvbkNvbmZpcm1hdGlvbhJaCgdHZXRCeUlkEisuaG9sbXMudHlwZXMub3Bl",
"cmF0aW9ucy5yb29tcy5Sb29tSW5kaWNhdG9yGiIuaG9sbXMudHlwZXMub3Bl",
"cmF0aW9ucy5yb29tcy5Sb29tEpcBChlHZXRCeU9jY3VweWluZ1Jlc2VydmF0",
"aW9uEjQuaG9sbXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3JzLlJlc2VydmF0",
"aW9uSW5kaWNhdG9yGkQuaG9sbXMudHlwZXMub3BlcmF0aW9ucy5ycGMuUm9v",
"bVN2Y0dldEJ5T2NjdXB5aW5nUmVzZXJ2YXRpb25SZXNwb25zZRKEAQoSQ2xh",
"aW1Sb29tT2NjdXBhbmN5EjMuaG9sbXMudHlwZXMub3BlcmF0aW9ucy5ycGMu",
"Um9vbVN2Y09jY3VwYW5jeVJlcXVlc3QaOS5ob2xtcy50eXBlcy5vcGVyYXRp",
"b25zLnJwYy5Sb29tU3ZjQ2xhaW1PY2N1cGFuY3lSZXNwb25zZRKIAQoUUmVs",
"ZWFzZVJvb21PY2N1cGFuY3kSMy5ob2xtcy50eXBlcy5vcGVyYXRpb25zLnJw",
"Yy5Sb29tU3ZjT2NjdXBhbmN5UmVxdWVzdBo7LmhvbG1zLnR5cGVzLm9wZXJh",
"dGlvbnMucnBjLlJvb21TdmNSZWxlYXNlT2NjdXBhbmN5UmVzcG9uc2USfwoM",
"SXNzdWVSb29tS2V5EjYuaG9sbXMudHlwZXMub3BlcmF0aW9ucy5ycGMuUm9v",
"bVN2Y0lzc3VlUm9vbUtleVJlcXVlc3QaNy5ob2xtcy50eXBlcy5vcGVyYXRp",
"b25zLnJwYy5Sb29tU3ZjSXNzdWVSb29tS2V5UmVzcG9uc2USmwEKGUdldEhv",
"dXNla2VlcGluZ1Jvb21TdGF0dXMSOC5ob2xtcy50eXBlcy50ZW5hbmN5X2Nv",
"bmZpZy5pbmRpY2F0b3JzLlByb3BlcnR5SW5kaWNhdG9yGkQuaG9sbXMudHlw",
"ZXMub3BlcmF0aW9ucy5ycGMuUm9vbVN2Y0dldEhvdXNla2VlcGluZ1Jvb21T",
"dGF0dXNSZXNwb25zZUIdqgIaSE9MTVMuVHlwZXMuT3BlcmF0aW9ucy5SUENi",
"BnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::HOLMS.Types.Operations.Housekeeping.HousekeepingRoomStatusReflection.Descriptor, global::HOLMS.Types.Operations.Rooms.RoomReflection.Descriptor, global::HOLMS.Types.Operations.Rooms.RoomIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.ServerActionConfirmationReflection.Descriptor, global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicatorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResult), typeof(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyClaimResult), typeof(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyReleaseResult), typeof(global::HOLMS.Types.Operations.RPC.ROOM_SVC_ISSUE_ROOM_KEY_RESULT), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.RoomSvcAllResponse), global::HOLMS.Types.Operations.RPC.RoomSvcAllResponse.Parser, new[]{ "Rooms" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse), global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse.Parser, new[]{ "CrudResult", "Room" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest), global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest.Parser, new[]{ "Room", "Reservation" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.RoomSvcClaimOccupancyResponse), global::HOLMS.Types.Operations.RPC.RoomSvcClaimOccupancyResponse.Parser, new[]{ "Result" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.RoomSvcReleaseOccupancyResponse), global::HOLMS.Types.Operations.RPC.RoomSvcReleaseOccupancyResponse.Parser, new[]{ "Result" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.RoomSvcGetByOccupyingReservationResponse), global::HOLMS.Types.Operations.RPC.RoomSvcGetByOccupyingReservationResponse.Parser, new[]{ "ReservationHasRoomClaim", "ClaimedRoom" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyRequest), global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyRequest.Parser, new[]{ "Reservation", "ExpiryTime", "NumberOfKeys", "IsNewKey", "TerminalNumber" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyResponse), global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyResponse.Parser, new[]{ "Result" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.RoomSvcGetHousekeepingRoomStatusResponse), global::HOLMS.Types.Operations.RPC.RoomSvcGetHousekeepingRoomStatusResponse.Parser, new[]{ "Statuses" }, null, null, null)
}));
}
#endregion
}
#region Enums
public enum RoomSvcCRUDResult {
[pbr::OriginalName("CRUD_SUCCESS")] CrudSuccess = 0,
[pbr::OriginalName("UNKNOWN_ERROR")] UnknownError = 1,
[pbr::OriginalName("DUPLICATE_TRUNK_ID")] DuplicateTrunkId = 2,
}
public enum RoomSvcOccupancyClaimResult {
[pbr::OriginalName("OCCUPANCY_CLAIM_SUCCESS")] OccupancyClaimSuccess = 0,
[pbr::OriginalName("FAIL_ROOM_ALREADY_OCCUPIED")] FailRoomAlreadyOccupied = 1,
[pbr::OriginalName("FAIL_RESERVATION_HAS_EXISTING_CLAIM")] FailReservationHasExistingClaim = 2,
[pbr::OriginalName("OCCUPANCY_CLAIM_RESULT_ROOM_NOT_ASSIGNED")] OccupancyClaimResultRoomNotAssigned = 3,
[pbr::OriginalName("FAIL_UNKNOWN")] FailUnknown = 4,
}
public enum RoomSvcOccupancyReleaseResult {
[pbr::OriginalName("OCCUPANCY_RELEASE_SUCCESS")] OccupancyReleaseSuccess = 0,
[pbr::OriginalName("FAIL_NO_EXISTING_OCCUPANCY_CLAIM")] FailNoExistingOccupancyClaim = 1,
[pbr::OriginalName("FAIL_RESERVATION_OCCUPYING_DIFFERENT_ROOM")] FailReservationOccupyingDifferentRoom = 2,
[pbr::OriginalName("FAIL_UNNOWN")] FailUnnown = 4,
}
public enum ROOM_SVC_ISSUE_ROOM_KEY_RESULT {
[pbr::OriginalName("SUCCESS")] Success = 0,
[pbr::OriginalName("TIMEOUT")] Timeout = 1,
[pbr::OriginalName("INVALID_CONFIG")] InvalidConfig = 2,
[pbr::OriginalName("FAILURE")] Failure = 3,
}
#endregion
#region Messages
public sealed partial class RoomSvcAllResponse : pb::IMessage<RoomSvcAllResponse> {
private static readonly pb::MessageParser<RoomSvcAllResponse> _parser = new pb::MessageParser<RoomSvcAllResponse>(() => new RoomSvcAllResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RoomSvcAllResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.RPC.RoomSvcReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcAllResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcAllResponse(RoomSvcAllResponse other) : this() {
rooms_ = other.rooms_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcAllResponse Clone() {
return new RoomSvcAllResponse(this);
}
/// <summary>Field number for the "rooms" field.</summary>
public const int RoomsFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Operations.Rooms.Room> _repeated_rooms_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Operations.Rooms.Room.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Operations.Rooms.Room> rooms_ = new pbc::RepeatedField<global::HOLMS.Types.Operations.Rooms.Room>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Operations.Rooms.Room> Rooms {
get { return rooms_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RoomSvcAllResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RoomSvcAllResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!rooms_.Equals(other.rooms_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= rooms_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
rooms_.WriteTo(output, _repeated_rooms_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += rooms_.CalculateSize(_repeated_rooms_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RoomSvcAllResponse other) {
if (other == null) {
return;
}
rooms_.Add(other.rooms_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
rooms_.AddEntriesFrom(input, _repeated_rooms_codec);
break;
}
}
}
}
}
public sealed partial class RoomSvcCRUDResponse : pb::IMessage<RoomSvcCRUDResponse> {
private static readonly pb::MessageParser<RoomSvcCRUDResponse> _parser = new pb::MessageParser<RoomSvcCRUDResponse>(() => new RoomSvcCRUDResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RoomSvcCRUDResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.RPC.RoomSvcReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcCRUDResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcCRUDResponse(RoomSvcCRUDResponse other) : this() {
crudResult_ = other.crudResult_;
Room = other.room_ != null ? other.Room.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcCRUDResponse Clone() {
return new RoomSvcCRUDResponse(this);
}
/// <summary>Field number for the "crud_result" field.</summary>
public const int CrudResultFieldNumber = 1;
private global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResult crudResult_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResult CrudResult {
get { return crudResult_; }
set {
crudResult_ = value;
}
}
/// <summary>Field number for the "room" field.</summary>
public const int RoomFieldNumber = 2;
private global::HOLMS.Types.Operations.Rooms.Room room_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.Rooms.Room Room {
get { return room_; }
set {
room_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RoomSvcCRUDResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RoomSvcCRUDResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (CrudResult != other.CrudResult) return false;
if (!object.Equals(Room, other.Room)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (CrudResult != 0) hash ^= CrudResult.GetHashCode();
if (room_ != null) hash ^= Room.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (CrudResult != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) CrudResult);
}
if (room_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Room);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (CrudResult != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) CrudResult);
}
if (room_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Room);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RoomSvcCRUDResponse other) {
if (other == null) {
return;
}
if (other.CrudResult != 0) {
CrudResult = other.CrudResult;
}
if (other.room_ != null) {
if (room_ == null) {
room_ = new global::HOLMS.Types.Operations.Rooms.Room();
}
Room.MergeFrom(other.Room);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
crudResult_ = (global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResult) input.ReadEnum();
break;
}
case 18: {
if (room_ == null) {
room_ = new global::HOLMS.Types.Operations.Rooms.Room();
}
input.ReadMessage(room_);
break;
}
}
}
}
}
public sealed partial class RoomSvcOccupancyRequest : pb::IMessage<RoomSvcOccupancyRequest> {
private static readonly pb::MessageParser<RoomSvcOccupancyRequest> _parser = new pb::MessageParser<RoomSvcOccupancyRequest>(() => new RoomSvcOccupancyRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RoomSvcOccupancyRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.RPC.RoomSvcReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcOccupancyRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcOccupancyRequest(RoomSvcOccupancyRequest other) : this() {
Room = other.room_ != null ? other.Room.Clone() : null;
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcOccupancyRequest Clone() {
return new RoomSvcOccupancyRequest(this);
}
/// <summary>Field number for the "room" field.</summary>
public const int RoomFieldNumber = 1;
private global::HOLMS.Types.Operations.Rooms.RoomIndicator room_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.Rooms.RoomIndicator Room {
get { return room_; }
set {
room_ = value;
}
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 2;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RoomSvcOccupancyRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RoomSvcOccupancyRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Room, other.Room)) return false;
if (!object.Equals(Reservation, other.Reservation)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (room_ != null) hash ^= Room.GetHashCode();
if (reservation_ != null) hash ^= Reservation.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (room_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Room);
}
if (reservation_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Reservation);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (room_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Room);
}
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RoomSvcOccupancyRequest other) {
if (other == null) {
return;
}
if (other.room_ != null) {
if (room_ == null) {
room_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator();
}
Room.MergeFrom(other.Room);
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (room_ == null) {
room_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator();
}
input.ReadMessage(room_);
break;
}
case 18: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
}
}
}
}
public sealed partial class RoomSvcClaimOccupancyResponse : pb::IMessage<RoomSvcClaimOccupancyResponse> {
private static readonly pb::MessageParser<RoomSvcClaimOccupancyResponse> _parser = new pb::MessageParser<RoomSvcClaimOccupancyResponse>(() => new RoomSvcClaimOccupancyResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RoomSvcClaimOccupancyResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.RPC.RoomSvcReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcClaimOccupancyResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcClaimOccupancyResponse(RoomSvcClaimOccupancyResponse other) : this() {
result_ = other.result_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcClaimOccupancyResponse Clone() {
return new RoomSvcClaimOccupancyResponse(this);
}
/// <summary>Field number for the "result" field.</summary>
public const int ResultFieldNumber = 1;
private global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyClaimResult result_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyClaimResult Result {
get { return result_; }
set {
result_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RoomSvcClaimOccupancyResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RoomSvcClaimOccupancyResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Result != other.Result) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Result != 0) hash ^= Result.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Result != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Result);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Result != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RoomSvcClaimOccupancyResponse other) {
if (other == null) {
return;
}
if (other.Result != 0) {
Result = other.Result;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
result_ = (global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyClaimResult) input.ReadEnum();
break;
}
}
}
}
}
public sealed partial class RoomSvcReleaseOccupancyResponse : pb::IMessage<RoomSvcReleaseOccupancyResponse> {
private static readonly pb::MessageParser<RoomSvcReleaseOccupancyResponse> _parser = new pb::MessageParser<RoomSvcReleaseOccupancyResponse>(() => new RoomSvcReleaseOccupancyResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RoomSvcReleaseOccupancyResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.RPC.RoomSvcReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcReleaseOccupancyResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcReleaseOccupancyResponse(RoomSvcReleaseOccupancyResponse other) : this() {
result_ = other.result_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcReleaseOccupancyResponse Clone() {
return new RoomSvcReleaseOccupancyResponse(this);
}
/// <summary>Field number for the "result" field.</summary>
public const int ResultFieldNumber = 1;
private global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyReleaseResult result_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyReleaseResult Result {
get { return result_; }
set {
result_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RoomSvcReleaseOccupancyResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RoomSvcReleaseOccupancyResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Result != other.Result) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Result != 0) hash ^= Result.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Result != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Result);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Result != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RoomSvcReleaseOccupancyResponse other) {
if (other == null) {
return;
}
if (other.Result != 0) {
Result = other.Result;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
result_ = (global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyReleaseResult) input.ReadEnum();
break;
}
}
}
}
}
public sealed partial class RoomSvcGetByOccupyingReservationResponse : pb::IMessage<RoomSvcGetByOccupyingReservationResponse> {
private static readonly pb::MessageParser<RoomSvcGetByOccupyingReservationResponse> _parser = new pb::MessageParser<RoomSvcGetByOccupyingReservationResponse>(() => new RoomSvcGetByOccupyingReservationResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RoomSvcGetByOccupyingReservationResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.RPC.RoomSvcReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcGetByOccupyingReservationResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcGetByOccupyingReservationResponse(RoomSvcGetByOccupyingReservationResponse other) : this() {
reservationHasRoomClaim_ = other.reservationHasRoomClaim_;
ClaimedRoom = other.claimedRoom_ != null ? other.ClaimedRoom.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcGetByOccupyingReservationResponse Clone() {
return new RoomSvcGetByOccupyingReservationResponse(this);
}
/// <summary>Field number for the "reservation_has_room_claim" field.</summary>
public const int ReservationHasRoomClaimFieldNumber = 1;
private bool reservationHasRoomClaim_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ReservationHasRoomClaim {
get { return reservationHasRoomClaim_; }
set {
reservationHasRoomClaim_ = value;
}
}
/// <summary>Field number for the "claimed_room" field.</summary>
public const int ClaimedRoomFieldNumber = 2;
private global::HOLMS.Types.Operations.Rooms.Room claimedRoom_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.Rooms.Room ClaimedRoom {
get { return claimedRoom_; }
set {
claimedRoom_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RoomSvcGetByOccupyingReservationResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RoomSvcGetByOccupyingReservationResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ReservationHasRoomClaim != other.ReservationHasRoomClaim) return false;
if (!object.Equals(ClaimedRoom, other.ClaimedRoom)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ReservationHasRoomClaim != false) hash ^= ReservationHasRoomClaim.GetHashCode();
if (claimedRoom_ != null) hash ^= ClaimedRoom.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ReservationHasRoomClaim != false) {
output.WriteRawTag(8);
output.WriteBool(ReservationHasRoomClaim);
}
if (claimedRoom_ != null) {
output.WriteRawTag(18);
output.WriteMessage(ClaimedRoom);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ReservationHasRoomClaim != false) {
size += 1 + 1;
}
if (claimedRoom_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ClaimedRoom);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RoomSvcGetByOccupyingReservationResponse other) {
if (other == null) {
return;
}
if (other.ReservationHasRoomClaim != false) {
ReservationHasRoomClaim = other.ReservationHasRoomClaim;
}
if (other.claimedRoom_ != null) {
if (claimedRoom_ == null) {
claimedRoom_ = new global::HOLMS.Types.Operations.Rooms.Room();
}
ClaimedRoom.MergeFrom(other.ClaimedRoom);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
ReservationHasRoomClaim = input.ReadBool();
break;
}
case 18: {
if (claimedRoom_ == null) {
claimedRoom_ = new global::HOLMS.Types.Operations.Rooms.Room();
}
input.ReadMessage(claimedRoom_);
break;
}
}
}
}
}
public sealed partial class RoomSvcIssueRoomKeyRequest : pb::IMessage<RoomSvcIssueRoomKeyRequest> {
private static readonly pb::MessageParser<RoomSvcIssueRoomKeyRequest> _parser = new pb::MessageParser<RoomSvcIssueRoomKeyRequest>(() => new RoomSvcIssueRoomKeyRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RoomSvcIssueRoomKeyRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.RPC.RoomSvcReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcIssueRoomKeyRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcIssueRoomKeyRequest(RoomSvcIssueRoomKeyRequest other) : this() {
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
ExpiryTime = other.expiryTime_ != null ? other.ExpiryTime.Clone() : null;
numberOfKeys_ = other.numberOfKeys_;
isNewKey_ = other.isNewKey_;
terminalNumber_ = other.terminalNumber_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcIssueRoomKeyRequest Clone() {
return new RoomSvcIssueRoomKeyRequest(this);
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "expiry_time" field.</summary>
public const int ExpiryTimeFieldNumber = 2;
private global::Google.Protobuf.WellKnownTypes.Timestamp expiryTime_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp ExpiryTime {
get { return expiryTime_; }
set {
expiryTime_ = value;
}
}
/// <summary>Field number for the "number_of_keys" field.</summary>
public const int NumberOfKeysFieldNumber = 3;
private int numberOfKeys_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int NumberOfKeys {
get { return numberOfKeys_; }
set {
numberOfKeys_ = value;
}
}
/// <summary>Field number for the "is_new_key" field.</summary>
public const int IsNewKeyFieldNumber = 4;
private bool isNewKey_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsNewKey {
get { return isNewKey_; }
set {
isNewKey_ = value;
}
}
/// <summary>Field number for the "terminal_number" field.</summary>
public const int TerminalNumberFieldNumber = 5;
private uint terminalNumber_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint TerminalNumber {
get { return terminalNumber_; }
set {
terminalNumber_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RoomSvcIssueRoomKeyRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RoomSvcIssueRoomKeyRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Reservation, other.Reservation)) return false;
if (!object.Equals(ExpiryTime, other.ExpiryTime)) return false;
if (NumberOfKeys != other.NumberOfKeys) return false;
if (IsNewKey != other.IsNewKey) return false;
if (TerminalNumber != other.TerminalNumber) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (reservation_ != null) hash ^= Reservation.GetHashCode();
if (expiryTime_ != null) hash ^= ExpiryTime.GetHashCode();
if (NumberOfKeys != 0) hash ^= NumberOfKeys.GetHashCode();
if (IsNewKey != false) hash ^= IsNewKey.GetHashCode();
if (TerminalNumber != 0) hash ^= TerminalNumber.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (reservation_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Reservation);
}
if (expiryTime_ != null) {
output.WriteRawTag(18);
output.WriteMessage(ExpiryTime);
}
if (NumberOfKeys != 0) {
output.WriteRawTag(24);
output.WriteInt32(NumberOfKeys);
}
if (IsNewKey != false) {
output.WriteRawTag(32);
output.WriteBool(IsNewKey);
}
if (TerminalNumber != 0) {
output.WriteRawTag(40);
output.WriteUInt32(TerminalNumber);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
if (expiryTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ExpiryTime);
}
if (NumberOfKeys != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(NumberOfKeys);
}
if (IsNewKey != false) {
size += 1 + 1;
}
if (TerminalNumber != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(TerminalNumber);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RoomSvcIssueRoomKeyRequest other) {
if (other == null) {
return;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
if (other.expiryTime_ != null) {
if (expiryTime_ == null) {
expiryTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
ExpiryTime.MergeFrom(other.ExpiryTime);
}
if (other.NumberOfKeys != 0) {
NumberOfKeys = other.NumberOfKeys;
}
if (other.IsNewKey != false) {
IsNewKey = other.IsNewKey;
}
if (other.TerminalNumber != 0) {
TerminalNumber = other.TerminalNumber;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 18: {
if (expiryTime_ == null) {
expiryTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(expiryTime_);
break;
}
case 24: {
NumberOfKeys = input.ReadInt32();
break;
}
case 32: {
IsNewKey = input.ReadBool();
break;
}
case 40: {
TerminalNumber = input.ReadUInt32();
break;
}
}
}
}
}
public sealed partial class RoomSvcIssueRoomKeyResponse : pb::IMessage<RoomSvcIssueRoomKeyResponse> {
private static readonly pb::MessageParser<RoomSvcIssueRoomKeyResponse> _parser = new pb::MessageParser<RoomSvcIssueRoomKeyResponse>(() => new RoomSvcIssueRoomKeyResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RoomSvcIssueRoomKeyResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.RPC.RoomSvcReflection.Descriptor.MessageTypes[7]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcIssueRoomKeyResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcIssueRoomKeyResponse(RoomSvcIssueRoomKeyResponse other) : this() {
result_ = other.result_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcIssueRoomKeyResponse Clone() {
return new RoomSvcIssueRoomKeyResponse(this);
}
/// <summary>Field number for the "result" field.</summary>
public const int ResultFieldNumber = 1;
private global::HOLMS.Types.Operations.RPC.ROOM_SVC_ISSUE_ROOM_KEY_RESULT result_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.RPC.ROOM_SVC_ISSUE_ROOM_KEY_RESULT Result {
get { return result_; }
set {
result_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RoomSvcIssueRoomKeyResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RoomSvcIssueRoomKeyResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Result != other.Result) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Result != 0) hash ^= Result.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Result != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Result);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Result != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RoomSvcIssueRoomKeyResponse other) {
if (other == null) {
return;
}
if (other.Result != 0) {
Result = other.Result;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
result_ = (global::HOLMS.Types.Operations.RPC.ROOM_SVC_ISSUE_ROOM_KEY_RESULT) input.ReadEnum();
break;
}
}
}
}
}
public sealed partial class RoomSvcGetHousekeepingRoomStatusResponse : pb::IMessage<RoomSvcGetHousekeepingRoomStatusResponse> {
private static readonly pb::MessageParser<RoomSvcGetHousekeepingRoomStatusResponse> _parser = new pb::MessageParser<RoomSvcGetHousekeepingRoomStatusResponse>(() => new RoomSvcGetHousekeepingRoomStatusResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RoomSvcGetHousekeepingRoomStatusResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.RPC.RoomSvcReflection.Descriptor.MessageTypes[8]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcGetHousekeepingRoomStatusResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcGetHousekeepingRoomStatusResponse(RoomSvcGetHousekeepingRoomStatusResponse other) : this() {
statuses_ = other.statuses_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomSvcGetHousekeepingRoomStatusResponse Clone() {
return new RoomSvcGetHousekeepingRoomStatusResponse(this);
}
/// <summary>Field number for the "statuses" field.</summary>
public const int StatusesFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Operations.Housekeeping.HousekeepingRoomStatus> _repeated_statuses_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Operations.Housekeeping.HousekeepingRoomStatus.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Operations.Housekeeping.HousekeepingRoomStatus> statuses_ = new pbc::RepeatedField<global::HOLMS.Types.Operations.Housekeeping.HousekeepingRoomStatus>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Operations.Housekeeping.HousekeepingRoomStatus> Statuses {
get { return statuses_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RoomSvcGetHousekeepingRoomStatusResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RoomSvcGetHousekeepingRoomStatusResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!statuses_.Equals(other.statuses_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= statuses_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
statuses_.WriteTo(output, _repeated_statuses_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += statuses_.CalculateSize(_repeated_statuses_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RoomSvcGetHousekeepingRoomStatusResponse other) {
if (other == null) {
return;
}
statuses_.Add(other.statuses_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
statuses_.AddEntriesFrom(input, _repeated_statuses_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.Messages;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs
{
/// <summary>
/// Packets for SmbTrans2CreateDirectoryFinal Request
/// </summary>
public class SmbTrans2CreateDirectoryRequestPacket : SmbTransaction2RequestPacket
{
#region Fields
private TRANS2_CREATE_DIRECTORY_Request_Trans2_Parameters trans2Parameters;
private TRANS2_CREATE_DIRECTORY_Request_Trans2_Data trans2Data;
/// <summary>
/// The size of Reserved field in trans2Parameters
/// </summary>
private const ushort reservedLength = 4;
/// <summary>
/// The size of SizeOfListInBytes field in trans2Data
/// </summary>
private const ushort sizeOfListInBytesLength = 4;
#endregion
#region Properties
/// <summary>
/// get or set the Trans2_Parameters:TRANS2_CREATE_DIRECTORY_Request_Trans2_Parameters
/// </summary>
public TRANS2_CREATE_DIRECTORY_Request_Trans2_Parameters Trans2Parameters
{
get
{
return this.trans2Parameters;
}
set
{
this.trans2Parameters = value;
}
}
/// <summary>
/// get or set the Trans2_Data:TRANS2_CREATE_DIRECTORY_Request_Trans2_Data
/// </summary>
public TRANS2_CREATE_DIRECTORY_Request_Trans2_Data Trans2Data
{
get
{
return this.trans2Data;
}
set
{
this.trans2Data = value;
}
}
/// <summary>
/// get the FID of Trans2_Parameters
/// </summary>
internal override ushort FID
{
get
{
return INVALID_FID;
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public SmbTrans2CreateDirectoryRequestPacket()
: base()
{
this.InitDefaultValue();
}
/// <summary>
/// Constructor: Create a request directly from a buffer.
/// </summary>
public SmbTrans2CreateDirectoryRequestPacket(byte[] data)
: base(data)
{
}
/// <summary>
/// Deep copy constructor.
/// </summary>
public SmbTrans2CreateDirectoryRequestPacket(SmbTrans2CreateDirectoryRequestPacket packet)
: base(packet)
{
this.InitDefaultValue();
this.trans2Parameters.Reserved = packet.trans2Parameters.Reserved;
this.trans2Parameters.DirectoryName = new byte[packet.trans2Parameters.DirectoryName.Length];
Array.Copy(packet.trans2Parameters.DirectoryName,
this.trans2Parameters.DirectoryName, packet.trans2Parameters.DirectoryName.Length);
this.trans2Data.ExtendedAttributeList.SizeOfListInBytes =
packet.trans2Data.ExtendedAttributeList.SizeOfListInBytes;
if (packet.trans2Data.ExtendedAttributeList.FEAList != null)
{
this.trans2Data.ExtendedAttributeList.FEAList =
new SMB_FEA[packet.trans2Data.ExtendedAttributeList.FEAList.Length];
Array.Copy(packet.trans2Data.ExtendedAttributeList.FEAList,
this.trans2Data.ExtendedAttributeList.FEAList,
packet.trans2Data.ExtendedAttributeList.FEAList.Length);
}
else
{
this.trans2Data.ExtendedAttributeList.FEAList = new SMB_FEA[0];
}
}
#endregion
#region override methods
/// <summary>
/// to create an instance of the StackPacket class that is identical to the current StackPacket.
/// </summary>
/// <returns>a new Packet cloned from this.</returns>
public override StackPacket Clone()
{
return new SmbTrans2CreateDirectoryRequestPacket(this);
}
/// <summary>
/// Encode the struct of Trans2Parameters into the byte array in SmbData.Trans2_Parameters
/// </summary>
protected override void EncodeTrans2Parameters()
{
int trans2ParametersCount = reservedLength;
if (this.trans2Parameters.DirectoryName != null)
{
trans2ParametersCount += this.trans2Parameters.DirectoryName.Length;
}
this.smbData.Trans2_Parameters = new byte[trans2ParametersCount];
using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Parameters))
{
using (Channel channel = new Channel(null, memoryStream))
{
channel.BeginWriteGroup();
channel.Write<uint>(this.trans2Parameters.Reserved);
if (this.trans2Parameters.DirectoryName != null)
{
channel.WriteBytes(this.trans2Parameters.DirectoryName);
}
channel.EndWriteGroup();
}
}
}
/// <summary>
/// Encode the struct of Trans2Data into the byte array in SmbData.Trans2_Data
/// </summary>
protected override void EncodeTrans2Data()
{
this.smbData.Trans2_Data = new byte[sizeOfListInBytesLength + CifsMessageUtils.GetSmbEAListSize(
this.trans2Data.ExtendedAttributeList.FEAList)];
using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data))
{
using (Channel channel = new Channel(null, memoryStream))
{
channel.BeginWriteGroup();
channel.Write<uint>(this.trans2Data.ExtendedAttributeList.SizeOfListInBytes);
if (this.trans2Data.ExtendedAttributeList.FEAList != null)
{
foreach (SMB_FEA smbEa in this.trans2Data.ExtendedAttributeList.FEAList)
{
channel.Write<byte>(smbEa.ExtendedAttributeFlag);
channel.Write<byte>(smbEa.AttributeNameLengthInBytes);
channel.Write<ushort>(smbEa.ValueNameLengthInBytes);
if (smbEa.AttributeName != null)
{
channel.WriteBytes(smbEa.AttributeName);
}
if (smbEa.ValueName != null)
{
channel.WriteBytes(smbEa.ValueName);
}
}
}
channel.EndWriteGroup();
}
}
}
/// <summary>
/// to decode the Trans2 parameters: from the general Trans2Parameters to the concrete Trans2 Parameters.
/// </summary>
protected override void DecodeTrans2Parameters()
{
if (this.smbData.Trans2_Parameters != null)
{
using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Parameters))
{
using (Channel channel = new Channel(null, memoryStream))
{
this.trans2Parameters.Reserved = channel.Read<uint>();
this.trans2Parameters.DirectoryName = channel.ReadBytes(this.smbParameters.ParameterCount
- reservedLength);
}
}
}
}
/// <summary>
/// to decode the Trans2 data: from the general Trans2Dada to the concrete Trans2 Data.
/// </summary>
protected override void DecodeTrans2Data()
{
using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data))
{
using (Channel channel = new Channel(null, memoryStream))
{
this.trans2Data.ExtendedAttributeList.SizeOfListInBytes = channel.Read<uint>();
uint sizeOfListInBytes =
this.trans2Data.ExtendedAttributeList.SizeOfListInBytes - sizeOfListInBytesLength;
List<SMB_FEA> attributeList = new List<SMB_FEA>();
while (sizeOfListInBytes > 0)
{
SMB_FEA smbEa = channel.Read<SMB_FEA>();
attributeList.Add(smbEa);
sizeOfListInBytes -= (uint)(EA.SMB_EA_FIXED_SIZE + smbEa.AttributeName.Length +
smbEa.ValueName.Length);
}
this.trans2Data.ExtendedAttributeList.FEAList = attributeList.ToArray();
}
}
}
#endregion
#region initialize fields with default value
/// <summary>
/// init packet, set default field data
/// </summary>
private void InitDefaultValue()
{
}
#endregion
}
}
| |
using SME;
using System;
using System.Threading.Tasks;
namespace StateMachineTester
{
public class EmptyStates : StateMachineTest
{
public EmptyStates()
{
go1s = new bool[] { };
go2s = new bool[] { };
values = new int[] { };
states = new int[] { 1, 1, 1, 2 };
}
protected async override Task OnTickAsync()
{
result.State = 1;
await ClockAsync();
await ClockAsync();
await ClockAsync();
result.State = 2;
}
}
public class NestedForLoop : StateMachineTest
{
public NestedForLoop()
{
go1s = new bool[] { };
go2s = new bool[] { };
values = new int[] { };
states = new int[] {
1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3,
1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3,
1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3,
1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3,
1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3,
4,
};
}
protected async override Task OnTickAsync()
{
result.State = 0;
for (var i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
result.State = 1;
await ClockAsync();
result.State = 2;
}
await ClockAsync();
for (int j = 0; j < 5; j++)
{
result.State = 3;
await ClockAsync();
result.State = 4;
}
}
}
}
public class NestedForWithinWhile : StateMachineTest
{
public NestedForWithinWhile()
{
go1s = new bool[] {
false,
true, true, true, true, true, true, true, true, true, true, true,
true, false
};
go2s = new bool[] { };
values = new int[] { };
states = new int[] {
7,
2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4,
2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4,
7, 7
};
}
protected async override Task OnTickAsync()
{
result.State = 0;
while (control.Go1)
{
result.State = 1;
for (int i = 0; i < 5; i++)
{
result.State = 2;
await ClockAsync();
result.State = 3;
}
await ClockAsync();
for (int i = 0; i < 5; i++)
{
result.State = 4;
await ClockAsync();
result.State = 5;
}
result.State = 6;
}
result.State = 7;
}
}
public class NestedIfElseStatement : StateMachineTest
{
public NestedIfElseStatement()
{
go1s = new bool[] { true, true, true, true, false, false, false, false };
go2s = new bool[] { true, true, false, false, true, true, false, false };
values = new int[] { };
states = new int[] { 2, 3, 4, 5, 7, 8, 9, 10 };
}
protected async override Task OnTickAsync()
{
result.State = 0;
if (control.Go1)
{
result.State = 1;
if (control.Go2)
{
result.State = 2;
await ClockAsync();
result.State = 3;
}
else
{
result.State = 4;
await ClockAsync();
result.State = 5;
}
}
else
{
result.State = 6;
if (control.Go2)
{
result.State = 7;
await ClockAsync();
result.State = 8;
}
else
{
result.State = 9;
await ClockAsync();
result.State = 10;
}
}
}
}
public class NestedIfStatement : StateMachineTest
{
public NestedIfStatement()
{
go1s = new bool[] { false, true, true, true, true, true };
go2s = new bool[] { false, false, false, true, true, true };
values = new int[] { };
states = new int[] { 6, 1, 6, 1, 3, 6 };
}
protected async override Task OnTickAsync()
{
result.State = 0;
if (control.Go1)
{
result.State = 1;
await ClockAsync();
result.State = 2;
if (control.Go2)
{
result.State = 3;
await ClockAsync();
result.State = 4;
}
result.State = 5;
}
result.State = 6;
}
}
public class NestedIfWithinWhile : StateMachineTest
{
public NestedIfWithinWhile()
{
go1s = new bool[] { false, true, true, true, true, false };
go2s = new bool[] { false, false, false, true, true, true };
values = new int[] { };
states = new int[] { 7, 4, 4, 2, 2, 7 };
}
protected async override Task OnTickAsync()
{
result.State = 0;
while (control.Go1)
{
result.State = 1;
if (control.Go2)
{
result.State = 2;
await ClockAsync();
result.State = 3;
}
else
{
result.State = 4;
await ClockAsync();
result.State = 5;
}
result.State = 6;
}
result.State = 7;
}
}
public class NestedSwitchStatement : StateMachineTest
{
public NestedSwitchStatement()
{
go1s = new bool[] { };
go2s = new bool[] { };
values = new int[] { 0, 0, 0, 0, 1, 1, 0, 2, 2, 1, 1, 2, 2 };
states = new int[] { 1, 3, 14, 1, 5, 14, 1, 7, 14, 10, 14, 12, 14 };
}
protected async override Task OnTickAsync()
{
result.State = 0;
switch (control.Value)
{
case 0:
result.State = 1;
await ClockAsync();
result.State = 2;
switch (control.Value)
{
case 0:
result.State = 3;
await ClockAsync();
result.State = 4;
break;
case 1:
result.State = 5;
await ClockAsync();
result.State = 6;
break;
default:
result.State = 7;
await ClockAsync();
result.State = 8;
break;
}
result.State = 9;
break;
case 1:
result.State = 10;
await ClockAsync();
result.State = 11;
break;
default:
result.State = 12;
await ClockAsync();
result.State = 13;
break;
}
result.State = 14;
}
}
public class NestedSwitchWithinWhile : StateMachineTest
{
public NestedSwitchWithinWhile()
{
go1s = new bool[] { false, true, true, true, true, false };
go2s = new bool[] { };
values = new int[] { 0, 0, 1, 2, 5, 5 };
states = new int[] { 9, 2, 4, 6, 6, 9 };
}
protected async override Task OnTickAsync()
{
result.State = 0;
while (control.Go1)
{
result.State = 1;
switch (control.Value)
{
case 0:
result.State = 2;
await ClockAsync();
result.State = 3;
break;
case 1:
result.State = 4;
await ClockAsync();
result.State = 5;
break;
default:
result.State = 6;
await ClockAsync();
result.State = 7;
break;
}
result.State = 8;
}
result.State = 9;
}
}
public class NestedWhileLoop : StateMachineTest
{
public NestedWhileLoop()
{
go1s = new bool[] { false, true, true, true, true, false, false, false, false, false };
go2s = new bool[] { false, false, false, true, true, true, false, false, true, false };
values = new int[] { };
states = new int[] { 7, 1, 4, 2, 2, 2, 3, 4, 7, 7 };
}
protected async override Task OnTickAsync()
{
result.State = 0;
while (control.Go1)
{
result.State = 1;
while (control.Go2)
{
result.State = 2;
await ClockAsync();
result.State = 3;
}
await ClockAsync();
while (!control.Go2)
{
result.State = 4;
await ClockAsync();
result.State = 5;
}
result.State = 6;
}
result.State = 7;
}
}
public class SingleForLoop : StateMachineTest
{
public SingleForLoop()
{
go1s = new bool[] { };
go2s = new bool[] { };
values = new int[] { };
states = new int[] { 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 3 };
}
protected async override Task OnTickAsync()
{
result.State = 0;
for (var i = 0; i < 5; i++)
{
result.State = 1;
await ClockAsync();
result.State = 2;
}
result.State = 3;
}
}
public class SingleIfElseStatement : StateMachineTest
{
public SingleIfElseStatement()
{
go1s = new bool[] { false, false, true, true, false, false };
go2s = new bool[] { };
values = new int[] { };
states = new int[] { 3, 5, 1, 5, 3, 5 };
}
protected async override Task OnTickAsync()
{
result.State = 0;
if (control.Go1)
{
result.State = 1;
await ClockAsync();
result.State = 2;
}
else
{
result.State = 3;
await ClockAsync();
result.State = 4;
}
result.State = 5;
}
}
public class SingleIfStatement : StateMachineTest
{
public SingleIfStatement()
{
go1s = new bool[] { false, true, false };
go2s = new bool[] { };
values = new int[] { };
states = new int[] { 3, 1, 3 };
}
protected async override Task OnTickAsync()
{
result.State = 0;
if (control.Go1)
{
result.State = 1;
await ClockAsync();
result.State = 2;
}
result.State = 3;
}
}
public class SingleSwitchStatement : StateMachineTest
{
public SingleSwitchStatement()
{
go1s = new bool[] { };
go2s = new bool[] { };
values = new int[] { 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5 };
states = new int[] { 0, 1, 9, 0, 3, 4, 9, 0, 6, 9, 0, 9, 0, 9 };
}
protected async override Task OnTickAsync()
{
result.State = 0;
await ClockAsync();
switch (control.Value)
{
case 0:
result.State = 1;
await ClockAsync();
result.State = 2;
break;
case 1:
result.State = 3;
await ClockAsync();
result.State = 4;
await ClockAsync();
result.State = 5;
break;
case 2:
result.State = 6;
await ClockAsync();
break;
case 3:
result.State = 7;
break;
default:
result.State = 8;
break;
}
result.State = 9;
}
}
public class SingleWhileLoop : StateMachineTest
{
public SingleWhileLoop()
{
go1s = new bool[] { false, true, true, true, false };
go2s = new bool[] { };
values = new int[] { };
states = new int[] { 3, 1, 1, 1, 3 };
}
protected async override Task OnTickAsync()
{
result.State = 0;
while (control.Go1)
{
result.State = 1;
await ClockAsync();
result.State = 2;
}
result.State = 3;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExpressRouteCircuitPeeringsOperations operations.
/// </summary>
internal partial class ExpressRouteCircuitPeeringsOperations : IServiceOperations<NetworkClient>, IExpressRouteCircuitPeeringsOperations
{
/// <summary>
/// Initializes a new instance of the ExpressRouteCircuitPeeringsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ExpressRouteCircuitPeeringsOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified peering from the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (peeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "peeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("peeringName", peeringName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{peeringName}", System.Uri.EscapeDataString(peeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitPeering>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a peering in the specified express route circuits.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ExpressRouteCircuitPeering> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, peeringParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified peering from the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (peeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "peeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("peeringName", peeringName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{peeringName}", System.Uri.EscapeDataString(peeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a peering in the specified express route circuits.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (peeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "peeringName");
}
if (peeringParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "peeringParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("peeringName", peeringName);
tracingParameters.Add("peeringParameters", peeringParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{peeringName}", System.Uri.EscapeDataString(peeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(peeringParameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(peeringParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitPeering>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
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;
//UPGRADE_WARNING: The entire project must be compiled once before a form with an ActiveX Control Array can be displayed
using System.ComponentModel;
namespace _4PosBackOffice.NET
{
[ProvideProperty("Index", typeof(System.Windows.Forms.MonthCalendar))]
public class AxMonthViewArray : Microsoft.VisualBasic.Compatibility.VB6.BaseOcxArray, IExtenderProvider
{
public AxMonthViewArray() : base()
{
}
public AxMonthViewArray(IContainer Container) : base(Container)
{
}
public new event DateClickEventHandler DateClick;
public new delegate void DateClickEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_DateClickEvent e);
public new event DateDblClickEventHandler DateDblClick;
public new delegate void DateDblClickEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_DateDblClickEvent e);
public new event GetDayBoldEventHandler GetDayBold;
public new delegate void GetDayBoldEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_GetDayBoldEvent e);
public new event SelChangeEventHandler SelChange;
public new delegate void SelChangeEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_SelChangeEvent e);
public new event ClickEventEventHandler ClickEvent;
public new delegate void ClickEventEventHandler(System.Object sender, System.EventArgs e);
public new event DblClickEventHandler DblClick;
public new delegate void DblClickEventHandler(System.Object sender, System.EventArgs e);
public new event KeyDownEventHandler KeyDown;
public new delegate void KeyDownEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_KeyDown e);
public new event KeyUpEventEventHandler KeyUpEvent;
public new delegate void KeyUpEventEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_KeyUpEvent e);
public new event KeyPressEventHandler KeyPress;
public new delegate void KeyPressEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_KeyPress e);
public new event MouseDownEventHandler MouseDown;
public new delegate void MouseDownEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_MouseDown e);
public new event MouseMoveEventEventHandler MouseMoveEvent;
public new delegate void MouseMoveEventEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_MouseMoveEvent e);
public new event MouseUpEventEventHandler MouseUpEvent;
public new delegate void MouseUpEventEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_MouseUpEvent e);
public new event OLEStartDragEventHandler OLEStartDrag;
public new delegate void OLEStartDragEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_OLEStartDragEvent e);
public new event OLEGiveFeedbackEventHandler OLEGiveFeedback;
public new delegate void OLEGiveFeedbackEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_OLEGiveFeedbackEvent e);
public new event OLESetDataEventHandler OLESetData;
public new delegate void OLESetDataEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_OLESetDataEvent e);
public new event OLECompleteDragEventHandler OLECompleteDrag;
public new delegate void OLECompleteDragEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_OLECompleteDragEvent e);
public new event OLEDragOverEventHandler OLEDragOver;
public new delegate void OLEDragOverEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_OLEDragOverEvent e);
public new event OLEDragDropEventHandler OLEDragDrop;
public new delegate void OLEDragDropEventHandler(System.Object sender, AxMSComCtl2.DMonthViewEvents_OLEDragDropEvent e);
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public bool CanExtend(object target)
{
if (target is System.Windows.Forms.MonthCalendar) {
return BaseCanExtend(target);
}
}
public short GetIndex(System.Windows.Forms.MonthCalendar o)
{
return BaseGetIndex(o);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void SetIndex(System.Windows.Forms.MonthCalendar o, short Index)
{
BaseSetIndex(o, Index);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public bool ShouldSerializeIndex(System.Windows.Forms.MonthCalendar o)
{
return BaseShouldSerializeIndex(o);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void ResetIndex(System.Windows.Forms.MonthCalendar o)
{
BaseResetIndex(o);
}
public System.Windows.Forms.MonthCalendar this[short Index] {
get { return (System.Windows.Forms.MonthCalendar)BaseGetItem(Index); }
}
protected override System.Type GetControlInstanceType()
{
return typeof(System.Windows.Forms.MonthCalendar);
}
protected override void HookUpControlEvents(object o)
{
System.Windows.Forms.MonthCalendar ctl = (System.Windows.Forms.MonthCalendar)o;
base.HookUpControlEvents(o);
if ((DateClickEvent != null)) {
ctl.DateClick += new AxMSComCtl2.DMonthViewEvents_DateClickEventHandler(HandleDateClick);
}
if ((DateDblClickEvent != null)) {
ctl.DateDblClick += new AxMSComCtl2.DMonthViewEvents_DateDblClickEventHandler(HandleDateDblClick);
}
if ((GetDayBoldEvent != null)) {
ctl.GetDayBold += new AxMSComCtl2.DMonthViewEvents_GetDayBoldEventHandler(HandleGetDayBold);
}
if ((SelChangeEvent != null)) {
ctl.SelChange += new AxMSComCtl2.DMonthViewEvents_SelChangeEventHandler(HandleSelChange);
}
if ((ClickEventEvent != null)) {
ctl.ClickEvent += new System.EventHandler(HandleClickEvent);
}
if ((DblClickEvent != null)) {
ctl.DblClick += new System.EventHandler(HandleDblClick);
}
if ((KeyDownEvent != null)) {
ctl.KeyDown += new AxMSComCtl2.DMonthViewEvents_KeyDownHandler(HandleKeyDown);
}
if ((KeyUpEventEvent != null)) {
ctl.KeyUpEvent += new AxMSComCtl2.DMonthViewEvents_KeyUpEventHandler(HandleKeyUpEvent);
}
if ((KeyPressEvent != null)) {
ctl.KeyPress += new AxMSComCtl2.DMonthViewEvents_KeyPressHandler(HandleKeyPress);
}
if ((MouseDownEvent != null)) {
ctl.MouseDown += new AxMSComCtl2.DMonthViewEvents_MouseDownHandler(HandleMouseDown);
}
if ((MouseMoveEventEvent != null)) {
ctl.MouseMoveEvent += new AxMSComCtl2.DMonthViewEvents_MouseMoveEventHandler(HandleMouseMoveEvent);
}
if ((MouseUpEventEvent != null)) {
ctl.MouseUpEvent += new AxMSComCtl2.DMonthViewEvents_MouseUpEventHandler(HandleMouseUpEvent);
}
if ((OLEStartDragEvent != null)) {
ctl.OLEStartDrag += new AxMSComCtl2.DMonthViewEvents_OLEStartDragEventHandler(HandleOLEStartDrag);
}
if ((OLEGiveFeedbackEvent != null)) {
ctl.OLEGiveFeedback += new AxMSComCtl2.DMonthViewEvents_OLEGiveFeedbackEventHandler(HandleOLEGiveFeedback);
}
if ((OLESetDataEvent != null)) {
ctl.OLESetData += new AxMSComCtl2.DMonthViewEvents_OLESetDataEventHandler(HandleOLESetData);
}
if ((OLECompleteDragEvent != null)) {
ctl.OLECompleteDrag += new AxMSComCtl2.DMonthViewEvents_OLECompleteDragEventHandler(HandleOLECompleteDrag);
}
if ((OLEDragOverEvent != null)) {
ctl.OLEDragOver += new AxMSComCtl2.DMonthViewEvents_OLEDragOverEventHandler(HandleOLEDragOver);
}
if ((OLEDragDropEvent != null)) {
ctl.OLEDragDrop += new AxMSComCtl2.DMonthViewEvents_OLEDragDropEventHandler(HandleOLEDragDrop);
}
}
private void HandleDateClick(System.Object sender, AxMSComCtl2.DMonthViewEvents_DateClickEvent e)
{
if (DateClick != null) {
DateClick(sender, e);
}
}
private void HandleDateDblClick(System.Object sender, AxMSComCtl2.DMonthViewEvents_DateDblClickEvent e)
{
if (DateDblClick != null) {
DateDblClick(sender, e);
}
}
private void HandleGetDayBold(System.Object sender, AxMSComCtl2.DMonthViewEvents_GetDayBoldEvent e)
{
if (GetDayBold != null) {
GetDayBold(sender, e);
}
}
private void HandleSelChange(System.Object sender, AxMSComCtl2.DMonthViewEvents_SelChangeEvent e)
{
if (SelChange != null) {
SelChange(sender, e);
}
}
private void HandleClickEvent(System.Object sender, System.EventArgs e)
{
if (ClickEvent != null) {
ClickEvent(sender, e);
}
}
private void HandleDblClick(System.Object sender, System.EventArgs e)
{
if (DblClick != null) {
DblClick(sender, e);
}
}
private void HandleKeyDown(System.Object sender, AxMSComCtl2.DMonthViewEvents_KeyDown e)
{
if (KeyDown != null) {
KeyDown(sender, e);
}
}
private void HandleKeyUpEvent(System.Object sender, AxMSComCtl2.DMonthViewEvents_KeyUpEvent e)
{
if (KeyUpEvent != null) {
KeyUpEvent(sender, e);
}
}
private void HandleKeyPress(System.Object sender, AxMSComCtl2.DMonthViewEvents_KeyPress e)
{
if (KeyPress != null) {
KeyPress(sender, e);
}
}
private void HandleMouseDown(System.Object sender, AxMSComCtl2.DMonthViewEvents_MouseDown e)
{
if (MouseDown != null) {
MouseDown(sender, e);
}
}
private void HandleMouseMoveEvent(System.Object sender, AxMSComCtl2.DMonthViewEvents_MouseMoveEvent e)
{
if (MouseMoveEvent != null) {
MouseMoveEvent(sender, e);
}
}
private void HandleMouseUpEvent(System.Object sender, AxMSComCtl2.DMonthViewEvents_MouseUpEvent e)
{
if (MouseUpEvent != null) {
MouseUpEvent(sender, e);
}
}
private void HandleOLEStartDrag(System.Object sender, AxMSComCtl2.DMonthViewEvents_OLEStartDragEvent e)
{
if (OLEStartDrag != null) {
OLEStartDrag(sender, e);
}
}
private void HandleOLEGiveFeedback(System.Object sender, AxMSComCtl2.DMonthViewEvents_OLEGiveFeedbackEvent e)
{
if (OLEGiveFeedback != null) {
OLEGiveFeedback(sender, e);
}
}
private void HandleOLESetData(System.Object sender, AxMSComCtl2.DMonthViewEvents_OLESetDataEvent e)
{
if (OLESetData != null) {
OLESetData(sender, e);
}
}
private void HandleOLECompleteDrag(System.Object sender, AxMSComCtl2.DMonthViewEvents_OLECompleteDragEvent e)
{
if (OLECompleteDrag != null) {
OLECompleteDrag(sender, e);
}
}
private void HandleOLEDragOver(System.Object sender, AxMSComCtl2.DMonthViewEvents_OLEDragOverEvent e)
{
if (OLEDragOver != null) {
OLEDragOver(sender, e);
}
}
private void HandleOLEDragDrop(System.Object sender, AxMSComCtl2.DMonthViewEvents_OLEDragDropEvent e)
{
if (OLEDragDrop != null) {
OLEDragDrop(sender, e);
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.Windows.Forms;
using System.Xml.Serialization;
using ScanMaster.Acquire.Plugin;
using ScanMaster.Acquire.Plugins;
using ScanMaster.GUI;
namespace ScanMaster
{
public delegate void TweakEventHandler(object sender, TweakEventArgs e);
/// <summary>
/// The profile manager stores and edits profiles. It owns a window and a command processor
/// and handles control flow between them.
/// </summary>
[Serializable]
public class ProfileManager
{
// when the profile manager is in tweak mode it will fire Tweak events
public event TweakEventHandler Tweak;
private ControllerWindow window;
public ControllerWindow Window
{
get { return window; }
set { window = value; }
}
private CommandProcessor processor;
public CommandProcessor Processor
{
get { return processor; }
}
private ArrayList profiles = new ArrayList();
public ArrayList Profiles
{
get { return profiles; }
set { profiles = value; }
}
private Profile currentProfile;
public Profile CurrentProfile
{
get { return currentProfile; }
set { currentProfile = value; }
}
public bool ProfilesChanged = false;
public void Start()
{
// stick in a dummy profiles for now
profiles.Add(new Profile());
processor = new CommandProcessor(this);
processor.Start();
window.UpdateUI();
}
public void Exit()
{
if (ProfilesChanged)
{
if (MessageBox.Show("Profile set has been modified. Save ?", "Save profiles", MessageBoxButtons.YesNo,
MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
Controller.GetController().SaveProfileSet();
}
}
}
public void LoadProfileSetFromSoap(FileStream stream)
{
// load the settings; soap format
SoapFormatter s = new SoapFormatter();
profiles = (ArrayList)s.Deserialize(stream);
currentProfile = null;
window.UpdateUI();
}
public void LoadProfileSetFromXml(FileStream stream)
{
// load the settings; xml format
XmlSerializer s = new XmlSerializer(typeof(ProfileSet));
ProfileSet ps = (ProfileSet)s.Deserialize(stream);
profiles = ps.Profiles;
currentProfile = null;
// Xml serialization cannot handle circular referencing, so each of the plugins need to be
// assigned their AquisitorConfigurations 'by hand'.
foreach(Profile p in profiles)
{
p.AcquisitorConfig.outputPlugin.Config = p.AcquisitorConfig;
p.AcquisitorConfig.switchPlugin.Config = p.AcquisitorConfig;
p.AcquisitorConfig.shotGathererPlugin.Config = p.AcquisitorConfig;
p.AcquisitorConfig.pgPlugin.Config = p.AcquisitorConfig;
p.AcquisitorConfig.yagPlugin.Config = p.AcquisitorConfig;
p.AcquisitorConfig.analogPlugin.Config = p.AcquisitorConfig;
p.AcquisitorConfig.gpibPlugin.Config = p.AcquisitorConfig;
}
window.UpdateUI();
}
public void SaveProfileSetAsSoap(FileStream stream)
{
//save the settings; soap format
SoapFormatter s = new SoapFormatter();
s.Serialize(stream, Profiles);
}
public void SaveProfileSetAsXml(FileStream stream)
{
// save the settings; xml format
XmlSerializer s = new XmlSerializer(typeof(ProfileSet));
ProfileSet ps = new ProfileSet();
ps.Profiles = this.Profiles;
s.Serialize(stream, ps);
}
public void AddNewProfile()
{
profiles.Add(new Profile());
ProfilesChanged = true;
}
public void DeleteProfile(int index)
{
profiles.RemoveAt(index);
ProfilesChanged = true;
}
public void SelectProfile(int index)
{
// no changing profiles while the thing is running - just too confusing !
if (Controller.GetController().appState == Controller.AppState.running) return;
currentProfile = (Profile)profiles[index];
window.WriteLine("Profile changed");
if (processor.groupEditMode)
{
window.WriteLine("Group changed to " + currentProfile.Group);
window.Prompt = currentProfile.Group + ":>";
}
window.UpdateUI();
}
public void SelectProfile(String profile)
{
int index = -1;
for (int i = 0 ; i < profiles.Count ; i++)
{
if (((Profile)profiles[i]).Name == profile) index = i;
}
if (index != -1) SelectProfile(index);
}
public void CloneProfile(int index)
{
profiles.Add(((Profile)profiles[index]).Clone());
ProfilesChanged = true;
}
public Profile GetCloneOfCurrentProfile()
{
return (Profile)currentProfile.Clone();
}
public ArrayList ProfilesInGroup(String group)
{
ArrayList groupProfiles = new ArrayList();
foreach (Profile p in profiles) if (p.Group == group) groupProfiles.Add(p);
return groupProfiles;
}
public void FireTweak(TweakEventArgs e)
{
OnTweak(e);
}
protected virtual void OnTweak( TweakEventArgs e )
{
if (Tweak != null) Tweak(this, e);
}
// When a new setting is introduced into a plugin, there needs to be a way to introduce it into existing
// profile sets. This is the code that does it.
// For each profile, p, a dummy profile, d, is created whose plugins are the same as those of p.
// Because d is constructed anew, all plugin settings will have their default values and any newly
// introduced settings will be present in d. Any settings that are in d, but not in p, are then copied over
// into p. This is done for all the profiles in the set.
public void UpdateProfiles()
{
Type pluginType;
System.Reflection.ConstructorInfo info;
Profile tempProfile = new Profile();
foreach (Profile prof in profiles)
{
// analog input plugin
pluginType = (Type)prof.AcquisitorConfig.analogPlugin.GetType();
info = pluginType.GetConstructor(new Type[] { });
tempProfile.AcquisitorConfig.analogPlugin = (AnalogInputPlugin)info.Invoke(new object[] { });
updateSettings(prof.AcquisitorConfig.analogPlugin.Settings, tempProfile.AcquisitorConfig.analogPlugin.Settings);
// scan output plugin
pluginType = (Type)prof.AcquisitorConfig.outputPlugin.GetType();
info = pluginType.GetConstructor(new Type[] { });
tempProfile.AcquisitorConfig.outputPlugin = (ScanOutputPlugin)info.Invoke(new object[] { });
updateSettings(prof.AcquisitorConfig.outputPlugin.Settings, tempProfile.AcquisitorConfig.outputPlugin.Settings);
// pattern plugin
pluginType = (Type)prof.AcquisitorConfig.pgPlugin.GetType();
info = pluginType.GetConstructor(new Type[] { });
tempProfile.AcquisitorConfig.pgPlugin = (PatternPlugin)info.Invoke(new object[] { });
updateSettings(prof.AcquisitorConfig.pgPlugin.Settings, tempProfile.AcquisitorConfig.pgPlugin.Settings);
// shot gatherer plugin
pluginType = (Type)prof.AcquisitorConfig.shotGathererPlugin.GetType();
info = pluginType.GetConstructor(new Type[] { });
tempProfile.AcquisitorConfig.shotGathererPlugin = (ShotGathererPlugin)info.Invoke(new object[] { });
updateSettings(prof.AcquisitorConfig.shotGathererPlugin.Settings, tempProfile.AcquisitorConfig.shotGathererPlugin.Settings);
// switch plugin
pluginType = (Type)prof.AcquisitorConfig.switchPlugin.GetType();
info = pluginType.GetConstructor(new Type[] { });
tempProfile.AcquisitorConfig.switchPlugin = (SwitchOutputPlugin)info.Invoke(new object[] { });
updateSettings(prof.AcquisitorConfig.switchPlugin.Settings, tempProfile.AcquisitorConfig.switchPlugin.Settings);
// yag plugin
pluginType = (Type)prof.AcquisitorConfig.yagPlugin.GetType();
info = pluginType.GetConstructor(new Type[] { });
tempProfile.AcquisitorConfig.yagPlugin = (YAGPlugin)info.Invoke(new object[] { });
updateSettings(prof.AcquisitorConfig.yagPlugin.Settings, tempProfile.AcquisitorConfig.yagPlugin.Settings);
}
}
// Supports the updateProfiles method
private void updateSettings(PluginSettings currentSettings, PluginSettings defaultSettings)
{
ICollection defaultKeys = defaultSettings.Keys;
String[] defaults = new String[defaultKeys.Count];
defaultKeys.CopyTo(defaults, 0);
foreach (String s in defaults)
if (currentSettings[s] == null) currentSettings[s] = defaultSettings[s];
}
}
public class TweakEventArgs : EventArgs
{
public String parameter;
public double newValue;
public TweakEventArgs( String parameter, int newValue)
{
this.parameter = parameter;
this.newValue = newValue;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C07_RegionColl (editable child list).<br/>
/// This is a generated base class of <see cref="C07_RegionColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="C06_Country"/> editable child object.<br/>
/// The items of the collection are <see cref="C08_Region"/> objects.
/// </remarks>
[Serializable]
public partial class C07_RegionColl : BusinessListBase<C07_RegionColl, C08_Region>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="C08_Region"/> item from the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to be removed.</param>
public void Remove(int region_ID)
{
foreach (var c08_Region in this)
{
if (c08_Region.Region_ID == region_ID)
{
Remove(c08_Region);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="C08_Region"/> item is in the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the C08_Region is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int region_ID)
{
foreach (var c08_Region in this)
{
if (c08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="C08_Region"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the C08_Region is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int region_ID)
{
foreach (var c08_Region in DeletedList)
{
if (c08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="C08_Region"/> item of the <see cref="C07_RegionColl"/> collection, based on a given Region_ID.
/// </summary>
/// <param name="region_ID">The Region_ID.</param>
/// <returns>A <see cref="C08_Region"/> object.</returns>
public C08_Region FindC08_RegionByRegion_ID(int region_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Region_ID.Equals(region_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C07_RegionColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="C07_RegionColl"/> collection.</returns>
internal static C07_RegionColl NewC07_RegionColl()
{
return DataPortal.CreateChild<C07_RegionColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="C07_RegionColl"/> collection, based on given parameters.
/// </summary>
/// <param name="parent_Country_ID">The Parent_Country_ID parameter of the C07_RegionColl to fetch.</param>
/// <returns>A reference to the fetched <see cref="C07_RegionColl"/> collection.</returns>
internal static C07_RegionColl GetC07_RegionColl(int parent_Country_ID)
{
return DataPortal.FetchChild<C07_RegionColl>(parent_Country_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C07_RegionColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public C07_RegionColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="C07_RegionColl"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="parent_Country_ID">The Parent Country ID.</param>
protected void Child_Fetch(int parent_Country_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetC07_RegionColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_Country_ID", parent_Country_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, parent_Country_ID);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
foreach (var item in this)
{
item.FetchChildren();
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="C07_RegionColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(C08_Region.GetC08_Region(dr));
}
RaiseListChangedEvents = rlce;
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Net;
using System.Net.Sockets;
using OpenNETCF.IO.Ports;
namespace OpenNETCF.IO.Ports.Streams
{
/// <summary>
/// This class is a wrapper on top of the NetworkStream.
/// Use it when serial port gets exposed as a network port
/// </summary>
public class SerialStreamSocket : NetworkStream, ISerialStreamCtrl
{
public class Consts
{
public const int FIONREAD = 0x4004667F;
}
/// <summary>
/// Checks if portName has the format of a networked serial port: "ip_address:port"
/// </summary>
/// <param name="portName"></param>
/// <returns></returns>
public static bool IsCompatible( string portName )
{
// quick and dirty way - must have 1 collon and 1 or more dots, and end in a digit
int collonInd = portName.IndexOf(':');
if( collonInd > 0 && collonInd < portName.Length &&
collonInd == portName.LastIndexOf(':') &&
portName.IndexOf('.') > 0 &&
Char.IsDigit( portName, portName.Length - 1 )
)
return true;
else
return false;
}
public static SerialStreamSocket CreateInstance( string portName )
{
if( portName == null )
throw new ArgumentNullException( "portName" );
string[] strParts = portName.Split( ':' );
if( strParts.Length != 2 )
throw new ArgumentException( "Invalid format", "portName" );
// Get port number
int port = int.Parse( strParts[1] );
// Get host related information.
IPHostEntry iphe = Dns.Resolve( strParts[0] );
// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception to be thrown if the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach( IPAddress ipad in iphe.AddressList )
{
IPEndPoint ipe = new IPEndPoint(ipad, port);
Socket socket = new Socket( ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp );
socket.Connect(ipe);
if( socket.Connected )
return new SerialStreamSocket( socket );
}
throw new ApplicationException( "Unable to connect" );
}
public SerialStreamSocket( Socket socket ) : base( socket )
{}
public int BaudRate
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool BreakState
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public int BytesToRead
{
get
{
// 0x4004667F
// IOVT T|vendor/addr fmly| code
// 0100 0|000 0000 0100 | 0110 0110 0111 1111
//
byte[] outValue = BitConverter.GetBytes(0); // (int)0 -> byte[4]
// Check how many bytes have been received.
base.Socket.IOControl(Consts.FIONREAD, null, outValue);
return (int)BitConverter.ToUInt32(outValue, 0);
}
}
public int BytesToWrite
{
get { return 0; } // always report as if everything has been transmitted
}
public bool CDHolding
{
get { throw new NotImplementedException(); }
}
public bool CtsHolding
{
get { throw new NotImplementedException(); }
}
public int DataBits
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool DiscardNull
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool DsrHolding
{
get { throw new NotImplementedException(); }
}
public bool DtrEnable
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public static string[] GetPortNames()
{
throw new NotImplementedException();
}
public Handshake Handshake
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool IsOpen
{
get { throw new NotImplementedException(); }
}
public Parity Parity
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public byte ParityReplace
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public int ReadBufferSize
{
get
{
return (int) base.Socket.GetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer );
}
set
{
base.Socket.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer,
value );
}
}
public int ReadTimeout
{
get
{
return (int) base.Socket.GetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout );
}
set
{
base.Socket.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout,
value );
}
}
public int ReceivedBytesThreshold
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool RtsEnable
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public StopBits StopBits
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public int WriteBufferSize
{
get
{
return (int) base.Socket.GetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.SendBuffer );
}
set
{
base.Socket.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.SendBuffer,
value );
}
}
public int WriteTimeout
{
get
{
return (int) base.Socket.GetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.SendTimeout );
}
set
{
base.Socket.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.SendTimeout,
value );
}
}
public event SerialErrorEventHandler ErrorEvent
{
add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }
}
public event SerialReceivedEventHandler ReceivedEvent
{
add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }
}
public event SerialPinChangedEventHandler PinChangedEvent
{
add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }
}
public void DiscardInBuffer()
{
throw new NotImplementedException();
}
public void DiscardOutBuffer()
{
throw new NotImplementedException();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
/// <summary>
/// StringBuilderAppend(String,Int32,Int32)
/// </summary>
public class StringBuilderAppend19
{
private const int c_MIN_STR_LENGTH = 8;
private const int c_MAX_STR_LENGTH = 256;
public static int Main()
{
StringBuilderAppend19 sbAppend19 = new StringBuilderAppend19();
TestLibrary.TestFramework.BeginTestCase("StringBuilderAppend19");
if (sbAppend19.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke Append method in the initial StringBuilder 1");
try
{
StringBuilder sb = new StringBuilder();
string strVal = null;
int startIndex = 0;
int count = 0;
sb = sb.Append(strVal, startIndex, count);
if (sb.ToString() != string.Empty)
{
TestLibrary.TestFramework.LogError("001", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke Append method in the initial StringBuilder 2");
try
{
StringBuilder sb = new StringBuilder();
string strVal = TestLibrary.Generator.GetString(-55, false,c_MIN_STR_LENGTH,c_MAX_STR_LENGTH);
int startIndex = 0;
int count = strVal.Length;
sb = sb.Append(strVal, startIndex, count);
if (sb.ToString() != strVal)
{
TestLibrary.TestFramework.LogError("003", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3:Invoke Append method in the initial StringBuilder 3");
try
{
string strSource = "formytest";
StringBuilder sb = new StringBuilder(strSource);
string strVal = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LENGTH, c_MAX_STR_LENGTH);
int startIndex = 0;
int count = strVal.Length;
sb = sb.Append(strVal, startIndex, count);
if (sb.ToString() != strSource + strVal)
{
TestLibrary.TestFramework.LogError("005", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4:Invoke Append method in the initial StringBuilder 4");
try
{
string strSource = null;
StringBuilder sb = new StringBuilder(strSource);
string strVal = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LENGTH, c_MAX_STR_LENGTH);
int startIndex = this.GetInt32(0, strVal.Length);
int count = strVal.Length - startIndex;
sb = sb.Append(strVal, startIndex, count);
if (sb.ToString() != strVal.Substring(startIndex,count))
{
TestLibrary.TestFramework.LogError("007", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1:The value of the string is null");
try
{
StringBuilder sb = new StringBuilder();
string strVal = null;
int startIndex = 1;
int count = 1;
sb = sb.Append(strVal, startIndex, count);
TestLibrary.TestFramework.LogError("N001", "The value of the string is null but not throw exception");
retVal = false;
}
catch (ArgumentNullException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2:The count is less than zero");
try
{
StringBuilder sb = new StringBuilder();
string strVal = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LENGTH,c_MAX_STR_LENGTH);
int startIndex = 0;
int count = this.GetInt32(1, Int32.MaxValue) * (-1);
sb = sb.Append(strVal, startIndex, count);
TestLibrary.TestFramework.LogError("N003", "The count is less than zero but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3:The startIndex is less than zero");
try
{
StringBuilder sb = new StringBuilder();
string strVal = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LENGTH, c_MAX_STR_LENGTH);
int startIndex = this.GetInt32(1, 10) * (-1);
int count = strVal.Length;
sb = sb.Append(strVal, startIndex, count);
TestLibrary.TestFramework.LogError("N005", "The startIndex is less than zero but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4:The startIndex plus charCount is larger than char array length");
try
{
StringBuilder sb = new StringBuilder();
string strVal = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LENGTH, c_MAX_STR_LENGTH);
int startIndex = 0;
int count = strVal.Length + 1;
sb = sb.Append(strVal, startIndex, count);
TestLibrary.TestFramework.LogError("N007", "The startIndex plus charCount is larger than char array length but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region HelpMethod
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
/*
* 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.
*/
// ReSharper disable UnusedVariable
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace Apache.Ignite.Core.Tests
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Portable;
using Apache.Ignite.Core.Resource;
using Apache.Ignite.Core.Tests.Process;
using Microsoft.CSharp;
using NUnit.Framework;
/// <summary>
/// Tests for executable.
/// </summary>
[Ignore("IGNITE-1367")]
public class ExecutableTest
{
/** Spring configuration path. */
private static readonly string SpringCfgPath = "config\\compute\\compute-standalone.xml";
/** Min memory Java task. */
private const string MinMemTask = "org.apache.ignite.platform.PlatformMinMemoryTask";
/** Max memory Java task. */
private const string MaxMemTask = "org.apache.ignite.platform.PlatformMaxMemoryTask";
/** Grid. */
private IIgnite _grid;
/// <summary>
/// Test fixture set-up routine.
/// </summary>
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
TestUtils.KillProcesses();
_grid = Ignition.Start(Configuration(SpringCfgPath));
}
/// <summary>
/// Test fixture tear-down routine.
/// </summary>
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
Ignition.StopAll(true);
TestUtils.KillProcesses();
}
/// <summary>
/// Set-up routine.
/// </summary>
[SetUp]
public void SetUp()
{
TestUtils.KillProcesses();
Assert.IsTrue(_grid.WaitTopology(1, 30000));
IgniteProcess.SaveConfigurationBackup();
}
/// <summary>
/// Tear-down routine.
/// </summary>
[TearDown]
public void TearDown()
{
IgniteProcess.RestoreConfigurationBackup();
}
/// <summary>
/// Test data pass through configuration file.
/// </summary>
[Test]
public void TestConfig()
{
IgniteProcess.ReplaceConfiguration("config\\Ignite.exe.config.test");
GenerateDll("test-1.dll");
GenerateDll("test-2.dll");
IgniteProcess proc = new IgniteProcess(
"-jvmClasspath=" + TestUtils.CreateTestClasspath()
);
Assert.IsTrue(_grid.WaitTopology(2, 30000));
RemoteConfiguration cfg = RemoteConfig();
Assert.AreEqual(SpringCfgPath, cfg.SpringConfigUrl);
Assert.IsTrue(cfg.JvmOptions.Contains("-DOPT1") && cfg.JvmOptions.Contains("-DOPT2"));
Assert.IsTrue(cfg.Assemblies.Contains("test-1.dll") && cfg.Assemblies.Contains("test-2.dll"));
Assert.AreEqual(601, cfg.JvmInitialMemoryMb);
Assert.AreEqual(702, cfg.JvmMaxMemoryMb);
}
/// <summary>
/// Test assemblies passing through command-line.
/// </summary>
[Test]
public void TestAssemblyCmd()
{
GenerateDll("test-1.dll");
GenerateDll("test-2.dll");
IgniteProcess proc = new IgniteProcess(
"-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-springConfigUrl=" + SpringCfgPath,
"-assembly=test-1.dll",
"-assembly=test-2.dll"
);
Assert.IsTrue(_grid.WaitTopology(2, 30000));
RemoteConfiguration cfg = RemoteConfig();
Assert.IsTrue(cfg.Assemblies.Contains("test-1.dll") && cfg.Assemblies.Contains("test-2.dll"));
}
/// <summary>
/// Test JVM options passing through command-line.
/// </summary>
[Test]
public void TestJvmOptsCmd()
{
IgniteProcess proc = new IgniteProcess(
"-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-springConfigUrl=" + SpringCfgPath,
"-J-DOPT1",
"-J-DOPT2"
);
Assert.IsTrue(_grid.WaitTopology(2, 30000));
RemoteConfiguration cfg = RemoteConfig();
Assert.IsTrue(cfg.JvmOptions.Contains("-DOPT1") && cfg.JvmOptions.Contains("-DOPT2"));
}
/// <summary>
/// Test JVM memory options passing through command-line: raw java options.
/// </summary>
[Test]
public void TestJvmMemoryOptsCmdRaw()
{
var proc = new IgniteProcess(
"-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-springConfigUrl=" + SpringCfgPath,
"-J-Xms506m",
"-J-Xmx607m"
);
Assert.IsTrue(_grid.WaitTopology(2, 30000));
var minMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 506*1024*1024, minMem);
var maxMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 607*1024*1024, maxMem);
}
/// <summary>
/// Test JVM memory options passing through command-line: custom options.
/// </summary>
[Test]
public void TestJvmMemoryOptsCmdCustom()
{
var proc = new IgniteProcess(
"-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-springConfigUrl=" + SpringCfgPath,
"-JvmInitialMemoryMB=615",
"-JvmMaxMemoryMB=863"
);
Assert.IsTrue(_grid.WaitTopology(2, 30000));
var minMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 615*1024*1024, minMem);
var maxMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 863*1024*1024, maxMem);
}
/// <summary>
/// Test JVM memory options passing from application configuration.
/// </summary>
[Test]
public void TestJvmMemoryOptsAppConfig()
{
IgniteProcess.ReplaceConfiguration("config\\Ignite.exe.config.test");
GenerateDll("test-1.dll");
GenerateDll("test-2.dll");
var proc = new IgniteProcess("-jvmClasspath=" + TestUtils.CreateTestClasspath());
Assert.IsTrue(_grid.WaitTopology(2, 30000));
var minMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 601*1024*1024, minMem);
var maxMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 702*1024*1024, maxMem);
proc.Kill();
Assert.IsTrue(_grid.WaitTopology(1, 30000));
// Command line options overwrite config file options
// ReSharper disable once RedundantAssignment
proc = new IgniteProcess("-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-J-Xms605m", "-J-Xmx706m");
Assert.IsTrue(_grid.WaitTopology(2, 30000));
minMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 605*1024*1024, minMem);
maxMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 706*1024*1024, maxMem);
}
/// <summary>
/// Test JVM memory options passing through command-line: custom options + raw options.
/// </summary>
[Test]
public void TestJvmMemoryOptsCmdCombined()
{
var proc = new IgniteProcess(
"-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-springConfigUrl=" + SpringCfgPath,
"-J-Xms555m",
"-J-Xmx666m",
"-JvmInitialMemoryMB=128",
"-JvmMaxMemoryMB=256"
);
Assert.IsTrue(_grid.WaitTopology(2, 30000));
// Raw JVM options (Xms/Xmx) should override custom options
var minMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 555*1024*1024, minMem);
var maxMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 666*1024*1024, maxMem);
}
/// <summary>
/// Get remote node configuration.
/// </summary>
/// <returns>Configuration.</returns>
private RemoteConfiguration RemoteConfig()
{
return _grid.Cluster.ForRemotes().Compute().Call(new RemoteConfigurationClosure());
}
/// <summary>
/// Configuration for node.
/// </summary>
/// <param name="path">Path to Java XML configuration.</param>
/// <returns>Node configuration.</returns>
private static IgniteConfiguration Configuration(string path)
{
IgniteConfiguration cfg = new IgniteConfiguration();
PortableConfiguration portCfg = new PortableConfiguration();
ICollection<PortableTypeConfiguration> portTypeCfgs = new List<PortableTypeConfiguration>();
portTypeCfgs.Add(new PortableTypeConfiguration(typeof (RemoteConfiguration)));
portTypeCfgs.Add(new PortableTypeConfiguration(typeof (RemoteConfigurationClosure)));
portCfg.TypeConfigurations = portTypeCfgs;
cfg.PortableConfiguration = portCfg;
cfg.JvmClasspath = TestUtils.CreateTestClasspath();
cfg.JvmOptions = new List<string>
{
"-ea",
"-Xcheck:jni",
"-Xms4g",
"-Xmx4g",
"-DGRIDGAIN_QUIET=false",
"-Xnoagent",
"-Djava.compiler=NONE",
"-Xdebug",
"-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005",
"-XX:+HeapDumpOnOutOfMemoryError"
};
cfg.SpringConfigUrl = path;
return cfg;
}
/// <summary>
///
/// </summary>
/// <param name="outputPath"></param>
private static void GenerateDll(string outputPath)
{
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
#pragma warning disable 0618
ICodeCompiler icc = codeProvider.CreateCompiler();
#pragma warning restore 0618
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = outputPath;
string src = "namespace GridGain.Client.Test { public class Foo {}}";
CompilerResults results = icc.CompileAssemblyFromSource(parameters, src);
Assert.False(results.Errors.HasErrors);
}
/// <summary>
/// Asserts that JVM maximum memory corresponds to Xmx parameter value.
/// </summary>
private static void AssertJvmMaxMemory(long expected, long actual)
{
// allow 20% tolerance because max memory in Java is not exactly equal to Xmx parameter value
Assert.LessOrEqual(actual, expected);
Assert.Greater(actual, expected/5*4);
}
/// <summary>
/// Closure which extracts configuration and passes it back.
/// </summary>
public class RemoteConfigurationClosure : IComputeFunc<RemoteConfiguration>
{
#pragma warning disable 0649
/** Grid. */
[InstanceResource] private IIgnite _grid;
#pragma warning restore 0649
/** <inheritDoc /> */
public RemoteConfiguration Invoke()
{
Ignite grid0 = (Ignite) ((IgniteProxy) _grid).Target;
IgniteConfiguration cfg = grid0.Configuration;
RemoteConfiguration res = new RemoteConfiguration
{
IgniteHome = cfg.IgniteHome,
SpringConfigUrl = cfg.SpringConfigUrl,
JvmDll = cfg.JvmDllPath,
JvmClasspath = cfg.JvmClasspath,
JvmOptions = cfg.JvmOptions,
Assemblies = cfg.Assemblies,
JvmInitialMemoryMb = cfg.JvmInitialMemoryMb,
JvmMaxMemoryMb = cfg.JvmMaxMemoryMb
};
Console.WriteLine("RETURNING CFG: " + cfg);
return res;
}
}
/// <summary>
/// Configuration.
/// </summary>
public class RemoteConfiguration
{
/// <summary>
/// GG home.
/// </summary>
public string IgniteHome { get; set; }
/// <summary>
/// Spring config URL.
/// </summary>
public string SpringConfigUrl { get; set; }
/// <summary>
/// JVM DLL.
/// </summary>
public string JvmDll { get; set; }
/// <summary>
/// JVM classpath.
/// </summary>
public string JvmClasspath { get; set; }
/// <summary>
/// JVM options.
/// </summary>
public ICollection<string> JvmOptions { get; set; }
/// <summary>
/// Assemblies.
/// </summary>
public ICollection<string> Assemblies { get; set; }
/// <summary>
/// Minimum JVM memory (Xms).
/// </summary>
public int JvmInitialMemoryMb { get; set; }
/// <summary>
/// Maximum JVM memory (Xms).
/// </summary>
public int JvmMaxMemoryMb { get; set; }
}
}
}
| |
using System;
using System.Diagnostics;
namespace OTFontFile
{
/// <summary>
/// Summary description for Table_LTSH.
/// </summary>
public class Table_LTSH : OTTable
{
/************************
* constructors
*/
public Table_LTSH(OTTag tag, MBOBuffer buf) : base(tag, buf)
{
}
/************************
* field offset values
*/
public enum FieldOffsets
{
version = 0,
numGlyphs = 2,
yPels = 4
}
/************************
* accessors
*/
public ushort version
{
get {return m_bufTable.GetUshort((uint)FieldOffsets.version);}
}
public ushort numGlyphs
{
get {return m_bufTable.GetUshort((uint)FieldOffsets.numGlyphs);}
}
public byte GetYPel(uint iGlyph)
{
return m_bufTable.GetByte((uint)FieldOffsets.yPels + iGlyph);
}
/************************
* DataCache class
*/
public override DataCache GetCache()
{
if (m_cache == null)
{
m_cache = new LTSH_cache(this);
}
return m_cache;
}
public class LTSH_cache : DataCache
{
protected ushort m_version;
protected ushort m_numGlyphs;
protected byte[] m_yPels;
// constructor
public LTSH_cache(Table_LTSH OwnerTable)
{
m_version = OwnerTable.version;
m_numGlyphs = OwnerTable.numGlyphs;
m_yPels = new byte[m_numGlyphs];
for( ushort i = 0; i < m_numGlyphs; i++ )
{
m_yPels[i] = OwnerTable.GetYPel( i );
}
}
public ushort version
{
get {return m_version;}
set
{
m_version = value;
m_bDirty = true;
}
}
// NOTE: I am not sure we should allow this to be set here
// this is already set when a yPel of a glyph is removed or added
public ushort numGlyphs
{
get {return m_numGlyphs;}
set
{
m_numGlyphs = value;
m_bDirty = true;
}
}
// Just as you would expect this returns a requested yPel
public byte GetYPel( ushort nIndex )
{
byte nYPel;
if( nIndex < m_numGlyphs )
{
nYPel = m_yPels[nIndex];
}
else
{
throw new ArgumentOutOfRangeException("Tried to access a yPel that did not exist.");
}
return nYPel;
}
// Sets a yPel
public bool SetYPel( ushort nIndex, byte nYPel )
{
bool bResult = true;
if( nIndex < m_numGlyphs )
{
m_yPels[nIndex] = nYPel;
}
else
{
throw new ArgumentOutOfRangeException("Tried to access a yPel that did not exist.");
}
return bResult;
}
// NOTE: not sure if the application might need to add past numGlyphs + 1
public bool addYPel( ushort nIndex, byte nYPel )
{
bool bResult = true;
if( nIndex <= m_numGlyphs )
{
// NOTE: Table maxp numGlyphs isn't being dynamically updated
m_numGlyphs++;
byte[] updatedYPels = new byte[m_numGlyphs];
for( ushort i = 0, n = 0; i < m_numGlyphs; i++, n++ )
{
if( i != nIndex )
{
updatedYPels[i]= m_yPels[n];
}
else
{
updatedYPels[i] = nYPel;
i++;
}
}
m_yPels = updatedYPels;
m_bDirty = true;
}
else
{
bResult = false;
throw new ArgumentOutOfRangeException("Tried to add a yPel to a position greater than the number of Glyphs + 1.");
}
return bResult;
}
// Pulls out a Vertical Matric and updates vhea if necessary
public bool removeYPel( ushort nIndex )
{
bool bResult = true;
if( nIndex < m_numGlyphs )
{
// NOTE: Table maxp numGlyphs isn't being dynamically updated
m_numGlyphs--;
byte[] updatedYPels = new byte[m_numGlyphs];
for( ushort i = 0, n = 0; i < m_numGlyphs; i++, n++ )
{
if( n != nIndex )
{
updatedYPels[i] = m_yPels[n];
}
else
{
n++;
}
}
m_yPels = updatedYPels;
m_bDirty = true;
}
else
{
bResult = false;
throw new ArgumentOutOfRangeException("Tried to remove a yPel that did not exist.");
}
return bResult;
}
public override OTTable GenerateTable()
{
// create a Motorola Byte Order buffer for the new table
MBOBuffer newbuf = new MBOBuffer((uint)(Table_LTSH.FieldOffsets.yPels + m_numGlyphs));
newbuf.SetUshort( m_version, (uint)Table_LTSH.FieldOffsets.version);
newbuf.SetUshort( m_numGlyphs, (uint)Table_LTSH.FieldOffsets.numGlyphs);
// Fill the buffer with the yPels
for( int i = 0; i < m_numGlyphs; i++ )
{
newbuf.SetByte( m_yPels[i], (uint)(Table_LTSH.FieldOffsets.yPels + i));
}
// put the buffer into a Table_maxp object and return it
Table_LTSH LTSHTable = new Table_LTSH("LTSH", newbuf);
return LTSHTable;
}
}
}
}
| |
using System;
using Eto.Forms;
namespace Eto.GtkSharp.Forms.Controls
{
public class SplitterHandler : GtkContainer<Gtk.Paned, Splitter, Splitter.ICallback>, Splitter.IHandler
{
readonly Gtk.EventBox container;
Control panel1;
Control panel2;
Orientation orientation;
SplitterFixedPanel fixedPanel;
int? position;
double relative = double.NaN;
int suppressSplitterMoved;
int GetPreferredPanelSize(int width1, int width2)
{
if (position.HasValue)
width1 = position.Value;
else
{
if (!double.IsNaN(relative))
{
if (fixedPanel == SplitterFixedPanel.Panel1)
width1 = (int)Math.Round(relative);
else if (fixedPanel == SplitterFixedPanel.Panel2)
width2 = (int)Math.Round(relative);
else if (relative <= 0.0)
width1 = 0;
else if (relative >= 1.0)
width2 = 0;
else
{
// both get at least the preferred size
return (int)Math.Round(Math.Max(
width1 / relative, width2 / (1 - relative)));
}
}
}
return width1 + width2 + SplitterWidth;
}
class EtoHPaned : Gtk.HPaned
{
public SplitterHandler Handler { get; set; }
#if GTK2
protected override void OnSizeRequested(ref Gtk.Requisition requisition)
{
var size1 = Child1.SizeRequest();
var size2 = Child2.SizeRequest();
requisition.Height = Math.Max(size1.Height, size2.Height);
requisition.Width = Handler.GetPreferredPanelSize(size1.Width, size2.Width);
}
#else
protected override void OnGetPreferredHeightForWidth(int width, out int minimum_height, out int natural_height)
{
base.OnGetPreferredHeightForWidth(width, out minimum_height, out natural_height);
minimum_height = 0;
}
protected override void OnGetPreferredWidth(out int minimum_width, out int natural_width)
{
int min1, width1, min2, width2, sw = Handler.SplitterWidth;
Child1.GetPreferredWidth(out min1, out width1);
Child2.GetPreferredWidth(out min2, out width2);
minimum_width = Handler.GetPreferredPanelSize(min1, min2);
natural_width = Handler.GetPreferredPanelSize(width1, width2);
}
protected override void OnGetPreferredWidthForHeight(int height, out int minimum_width, out int natural_width)
{
int min1, width1, min2, width2, sw = Handler.SplitterWidth;
Child1.GetPreferredWidthForHeight(height, out min1, out width1);
Child2.GetPreferredWidthForHeight(height, out min2, out width2);
minimum_width = Handler.GetPreferredPanelSize(min1, min2);
natural_width = Handler.GetPreferredPanelSize(width1, width2);
}
#endif
protected override void OnSizeAllocated(Gdk.Rectangle allocation)
{
var it = Handler;
if (it == null || double.IsNaN(it.relative))
{
base.OnSizeAllocated(allocation);
return;
}
it.suppressSplitterMoved++;
base.OnSizeAllocated(allocation);
it.SetRelative(it.relative);
it.suppressSplitterMoved--;
}
}
class EtoVPaned : Gtk.VPaned
{
public SplitterHandler Handler { get; set; }
#if GTK2
protected override void OnSizeRequested(ref Gtk.Requisition requisition)
{
var size1 = Child1.SizeRequest();
var size2 = Child2.SizeRequest();
requisition.Width = Math.Max(size1.Width, size2.Width);
requisition.Height = Handler.GetPreferredPanelSize(size1.Height, size2.Height);
}
#else
protected override void OnGetPreferredWidthForHeight(int height, out int minimum_width, out int natural_width)
{
base.OnGetPreferredWidthForHeight(height, out minimum_width, out natural_width);
minimum_width = 0;
}
protected override void OnGetPreferredHeight(out int minimum_height, out int natural_height)
{
int min1, height1, min2, height2, sw = Handler.SplitterWidth;
Child1.GetPreferredHeight(out min1, out height1);
Child2.GetPreferredHeight(out min2, out height2);
minimum_height = Handler.GetPreferredPanelSize(min1, min2);
natural_height = Handler.GetPreferredPanelSize(height1, height2);
}
protected override void OnGetPreferredHeightForWidth(int width, out int minimum_height, out int natural_height)
{
int min1, height1, min2, height2, sw = Handler.SplitterWidth;
Child1.GetPreferredHeightForWidth(width, out min1, out height1);
Child2.GetPreferredHeightForWidth(width, out min2, out height2);
minimum_height = Handler.GetPreferredPanelSize(min1, min2);
natural_height = Handler.GetPreferredPanelSize(height1, height2);
}
#endif
protected override void OnSizeAllocated(Gdk.Rectangle allocation)
{
var it = Handler;
if (it == null || double.IsNaN(it.relative))
{
base.OnSizeAllocated(allocation);
return;
}
it.suppressSplitterMoved++;
base.OnSizeAllocated(allocation);
it.SetRelative(it.relative);
it.suppressSplitterMoved--;
}
}
public override Gtk.Widget ContainerControl
{
get { return container; }
}
public SplitterHandler()
{
container = new Gtk.EventBox();
Create();
}
public int Position
{
get { return Control.Position; }
set
{
if (value != position)
{
position = value;
relative = double.NaN;
if (Control.IsRealized)
SetPosition(value);
}
}
}
public int SplitterWidth
{
get { return Control.StyleGetProperty("handle-size") as int? ?? 5; }
set { /* not implemented */ }
}
int GetAvailableSize()
{
return GetAvailableSize(!Control.IsRealized);
}
int GetAvailableSize(bool desired)
{
if (desired)
{
var size = PreferredSize;
var pick = Orientation == Orientation.Horizontal ?
size.Width : size.Height;
if (pick >= 0)
return pick - SplitterWidth;
}
return (Orientation == Orientation.Horizontal ?
Control.Allocation.Width : Control.Allocation.Height) - SplitterWidth;
}
void UpdateRelative()
{
var pos = Position;
if (fixedPanel == SplitterFixedPanel.Panel1)
relative = pos;
else
{
var sz = GetAvailableSize();
if (fixedPanel == SplitterFixedPanel.Panel2)
relative = sz <= 0 ? 0 : sz - pos;
else
relative = sz <= 0 ? 0.5 : pos / (double)sz;
}
}
public double RelativePosition
{
get
{
if (double.IsNaN(relative))
UpdateRelative();
return relative;
}
set
{
if (relative == value)
return;
relative = value;
position = null;
if (Control.IsRealized)
SetRelative(value);
Callback.OnPositionChanged(Widget, EventArgs.Empty);
}
}
void SetPosition(int newPosition)
{
position = null;
var size = GetAvailableSize();
relative = fixedPanel == SplitterFixedPanel.Panel1 ? Math.Max(0, newPosition)
: fixedPanel == SplitterFixedPanel.Panel2 ? Math.Max(0, size - newPosition)
: size <= 0 ? 0.5 : Math.Max(0.0, Math.Min(1.0, newPosition / (double)size));
Control.Position = newPosition;
}
void SetRelative(double newRelative)
{
position = null;
relative = newRelative;
var size = GetAvailableSize();
if (size <= 0)
return;
switch (fixedPanel)
{
case SplitterFixedPanel.Panel1:
Control.Position = Math.Max(0, Math.Min(size, (int)Math.Round(relative)));
break;
case SplitterFixedPanel.Panel2:
Control.Position = Math.Max(0, Math.Min(size, size - (int)Math.Round(relative)));
break;
case SplitterFixedPanel.None:
Control.Position = Math.Max(0, Math.Min(size, (int)Math.Round(size * relative)));
break;
}
}
public SplitterFixedPanel FixedPanel
{
get { return fixedPanel; }
set
{
if (fixedPanel != value)
{
fixedPanel = value;
((Gtk.Paned.PanedChild)Control[Control.Child1]).Resize = value != SplitterFixedPanel.Panel1;
((Gtk.Paned.PanedChild)Control[Control.Child2]).Resize = value != SplitterFixedPanel.Panel2;
}
}
}
public Orientation Orientation
{
get { return (Control is Gtk.HPaned) ? Orientation.Horizontal : Orientation.Vertical; }
set
{
if (orientation != value)
{
orientation = value;
Create();
}
}
}
void Create()
{
Gtk.Paned old = Control;
if (orientation == Orientation.Horizontal)
Control = new EtoHPaned() { Handler = this };
else
Control = new EtoVPaned() { Handler = this };
if (container.Child != null)
container.Remove(container.Child);
container.Child = Control;
if (old != null)
{
var child1 = old.Child1;
var child2 = old.Child2;
old.Remove(child2);
old.Remove(child1);
Control.Pack1(child1 ?? EmptyContainer(), fixedPanel != SplitterFixedPanel.Panel1, true);
Control.Pack2(child2 ?? EmptyContainer(), fixedPanel != SplitterFixedPanel.Panel2, true);
old.Destroy();
}
else
{
Control.Pack1(EmptyContainer(), fixedPanel != SplitterFixedPanel.Panel1, true);
Control.Pack2(EmptyContainer(), fixedPanel != SplitterFixedPanel.Panel2, true);
}
Control.Realized += (sender, e) =>
{
SetInitialPosition();
HookEvents();
};
}
void HookEvents()
{
Control.AddNotification("position", (o, args) =>
{
if (Widget.ParentWindow == null || !Widget.Loaded || suppressSplitterMoved > 0)
return;
// keep track of the desired position (for removing/re-adding/resizing the control)
UpdateRelative();
Callback.OnPositionChanged(Widget, EventArgs.Empty);
});
}
public override void AttachEvent(string id)
{
switch (id)
{
case Splitter.PositionChangedEvent:
break;
default:
base.AttachEvent(id);
break;
}
}
public override void OnLoad(EventArgs e)
{
base.OnLoad(e);
suppressSplitterMoved++;
if (Control.IsRealized)
SetInitialPosition();
}
public override void OnLoadComplete(EventArgs e)
{
base.OnLoadComplete(e);
suppressSplitterMoved--;
}
void SetInitialPosition()
{
suppressSplitterMoved++;
try
{
if (position != null)
{
var pos = position.Value;
if (fixedPanel != SplitterFixedPanel.Panel1)
{
var size = GetAvailableSize(false);
var want = GetAvailableSize(true);
if (size != want)
{
if (FixedPanel == SplitterFixedPanel.Panel2)
pos += size - want;
else
{
SetRelative(pos / (double)want);
return;
}
}
}
SetPosition(pos);
}
else if (!double.IsNaN(relative))
{
SetRelative(relative);
}
else if (fixedPanel == SplitterFixedPanel.Panel1)
{
var size1 = Control.Child1.GetPreferredSize();
SetRelative(Orientation == Orientation.Horizontal ? size1.Width : size1.Height);
}
else if (fixedPanel == SplitterFixedPanel.Panel2)
{
var size2 = Control.Child2.GetPreferredSize();
SetRelative(Orientation == Orientation.Horizontal ? size2.Width : size2.Height);
}
else
{
var size1 = Control.Child1.GetPreferredSize();
var size2 = Control.Child2.GetPreferredSize();
SetRelative(Orientation == Orientation.Horizontal
? size1.Width / (double)(size1.Width + size2.Width)
: size1.Height / (double)(size1.Height + size2.Height));
}
}
finally
{
suppressSplitterMoved--;
}
}
static Gtk.Widget EmptyContainer()
{
var bin = new Gtk.VBox();
return bin;
}
public Control Panel1
{
get { return panel1; }
set
{
panel1 = value;
var setposition = position != null && (Control.Child1 == null || Control.Child2 == null);
if (Control.Child1 != null)
Control.Remove(Control.Child1);
var widget = panel1 != null ? panel1.GetContainerWidget() : EmptyContainer();
Control.Pack1(widget, fixedPanel != SplitterFixedPanel.Panel1, true);
if (setposition)
Control.Position = position.Value;
widget.ShowAll();
}
}
public Control Panel2
{
get { return panel2; }
set
{
panel2 = value;
var setposition = position != null && (Control.Child1 == null || Control.Child2 == null);
if (Control.Child2 != null)
Control.Remove(Control.Child2);
var widget = panel2 != null ? panel2.GetContainerWidget() : EmptyContainer();
Control.Pack2(widget, fixedPanel != SplitterFixedPanel.Panel2, true);
if (setposition)
Control.Position = position.Value;
widget.ShowAll();
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SizeConverter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Drawing {
using System.Runtime.Serialization.Formatters;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;
/// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter"]/*' />
/// <devdoc>
/// SizeConverter is a class that can be used to convert
/// Size from one data type to another. Access this
/// class through the TypeDescriptor.
/// </devdoc>
public class SizeConverter : TypeConverter {
/// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.CanConvertFrom"]/*' />
/// <devdoc>
/// Determines if this converter can convert an object in the given source
/// type to the native type of the converter.
/// </devdoc>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.CanConvertTo"]/*' />
/// <devdoc>
/// <para>Gets a value indicating whether this converter can
/// convert an object to the given destination type using the context.</para>
/// </devdoc>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (destinationType == typeof(InstanceDescriptor)) {
return true;
}
return base.CanConvertTo(context, destinationType);
}
/// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.ConvertFrom"]/*' />
/// <devdoc>
/// Converts the given object to the converter's native type.
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")]
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
string strValue = value as string;
if (strValue != null) {
string text = strValue.Trim();
if (text.Length == 0) {
return null;
}
else {
// Parse 2 integer values.
//
if (culture == null) {
culture = CultureInfo.CurrentCulture;
}
char sep = culture.TextInfo.ListSeparator[0];
string[] tokens = text.Split(new char[] {sep});
int[] values = new int[tokens.Length];
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
for (int i = 0; i < values.Length; i++) {
// Note: ConvertFromString will raise exception if value cannot be converted.
values[i] = (int)intConverter.ConvertFromString(context, culture, tokens[i]);
}
if (values.Length == 2) {
return new Size(values[0], values[1]);
}
else {
throw new ArgumentException(SR.GetString(SR.TextParseFailedFormat,
text,
"Width,Height"));
}
}
}
return base.ConvertFrom(context, culture, value);
}
/// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.ConvertTo"]/*' />
/// <devdoc>
/// Converts the given object to another type. The most common types to convert
/// are to and from a string object. The default implementation will make a call
/// to ToString on the object if the object is valid and if the destination
/// type is string. If this cannot convert to the desitnation type, this will
/// throw a NotSupportedException.
/// </devdoc>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (destinationType == null) {
throw new ArgumentNullException("destinationType");
}
if(value is Size){
if (destinationType == typeof(string)) {
Size size = (Size)value;
if (culture == null) {
culture = CultureInfo.CurrentCulture;
}
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
string[] args = new string[2];
int nArg = 0;
// Note: ConvertToString will raise exception if value cannot be converted.
args[nArg++] = intConverter.ConvertToString(context, culture, size.Width);
args[nArg++] = intConverter.ConvertToString(context, culture, size.Height);
return string.Join(sep, args);
}
if (destinationType == typeof(InstanceDescriptor)) {
Size size = (Size)value;
ConstructorInfo ctor = typeof(Size).GetConstructor(new Type[] {typeof(int), typeof(int)});
if (ctor != null) {
return new InstanceDescriptor(ctor, new object[] {size.Width, size.Height});
}
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
/// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.CreateInstance"]/*' />
/// <devdoc>
/// Creates an instance of this type given a set of property values
/// for the object. This is useful for objects that are immutable, but still
/// want to provide changable properties.
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")]
[SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")]
public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) {
if( propertyValues == null ){
throw new ArgumentNullException( "propertyValues" );
}
object width = propertyValues["Width"];
object height = propertyValues["Height"];
if(width == null || height == null ||
!(width is int) || !(height is int)) {
throw new ArgumentException(SR.GetString(SR.PropertyValueInvalidEntry));
}
return new Size((int)width,
(int)height);
}
/// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.GetCreateInstanceSupported"]/*' />
/// <devdoc>
/// Determines if changing a value on this object should require a call to
/// CreateInstance to create a new value.
/// </devdoc>
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) {
return true;
}
/// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.GetProperties"]/*' />
/// <devdoc>
/// Retrieves the set of properties for this type. By default, a type has
/// does not return any properties. An easy implementation of this method
/// can just call TypeDescriptor.GetProperties for the correct data type.
/// </devdoc>
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) {
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(Size), attributes);
return props.Sort(new string[] {"Width", "Height"});
}
/// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.GetPropertiesSupported"]/*' />
/// <devdoc>
/// Determines if this object supports properties. By default, this
/// is false.
/// </devdoc>
public override bool GetPropertiesSupported(ITypeDescriptorContext context) {
return true;
}
}
}
| |
using CellSpacePartitionLib;
using CollisionBuddy;
using FlockBuddy.Interfaces;
using GameTimer;
using Microsoft.Xna.Framework;
using PrimitiveBuddy;
using System;
using System.Collections.Generic;
namespace FlockBuddy
{
/// <summary>
/// This holds all the data for a single flock...
/// It has all the boids, which will be updated here.
/// It has all the enemies, which are updated ELSEWHERE.
/// It has all the prey items, which are updated ELSEWHERE
/// It has all the obstacles, walls, and path, which are also all updated somewhere else in the game.
/// </summary>
public class Flock : IFlock
{
#region Fields
/// <summary>
/// crappy lock object for list access
/// </summary>
protected object _listLock = new object();
#endregion //Fields
#region Properties
public Color DebugColor { get; private set; }
public string Name { get; set; }
/// <summary>
/// Used for database persistance
/// </summary>
public int? Id { get; set; }
/// <summary>
/// a container of all the moving entities this boid is managing
/// </summary>
public List<IMover> Boids { get; set; }
/// <summary>
/// The game clock to manage this flock
/// </summary>
private GameClock FlockTimer { get; set; }
/// <summary>
/// break up the game world into cells to make it easier to update the flock
/// </summary>
public CellSpacePartition<IMover> CellSpace { get; set; }
public List<IFlock> Predators { get; private set; }
public List<IFlock> Prey { get; private set; }
public List<IFlock> Vips { get; private set; }
/// <summary>
/// any obstacles for this flock
/// </summary>
public List<IBaseEntity> Obstacles { private get; set; }
/// <summary>
/// container containing any walls in the environment
/// </summary>
public List<ILine> Walls { get; set; }
public List<Vector2> Waypoints { get; set; }
//any path we may create for the vehicles to follow
//List<vector2> Path { get; private set; }
/// <summary>
/// whether or not to use the cell space partitioning
/// </summary>
public bool UseCellSpace => null != CellSpace;
/// <summary>
/// Whether or not to constrian boids to within toroid world
/// </summary>
public bool UseWorldWrap { get; set; }
/// <summary>
/// The size of the world!
/// </summary>
public Vector2 WorldSize { get; private set; } = new Vector2(1024.0f, 768.0f);
#endregion //Members
#region Methods
/// <summary>
/// Construct the flock!
/// </summary>
public Flock()
{
UseWorldWrap = false;
Boids = new List<IMover>();
FlockTimer = new GameClock();
Predators = new List<IFlock>();
Prey = new List<IFlock>();
Vips = new List<IFlock>();
Waypoints = new List<Vector2>();
}
/// <summary>
/// add a boid to the flock.
/// This is the only way that boids should be added to ensure they go in the cell space corerctly.
/// </summary>
/// <param name="boid"></param>
public void AddBoid(IMover boid)
{
lock (_listLock)
{
Boids.Add(boid);
if (UseCellSpace)
{
CellSpace.Add(boid);
}
}
}
public void AddBoids(IEnumerable<IMover> boids)
{
lock (_listLock)
{
Boids.AddRange(boids);
if (UseCellSpace)
{
foreach (var boid in boids)
{
CellSpace.Add(boid);
}
}
}
}
/// <summary>
/// Remove a boid from the list
/// </summary>
/// <param name="boid"></param>
public void RemoveBoid(IMover boid)
{
Boids.Remove(boid);
if (UseCellSpace)
{
CellSpace.Remove(boid);
}
}
/// <summary>
/// Remove all the boids from this flock.
/// </summary>
public virtual void Clear()
{
Boids.Clear();
if (UseCellSpace)
{
CellSpace.Clear();
}
}
public void AddDefaultWalls(DefaultWalls wallsType, Rectangle rect)
{
//only keep the walls we want
switch (wallsType)
{
case DefaultWalls.All:
{
Walls = Line.ExtendedInsideRect(rect, 128f);
}
break;
case DefaultWalls.None:
{
//empty list!
Walls = new List<ILine>();
}
break;
case DefaultWalls.TopBottom:
{
var walls = Line.ExtendedInsideRect(rect, 128f);
Walls = new List<ILine>()
{
walls[0],
walls[2]
};
}
break;
case DefaultWalls.LeftRight:
{
var walls = Line.ExtendedInsideRect(rect, 128f);
Walls = new List<ILine>()
{
walls[1],
walls[3]
};
}
break;
}
}
/// <summary>
/// update the flock!
/// This assumes that you have already updated all the external entities (enemies, targets, etc.)
/// </summary>
/// <param name="curTime"></param>
public virtual void Update(GameClock curTime)
{
//update the time
FlockTimer.Update(curTime);
//Update all the flock boids
for (int i = 0; i < Boids.Count; i++)
{
if (Boids[i] is Boid boid)
{
boid.Update(FlockTimer);
}
}
//update the vehicle's current cell if space partitioning is turned on
if (UseCellSpace)
{
for (int i = 0; i < Boids.Count; i++)
{
CellSpace.Update(Boids[i]);
}
}
}
/// <summary>
/// given a position, wrap them around the screen
/// </summary>
public Vector2 WrapWorldPosition(Vector2 pos)
{
if (UseWorldWrap)
{
//wrap aroud the edge
if (pos.X > WorldSize.X)
{
pos.X = 0.0f;
}
else if (pos.X < 0.0f)
{
pos.X = WorldSize.X;
}
//wrap around the floor/ceiling
if (pos.Y > WorldSize.Y)
{
pos.Y = 0.0f;
}
else if (pos.Y < 0.0f)
{
pos.Y = WorldSize.Y;
}
}
return pos;
}
public void RemoveFlock(IFlock flock)
{
Predators.Remove(flock);
Prey.Remove(flock);
Vips.Remove(flock);
}
public void AddFlockToGroup(IFlock flock, FlockGroup group)
{
//remove the flock from all groups
RemoveFlock(flock);
//add the flock to the correct group
switch (group)
{
case FlockGroup.Predator:
{
Predators.Add(flock);
}
break;
case FlockGroup.Prey:
{
Prey.Add(flock);
}
break;
case FlockGroup.Vip:
{
Vips.Add(flock);
}
break;
}
}
public bool IsFlockInGroup(IFlock flock, FlockGroup group)
{
switch (group)
{
case FlockGroup.None:
{
return !IsFlockInGroup(flock, FlockGroup.Predator) &&
!IsFlockInGroup(flock, FlockGroup.Prey) &&
!IsFlockInGroup(flock, FlockGroup.Vip);
}
case FlockGroup.Predator:
{
return Predators.Contains(flock);
}
case FlockGroup.Prey:
{
return Prey.Contains(flock);
}
case FlockGroup.Vip:
{
return Vips.Contains(flock);
}
default:
{
throw new Exception("did you add a new flock group?");
}
}
}
#region Find Methods
public IMover FindClosestBoidInRange(IBoid boid, float queryRadius)
{
//get all the dudes in range
var inRange = FindBoidsInRange(boid, queryRadius);
return FindClosestFromList(boid, inRange);
}
public IMover FindBoidAtPosition(Vector2 position, float boidRadius)
{
if (UseCellSpace)
{
return CellSpace.NearestNeighbor(position, boidRadius);
}
else
{
//get all the dudes in range
var inRange = FindBoidsAtPosition(position, boidRadius);
//find the closest out of all of those
return FindClosestFromList(position, inRange);
}
}
/// <summary>
/// Tag all the guys inteh flock that are neightbors of a boid.
/// </summary>
/// <param name="boid"></param>
public List<IMover> FindBoidsInRange(IBoid boid, float queryRadius)
{
if (UseCellSpace)
{
//Update the cell space to find all the boids neighbors
return CellSpace.CalculateNeighbors(boid.Position, queryRadius, true);
}
else
{
//go through all the boids and tag them up
return FindBoidsInRange(boid, Boids, queryRadius);
}
}
public List<IMover> FindBoidsAtPosition(Vector2 position, float boidRadius)
{
if (UseCellSpace)
{
//Update the cell space to find all the boids neighbors
return CellSpace.CalculateNeighbors(position, boidRadius);
}
else
{
//go through all the boids and tag them up
return FindBoidsAtPosition(position, Boids);
}
}
public List<IBaseEntity> FindObstaclesInRange(IBoid boid, float queryRadius)
{
return FindObjectsInRange(boid, Obstacles, queryRadius);
}
/// <summary>
/// Calculate the enemies of a boid.
/// Right now just pulls out the first two boids.
/// </summary>
/// <param name="boid"></param>
/// <param name="enemy1"></param>
/// <param name="enemy2"></param>
public IMover FindClosestPredatorInRange(IBoid boid, float queryRadius)
{
return FindClosestFromFlockList(boid, queryRadius, Predators);
}
/// <summary>
/// Find any targets in the list.
/// Right now just returns the first boid in the list.
/// </summary>
/// <param name="boid"></param>
/// <param name="target"></param>
public IMover FindClosestPreyInRange(IBoid boid, float queryRadius)
{
return FindClosestFromFlockList(boid, queryRadius, Prey);
}
public IMover FindClosestVipInRange(IBoid boid, float queryRadius)
{
return FindClosestFromFlockList(boid, queryRadius, Vips);
}
/// <summary>
/// Tag all the obstacles that a boid can see.
/// </summary>
/// <param name="boid"></param>
/// <param name="range"></param>
public List<IBaseEntity> FindObstacles(IBoid boid, float queryRadius)
{
return (null != boid ? FindObjectsInRange(boid, Obstacles, queryRadius) : new List<IBaseEntity>());
}
/// <summary>
/// tags any entities contained in a container that are within the radius of the single entity parameter
/// </summary>
/// <param name="boid"></param>
/// <param name="dudes">teh list of entities to tag as neighbors</param>
/// <param name="queryRadius">the disdtance to tag neightbors</param>
private List<IMover> FindBoidsInRange(IBoid boid, List<IMover> dudes, float queryRadius)
{
var neighbors = new List<IMover>();
//iterate through all entities checking for range
for (int i = 0; i < dudes.Count; i++)
{
if (CheckIfObjectInRange(boid, dudes[i], queryRadius))
{
neighbors.Add(dudes[i]);
}
}
return neighbors;
}
private List<IMover> FindBoidsAtPosition(Vector2 position, List<IMover> dudes)
{
var neighbors = new List<IMover>();
//iterate through all entities checking for range
for (int i = 0; i < dudes.Count; i++)
{
if (CheckIfObjectAtPosition(position, dudes[i]))
{
neighbors.Add(dudes[i]);
}
}
return neighbors;
}
/// <summary>
/// check if some non-boid dudes are in range
/// </summary>
/// <param name="boid"></param>
/// <param name="dudes"></param>
/// <param name="queryRadius"></param>
private List<IBaseEntity> FindObjectsInRange(IBoid boid, List<IBaseEntity> dudes, float queryRadius)
{
var neighbors = new List<IBaseEntity>();
//iterate through all entities checking for range
if (null != dudes)
{
for (int i = 0; i < dudes.Count; i++)
{
if (CheckIfObjectInRange(boid, dudes[i], queryRadius))
{
neighbors.Add(dudes[i]);
}
}
}
return neighbors;
}
private IMover FindClosestFromFlockList(IBoid boid, float queryRadius, List<IFlock> flocks)
{
var close = new List<IMover>();
foreach (var flock in flocks)
{
var closest = flock.FindClosestBoidInRange(boid, queryRadius);
if (null != closest)
{
close.Add(closest);
}
}
return FindClosestFromList(boid, close);
}
private IMover FindClosestFromList(IBoid boid, List<IMover> inRange)
{
float closestDistance = 0f;
IMover closest = null;
//set the "closest" to the first available
if (inRange.Count >= 1)
{
closest = inRange[0];
closestDistance = DistanceSquared(boid, inRange[0]);
}
//loop through the rest and see if there are any closer
if (inRange.Count >= 2)
{
for (int i = 1; i < inRange.Count; i++)
{
var distance = DistanceSquared(boid, inRange[i]);
if (distance < closestDistance)
{
closest = inRange[i];
closestDistance = distance;
}
}
}
return closest;
}
private IMover FindClosestFromList(Vector2 position, List<IMover> inRange)
{
float closestDistance = 0f;
IMover closest = null;
//set the "closest" to the first available
if (inRange.Count >= 1)
{
closest = inRange[0];
closestDistance = DistanceSquared(position, inRange[0]);
}
//loop through the rest and see if there are any closer
if (inRange.Count >= 2)
{
for (int i = 1; i < inRange.Count; i++)
{
var distance = DistanceSquared(position, inRange[i]);
if (distance < closestDistance)
{
closest = inRange[i];
closestDistance = distance;
}
}
}
return closest;
}
/// <summary>
/// check if a dude is in range
/// </summary>
/// <param name="boid"></param>
/// <param name="dude"></param>
/// <param name="queryRadius"></param>
private bool CheckIfObjectInRange(IBoid boid, IBaseEntity dude, float queryRadius)
{
if (null == dude)
{
return false;
}
//the bounding radius of the other is taken into account by adding it to the range
double range = queryRadius + dude.Radius;
//if entity within range, tag for further consideration.
//(working in distance-squared space to avoid sqrts)
return ((DistanceSquared(boid, dude) < (range * range)) && (dude != boid));
}
private bool CheckIfObjectAtPosition(Vector2 position, IBaseEntity dude)
{
if (null == dude)
{
return false;
}
//the bounding radius of the other is taken into account by adding it to the range
double range = dude.Radius;
//if entity within range, tag for further consideration.
//(working in distance-squared space to avoid sqrts)
return ((DistanceSquared(position, dude) < (range * range)));
}
private float DistanceSquared(IBoid boid, IBaseEntity dude)
{
return (dude.Position - boid.Position).LengthSquared();
}
private float DistanceSquared(Vector2 position, IBaseEntity dude)
{
return (dude.Position - position).LengthSquared();
}
#endregion //Find Methods
#region Drawing
public void Draw(IPrimitive prim, Color color)
{
foreach (Boid boid in Boids)
{
boid.Draw(prim, color);
boid.DrawSpeedForce(prim, Color.White);
}
}
/// <summary>
/// draw a bunch of debug info
/// </summary>
/// <param name="prim"></param>
public void DrawCells(IPrimitive prim)
{
if (UseCellSpace)
{
CellSpace.RenderCells(prim);
}
}
/// <summary>
/// draw the vectors of all the boids
/// </summary>
/// <param name="prim"></param>
public void DrawTotalForce(IPrimitive prim, Color color)
{
foreach (Boid boid in Boids)
{
boid.DrawTotalForce(prim, color);
}
}
/// <summary>
/// draw the wall whiskers of all the boids
/// </summary>
/// <param name="prim"></param>
public void DrawWhiskers(IPrimitive prim, Color color)
{
foreach (Boid boid in Boids)
{
boid.DrawWallFeelers(prim, color);
}
}
/// <summary>
/// draw all the walls
/// </summary>
/// <param name="prim"></param>
public void DrawWalls(IPrimitive prim)
{
foreach (var wall in Walls)
{
var line = wall as Line;
if (null != line)
{
line.Draw(prim, Color.Black);
}
}
}
#endregion //Drawing
#endregion //Methods
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management;
namespace Microsoft.WindowsAzure.Management
{
/// <summary>
/// The Service Management API provides programmatic access to much of the
/// functionality available through the Management Portal. The Service
/// Management API is a REST API. All API operations are performed over
/// SSL and are mutually authenticated using X.509 v3 certificates. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
/// more information)
/// </summary>
public partial class ManagementClient : ServiceClient<ManagementClient>, Microsoft.WindowsAzure.Management.IManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IAffinityGroupOperations _affinityGroups;
/// <summary>
/// Operations for managing affinity groups in your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460798.aspx
/// for more information)
/// </summary>
public virtual IAffinityGroupOperations AffinityGroups
{
get { return this._affinityGroups; }
}
private ILocationOperations _locations;
/// <summary>
/// The Service Management API includes operations for listing the
/// available data center locations for a hosted service in your
/// subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg441299.aspx
/// for more information)
/// </summary>
public virtual ILocationOperations Locations
{
get { return this._locations; }
}
private IManagementCertificateOperations _managementCertificates;
/// <summary>
/// You can use management certificates, which are also known as
/// subscription certificates, to authenticate clients attempting to
/// connect to resources associated with your Azure subscription.
/// (see http://msdn.microsoft.com/en-us/library/windowsazure/jj154124.aspx
/// for more information)
/// </summary>
public virtual IManagementCertificateOperations ManagementCertificates
{
get { return this._managementCertificates; }
}
private IRoleSizeOperations _roleSizes;
/// <summary>
/// The Service Management API includes operations for listing the
/// available role sizes for VMs in your subscription.
/// </summary>
public virtual IRoleSizeOperations RoleSizes
{
get { return this._roleSizes; }
}
private ISubscriptionOperations _subscriptions;
/// <summary>
/// Operations for listing subscription details. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715315.aspx
/// for more information)
/// </summary>
public virtual ISubscriptionOperations Subscriptions
{
get { return this._subscriptions; }
}
/// <summary>
/// Initializes a new instance of the ManagementClient class.
/// </summary>
private ManagementClient()
: base()
{
this._affinityGroups = new AffinityGroupOperations(this);
this._locations = new LocationOperations(this);
this._managementCertificates = new ManagementCertificateOperations(this);
this._roleSizes = new RoleSizeOperations(this);
this._subscriptions = new SubscriptionOperations(this);
this._apiVersion = "2014-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the ManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public ManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public ManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private ManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._affinityGroups = new AffinityGroupOperations(this);
this._locations = new LocationOperations(this);
this._managementCertificates = new ManagementCertificateOperations(this);
this._roleSizes = new RoleSizeOperations(this);
this._subscriptions = new SubscriptionOperations(this);
this._apiVersion = "2014-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the ManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another ManagementClient
/// instance
/// </summary>
/// <param name='client'>
/// Instance of ManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<ManagementClient> client)
{
base.Clone(client);
if (client is ManagementClient)
{
ManagementClient clonedClient = ((ManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
/// for more information)
/// </summary>
/// <param name='requestId'>
/// Required. The request ID for the request you wish to track. The
/// request ID is returned in the x-ms-request-id response header for
/// every request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async System.Threading.Tasks.Task<OperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken)
{
// Validate
if (requestId == null)
{
throw new ArgumentNullException("requestId");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("requestId", requestId);
Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/operations/" + requestId.Trim();
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OperationStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure"));
if (operationElement != null)
{
XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.Id = idInstance;
}
XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true));
result.Status = statusInstance;
}
XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
if (httpStatusCodeElement != null)
{
HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
result.HttpStatusCode = httpStatusCodeInstance;
}
XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails();
result.Error = errorInstance;
XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
errorInstance.Code = codeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Hosting;
using MbUnit.Framework;
using Moq;
using Subtext.Framework.UI.Skinning;
namespace UnitTests.Subtext.Framework.Skinning
{
[TestFixture]
public class SkinEngineTests
{
[Test]
public void GetSkinTemplates_WithFolders_ReturnsSkinPerFolder()
{
//arrange
var directories = new List<VirtualDirectory>();
for(int i = 0; i < 3; i++)
{
var skinDir = new Mock<VirtualDirectory>("~/skins/skin" + i);
skinDir.Setup(d => d.Name).Returns("Skin" + i);
directories.Add(skinDir.Object);
}
var skinsDir = new Mock<VirtualDirectory>("~/skins");
skinsDir.Setup(s => s.Directories).Returns(directories);
var vpp = new Mock<VirtualPathProvider>();
vpp.Setup(v => v.GetDirectory("~/skins")).Returns(skinsDir.Object);
var skins = new SkinEngine(vpp.Object);
//act
IDictionary<string, SkinTemplate> skinTemplates = skins.GetSkinTemplates(false /* mobile */);
//assert
Assert.AreEqual(3, skinTemplates.Count);
Assert.AreEqual("Skin0", skinTemplates.Values.First().Name);
Assert.AreEqual("Skin0", skinTemplates.Values.First().TemplateFolder);
}
[Test]
public void GetSkinTemplates_WithSpecialFolders_IgnoresSpecialFolders()
{
//arrange
var directories = new List<VirtualDirectory>();
var nonSkinDir = new Mock<VirtualDirectory>("~/skins/_system");
nonSkinDir.Setup(d => d.Name).Returns("_system");
directories.Add(nonSkinDir.Object);
var skinDir = new Mock<VirtualDirectory>("~/skins/skin1");
skinDir.Setup(d => d.Name).Returns("Skin1");
directories.Add(skinDir.Object);
var skinsDir = new Mock<VirtualDirectory>("~/skins");
skinsDir.Setup(s => s.Directories).Returns(directories);
var vpp = new Mock<VirtualPathProvider>();
vpp.Setup(v => v.GetDirectory("~/skins")).Returns(skinsDir.Object);
var skins = new SkinEngine(vpp.Object);
//act
IDictionary<string, SkinTemplate> skinTemplates = skins.GetSkinTemplates(false /* mobile */);
//assert
Assert.AreEqual(1, skinTemplates.Count);
Assert.AreEqual("Skin1", skinTemplates.Values.First().Name);
}
[Test]
public void GetSkinTemplates_WithSkinConfigInFolder_AppliesConfig()
{
//arrange
var virtualFile = new Mock<VirtualFile>("~/skins/skin1/skin.config");
Stream stream =
@"<?xml version=""1.0""?>
<SkinTemplates xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<SkinTemplate Name=""Skinny"" StyleMergeMode=""MergedAfter"" ScriptMergeMode=""Merge"">
<Styles>
<Style href=""~/skins/_System/commonstyle.css"" />
</Styles>
</SkinTemplate>
</SkinTemplates>"
.ToStream();
virtualFile.Setup(vf => vf.Open()).Returns(stream);
var directories = new List<VirtualDirectory>();
var skinDir = new Mock<VirtualDirectory>("~/skins/skin1");
skinDir.Setup(d => d.Name).Returns("Skin1");
directories.Add(skinDir.Object);
var skinsDir = new Mock<VirtualDirectory>("~/skins");
skinsDir.Setup(s => s.Directories).Returns(directories);
var vpp = new Mock<VirtualPathProvider>();
vpp.Setup(v => v.GetDirectory("~/skins")).Returns(skinsDir.Object);
vpp.Setup(v => v.FileExists("~/skins/Skin1/skin.config")).Returns(true);
vpp.Setup(v => v.GetFile("~/skins/Skin1/skin.config")).Returns(virtualFile.Object);
var skins = new SkinEngine(vpp.Object);
//act
IDictionary<string, SkinTemplate> skinTemplates = skins.GetSkinTemplates(false /* mobile */);
//assert
Assert.AreEqual(1, skinTemplates.Count);
SkinTemplate template = skinTemplates.Values.First();
Assert.AreEqual("Skinny", template.Name);
Assert.AreEqual("Skin1", template.TemplateFolder);
Assert.AreEqual(StyleMergeMode.MergedAfter, template.StyleMergeMode);
Assert.AreEqual(ScriptMergeMode.Merge, template.ScriptMergeMode);
Assert.AreEqual(1, template.Styles.Count());
}
[Test]
public void GetSkinTemplates_WithMobileSpecified_ReturnsSkinWithMobileSupportSetToMobileOnly()
{
//arrange
var virtualFile = new Mock<VirtualFile>("~/skins/skin1/skin.config");
Stream stream =
@"<?xml version=""1.0""?>
<SkinTemplates xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<SkinTemplate Name=""Mobile"" MobileSupport=""MobileOnly"">
<Styles>
<Style href=""~/skins/_System/commonstyle.css"" />
</Styles>
</SkinTemplate>
</SkinTemplates>"
.ToStream();
virtualFile.Setup(vf => vf.Open()).Returns(stream);
var directories = new List<VirtualDirectory>();
var skinDir = new Mock<VirtualDirectory>("~/skins/skin1");
skinDir.Setup(d => d.Name).Returns("Skin1");
directories.Add(skinDir.Object);
var skinsDir = new Mock<VirtualDirectory>("~/skins");
skinsDir.Setup(s => s.Directories).Returns(directories);
var vpp = new Mock<VirtualPathProvider>();
vpp.Setup(v => v.GetDirectory("~/skins")).Returns(skinsDir.Object);
vpp.Setup(v => v.FileExists("~/skins/Skin1/skin.config")).Returns(true);
vpp.Setup(v => v.GetFile("~/skins/Skin1/skin.config")).Returns(virtualFile.Object);
var skins = new SkinEngine(vpp.Object);
//act
IDictionary<string, SkinTemplate> skinTemplates = skins.GetSkinTemplates(true /* mobile */);
//assert
Assert.AreEqual(1, skinTemplates.Count);
SkinTemplate template = skinTemplates.Values.First();
Assert.AreEqual("Mobile", template.Name);
}
[Test]
public void GetSkinTemplates_WithMobileSpecified_ReturnsSkinWithMobileSupportSetToSupported()
{
//arrange
var virtualFile = new Mock<VirtualFile>("~/skins/skin1/skin.config");
Stream stream =
@"<?xml version=""1.0""?>
<SkinTemplates xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<SkinTemplate Name=""Mobile"" MobileSupport=""Supported"">
<Styles>
<Style href=""~/skins/_System/commonstyle.css"" />
</Styles>
</SkinTemplate>
</SkinTemplates>"
.ToStream();
virtualFile.Setup(vf => vf.Open()).Returns(stream);
var directories = new List<VirtualDirectory>();
var skinDir = new Mock<VirtualDirectory>("~/skins/skin1");
skinDir.Setup(d => d.Name).Returns("Skin1");
directories.Add(skinDir.Object);
var skinsDir = new Mock<VirtualDirectory>("~/skins");
skinsDir.Setup(s => s.Directories).Returns(directories);
var vpp = new Mock<VirtualPathProvider>();
vpp.Setup(v => v.GetDirectory("~/skins")).Returns(skinsDir.Object);
vpp.Setup(v => v.FileExists("~/skins/Skin1/skin.config")).Returns(true);
vpp.Setup(v => v.GetFile("~/skins/Skin1/skin.config")).Returns(virtualFile.Object);
var skins = new SkinEngine(vpp.Object);
//act
IDictionary<string, SkinTemplate> skinTemplates = skins.GetSkinTemplates(true /* mobile */);
//assert
Assert.AreEqual(1, skinTemplates.Count);
SkinTemplate template = skinTemplates.Values.First();
Assert.AreEqual("Mobile", template.Name);
}
[Test]
public void GetSkinTemplates_WithMobileNotSpecified_ReturnsSkinWithMobileSupportSetToSupported()
{
//arrange
var virtualFile = new Mock<VirtualFile>("~/skins/skin1/skin.config");
Stream stream =
@"<?xml version=""1.0""?>
<SkinTemplates xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<SkinTemplate Name=""Mobile"" MobileSupport=""Supported"">
<Styles>
<Style href=""~/skins/_System/commonstyle.css"" />
</Styles>
</SkinTemplate>
</SkinTemplates>"
.ToStream();
virtualFile.Setup(vf => vf.Open()).Returns(stream);
var directories = new List<VirtualDirectory>();
var skinDir = new Mock<VirtualDirectory>("~/skins/skin1");
skinDir.Setup(d => d.Name).Returns("Skin1");
directories.Add(skinDir.Object);
var skinsDir = new Mock<VirtualDirectory>("~/skins");
skinsDir.Setup(s => s.Directories).Returns(directories);
var vpp = new Mock<VirtualPathProvider>();
vpp.Setup(v => v.GetDirectory("~/skins")).Returns(skinsDir.Object);
vpp.Setup(v => v.FileExists("~/skins/Skin1/skin.config")).Returns(true);
vpp.Setup(v => v.GetFile("~/skins/Skin1/skin.config")).Returns(virtualFile.Object);
var skins = new SkinEngine(vpp.Object);
//act
IDictionary<string, SkinTemplate> skinTemplates = skins.GetSkinTemplates(false /* mobile */);
//assert
Assert.AreEqual(1, skinTemplates.Count);
SkinTemplate template = skinTemplates.Values.First();
Assert.AreEqual("Mobile", template.Name);
}
[Test]
public void GetSkinTemplates_WithMobileSpecified_DoesNotReturnSkinThatDoesNotSupportMobile()
{
//arrange
var virtualFile = new Mock<VirtualFile>("~/skins/skin1/skin.config");
Stream stream =
@"<?xml version=""1.0""?>
<SkinTemplates xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<SkinTemplate Name=""Skinny"" MobileSupported=""None"">
<Styles>
<Style href=""~/skins/_System/commonstyle.css"" />
</Styles>
</SkinTemplate>
</SkinTemplates>"
.ToStream();
virtualFile.Setup(vf => vf.Open()).Returns(stream);
var directories = new List<VirtualDirectory>();
var skinDir = new Mock<VirtualDirectory>("~/skins/skin1");
skinDir.Setup(d => d.Name).Returns("Skin1");
directories.Add(skinDir.Object);
var skinsDir = new Mock<VirtualDirectory>("~/skins");
skinsDir.Setup(s => s.Directories).Returns(directories);
var vpp = new Mock<VirtualPathProvider>();
vpp.Setup(v => v.GetDirectory("~/skins")).Returns(skinsDir.Object);
vpp.Setup(v => v.FileExists("~/skins/Skin1/skin.config")).Returns(true);
vpp.Setup(v => v.GetFile("~/skins/Skin1/skin.config")).Returns(virtualFile.Object);
var skins = new SkinEngine(vpp.Object);
//act
IDictionary<string, SkinTemplate> skinTemplates = skins.GetSkinTemplates(true /* mobile */);
//assert
Assert.AreEqual(0, skinTemplates.Count);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using MetroDemo.Models;
using System.Windows.Input;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using MetroDemo.Core;
using MetroDemo.ExampleViews;
using NHotkey;
using NHotkey.Wpf;
using System.Collections.ObjectModel;
using System.Windows.Data;
using ControlzEx.Theming;
namespace MetroDemo
{
public class AccentColorMenuData
{
public string Name { get; set; }
public Brush BorderColorBrush { get; set; }
public Brush ColorBrush { get; set; }
public AccentColorMenuData()
{
this.ChangeAccentCommand = new SimpleCommand(o => true, this.DoChangeTheme);
}
public ICommand ChangeAccentCommand { get; }
protected virtual void DoChangeTheme(object sender)
{
ThemeManager.Current.ChangeThemeColorScheme(Application.Current, this.Name);
}
}
public class AppThemeMenuData : AccentColorMenuData
{
protected override void DoChangeTheme(object sender)
{
ThemeManager.Current.ChangeThemeBaseColor(Application.Current, this.Name);
}
}
public class MainWindowViewModel : ViewModelBase, IDataErrorInfo, IDisposable
{
private readonly IDialogCoordinator _dialogCoordinator;
int? _integerGreater10Property = 2;
private bool _animateOnPositionChange = true;
public MainWindowViewModel(IDialogCoordinator dialogCoordinator)
{
this.Title = "Flyout Binding Test";
this._dialogCoordinator = dialogCoordinator;
SampleData.Seed();
// create accent color menu items for the demo
this.AccentColors = ThemeManager.Current.Themes
.GroupBy(x => x.ColorScheme)
.OrderBy(a => a.Key)
.Select(a => new AccentColorMenuData { Name = a.Key, ColorBrush = a.First().ShowcaseBrush })
.ToList();
// create metro theme color menu items for the demo
this.AppThemes = ThemeManager.Current.Themes
.GroupBy(x => x.BaseColorScheme)
.Select(x => x.First())
.Select(a => new AppThemeMenuData() { Name = a.BaseColorScheme, BorderColorBrush = a.Resources["MahApps.Brushes.ThemeForeground"] as Brush, ColorBrush = a.Resources["MahApps.Brushes.ThemeBackground"] as Brush })
.ToList();
this.Albums = new ObservableCollection<Album>(SampleData.Albums);
var cvs = CollectionViewSource.GetDefaultView(this.Albums);
cvs.GroupDescriptions.Add(new PropertyGroupDescription("Artist"));
this.Artists = SampleData.Artists;
this.FlipViewImages = new Uri[]
{
new Uri("pack://application:,,,/MahApps.Metro.Demo;component/Assets/Photos/Home.jpg", UriKind.RelativeOrAbsolute),
new Uri("pack://application:,,,/MahApps.Metro.Demo;component/Assets/Photos/Privat.jpg", UriKind.RelativeOrAbsolute),
new Uri("pack://application:,,,/MahApps.Metro.Demo;component/Assets/Photos/Settings.jpg", UriKind.RelativeOrAbsolute)
};
this.BrushResources = this.FindBrushResources();
this.CultureInfos = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures).OrderBy(c => c.DisplayName).ToList();
try
{
HotkeyManager.Current.AddOrReplace("demo", this.HotKey.Key, this.HotKey.ModifierKeys, (sender, e) => this.OnHotKey(sender, e));
}
catch (HotkeyAlreadyRegisteredException exception)
{
System.Diagnostics.Trace.TraceWarning("Uups, the hotkey {0} is already registered!", exception.Name);
}
this.EndOfScrollReachedCmdWithParameter = new SimpleCommand(o => true, async x => { await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("End of scroll reached!", $"Parameter: {x}"); });
this.CloseCmd = new SimpleCommand(o => this.CanCloseFlyout, x => ((Flyout)x).IsOpen = false);
this.TextBoxButtonCmd = new SimpleCommand(
o => true,
async x =>
{
if (x is string s)
{
await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("Wow, you typed Return and got", s).ConfigureAwait(false);
}
else if (x is RichTextBox richTextBox)
{
var text = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text;
await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("RichTextBox Button was clicked!", text).ConfigureAwait(false);
}
else if (x is TextBox textBox)
{
await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("TextBox Button was clicked!", textBox.Text).ConfigureAwait(false);
}
else if (x is PasswordBox passwordBox)
{
await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("PasswordBox Button was clicked!", passwordBox.Password).ConfigureAwait(false);
}
else if (x is DatePicker datePicker)
{
await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("DatePicker Button was clicked!", datePicker.Text).ConfigureAwait(false);
}
}
);
this.TextBoxButtonCmdWithParameter = new SimpleCommand(
o => true,
async x => { await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("TextBox Button with parameter was clicked!", $"Parameter: {x}"); }
);
this.SingleCloseTabCommand = new SimpleCommand(
o => true,
async x => { await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("Closing tab!", $"You are now closing the '{x}' tab"); }
);
this.NeverCloseTabCommand = new SimpleCommand(o => false);
this.ShowInputDialogCommand = new SimpleCommand(
o => true,
async x => { await this._dialogCoordinator.ShowInputAsync(this, "From a VM", "This dialog was shown from a VM, without knowledge of Window").ContinueWith(t => Console.WriteLine(t.Result)); }
);
this.ShowLoginDialogCommand = new SimpleCommand(
o => true,
async x => { await this._dialogCoordinator.ShowLoginAsync(this, "Login from a VM", "This login dialog was shown from a VM, so you can be all MVVM.").ContinueWith(t => Console.WriteLine(t.Result)); }
);
this.ShowMessageDialogCommand = new SimpleCommand(
o => true,
x => PerformDialogCoordinatorAction(this.ShowMessage((string)x), (string)x == "DISPATCHER_THREAD")
);
this.ShowProgressDialogCommand = new SimpleCommand(o => true, x => this.RunProgressFromVm());
this.ShowCustomDialogCommand = new SimpleCommand(o => true, x => this.RunCustomFromVm());
this.ToggleIconScalingCommand = new SimpleCommand(o => true, this.ToggleIconScaling);
this.OpenFirstFlyoutCommand = new SimpleCommand(o => true, o => (o as Flyout).IsOpen = !(o as Flyout).IsOpen);
this.ArtistsDropDownCommand = new SimpleCommand(o => false);
this.GenreDropDownMenuItemCommand = new SimpleCommand(
o => true,
async x => { await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("DropDownButton Menu", $"You are clicked the '{x}' menu item."); }
);
this.GenreSplitButtonItemCommand = new SimpleCommand(
o => true,
async x => { await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("Split Button", $"The selected item is '{x}'."); }
);
this.ShowHamburgerAboutCommand = ShowAboutCommand.Command;
this.ToggleSwitchCommand = new SimpleCommand(execute: async x => { await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("ToggleSwitch", $"The ToggleSwitch is now {((ToggleSwitch)x).IsOn}."); },
canExecute: x => this.CanUseToggleSwitch);
}
public ICommand ArtistsDropDownCommand { get; }
public ICommand GenreDropDownMenuItemCommand { get; }
public ICommand GenreSplitButtonItemCommand { get; }
public ICommand ShowHamburgerAboutCommand { get; }
public ICommand OpenFirstFlyoutCommand { get; }
public ICommand ChangeSyncModeCommand { get; } = new SimpleCommand(execute: x =>
{
ThemeManager.Current.ThemeSyncMode = (ThemeSyncMode)x;
ThemeManager.Current.SyncTheme();
});
public ICommand SyncThemeNowCommand { get; } = new SimpleCommand(execute: x => ThemeManager.Current.SyncTheme());
public ICommand ToggleSwitchCommand { get; }
private bool canUseToggleSwitch = true;
public bool CanUseToggleSwitch
{
get => this.canUseToggleSwitch;
set => this.Set(ref this.canUseToggleSwitch, value);
}
public ICommand ToggleSwitchOnCommand { get; } = new SimpleCommand(execute: async x => { await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("ToggleSwitch", "The ToggleSwitch is now On."); },
canExecute: x => x is MainWindowViewModel viewModel && viewModel.CanUseToggleSwitch);
public ICommand ToggleSwitchOffCommand { get; } = new SimpleCommand(execute: async x => { await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("ToggleSwitch", "The ToggleSwitch is now Off."); },
canExecute: x => x is MainWindowViewModel viewModel && viewModel.CanUseToggleSwitch);
public void Dispose()
{
HotkeyManager.Current.Remove("demo");
}
public string Title { get; set; }
public int SelectedIndex { get; set; }
public ICollection<Album> Albums { get; set; }
public List<Artist> Artists { get; set; }
private ObservableCollection<Artist> _selectedArtists = new ObservableCollection<Artist>();
public ObservableCollection<Artist> SelectedArtists
{
get => _selectedArtists;
set => Set(ref _selectedArtists, value);
}
public List<AccentColorMenuData> AccentColors { get; set; }
public List<AppThemeMenuData> AppThemes { get; set; }
public List<CultureInfo> CultureInfos { get; set; }
private CultureInfo currentCulture = CultureInfo.CurrentCulture;
public CultureInfo CurrentCulture
{
get => this.currentCulture;
set => this.Set(ref this.currentCulture, value);
}
private double? numericUpDownValue = null;
public double? NumericUpDownValue
{
get => this.numericUpDownValue;
set => this.Set(ref this.numericUpDownValue, value);
}
public ICommand EndOfScrollReachedCmdWithParameter { get; }
public int? IntegerGreater10Property
{
get => this._integerGreater10Property;
set => this.Set(ref this._integerGreater10Property, value);
}
private DateTime? _datePickerDate;
[Display(Prompt = "Auto resolved Watermark")]
public DateTime? DatePickerDate
{
get => this._datePickerDate;
set => this.Set(ref this._datePickerDate, value);
}
private bool _quitConfirmationEnabled;
public bool QuitConfirmationEnabled
{
get => this._quitConfirmationEnabled;
set => this.Set(ref this._quitConfirmationEnabled, value);
}
private bool showMyTitleBar = true;
public bool ShowMyTitleBar
{
get => this.showMyTitleBar;
set => this.Set(ref this.showMyTitleBar, value);
}
private bool canCloseFlyout = true;
public bool CanCloseFlyout
{
get => this.canCloseFlyout;
set => this.Set(ref this.canCloseFlyout, value);
}
public ICommand CloseCmd { get; }
private bool canShowHamburgerAboutCommand = true;
public bool CanShowHamburgerAboutCommand
{
get => this.canShowHamburgerAboutCommand;
set => this.Set(ref this.canShowHamburgerAboutCommand, value);
}
private bool isHamburgerMenuPaneOpen;
public bool IsHamburgerMenuPaneOpen
{
get => this.isHamburgerMenuPaneOpen;
set => this.Set(ref this.isHamburgerMenuPaneOpen, value);
}
public ICommand TextBoxButtonCmd { get; }
public ICommand TextBoxButtonCmdWithParameter { get; }
public string this[string columnName]
{
get
{
if (columnName == nameof(IntegerGreater10Property) && this.IntegerGreater10Property < 10)
{
return "Number is not greater than 10!";
}
if (columnName == nameof(DatePickerDate) && this.DatePickerDate == null)
{
return "No date given!";
}
if (columnName == nameof(HotKey) && this.HotKey != null && this.HotKey.Key == Key.D && this.HotKey.ModifierKeys == ModifierKeys.Shift)
{
return "SHIFT-D is not allowed";
}
if (columnName == nameof(TimePickerDate) && this.TimePickerDate == null)
{
return "No time given!";
}
if (columnName == nameof(IsToggleSwitchVisible) && !IsToggleSwitchVisible)
{
return "There is something hidden... \nActivate me to show it up.";
}
return null;
}
}
[Description("Test-Property")]
public string Error => string.Empty;
private DateTime? _timePickerDate;
[Display(Prompt = "Time needed...")]
public DateTime? TimePickerDate
{
get => this._timePickerDate;
set => this.Set(ref this._timePickerDate, value);
}
public ICommand SingleCloseTabCommand { get; }
public ICommand NeverCloseTabCommand { get; }
public ICommand ShowInputDialogCommand { get; }
public ICommand ShowLoginDialogCommand { get; }
public ICommand ShowMessageDialogCommand { get; }
private Action ShowMessage(string startingThread)
{
return () =>
{
var message = $"MVVM based messages!\n\nThis dialog was created by {startingThread} Thread with ID=\"{Thread.CurrentThread.ManagedThreadId}\"\n" +
$"The current DISPATCHER_THREAD Thread has the ID=\"{Application.Current.Dispatcher.Thread.ManagedThreadId}\"";
this._dialogCoordinator.ShowMessageAsync(this, $"Message from VM created by {startingThread}", message).ContinueWith(t => Console.WriteLine(t.Result));
};
}
public ICommand ShowProgressDialogCommand { get; }
private async void RunProgressFromVm()
{
var controller = await this._dialogCoordinator.ShowProgressAsync(this, "Progress from VM", "Progressing all the things, wait 3 seconds");
controller.SetIndeterminate();
await Task.Delay(3000);
await controller.CloseAsync();
}
private static void PerformDialogCoordinatorAction(Action action, bool runInMainThread)
{
if (!runInMainThread)
{
Task.Factory.StartNew(action);
}
else
{
action();
}
}
public ICommand ShowCustomDialogCommand { get; }
private async void RunCustomFromVm()
{
var customDialog = new CustomDialog() { Title = "Custom Dialog" };
var dataContext = new CustomDialogExampleContent(instance =>
{
this._dialogCoordinator.HideMetroDialogAsync(this, customDialog);
System.Diagnostics.Debug.WriteLine(instance.FirstName);
});
customDialog.Content = new CustomDialogExample { DataContext = dataContext };
await this._dialogCoordinator.ShowMetroDialogAsync(this, customDialog);
}
public IEnumerable<string> BrushResources { get; private set; }
public bool AnimateOnPositionChange
{
get => this._animateOnPositionChange;
set => this.Set(ref this._animateOnPositionChange, value);
}
private IEnumerable<string> FindBrushResources()
{
if (Application.Current.MainWindow != null)
{
var theme = ThemeManager.Current.DetectTheme(Application.Current.MainWindow);
var resources = theme.LibraryThemes.First(x => x.Origin == "MahApps.Metro").Resources.MergedDictionaries.First();
var brushResources = resources.Keys
.Cast<object>()
.Where(key => resources[key] is SolidColorBrush)
.Select(key => key.ToString())
.OrderBy(s => s)
.ToList();
return brushResources;
}
return Enumerable.Empty<string>();
}
public Uri[] FlipViewImages { get; set; }
public class RandomDataTemplateSelector : DataTemplateSelector
{
public DataTemplate TemplateOne { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
return this.TemplateOne;
}
}
private HotKey _hotKey = new HotKey(Key.Home, ModifierKeys.Control | ModifierKeys.Shift);
public HotKey HotKey
{
get => this._hotKey;
set
{
if (this.Set(ref this._hotKey, value))
{
if (value != null && value.Key != Key.None)
{
HotkeyManager.Current.AddOrReplace("demo", value.Key, value.ModifierKeys, async (sender, e) => await this.OnHotKey(sender, e));
}
else
{
HotkeyManager.Current.Remove("demo");
}
}
}
}
private async Task OnHotKey(object sender, HotkeyEventArgs e)
{
await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync(
"Hotkey pressed",
"You pressed the hotkey '" + this.HotKey + "' registered with the name '" + e.Name + "'");
}
public ICommand ToggleIconScalingCommand { get; }
private void ToggleIconScaling(object obj)
{
var multiFrameImageMode = (MultiFrameImageMode)obj;
((MetroWindow)Application.Current.MainWindow).IconScalingMode = multiFrameImageMode;
this.OnPropertyChanged(nameof(IsScaleDownLargerFrame));
this.OnPropertyChanged(nameof(IsNoScaleSmallerFrame));
}
public bool IsScaleDownLargerFrame => ((MetroWindow)Application.Current.MainWindow).IconScalingMode == MultiFrameImageMode.ScaleDownLargerFrame;
public bool IsNoScaleSmallerFrame => ((MetroWindow)Application.Current.MainWindow).IconScalingMode == MultiFrameImageMode.NoScaleSmallerFrame;
public bool IsToggleSwitchVisible { get; set; }
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.Threading;
using System.Transactions;
using System.ServiceModel.Diagnostics.Application;
using System.Runtime.Diagnostics;
using System.Security;
class ImmutableDispatchRuntime
{
readonly AuthenticationBehavior authenticationBehavior;
readonly AuthorizationBehavior authorizationBehavior;
readonly int correlationCount;
readonly ConcurrencyBehavior concurrency;
readonly IDemuxer demuxer;
readonly ErrorBehavior error;
readonly bool enableFaults;
readonly bool ignoreTransactionFlow;
readonly bool impersonateOnSerializingReply;
readonly IInputSessionShutdown[] inputSessionShutdownHandlers;
readonly InstanceBehavior instance;
readonly bool isOnServer;
readonly bool manualAddressing;
readonly IDispatchMessageInspector[] messageInspectors;
readonly int parameterInspectorCorrelationOffset;
readonly IRequestReplyCorrelator requestReplyCorrelator;
readonly SecurityImpersonationBehavior securityImpersonation;
readonly TerminatingOperationBehavior terminate;
readonly ThreadBehavior thread;
readonly TransactionBehavior transaction;
readonly bool validateMustUnderstand;
readonly bool receiveContextEnabledChannel;
readonly bool sendAsynchronously;
readonly bool requireClaimsPrincipalOnOperationContext;
readonly MessageRpcProcessor processMessage1;
readonly MessageRpcProcessor processMessage11;
readonly MessageRpcProcessor processMessage2;
readonly MessageRpcProcessor processMessage3;
readonly MessageRpcProcessor processMessage31;
readonly MessageRpcProcessor processMessage4;
readonly MessageRpcProcessor processMessage41;
readonly MessageRpcProcessor processMessage5;
readonly MessageRpcProcessor processMessage6;
readonly MessageRpcProcessor processMessage7;
readonly MessageRpcProcessor processMessage8;
readonly MessageRpcProcessor processMessage9;
readonly MessageRpcProcessor processMessageCleanup;
readonly MessageRpcProcessor processMessageCleanupError;
static AsyncCallback onFinalizeCorrelationCompleted =
Fx.ThunkCallback(new AsyncCallback(OnFinalizeCorrelationCompletedCallback));
static AsyncCallback onReplyCompleted =
Fx.ThunkCallback(new AsyncCallback(OnReplyCompletedCallback));
bool didTraceProcessMessage1 = false;
bool didTraceProcessMessage2 = false;
bool didTraceProcessMessage3 = false;
bool didTraceProcessMessage31 = false;
bool didTraceProcessMessage4 = false;
bool didTraceProcessMessage41 = false;
internal ImmutableDispatchRuntime(DispatchRuntime dispatch)
{
this.authenticationBehavior = AuthenticationBehavior.TryCreate(dispatch);
this.authorizationBehavior = AuthorizationBehavior.TryCreate(dispatch);
this.concurrency = new ConcurrencyBehavior(dispatch);
this.error = new ErrorBehavior(dispatch.ChannelDispatcher);
this.enableFaults = dispatch.EnableFaults;
this.inputSessionShutdownHandlers = EmptyArray<IInputSessionShutdown>.ToArray(dispatch.InputSessionShutdownHandlers);
this.instance = new InstanceBehavior(dispatch, this);
this.isOnServer = dispatch.IsOnServer;
this.manualAddressing = dispatch.ManualAddressing;
this.messageInspectors = EmptyArray<IDispatchMessageInspector>.ToArray(dispatch.MessageInspectors);
this.requestReplyCorrelator = new RequestReplyCorrelator();
this.securityImpersonation = SecurityImpersonationBehavior.CreateIfNecessary(dispatch);
this.requireClaimsPrincipalOnOperationContext = dispatch.RequireClaimsPrincipalOnOperationContext;
this.impersonateOnSerializingReply = dispatch.ImpersonateOnSerializingReply;
this.terminate = TerminatingOperationBehavior.CreateIfNecessary(dispatch);
this.thread = new ThreadBehavior(dispatch);
this.validateMustUnderstand = dispatch.ValidateMustUnderstand;
this.ignoreTransactionFlow = dispatch.IgnoreTransactionMessageProperty;
this.transaction = TransactionBehavior.CreateIfNeeded(dispatch);
this.receiveContextEnabledChannel = dispatch.ChannelDispatcher.ReceiveContextEnabled;
this.sendAsynchronously = dispatch.ChannelDispatcher.SendAsynchronously;
this.parameterInspectorCorrelationOffset = (dispatch.MessageInspectors.Count +
dispatch.MaxCallContextInitializers);
this.correlationCount = this.parameterInspectorCorrelationOffset + dispatch.MaxParameterInspectors;
DispatchOperationRuntime unhandled = new DispatchOperationRuntime(dispatch.UnhandledDispatchOperation, this);
if (dispatch.OperationSelector == null)
{
ActionDemuxer demuxer = new ActionDemuxer();
for (int i = 0; i < dispatch.Operations.Count; i++)
{
DispatchOperation operation = dispatch.Operations[i];
DispatchOperationRuntime operationRuntime = new DispatchOperationRuntime(operation, this);
demuxer.Add(operation.Action, operationRuntime);
}
demuxer.SetUnhandled(unhandled);
this.demuxer = demuxer;
}
else
{
CustomDemuxer demuxer = new CustomDemuxer(dispatch.OperationSelector);
for (int i = 0; i < dispatch.Operations.Count; i++)
{
DispatchOperation operation = dispatch.Operations[i];
DispatchOperationRuntime operationRuntime = new DispatchOperationRuntime(operation, this);
demuxer.Add(operation.Name, operationRuntime);
}
demuxer.SetUnhandled(unhandled);
this.demuxer = demuxer;
}
this.processMessage1 = new MessageRpcProcessor(this.ProcessMessage1);
this.processMessage11 = new MessageRpcProcessor(this.ProcessMessage11);
this.processMessage2 = new MessageRpcProcessor(this.ProcessMessage2);
this.processMessage3 = new MessageRpcProcessor(this.ProcessMessage3);
this.processMessage31 = new MessageRpcProcessor(this.ProcessMessage31);
this.processMessage4 = new MessageRpcProcessor(this.ProcessMessage4);
this.processMessage41 = new MessageRpcProcessor(this.ProcessMessage41);
this.processMessage5 = new MessageRpcProcessor(this.ProcessMessage5);
this.processMessage6 = new MessageRpcProcessor(this.ProcessMessage6);
this.processMessage7 = new MessageRpcProcessor(this.ProcessMessage7);
this.processMessage8 = new MessageRpcProcessor(this.ProcessMessage8);
this.processMessage9 = new MessageRpcProcessor(this.ProcessMessage9);
this.processMessageCleanup = new MessageRpcProcessor(this.ProcessMessageCleanup);
this.processMessageCleanupError = new MessageRpcProcessor(this.ProcessMessageCleanupError);
}
internal int CallContextCorrelationOffset
{
get { return this.messageInspectors.Length; }
}
internal int CorrelationCount
{
get { return this.correlationCount; }
}
internal bool EnableFaults
{
get { return this.enableFaults; }
}
internal InstanceBehavior InstanceBehavior
{
get { return this.instance; }
}
internal bool IsImpersonationEnabledOnSerializingReply
{
get { return this.impersonateOnSerializingReply; }
}
internal bool RequireClaimsPrincipalOnOperationContext
{
get { return this.requireClaimsPrincipalOnOperationContext; }
}
internal bool ManualAddressing
{
get { return this.manualAddressing; }
}
internal int MessageInspectorCorrelationOffset
{
get { return 0; }
}
internal int ParameterInspectorCorrelationOffset
{
get { return this.parameterInspectorCorrelationOffset; }
}
internal IRequestReplyCorrelator RequestReplyCorrelator
{
get { return this.requestReplyCorrelator; }
}
internal SecurityImpersonationBehavior SecurityImpersonation
{
get { return this.securityImpersonation; }
}
internal bool ValidateMustUnderstand
{
get { return validateMustUnderstand; }
}
internal ErrorBehavior ErrorBehavior
{
get { return this.error; }
}
bool AcquireDynamicInstanceContext(ref MessageRpc rpc)
{
if (rpc.InstanceContext.QuotaThrottle != null)
{
return AcquireDynamicInstanceContextCore(ref rpc);
}
else
{
return true;
}
}
bool AcquireDynamicInstanceContextCore(ref MessageRpc rpc)
{
bool success = rpc.InstanceContext.QuotaThrottle.Acquire(rpc.Pause());
if (success)
{
rpc.UnPause();
}
return success;
}
internal void AfterReceiveRequest(ref MessageRpc rpc)
{
if (this.messageInspectors.Length > 0)
{
AfterReceiveRequestCore(ref rpc);
}
}
internal void AfterReceiveRequestCore(ref MessageRpc rpc)
{
int offset = this.MessageInspectorCorrelationOffset;
try
{
for (int i = 0; i < this.messageInspectors.Length; i++)
{
rpc.Correlation[offset + i] = this.messageInspectors[i].AfterReceiveRequest(ref rpc.Request, (IClientChannel)rpc.Channel.Proxy, rpc.InstanceContext);
if (TD.MessageInspectorAfterReceiveInvokedIsEnabled())
{
TD.MessageInspectorAfterReceiveInvoked(rpc.EventTraceActivity, this.messageInspectors[i].GetType().FullName);
}
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ErrorBehavior.ShouldRethrowExceptionAsIs(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
}
void BeforeSendReply(ref MessageRpc rpc, ref Exception exception, ref bool thereIsAnUnhandledException)
{
if (this.messageInspectors.Length > 0)
{
BeforeSendReplyCore(ref rpc, ref exception, ref thereIsAnUnhandledException);
}
}
internal void BeforeSendReplyCore(ref MessageRpc rpc, ref Exception exception, ref bool thereIsAnUnhandledException)
{
int offset = this.MessageInspectorCorrelationOffset;
for (int i = 0; i < this.messageInspectors.Length; i++)
{
try
{
Message originalReply = rpc.Reply;
Message reply = originalReply;
this.messageInspectors[i].BeforeSendReply(ref reply, rpc.Correlation[offset + i]);
if (TD.MessageInspectorBeforeSendInvokedIsEnabled())
{
TD.MessageInspectorBeforeSendInvoked(rpc.EventTraceActivity, this.messageInspectors[i].GetType().FullName);
}
if ((reply == null) && (originalReply != null))
{
string message = SR.GetString(SR.SFxNullReplyFromExtension2, this.messageInspectors[i].GetType().ToString(), (rpc.Operation.Name ?? ""));
ErrorBehavior.ThrowAndCatch(new InvalidOperationException(message));
}
rpc.Reply = reply;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (!ErrorBehavior.ShouldRethrowExceptionAsIs(e))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
if (exception == null)
{
exception = e;
}
thereIsAnUnhandledException = (!this.error.HandleError(e)) || thereIsAnUnhandledException;
}
}
}
void FinalizeCorrelation(ref MessageRpc rpc)
{
Message reply = rpc.Reply;
if (reply != null && rpc.Error == null)
{
if (rpc.transaction != null && rpc.transaction.Current != null &&
rpc.transaction.Current.TransactionInformation.Status != TransactionStatus.Active)
{
return;
}
CorrelationCallbackMessageProperty callback;
if (CorrelationCallbackMessageProperty.TryGet(reply, out callback))
{
if (callback.IsFullyDefined)
{
try
{
rpc.RequestContextThrewOnReply = true;
rpc.CorrelationCallback = callback;
rpc.Reply = rpc.CorrelationCallback.FinalizeCorrelation(reply,
rpc.ReplyTimeoutHelper.RemainingTime());
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (!this.error.HandleError(e))
{
rpc.CorrelationCallback = null;
rpc.CanSendReply = false;
}
}
}
else
{
rpc.CorrelationCallback = new RpcCorrelationCallbackMessageProperty(callback, this, ref rpc);
reply.Properties[CorrelationCallbackMessageProperty.Name] = rpc.CorrelationCallback;
}
}
}
}
void BeginFinalizeCorrelation(ref MessageRpc rpc)
{
Message reply = rpc.Reply;
if (reply != null && rpc.Error == null)
{
if (rpc.transaction != null && rpc.transaction.Current != null &&
rpc.transaction.Current.TransactionInformation.Status != TransactionStatus.Active)
{
return;
}
CorrelationCallbackMessageProperty callback;
if (CorrelationCallbackMessageProperty.TryGet(reply, out callback))
{
if (callback.IsFullyDefined)
{
bool success = false;
try
{
rpc.RequestContextThrewOnReply = true;
rpc.CorrelationCallback = callback;
IResumeMessageRpc resume = rpc.Pause();
rpc.AsyncResult = rpc.CorrelationCallback.BeginFinalizeCorrelation(reply,
rpc.ReplyTimeoutHelper.RemainingTime(), onFinalizeCorrelationCompleted, resume);
success = true;
if (rpc.AsyncResult.CompletedSynchronously)
{
rpc.UnPause();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (!this.error.HandleError(e))
{
rpc.CorrelationCallback = null;
rpc.CanSendReply = false;
}
}
finally
{
if (!success)
{
rpc.UnPause();
}
}
}
else
{
rpc.CorrelationCallback = new RpcCorrelationCallbackMessageProperty(callback, this, ref rpc);
reply.Properties[CorrelationCallbackMessageProperty.Name] = rpc.CorrelationCallback;
}
}
}
}
void Reply(ref MessageRpc rpc)
{
rpc.RequestContextThrewOnReply = true;
rpc.SuccessfullySendReply = false;
try
{
rpc.RequestContext.Reply(rpc.Reply, rpc.ReplyTimeoutHelper.RemainingTime());
rpc.RequestContextThrewOnReply = false;
rpc.SuccessfullySendReply = true;
if (TD.DispatchMessageStopIsEnabled())
{
TD.DispatchMessageStop(rpc.EventTraceActivity);
}
}
catch (CommunicationException e)
{
this.error.HandleError(e);
}
catch (TimeoutException e)
{
this.error.HandleError(e);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (DiagnosticUtility.ShouldTraceError)
{
TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.ServiceOperationExceptionOnReply,
SR.GetString(SR.TraceCodeServiceOperationExceptionOnReply),
this, e);
}
if (!this.error.HandleError(e))
{
rpc.RequestContextThrewOnReply = true;
rpc.CanSendReply = false;
}
}
}
void BeginReply(ref MessageRpc rpc)
{
bool success = false;
try
{
IResumeMessageRpc resume = rpc.Pause();
rpc.AsyncResult = rpc.RequestContext.BeginReply(rpc.Reply, rpc.ReplyTimeoutHelper.RemainingTime(),
onReplyCompleted, resume);
success = true;
if (rpc.AsyncResult.CompletedSynchronously)
{
rpc.UnPause();
}
}
catch (CommunicationException e)
{
this.error.HandleError(e);
}
catch (TimeoutException e)
{
this.error.HandleError(e);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (DiagnosticUtility.ShouldTraceError)
{
TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Error,
TraceCode.ServiceOperationExceptionOnReply,
SR.GetString(SR.TraceCodeServiceOperationExceptionOnReply),
this, e);
}
if (!this.error.HandleError(e))
{
rpc.RequestContextThrewOnReply = true;
rpc.CanSendReply = false;
}
}
finally
{
if (!success)
{
rpc.UnPause();
}
}
}
internal bool Dispatch(ref MessageRpc rpc, bool isOperationContextSet)
{
rpc.ErrorProcessor = this.processMessage8;
rpc.NextProcessor = this.processMessage1;
return rpc.Process(isOperationContextSet);
}
void EndFinalizeCorrelation(ref MessageRpc rpc)
{
try
{
rpc.Reply = rpc.CorrelationCallback.EndFinalizeCorrelation(rpc.AsyncResult);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (!this.error.HandleError(e))
{
rpc.CanSendReply = false;
}
}
}
bool EndReply(ref MessageRpc rpc)
{
bool success = false;
try
{
rpc.RequestContext.EndReply(rpc.AsyncResult);
rpc.RequestContextThrewOnReply = false;
success = true;
if (TD.DispatchMessageStopIsEnabled())
{
TD.DispatchMessageStop(rpc.EventTraceActivity);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.error.HandleError(e);
}
return success;
}
internal void InputSessionDoneReceiving(ServiceChannel channel)
{
if (this.inputSessionShutdownHandlers.Length > 0)
{
this.InputSessionDoneReceivingCore(channel);
}
}
void InputSessionDoneReceivingCore(ServiceChannel channel)
{
IDuplexContextChannel proxy = channel.Proxy as IDuplexContextChannel;
if (proxy != null)
{
IInputSessionShutdown[] handlers = this.inputSessionShutdownHandlers;
try
{
for (int i = 0; i < handlers.Length; i++)
{
handlers[i].DoneReceiving(proxy);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (!this.error.HandleError(e))
{
proxy.Abort();
}
}
}
}
internal bool IsConcurrent(ref MessageRpc rpc)
{
return this.concurrency.IsConcurrent(ref rpc);
}
internal void InputSessionFaulted(ServiceChannel channel)
{
if (this.inputSessionShutdownHandlers.Length > 0)
{
this.InputSessionFaultedCore(channel);
}
}
void InputSessionFaultedCore(ServiceChannel channel)
{
IDuplexContextChannel proxy = channel.Proxy as IDuplexContextChannel;
if (proxy != null)
{
IInputSessionShutdown[] handlers = this.inputSessionShutdownHandlers;
try
{
for (int i = 0; i < handlers.Length; i++)
{
handlers[i].ChannelFaulted(proxy);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (!this.error.HandleError(e))
{
proxy.Abort();
}
}
}
}
static internal void GotDynamicInstanceContext(object state)
{
bool alreadyResumedNoLock;
((IResumeMessageRpc)state).Resume(out alreadyResumedNoLock);
if (alreadyResumedNoLock)
{
Fx.Assert("GotDynamicInstanceContext more than once for same call.");
}
}
void AddMessageProperties(Message message, OperationContext context, ServiceChannel replyChannel)
{
if (context.InternalServiceChannel == replyChannel)
{
if (context.HasOutgoingMessageHeaders)
{
message.Headers.CopyHeadersFrom(context.OutgoingMessageHeaders);
}
if (context.HasOutgoingMessageProperties)
{
message.Properties.MergeProperties(context.OutgoingMessageProperties);
}
}
}
static void OnFinalizeCorrelationCompletedCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
IResumeMessageRpc resume = result.AsyncState as IResumeMessageRpc;
if (resume == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxInvalidAsyncResultState0));
}
resume.Resume(result);
}
static void OnReplyCompletedCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
IResumeMessageRpc resume = result.AsyncState as IResumeMessageRpc;
if (resume == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxInvalidAsyncResultState0));
}
resume.Resume(result);
}
void PrepareReply(ref MessageRpc rpc)
{
RequestContext context = rpc.OperationContext.RequestContext;
Exception exception = null;
bool thereIsAnUnhandledException = false;
if (!rpc.Operation.IsOneWay)
{
if (DiagnosticUtility.ShouldTraceWarning)
{
// If a service both returns null and sets RequestContext null, that
// means they handled it (either by calling Close or Reply manually).
// These traces catch accidents, where you accidentally return null,
// or you accidentally close the context so we can't return your message.
if ((rpc.Reply == null) && (context != null))
{
TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Warning,
TraceCode.ServiceOperationMissingReply,
SR.GetString(SR.TraceCodeServiceOperationMissingReply, rpc.Operation.Name ?? String.Empty),
null, null);
}
else if ((context == null) && (rpc.Reply != null))
{
TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Warning,
TraceCode.ServiceOperationMissingReplyContext,
SR.GetString(SR.TraceCodeServiceOperationMissingReplyContext, rpc.Operation.Name ?? String.Empty),
null, null);
}
}
if ((context != null) && (rpc.Reply != null))
{
try
{
rpc.CanSendReply = PrepareAndAddressReply(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
thereIsAnUnhandledException = (!this.error.HandleError(e)) || thereIsAnUnhandledException;
exception = e;
}
}
}
this.BeforeSendReply(ref rpc, ref exception, ref thereIsAnUnhandledException);
if (rpc.Operation.IsOneWay)
{
rpc.CanSendReply = false;
}
if (!rpc.Operation.IsOneWay && (context != null) && (rpc.Reply != null))
{
if (exception != null)
{
// We don't call ProvideFault again, since we have already passed the
// point where SFx addresses the reply, and it is reasonable for
// ProvideFault to expect that SFx will address the reply. Instead
// we always just do 'internal server error' processing.
rpc.Error = exception;
this.error.ProvideOnlyFaultOfLastResort(ref rpc);
try
{
rpc.CanSendReply = PrepareAndAddressReply(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.error.HandleError(e);
}
}
}
else if ((exception != null) && thereIsAnUnhandledException)
{
rpc.Abort();
}
}
bool PrepareAndAddressReply(ref MessageRpc rpc)
{
bool canSendReply = true;
if (!this.manualAddressing)
{
if (!object.ReferenceEquals(rpc.RequestID, null))
{
System.ServiceModel.Channels.RequestReplyCorrelator.PrepareReply(rpc.Reply, rpc.RequestID);
}
if (!rpc.Channel.HasSession)
{
canSendReply = System.ServiceModel.Channels.RequestReplyCorrelator.AddressReply(rpc.Reply, rpc.ReplyToInfo);
}
}
AddMessageProperties(rpc.Reply, rpc.OperationContext, rpc.Channel);
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && rpc.EventTraceActivity != null)
{
rpc.Reply.Properties[EventTraceActivity.Name] = rpc.EventTraceActivity;
}
return canSendReply;
}
internal DispatchOperationRuntime GetOperation(ref Message message)
{
return this.demuxer.GetOperation(ref message);
}
internal void ProcessMessage1(ref MessageRpc rpc)
{
rpc.NextProcessor = this.processMessage11;
if (this.receiveContextEnabledChannel)
{
ReceiveContextRPCFacet.CreateIfRequired(this, ref rpc);
}
if (!rpc.IsPaused)
{
this.ProcessMessage11(ref rpc);
}
else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage1)
{
this.didTraceProcessMessage1 = true;
TraceUtility.TraceEvent(
TraceEventType.Information,
TraceCode.MessageProcessingPaused,
SR.GetString(SR.TraceCodeProcessMessage31Paused,
rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName,
rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress));
}
}
internal void ProcessMessage11(ref MessageRpc rpc)
{
rpc.NextProcessor = this.processMessage2;
if (rpc.Operation.IsOneWay)
{
rpc.RequestContext.Reply(null);
rpc.OperationContext.RequestContext = null;
}
else
{
if (!rpc.Channel.IsReplyChannel &&
((object)rpc.RequestID == null) &&
(rpc.Operation.Action != MessageHeaders.WildcardAction))
{
CommunicationException error = new CommunicationException(SR.GetString(SR.SFxOneWayMessageToTwoWayMethod0));
throw TraceUtility.ThrowHelperError(error, rpc.Request);
}
if (!this.manualAddressing)
{
EndpointAddress replyTo = rpc.ReplyToInfo.ReplyTo;
if (replyTo != null && replyTo.IsNone && rpc.Channel.IsReplyChannel)
{
CommunicationException error = new CommunicationException(SR.GetString(SR.SFxRequestReplyNone));
throw TraceUtility.ThrowHelperError(error, rpc.Request);
}
if (this.isOnServer)
{
EndpointAddress remoteAddress = rpc.Channel.RemoteAddress;
if ((remoteAddress != null) && !remoteAddress.IsAnonymous)
{
MessageHeaders headers = rpc.Request.Headers;
Uri remoteUri = remoteAddress.Uri;
if ((replyTo != null) && !replyTo.IsAnonymous && (remoteUri != replyTo.Uri))
{
string text = SR.GetString(SR.SFxRequestHasInvalidReplyToOnServer, replyTo.Uri, remoteUri);
Exception error = new InvalidOperationException(text);
throw TraceUtility.ThrowHelperError(error, rpc.Request);
}
EndpointAddress faultTo = headers.FaultTo;
if ((faultTo != null) && !faultTo.IsAnonymous && (remoteUri != faultTo.Uri))
{
string text = SR.GetString(SR.SFxRequestHasInvalidFaultToOnServer, faultTo.Uri, remoteUri);
Exception error = new InvalidOperationException(text);
throw TraceUtility.ThrowHelperError(error, rpc.Request);
}
if (rpc.RequestVersion.Addressing == AddressingVersion.WSAddressingAugust2004)
{
EndpointAddress from = headers.From;
if ((from != null) && !from.IsAnonymous && (remoteUri != from.Uri))
{
string text = SR.GetString(SR.SFxRequestHasInvalidFromOnServer, from.Uri, remoteUri);
Exception error = new InvalidOperationException(text);
throw TraceUtility.ThrowHelperError(error, rpc.Request);
}
}
}
}
}
}
if (this.concurrency.IsConcurrent(ref rpc))
{
rpc.Channel.IncrementActivity();
rpc.SuccessfullyIncrementedActivity = true;
}
if (this.authenticationBehavior != null)
{
this.authenticationBehavior.Authenticate(ref rpc);
}
if (this.authorizationBehavior != null)
{
this.authorizationBehavior.Authorize(ref rpc);
}
this.instance.EnsureInstanceContext(ref rpc);
this.TransferChannelFromPendingList(ref rpc);
this.AcquireDynamicInstanceContext(ref rpc);
if (!rpc.IsPaused)
{
this.ProcessMessage2(ref rpc);
}
}
void ProcessMessage2(ref MessageRpc rpc)
{
rpc.NextProcessor = this.processMessage3;
this.AfterReceiveRequest(ref rpc);
if (!this.ignoreTransactionFlow)
{
// Transactions need to have the context in the message
rpc.TransactionMessageProperty = TransactionMessageProperty.TryGet(rpc.Request);
}
this.concurrency.LockInstance(ref rpc);
if (!rpc.IsPaused)
{
this.ProcessMessage3(ref rpc);
}
else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage2)
{
this.didTraceProcessMessage2 = true;
TraceUtility.TraceEvent(
TraceEventType.Information,
TraceCode.MessageProcessingPaused,
SR.GetString(SR.TraceCodeProcessMessage2Paused,
rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName,
rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress));
}
}
void ProcessMessage3(ref MessageRpc rpc)
{
rpc.NextProcessor = this.processMessage31;
rpc.SuccessfullyLockedInstance = true;
// This also needs to happen after LockInstance, in case
// we are using an AutoComplete=false transaction.
if (this.transaction != null)
{
this.transaction.ResolveTransaction(ref rpc);
if (rpc.Operation.TransactionRequired)
{
this.transaction.SetCurrent(ref rpc);
}
}
if (!rpc.IsPaused)
{
this.ProcessMessage31(ref rpc);
}
else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage3)
{
this.didTraceProcessMessage3 = true;
TraceUtility.TraceEvent(
TraceEventType.Information,
TraceCode.MessageProcessingPaused,
SR.GetString(SR.TraceCodeProcessMessage3Paused,
rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName,
rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress));
}
}
void ProcessMessage31(ref MessageRpc rpc)
{
rpc.NextProcessor = this.ProcessMessage4;
if (this.transaction != null)
{
if (rpc.Operation.TransactionRequired)
{
ReceiveContextRPCFacet receiveContext = rpc.ReceiveContext;
if (receiveContext != null)
{
rpc.ReceiveContext = null;
receiveContext.Complete(this, ref rpc, TimeSpan.MaxValue, rpc.Transaction.Current);
}
}
}
if (!rpc.IsPaused)
{
this.ProcessMessage4(ref rpc);
}
else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage31)
{
this.didTraceProcessMessage31 = true;
TraceUtility.TraceEvent(
TraceEventType.Information,
TraceCode.MessageProcessingPaused,
SR.GetString(SR.TraceCodeProcessMessage31Paused,
rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName,
rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress));
}
}
void ProcessMessage4(ref MessageRpc rpc)
{
rpc.NextProcessor = this.processMessage41;
try
{
this.thread.BindThread(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e);
}
if (!rpc.IsPaused)
{
this.ProcessMessage41(ref rpc);
}
else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage4)
{
this.didTraceProcessMessage4 = true;
TraceUtility.TraceEvent(
TraceEventType.Information,
TraceCode.MessageProcessingPaused,
SR.GetString(SR.TraceCodeProcessMessage4Paused,
rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName,
rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress));
}
}
void ProcessMessage41(ref MessageRpc rpc)
{
rpc.NextProcessor = this.processMessage5;
// This needs to happen after LockInstance--LockInstance guarantees
// in-order delivery, so we can't receive the next message until we
// have acquired the lock.
//
// This also needs to happen after BindThread, since EricZ believes
// that running on UI thread should guarantee in-order delivery if
// the SynchronizationContext is single threaded.
// Note: for IManualConcurrencyOperationInvoker, the invoke assumes full control over pumping.
if (this.concurrency.IsConcurrent(ref rpc) && !(rpc.Operation.Invoker is IManualConcurrencyOperationInvoker))
{
rpc.EnsureReceive();
}
this.instance.EnsureServiceInstance(ref rpc);
if (!rpc.IsPaused)
{
this.ProcessMessage5(ref rpc);
}
else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage41)
{
this.didTraceProcessMessage41 = true;
TraceUtility.TraceEvent(
TraceEventType.Information,
TraceCode.MessageProcessingPaused,
SR.GetString(SR.TraceCodeProcessMessage4Paused,
rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName,
rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress));
}
}
void ProcessMessage5(ref MessageRpc rpc)
{
rpc.NextProcessor = this.processMessage6;
try
{
bool success = false;
try
{
if (!rpc.Operation.IsSynchronous)
{
// If async call completes in [....], it tells us through the gate below
rpc.PrepareInvokeContinueGate();
}
if (this.transaction != null)
{
this.transaction.InitializeCallContext(ref rpc);
}
SetActivityIdOnThread(ref rpc);
rpc.Operation.InvokeBegin(ref rpc);
success = true;
}
finally
{
try
{
try
{
if (this.transaction != null)
{
this.transaction.ClearCallContext(ref rpc);
}
}
finally
{
if (!rpc.Operation.IsSynchronous && rpc.IsPaused)
{
// Check if the callback produced the async result and set it back on the RPC on this stack
// and proceed only if the gate was signaled by the callback and completed synchronously
if (rpc.UnlockInvokeContinueGate(out rpc.AsyncResult))
{
rpc.UnPause();
}
}
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (success && (rpc.Operation.IsSynchronous || !rpc.IsPaused))
{
throw;
}
this.error.HandleError(e);
}
}
}
catch
{
// This catch clause forces ClearCallContext to run prior to stackwalks exiting this frame.
throw;
}
// Proceed if rpc is unpaused and invoke begin was successful.
if (!rpc.IsPaused)
{
this.ProcessMessage6(ref rpc);
}
}
void ProcessMessage6(ref MessageRpc rpc)
{
rpc.NextProcessor = (rpc.Operation.IsSynchronous) ?
this.processMessage8 :
this.processMessage7;
try
{
this.thread.BindEndThread(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e);
}
if (!rpc.IsPaused)
{
if (rpc.Operation.IsSynchronous)
{
this.ProcessMessage8(ref rpc);
}
else
{
this.ProcessMessage7(ref rpc);
}
}
}
void ProcessMessage7(ref MessageRpc rpc)
{
rpc.NextProcessor = null;
try
{
bool success = false;
try
{
if (this.transaction != null)
{
this.transaction.InitializeCallContext(ref rpc);
}
rpc.Operation.InvokeEnd(ref rpc);
success = true;
}
finally
{
try
{
if (this.transaction != null)
{
this.transaction.ClearCallContext(ref rpc);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (success)
{
// Throw the transaction.ClearContextException only if
// there isn't an exception on the thread already.
throw;
}
this.error.HandleError(e);
}
}
}
catch
{
// Make sure user Exception filters are not run with bad call context
throw;
}
// this never pauses
this.ProcessMessage8(ref rpc);
}
void ProcessMessage8(ref MessageRpc rpc)
{
rpc.NextProcessor = this.processMessage9;
try
{
this.error.ProvideMessageFault(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.error.HandleError(e);
}
this.PrepareReply(ref rpc);
if (rpc.CanSendReply)
{
rpc.ReplyTimeoutHelper = new TimeoutHelper(rpc.Channel.OperationTimeout);
if (this.sendAsynchronously)
{
this.BeginFinalizeCorrelation(ref rpc);
}
else
{
this.FinalizeCorrelation(ref rpc);
}
}
if (!rpc.IsPaused)
{
this.ProcessMessage9(ref rpc);
}
}
void ProcessMessage9(ref MessageRpc rpc)
{
rpc.NextProcessor = this.processMessageCleanup;
if (rpc.FinalizeCorrelationImplicitly && this.sendAsynchronously)
{
this.EndFinalizeCorrelation(ref rpc);
}
if (rpc.CorrelationCallback == null || rpc.FinalizeCorrelationImplicitly)
{
this.ResolveTransactionOutcome(ref rpc);
}
if (rpc.CanSendReply)
{
if (rpc.Reply != null)
{
TraceUtility.MessageFlowAtMessageSent(rpc.Reply, rpc.EventTraceActivity);
}
if (this.sendAsynchronously)
{
this.BeginReply(ref rpc);
}
else
{
this.Reply(ref rpc);
}
}
if (!rpc.IsPaused)
{
this.ProcessMessageCleanup(ref rpc);
}
}
// Logic for knowing when to close stuff:
//
// ASSUMPTIONS:
// Closing a stream over a message also closes the message.
// Closing a message over a stream does not close the stream.
// (OperationStreamProvider.ReleaseStream is no-op)
//
// This is a table of what should be disposed in what cases.
// The rows represent the type of parameter to the method and
// whether we are disposing parameters or not. The columns
// are for the inputs vs. the outputs. The cells contain the
// values that need to be Disposed. M^P means that exactly
// one of the message and parameter needs to be disposed,
// since they refer to the same object.
//
// Request Reply
// Message | M or P | M or P
// Dispose Stream | P | M and P
// Params | M and P | M and P
// | |
// Message | none | none
// NoDispose Stream | none | M
// Params | M | M
//
// By choosing to dispose the parameter in both of the "M or P"
// cases, the logic needed to generate this table is:
//
// CloseRequestMessage = IsParams
// CloseRequestParams = rpc.Operation.DisposeParameters
// CloseReplyMessage = rpc.Operation.SerializeReply
// CloseReplyParams = rpc.Operation.DisposeParameters
//
// IsParams can be calculated based on whether the request
// message was consumed after deserializing but before calling
// the user. This is stored as rpc.DidDeserializeRequestBody.
//
void ProcessMessageCleanup(ref MessageRpc rpc)
{
Fx.Assert(
!object.ReferenceEquals(rpc.ErrorProcessor, this.processMessageCleanupError),
"ProcessMessageCleanup run twice on the same MessageRpc!");
rpc.ErrorProcessor = this.processMessageCleanupError;
bool replyWasSent = false;
if (rpc.CanSendReply)
{
if (this.sendAsynchronously)
{
replyWasSent = this.EndReply(ref rpc);
}
else
{
replyWasSent = rpc.SuccessfullySendReply;
}
}
try
{
try
{
if (rpc.DidDeserializeRequestBody)
{
rpc.Request.Close();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.error.HandleError(e);
}
if (rpc.HostingProperty != null)
{
try
{
rpc.HostingProperty.Close();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e);
}
}
// for wf, wf owns the lifetime of the request message. So in that case, we should not dispose the inputs
IManualConcurrencyOperationInvoker manualInvoker = rpc.Operation.Invoker as IManualConcurrencyOperationInvoker;
rpc.DisposeParameters(manualInvoker != null && manualInvoker.OwnsFormatter); //Dispose all input/output/return parameters
if (rpc.FaultInfo.IsConsideredUnhandled)
{
if (!replyWasSent)
{
rpc.AbortRequestContext();
rpc.AbortChannel();
}
else
{
rpc.CloseRequestContext();
rpc.CloseChannel();
}
rpc.AbortInstanceContext();
}
else
{
if (rpc.RequestContextThrewOnReply)
{
rpc.AbortRequestContext();
}
else
{
rpc.CloseRequestContext();
}
}
if ((rpc.Reply != null) && (rpc.Reply != rpc.ReturnParameter))
{
try
{
rpc.Reply.Close();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.error.HandleError(e);
}
}
if ((rpc.FaultInfo.Fault != null) && (rpc.FaultInfo.Fault.State != MessageState.Closed))
{
// maybe ProvideFault gave a Message, but then BeforeSendReply replaced it
// in that case, we need to close the one from ProvideFault
try
{
rpc.FaultInfo.Fault.Close();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.error.HandleError(e);
}
}
try
{
rpc.OperationContext.FireOperationCompleted();
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
this.instance.AfterReply(ref rpc, this.error);
if (rpc.SuccessfullyLockedInstance)
{
try
{
this.concurrency.UnlockInstance(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
Fx.Assert("Exceptions should be caught by callee");
rpc.InstanceContext.FaultInternal();
this.error.HandleError(e);
}
}
if (this.terminate != null)
{
try
{
this.terminate.AfterReply(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.error.HandleError(e);
}
}
if (rpc.SuccessfullyIncrementedActivity)
{
try
{
rpc.Channel.DecrementActivity();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.error.HandleError(e);
}
}
}
finally
{
if (rpc.MessageRpcOwnsInstanceContextThrottle && rpc.channelHandler.InstanceContextServiceThrottle != null)
{
rpc.channelHandler.InstanceContextServiceThrottle.DeactivateInstanceContext();
}
if (rpc.Activity != null && DiagnosticUtility.ShouldUseActivity)
{
rpc.Activity.Stop();
}
}
this.error.HandleError(ref rpc);
}
void ProcessMessageCleanupError(ref MessageRpc rpc)
{
this.error.HandleError(ref rpc);
}
void ResolveTransactionOutcome(ref MessageRpc rpc)
{
if (this.transaction != null)
{
try
{
bool hadError = (rpc.Error != null);
try
{
this.transaction.ResolveOutcome(ref rpc);
}
catch (FaultException e)
{
if (rpc.Error == null)
{
rpc.Error = e;
}
}
finally
{
if (!hadError && rpc.Error != null)
{
this.error.ProvideMessageFault(ref rpc);
this.PrepareAndAddressReply(ref rpc);
}
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.error.HandleError(e);
}
}
}
[Fx.Tag.SecurityNote(Critical = "Calls security critical method to set the ActivityId on the thread",
Safe = "Set the ActivityId only when MessageRpc is available")]
[SecuritySafeCritical]
void SetActivityIdOnThread(ref MessageRpc rpc)
{
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && rpc.EventTraceActivity != null)
{
// Propogate the ActivityId to the service operation
EventTraceActivityHelper.SetOnThread(rpc.EventTraceActivity);
}
}
void TransferChannelFromPendingList(ref MessageRpc rpc)
{
if (rpc.Channel.IsPending)
{
rpc.Channel.IsPending = false;
ChannelDispatcher channelDispatcher = rpc.Channel.ChannelDispatcher;
IInstanceContextProvider provider = this.instance.InstanceContextProvider;
if (!InstanceContextProviderBase.IsProviderSessionful(provider) &&
!InstanceContextProviderBase.IsProviderSingleton(provider))
{
IChannel proxy = rpc.Channel.Proxy as IChannel;
if (!rpc.InstanceContext.IncomingChannels.Contains(proxy))
{
channelDispatcher.Channels.Add(proxy);
}
}
channelDispatcher.PendingChannels.Remove(rpc.Channel.Binder.Channel);
}
}
interface IDemuxer
{
DispatchOperationRuntime GetOperation(ref Message request);
}
class ActionDemuxer : IDemuxer
{
HybridDictionary map;
DispatchOperationRuntime unhandled;
internal ActionDemuxer()
{
this.map = new HybridDictionary();
}
internal void Add(string action, DispatchOperationRuntime operation)
{
if (map.Contains(action))
{
DispatchOperationRuntime existingOperation = (DispatchOperationRuntime)map[action];
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxActionDemuxerDuplicate, existingOperation.Name, operation.Name, action)));
}
this.map.Add(action, operation);
}
internal void SetUnhandled(DispatchOperationRuntime operation)
{
this.unhandled = operation;
}
public DispatchOperationRuntime GetOperation(ref Message request)
{
string action = request.Headers.Action;
if (action == null)
{
action = MessageHeaders.WildcardAction;
}
DispatchOperationRuntime operation = (DispatchOperationRuntime)this.map[action];
if (operation != null)
{
return operation;
}
return this.unhandled;
}
}
class CustomDemuxer : IDemuxer
{
Dictionary<string, DispatchOperationRuntime> map;
IDispatchOperationSelector selector;
DispatchOperationRuntime unhandled;
internal CustomDemuxer(IDispatchOperationSelector selector)
{
this.selector = selector;
this.map = new Dictionary<string, DispatchOperationRuntime>();
}
internal void Add(string name, DispatchOperationRuntime operation)
{
this.map.Add(name, operation);
}
internal void SetUnhandled(DispatchOperationRuntime operation)
{
this.unhandled = operation;
}
public DispatchOperationRuntime GetOperation(ref Message request)
{
string operationName = this.selector.SelectOperation(ref request);
DispatchOperationRuntime operation = null;
if (this.map.TryGetValue(operationName, out operation))
{
return operation;
}
else
{
return this.unhandled;
}
}
}
class RpcCorrelationCallbackMessageProperty : CorrelationCallbackMessageProperty
{
CorrelationCallbackMessageProperty innerCallback;
MessageRpc rpc;
ImmutableDispatchRuntime runtime;
TransactionScope scope;
// This constructor should be used when creating the RPCCorrelationMessageproperty the first time
// Here we copy the data & the needed data from the original callback
public RpcCorrelationCallbackMessageProperty(CorrelationCallbackMessageProperty innerCallback,
ImmutableDispatchRuntime runtime, ref MessageRpc rpc)
: base(innerCallback)
{
this.innerCallback = innerCallback;
this.runtime = runtime;
this.rpc = rpc;
}
// This constructor should be used when we are making a copy from the already initialized RPCCorrelationCallbackMessageProperty
public RpcCorrelationCallbackMessageProperty(RpcCorrelationCallbackMessageProperty rpcCallbackMessageProperty)
: base(rpcCallbackMessageProperty)
{
this.innerCallback = rpcCallbackMessageProperty.innerCallback;
this.runtime = rpcCallbackMessageProperty.runtime;
this.rpc = rpcCallbackMessageProperty.rpc;
}
public override IMessageProperty CreateCopy()
{
return new RpcCorrelationCallbackMessageProperty(this);
}
protected override IAsyncResult OnBeginFinalizeCorrelation(Message message, TimeSpan timeout,
AsyncCallback callback, object state)
{
bool success = false;
this.Enter();
try
{
IAsyncResult result = this.innerCallback.BeginFinalizeCorrelation(message, timeout, callback, state);
success = true;
return result;
}
finally
{
this.Leave(success);
}
}
protected override Message OnEndFinalizeCorrelation(IAsyncResult result)
{
bool success = false;
this.Enter();
try
{
Message message = this.innerCallback.EndFinalizeCorrelation(result);
success = true;
return message;
}
finally
{
this.Leave(success);
this.CompleteTransaction();
}
}
protected override Message OnFinalizeCorrelation(Message message, TimeSpan timeout)
{
bool success = false;
this.Enter();
try
{
Message newMessage = this.innerCallback.FinalizeCorrelation(message, timeout);
success = true;
return newMessage;
}
finally
{
this.Leave(success);
this.CompleteTransaction();
}
}
void CompleteTransaction()
{
this.runtime.ResolveTransactionOutcome(ref this.rpc);
}
void Enter()
{
if (this.rpc.transaction != null && this.rpc.transaction.Current != null)
{
this.scope = new TransactionScope(this.rpc.transaction.Current);
}
}
void Leave(bool complete)
{
if (this.scope != null)
{
if (complete)
{
scope.Complete();
}
scope.Dispose();
this.scope = null;
}
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcdv = Google.Cloud.Dataproc.V1;
using sys = System;
namespace Google.Cloud.Dataproc.V1
{
/// <summary>Resource name for the <c>Batch</c> resource.</summary>
public sealed partial class BatchName : gax::IResourceName, sys::IEquatable<BatchName>
{
/// <summary>The possible contents of <see cref="BatchName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/batches/{batch}</c>.
/// </summary>
ProjectLocationBatch = 1,
}
private static gax::PathTemplate s_projectLocationBatch = new gax::PathTemplate("projects/{project}/locations/{location}/batches/{batch}");
/// <summary>Creates a <see cref="BatchName"/> 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="BatchName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static BatchName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new BatchName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="BatchName"/> with the pattern
/// <c>projects/{project}/locations/{location}/batches/{batch}</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="batchId">The <c>Batch</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="BatchName"/> constructed from the provided ids.</returns>
public static BatchName FromProjectLocationBatch(string projectId, string locationId, string batchId) =>
new BatchName(ResourceNameType.ProjectLocationBatch, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), batchId: gax::GaxPreconditions.CheckNotNullOrEmpty(batchId, nameof(batchId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BatchName"/> with pattern
/// <c>projects/{project}/locations/{location}/batches/{batch}</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="batchId">The <c>Batch</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BatchName"/> with pattern
/// <c>projects/{project}/locations/{location}/batches/{batch}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string batchId) =>
FormatProjectLocationBatch(projectId, locationId, batchId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BatchName"/> with pattern
/// <c>projects/{project}/locations/{location}/batches/{batch}</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="batchId">The <c>Batch</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BatchName"/> with pattern
/// <c>projects/{project}/locations/{location}/batches/{batch}</c>.
/// </returns>
public static string FormatProjectLocationBatch(string projectId, string locationId, string batchId) =>
s_projectLocationBatch.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(batchId, nameof(batchId)));
/// <summary>Parses the given resource name string into a new <see cref="BatchName"/> 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}/locations/{location}/batches/{batch}</c></description></item>
/// </list>
/// </remarks>
/// <param name="batchName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="BatchName"/> if successful.</returns>
public static BatchName Parse(string batchName) => Parse(batchName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="BatchName"/> 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}/locations/{location}/batches/{batch}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="batchName">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="BatchName"/> if successful.</returns>
public static BatchName Parse(string batchName, bool allowUnparsed) =>
TryParse(batchName, allowUnparsed, out BatchName 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="BatchName"/> 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}/locations/{location}/batches/{batch}</c></description></item>
/// </list>
/// </remarks>
/// <param name="batchName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BatchName"/>, 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 batchName, out BatchName result) => TryParse(batchName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BatchName"/> 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}/locations/{location}/batches/{batch}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="batchName">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="BatchName"/>, 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 batchName, bool allowUnparsed, out BatchName result)
{
gax::GaxPreconditions.CheckNotNull(batchName, nameof(batchName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationBatch.TryParseName(batchName, out resourceName))
{
result = FromProjectLocationBatch(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(batchName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private BatchName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string batchId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
BatchId = batchId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="BatchName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/batches/{batch}</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="batchId">The <c>Batch</c> ID. Must not be <c>null</c> or empty.</param>
public BatchName(string projectId, string locationId, string batchId) : this(ResourceNameType.ProjectLocationBatch, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), batchId: gax::GaxPreconditions.CheckNotNullOrEmpty(batchId, nameof(batchId)))
{
}
/// <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>Batch</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string BatchId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>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.ProjectLocationBatch: return s_projectLocationBatch.Expand(ProjectId, LocationId, BatchId);
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 BatchName);
/// <inheritdoc/>
public bool Equals(BatchName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(BatchName a, BatchName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(BatchName a, BatchName b) => !(a == b);
}
public partial class CreateBatchRequest
{
/// <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() ?? "";
}
}
public partial class GetBatchRequest
{
/// <summary>
/// <see cref="gcdv::BatchName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::BatchName BatchName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::BatchName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListBatchesRequest
{
/// <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() ?? "";
}
}
public partial class DeleteBatchRequest
{
/// <summary>
/// <see cref="gcdv::BatchName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::BatchName BatchName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::BatchName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Batch
{
/// <summary>
/// <see cref="gcdv::BatchName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::BatchName BatchName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::BatchName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Linq;
namespace SteamNative
{
internal unsafe class SteamController : IDisposable
{
//
// Holds a platform specific implentation
//
internal Platform.Interface platform;
internal Facepunch.Steamworks.BaseSteamworks steamworks;
//
// Constructor decides which implementation to use based on current platform
//
internal SteamController( Facepunch.Steamworks.BaseSteamworks steamworks, IntPtr pointer )
{
this.steamworks = steamworks;
if ( Platform.IsWindows64 ) platform = new Platform.Win64( pointer );
else if ( Platform.IsWindows32 ) platform = new Platform.Win32( pointer );
else if ( Platform.IsLinux32 ) platform = new Platform.Linux32( pointer );
else if ( Platform.IsLinux64 ) platform = new Platform.Linux64( pointer );
else if ( Platform.IsOsx ) platform = new Platform.Mac( pointer );
}
//
// Class is invalid if we don't have a valid implementation
//
public bool IsValid{ get{ return platform != null && platform.IsValid; } }
//
// When shutting down clear all the internals to avoid accidental use
//
public virtual void Dispose()
{
if ( platform != null )
{
platform.Dispose();
platform = null;
}
}
// void
public void ActivateActionSet( ControllerHandle_t controllerHandle /*ControllerHandle_t*/, ControllerActionSetHandle_t actionSetHandle /*ControllerActionSetHandle_t*/ )
{
platform.ISteamController_ActivateActionSet( controllerHandle.Value, actionSetHandle.Value );
}
// ControllerActionSetHandle_t
public ControllerActionSetHandle_t GetActionSetHandle( string pszActionSetName /*const char **/ )
{
return platform.ISteamController_GetActionSetHandle( pszActionSetName );
}
// ControllerAnalogActionData_t
public ControllerAnalogActionData_t GetAnalogActionData( ControllerHandle_t controllerHandle /*ControllerHandle_t*/, ControllerAnalogActionHandle_t analogActionHandle /*ControllerAnalogActionHandle_t*/ )
{
return platform.ISteamController_GetAnalogActionData( controllerHandle.Value, analogActionHandle.Value );
}
// ControllerAnalogActionHandle_t
public ControllerAnalogActionHandle_t GetAnalogActionHandle( string pszActionName /*const char **/ )
{
return platform.ISteamController_GetAnalogActionHandle( pszActionName );
}
// int
public int GetAnalogActionOrigins( ControllerHandle_t controllerHandle /*ControllerHandle_t*/, ControllerActionSetHandle_t actionSetHandle /*ControllerActionSetHandle_t*/, ControllerAnalogActionHandle_t analogActionHandle /*ControllerAnalogActionHandle_t*/, out ControllerActionOrigin originsOut /*EControllerActionOrigin **/ )
{
return platform.ISteamController_GetAnalogActionOrigins( controllerHandle.Value, actionSetHandle.Value, analogActionHandle.Value, out originsOut );
}
// int
public int GetConnectedControllers( IntPtr handlesOut /*ControllerHandle_t **/ )
{
return platform.ISteamController_GetConnectedControllers( (IntPtr) handlesOut );
}
// ControllerHandle_t
public ControllerHandle_t GetControllerForGamepadIndex( int nIndex /*int*/ )
{
return platform.ISteamController_GetControllerForGamepadIndex( nIndex );
}
// ControllerActionSetHandle_t
public ControllerActionSetHandle_t GetCurrentActionSet( ControllerHandle_t controllerHandle /*ControllerHandle_t*/ )
{
return platform.ISteamController_GetCurrentActionSet( controllerHandle.Value );
}
// ControllerDigitalActionData_t
public ControllerDigitalActionData_t GetDigitalActionData( ControllerHandle_t controllerHandle /*ControllerHandle_t*/, ControllerDigitalActionHandle_t digitalActionHandle /*ControllerDigitalActionHandle_t*/ )
{
return platform.ISteamController_GetDigitalActionData( controllerHandle.Value, digitalActionHandle.Value );
}
// ControllerDigitalActionHandle_t
public ControllerDigitalActionHandle_t GetDigitalActionHandle( string pszActionName /*const char **/ )
{
return platform.ISteamController_GetDigitalActionHandle( pszActionName );
}
// int
public int GetDigitalActionOrigins( ControllerHandle_t controllerHandle /*ControllerHandle_t*/, ControllerActionSetHandle_t actionSetHandle /*ControllerActionSetHandle_t*/, ControllerDigitalActionHandle_t digitalActionHandle /*ControllerDigitalActionHandle_t*/, out ControllerActionOrigin originsOut /*EControllerActionOrigin **/ )
{
return platform.ISteamController_GetDigitalActionOrigins( controllerHandle.Value, actionSetHandle.Value, digitalActionHandle.Value, out originsOut );
}
// int
public int GetGamepadIndexForController( ControllerHandle_t ulControllerHandle /*ControllerHandle_t*/ )
{
return platform.ISteamController_GetGamepadIndexForController( ulControllerHandle.Value );
}
// string
// with: Detect_StringReturn
public string GetGlyphForActionOrigin( ControllerActionOrigin eOrigin /*EControllerActionOrigin*/ )
{
IntPtr string_pointer;
string_pointer = platform.ISteamController_GetGlyphForActionOrigin( eOrigin );
return Marshal.PtrToStringAnsi( string_pointer );
}
// ControllerMotionData_t
public ControllerMotionData_t GetMotionData( ControllerHandle_t controllerHandle /*ControllerHandle_t*/ )
{
return platform.ISteamController_GetMotionData( controllerHandle.Value );
}
// string
// with: Detect_StringReturn
public string GetStringForActionOrigin( ControllerActionOrigin eOrigin /*EControllerActionOrigin*/ )
{
IntPtr string_pointer;
string_pointer = platform.ISteamController_GetStringForActionOrigin( eOrigin );
return Marshal.PtrToStringAnsi( string_pointer );
}
// bool
public bool Init()
{
return platform.ISteamController_Init();
}
// void
public void RunFrame()
{
platform.ISteamController_RunFrame();
}
// void
public void SetLEDColor( ControllerHandle_t controllerHandle /*ControllerHandle_t*/, byte nColorR /*uint8*/, byte nColorG /*uint8*/, byte nColorB /*uint8*/, uint nFlags /*unsigned int*/ )
{
platform.ISteamController_SetLEDColor( controllerHandle.Value, nColorR, nColorG, nColorB, nFlags );
}
// bool
public bool ShowAnalogActionOrigins( ControllerHandle_t controllerHandle /*ControllerHandle_t*/, ControllerAnalogActionHandle_t analogActionHandle /*ControllerAnalogActionHandle_t*/, float flScale /*float*/, float flXPosition /*float*/, float flYPosition /*float*/ )
{
return platform.ISteamController_ShowAnalogActionOrigins( controllerHandle.Value, analogActionHandle.Value, flScale, flXPosition, flYPosition );
}
// bool
public bool ShowBindingPanel( ControllerHandle_t controllerHandle /*ControllerHandle_t*/ )
{
return platform.ISteamController_ShowBindingPanel( controllerHandle.Value );
}
// bool
public bool ShowDigitalActionOrigins( ControllerHandle_t controllerHandle /*ControllerHandle_t*/, ControllerDigitalActionHandle_t digitalActionHandle /*ControllerDigitalActionHandle_t*/, float flScale /*float*/, float flXPosition /*float*/, float flYPosition /*float*/ )
{
return platform.ISteamController_ShowDigitalActionOrigins( controllerHandle.Value, digitalActionHandle.Value, flScale, flXPosition, flYPosition );
}
// bool
public bool Shutdown()
{
return platform.ISteamController_Shutdown();
}
// void
public void StopAnalogActionMomentum( ControllerHandle_t controllerHandle /*ControllerHandle_t*/, ControllerAnalogActionHandle_t eAction /*ControllerAnalogActionHandle_t*/ )
{
platform.ISteamController_StopAnalogActionMomentum( controllerHandle.Value, eAction.Value );
}
// void
public void TriggerHapticPulse( ControllerHandle_t controllerHandle /*ControllerHandle_t*/, SteamControllerPad eTargetPad /*ESteamControllerPad*/, ushort usDurationMicroSec /*unsigned short*/ )
{
platform.ISteamController_TriggerHapticPulse( controllerHandle.Value, eTargetPad, usDurationMicroSec );
}
// void
public void TriggerRepeatedHapticPulse( ControllerHandle_t controllerHandle /*ControllerHandle_t*/, SteamControllerPad eTargetPad /*ESteamControllerPad*/, ushort usDurationMicroSec /*unsigned short*/, ushort usOffMicroSec /*unsigned short*/, ushort unRepeat /*unsigned short*/, uint nFlags /*unsigned int*/ )
{
platform.ISteamController_TriggerRepeatedHapticPulse( controllerHandle.Value, eTargetPad, usDurationMicroSec, usOffMicroSec, unRepeat, nFlags );
}
// void
public void TriggerVibration( ControllerHandle_t controllerHandle /*ControllerHandle_t*/, ushort usLeftSpeed /*unsigned short*/, ushort usRightSpeed /*unsigned short*/ )
{
platform.ISteamController_TriggerVibration( controllerHandle.Value, usLeftSpeed, usRightSpeed );
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="PointF.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Drawing {
using System.Diagnostics;
using System.Drawing;
using System.ComponentModel;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
/**
* Represents a point in 2D coordinate space
* (float precision floating-point coordinates)
*/
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF"]/*' />
/// <devdoc>
/// Represents an ordered pair of x and y coordinates that
/// define a point in a two-dimensional plane.
/// </devdoc>
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct PointF {
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF.Empty"]/*' />
/// <devdoc>
/// <para>
/// Creates a new instance of the <see cref='System.Drawing.PointF'/> class
/// with member data left uninitialized.
/// </para>
/// </devdoc>
public static readonly PointF Empty = new PointF();
private float x;
private float y;
/**
* Create a new Point object at the given location
*/
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF.PointF"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Drawing.PointF'/> class
/// with the specified coordinates.
/// </para>
/// </devdoc>
public PointF(float x, float y) {
this.x = x;
this.y = y;
}
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF.IsEmpty"]/*' />
/// <devdoc>
/// <para>
/// Gets a value indicating whether this <see cref='System.Drawing.PointF'/> is empty.
/// </para>
/// </devdoc>
[Browsable(false)]
public bool IsEmpty {
get {
return x == 0f && y == 0f;
}
}
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF.X"]/*' />
/// <devdoc>
/// <para>
/// Gets the x-coordinate of this <see cref='System.Drawing.PointF'/>.
/// </para>
/// </devdoc>
public float X {
get {
return x;
}
set {
x = value;
}
}
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF.Y"]/*' />
/// <devdoc>
/// <para>
/// Gets the y-coordinate of this <see cref='System.Drawing.PointF'/>.
/// </para>
/// </devdoc>
public float Y {
get {
return y;
}
set {
y = value;
}
}
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF.operator+"]/*' />
/// <devdoc>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by a given <see cref='System.Drawing.Size'/> .
/// </para>
/// </devdoc>
public static PointF operator +(PointF pt, Size sz) {
return Add(pt, sz);
}
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF.operator-"]/*' />
/// <devdoc>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by the negative of a given <see cref='System.Drawing.Size'/> .
/// </para>
/// </devdoc>
public static PointF operator -(PointF pt, Size sz) {
return Subtract(pt, sz);
}
/// <devdoc>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by a given <see cref='System.Drawing.SizeF'/> .
/// </para>
/// </devdoc>
public static PointF operator +(PointF pt, SizeF sz) {
return Add(pt, sz);
}
/// <devdoc>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by the negative of a given <see cref='System.Drawing.SizeF'/> .
/// </para>
/// </devdoc>
public static PointF operator -(PointF pt, SizeF sz) {
return Subtract(pt, sz);
}
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF.operator=="]/*' />
/// <devdoc>
/// <para>
/// Compares two <see cref='System.Drawing.PointF'/> objects. The result specifies
/// whether the values of the <see cref='System.Drawing.PointF.X'/> and <see cref='System.Drawing.PointF.Y'/> properties of the two <see cref='System.Drawing.PointF'/>
/// objects are equal.
/// </para>
/// </devdoc>
public static bool operator ==(PointF left, PointF right) {
return left.X == right.X && left.Y == right.Y;
}
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF.operator!="]/*' />
/// <devdoc>
/// <para>
/// Compares two <see cref='System.Drawing.PointF'/> objects. The result specifies whether the values
/// of the <see cref='System.Drawing.PointF.X'/> or <see cref='System.Drawing.PointF.Y'/> properties of the two
/// <see cref='System.Drawing.PointF'/>
/// objects are unequal.
/// </para>
/// </devdoc>
public static bool operator !=(PointF left, PointF right) {
return !(left == right);
}
/// <devdoc>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by a given <see cref='System.Drawing.Size'/> .
/// </para>
/// </devdoc>
public static PointF Add(PointF pt, Size sz) {
return new PointF(pt.X + sz.Width, pt.Y + sz.Height);
}
/// <devdoc>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by the negative of a given <see cref='System.Drawing.Size'/> .
/// </para>
/// </devdoc>
public static PointF Subtract(PointF pt, Size sz) {
return new PointF(pt.X - sz.Width, pt.Y - sz.Height);
}
/// <devdoc>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by a given <see cref='System.Drawing.SizeF'/> .
/// </para>
/// </devdoc>
public static PointF Add(PointF pt, SizeF sz){
return new PointF(pt.X + sz.Width, pt.Y + sz.Height);
}
/// <devdoc>
/// <para>
/// Translates a <see cref='System.Drawing.PointF'/> by the negative of a given <see cref='System.Drawing.SizeF'/> .
/// </para>
/// </devdoc>
public static PointF Subtract(PointF pt, SizeF sz){
return new PointF(pt.X - sz.Width, pt.Y - sz.Height);
}
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF.Equals"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override bool Equals(object obj) {
if (!(obj is PointF)) return false;
PointF comp = (PointF)obj;
return
comp.X == this.X &&
comp.Y == this.Y &&
comp.GetType().Equals(this.GetType());
}
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF.GetHashCode"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override int GetHashCode() {
return base.GetHashCode();
}
/// <include file='doc\PointF.uex' path='docs/doc[@for="PointF.ToString"]/*' />
public override string ToString() {
return string.Format(CultureInfo.CurrentCulture, "{{X={0}, Y={1}}}", x, y);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Xamarin.Forms.Xaml;
namespace Xamarin.Forms.Build.Tasks
{
class CreateObjectVisitor : IXamlNodeVisitor
{
public CreateObjectVisitor(ILContext context)
{
Context = context;
Module = context.Body.Method.Module;
}
public ILContext Context { get; }
ModuleDefinition Module { get; }
public bool VisitChildrenFirst
{
get { return true; }
}
public bool StopOnDataTemplate
{
get { return true; }
}
public bool StopOnResourceDictionary
{
get { return false; }
}
public void Visit(ValueNode node, INode parentNode)
{
Context.Values[node] = node.Value;
XmlName propertyName;
if (SetPropertiesVisitor.TryGetPropertyName(node, parentNode, out propertyName))
{
if (propertyName.NamespaceURI == "http://schemas.openxmlformats.org/markup-compatibility/2006" &&
propertyName.LocalName == "Ignorable")
{
(parentNode.IgnorablePrefixes ?? (parentNode.IgnorablePrefixes = new List<string>())).AddRange(
(node.Value as string).Split(','));
}
}
}
public void Visit(MarkupNode node, INode parentNode)
{
//At this point, all MarkupNodes are expanded to ElementNodes
}
public void Visit(ElementNode node, INode parentNode)
{
if (node.SkipPrefix((node.NamespaceResolver ?? parentNode.NamespaceResolver).LookupPrefix(node.NamespaceURI)))
return;
var typeref = node.XmlType.GetTypeReference(Module, node);
TypeDefinition typedef = typeref.Resolve();
if (IsXaml2009LanguagePrimitive(node))
{
var vardef = new VariableDefinition(typeref);
Context.Variables[node] = vardef;
Context.Body.Variables.Add(vardef);
Context.IL.Append(PushValueFromLanguagePrimitive(typedef, node));
Context.IL.Emit(OpCodes.Stloc, vardef);
}
else
{
MethodDefinition factoryCtorInfo = null;
MethodDefinition factoryMethodInfo = null;
MethodDefinition parameterizedCtorInfo = null;
MethodDefinition ctorInfo = null;
if (node.Properties.ContainsKey(XmlName.xArguments) && !node.Properties.ContainsKey(XmlName.xFactoryMethod))
{
factoryCtorInfo = typedef.AllMethods().FirstOrDefault(md => md.IsConstructor &&
!md.IsStatic &&
md.HasParameters &&
md.MatchXArguments(node, Module));
if (factoryCtorInfo == null)
{
throw new XamlParseException(
string.Format("No constructors found for {0} with matching x:Arguments", typedef.FullName), node);
}
ctorInfo = factoryCtorInfo;
if (!typedef.IsValueType) //for ctor'ing typedefs, we first have to ldloca before the params
Context.IL.Append(PushCtorXArguments(factoryCtorInfo, node));
}
else if (node.Properties.ContainsKey(XmlName.xFactoryMethod))
{
var factoryMethod = (string)(node.Properties[XmlName.xFactoryMethod] as ValueNode).Value;
factoryMethodInfo = typedef.AllMethods().FirstOrDefault(md => !md.IsConstructor &&
md.Name == factoryMethod &&
md.IsStatic &&
md.MatchXArguments(node, Module));
if (factoryMethodInfo == null)
{
throw new XamlParseException(
String.Format("No static method found for {0}::{1} ({2})", typedef.FullName, factoryMethod, null), node);
}
Context.IL.Append(PushCtorXArguments(factoryMethodInfo, node));
}
if (ctorInfo == null && factoryMethodInfo == null)
{
parameterizedCtorInfo = typedef.Methods.FirstOrDefault(md => md.IsConstructor &&
!md.IsStatic &&
md.HasParameters &&
md.Parameters.All(
pd =>
pd.CustomAttributes.Any(
ca =>
ca.AttributeType.FullName ==
"Xamarin.Forms.ParameterAttribute")));
}
if (parameterizedCtorInfo != null && ValidateCtorArguments(parameterizedCtorInfo, node))
{
ctorInfo = parameterizedCtorInfo;
// IL_0000: ldstr "foo"
Context.IL.Append(PushCtorArguments(parameterizedCtorInfo, node));
}
ctorInfo = ctorInfo ?? typedef.Methods.FirstOrDefault(md => md.IsConstructor && !md.HasParameters && !md.IsStatic);
var ctorinforef = ctorInfo?.ResolveGenericParameters(typeref, Module);
var factorymethodinforef = factoryMethodInfo?.ResolveGenericParameters(typeref, Module);
var implicitOperatorref = typedef.Methods.FirstOrDefault(md =>
md.IsPublic &&
md.IsStatic &&
md.IsSpecialName &&
md.Name == "op_Implicit" && md.Parameters[0].ParameterType.FullName == "System.String");
if (ctorinforef != null || factorymethodinforef != null || typedef.IsValueType)
{
VariableDefinition vardef = new VariableDefinition(typeref);
Context.Variables[node] = vardef;
Context.Body.Variables.Add(vardef);
ValueNode vnode = null;
if (node.CollectionItems.Count == 1 && (vnode = node.CollectionItems.First() as ValueNode) != null &&
vardef.VariableType.IsValueType)
{
//<Color>Purple</Color>
Context.IL.Append(vnode.PushConvertedValue(Context, typeref, new ICustomAttributeProvider[] { typedef },
node.PushServiceProvider(Context), false, true));
Context.IL.Emit(OpCodes.Stloc, vardef);
}
else if (node.CollectionItems.Count == 1 && (vnode = node.CollectionItems.First() as ValueNode) != null &&
implicitOperatorref != null)
{
//<FileImageSource>path.png</FileImageSource>
var implicitOperator = Module.Import(implicitOperatorref);
Context.IL.Emit(OpCodes.Ldstr, ((ValueNode)(node.CollectionItems.First())).Value as string);
Context.IL.Emit(OpCodes.Call, implicitOperator);
Context.IL.Emit(OpCodes.Stloc, vardef);
}
else if (factorymethodinforef != null)
{
var factory = Module.Import(factorymethodinforef);
Context.IL.Emit(OpCodes.Call, factory);
Context.IL.Emit(OpCodes.Stloc, vardef);
}
else if (!typedef.IsValueType)
{
var ctor = Module.Import(ctorinforef);
// IL_0001: newobj instance void class [Xamarin.Forms.Core]Xamarin.Forms.Button::'.ctor'()
// IL_0006: stloc.0
Context.IL.Emit(OpCodes.Newobj, ctor);
Context.IL.Emit(OpCodes.Stloc, vardef);
}
else if (ctorInfo != null && node.Properties.ContainsKey(XmlName.xArguments) &&
!node.Properties.ContainsKey(XmlName.xFactoryMethod) && ctorInfo.MatchXArguments(node, Module))
{
// IL_0008: ldloca.s 1
// IL_000a: ldc.i4.1
// IL_000b: call instance void valuetype Test/Foo::'.ctor'(bool)
var ctor = Module.Import(ctorinforef);
Context.IL.Emit(OpCodes.Ldloca, vardef);
Context.IL.Append(PushCtorXArguments(factoryCtorInfo, node));
Context.IL.Emit(OpCodes.Call, ctor);
}
else
{
// IL_0000: ldloca.s 0
// IL_0002: initobj Test/Foo
Context.IL.Emit(OpCodes.Ldloca, vardef);
Context.IL.Emit(OpCodes.Initobj, Module.Import(typedef));
}
if (typeref.FullName == "Xamarin.Forms.Xaml.TypeExtension")
{
var visitor = new SetPropertiesVisitor(Context);
foreach (var cnode in node.Properties.Values.ToList())
cnode.Accept(visitor, node);
foreach (var cnode in node.CollectionItems)
cnode.Accept(visitor, node);
//As we're stripping the TypeExtension bare, keep the type if we need it later (hint: we do need it)
INode ntype;
if (!node.Properties.TryGetValue(new XmlName("", "TypeName"), out ntype))
ntype = node.CollectionItems[0];
var type = ((ValueNode)ntype).Value as string;
var namespaceuri = type.Contains(":") ? node.NamespaceResolver.LookupNamespace(type.Split(':')[0].Trim()) : "";
type = type.Contains(":") ? type.Split(':')[1].Trim() : type;
Context.TypeExtensions[node] = new XmlType(namespaceuri, type, null).GetTypeReference(Module, node);
node.Properties.Clear();
node.CollectionItems.Clear();
var vardefref = new VariableDefinitionReference(vardef);
Context.IL.Append(SetPropertiesVisitor.ProvideValue(vardefref, Context, Module, node));
if (vardef != vardefref.VariableDefinition)
{
Context.Variables[node] = vardefref.VariableDefinition;
Context.Body.Variables.Add(vardefref.VariableDefinition);
}
}
}
}
}
public void Visit(RootNode node, INode parentNode)
{
// IL_0013: ldarg.0
// IL_0014: stloc.3
var ilnode = (ILRootNode)node;
var typeref = ilnode.TypeReference;
var vardef = new VariableDefinition(typeref);
Context.Variables[node] = vardef;
Context.Root = vardef;
Context.Body.Variables.Add(vardef);
Context.IL.Emit(OpCodes.Ldarg_0);
Context.IL.Emit(OpCodes.Stloc, vardef);
}
public void Visit(ListNode node, INode parentNode)
{
XmlName name;
if (SetPropertiesVisitor.TryGetPropertyName(node, parentNode, out name))
node.XmlName = name;
}
bool ValidateCtorArguments(MethodDefinition ctorinfo, ElementNode enode)
{
foreach (var parameter in ctorinfo.Parameters)
{
var propname =
parameter.CustomAttributes.First(ca => ca.AttributeType.FullName == "Xamarin.Forms.ParameterAttribute")
.ConstructorArguments.First()
.Value as string;
if (!enode.Properties.ContainsKey(new XmlName("", propname)))
return false;
}
return true;
}
IEnumerable<Instruction> PushCtorArguments(MethodDefinition ctorinfo, ElementNode enode)
{
foreach (var parameter in ctorinfo.Parameters)
{
var propname =
parameter.CustomAttributes.First(ca => ca.AttributeType.FullName == "Xamarin.Forms.ParameterAttribute")
.ConstructorArguments.First()
.Value as string;
var node = enode.Properties[new XmlName("", propname)];
enode.Properties.Remove(new XmlName("", propname));
VariableDefinition vardef;
ValueNode vnode = null;
if (node is IElementNode && (vardef = Context.Variables[node as IElementNode]) != null)
yield return Instruction.Create(OpCodes.Ldloc, vardef);
else if ((vnode = node as ValueNode) != null)
{
foreach (var instruction in vnode.PushConvertedValue(Context,
parameter.ParameterType,
new ICustomAttributeProvider[] { parameter, parameter.ParameterType.Resolve() },
enode.PushServiceProvider(Context), false, true))
yield return instruction;
}
}
}
IEnumerable<Instruction> PushCtorXArguments(MethodDefinition factoryCtorInfo, ElementNode enode)
{
if (!enode.Properties.ContainsKey(XmlName.xArguments))
yield break;
var arguments = new List<INode>();
var node = enode.Properties[XmlName.xArguments] as ElementNode;
if (node != null)
arguments.Add(node);
var list = enode.Properties[XmlName.xArguments] as ListNode;
if (list != null)
{
foreach (var n in list.CollectionItems)
arguments.Add(n);
}
for (var i = 0; i < factoryCtorInfo.Parameters.Count; i++)
{
var parameter = factoryCtorInfo.Parameters[i];
var arg = arguments[i];
VariableDefinition vardef;
ValueNode vnode = null;
if (arg is IElementNode && (vardef = Context.Variables[arg as IElementNode]) != null)
yield return Instruction.Create(OpCodes.Ldloc, vardef);
else if ((vnode = arg as ValueNode) != null)
{
foreach (var instruction in vnode.PushConvertedValue(Context,
parameter.ParameterType,
new ICustomAttributeProvider[] { parameter, parameter.ParameterType.Resolve() },
enode.PushServiceProvider(Context), false, true))
yield return instruction;
}
}
}
static bool IsXaml2009LanguagePrimitive(IElementNode node)
{
if (node.NamespaceURI == "http://schemas.microsoft.com/winfx/2009/xaml")
return true;
if (node.NamespaceURI != "clr-namespace:System;assembly=mscorlib")
return false;
var name = node.XmlType.Name.Split(':')[1];
if (name == "Boolean" ||
name == "String" ||
name == "Char" ||
name == "Decimal" ||
name == "Single" ||
name == "Double" ||
name == "Byte" ||
name == "Int16" ||
name == "Int32" ||
name == "Int64" ||
name == "TimeSpan" ||
name == "Uri")
return true;
return false;
}
IEnumerable<Instruction> PushValueFromLanguagePrimitive(TypeDefinition typedef, ElementNode node)
{
var hasValue = node.CollectionItems.Count == 1 && node.CollectionItems[0] is ValueNode &&
((ValueNode)node.CollectionItems[0]).Value is string;
var valueString = hasValue ? ((ValueNode)node.CollectionItems[0]).Value as string : string.Empty;
switch (typedef.FullName)
{
case "System.Boolean":
bool outbool;
if (hasValue && bool.TryParse(valueString, out outbool))
yield return Instruction.Create(outbool ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
else
yield return Instruction.Create(OpCodes.Ldc_I4_0);
break;
case "System.String":
yield return Instruction.Create(OpCodes.Ldstr, valueString);
break;
case "System.Object":
var ctorinfo =
Context.Body.Method.Module.TypeSystem.Object.Resolve()
.Methods.FirstOrDefault(md => md.IsConstructor && !md.HasParameters);
var ctor = Context.Body.Method.Module.Import(ctorinfo);
yield return Instruction.Create(OpCodes.Newobj, ctor);
break;
case "System.Char":
char outchar;
if (hasValue && char.TryParse(valueString, out outchar))
yield return Instruction.Create(OpCodes.Ldc_I4, outchar);
else
yield return Instruction.Create(OpCodes.Ldc_I4, 0x00);
break;
case "System.Decimal":
decimal outdecimal;
if (hasValue && decimal.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outdecimal))
{
var vardef = new VariableDefinition(Context.Body.Method.Module.Import(typeof (decimal)));
Context.Body.Variables.Add(vardef);
//Use an extra temp var so we can push the value to the stack, just like other cases
// IL_0003: ldstr "adecimal"
// IL_0008: ldc.i4.s 0x6f
// IL_000a: call class [mscorlib]System.Globalization.CultureInfo class [mscorlib]System.Globalization.CultureInfo::get_InvariantCulture()
// IL_000f: ldloca.s 0
// IL_0011: call bool valuetype [mscorlib]System.Decimal::TryParse(string, valuetype [mscorlib]System.Globalization.NumberStyles, class [mscorlib]System.IFormatProvider, [out] valuetype [mscorlib]System.Decimal&)
// IL_0016: pop
yield return Instruction.Create(OpCodes.Ldstr, valueString);
yield return Instruction.Create(OpCodes.Ldc_I4, 0x6f); //NumberStyles.Number
var getInvariantInfo =
Context.Body.Method.Module.Import(typeof (CultureInfo))
.Resolve()
.Properties.FirstOrDefault(pd => pd.Name == "InvariantCulture")
.GetMethod;
var getInvariant = Context.Body.Method.Module.Import(getInvariantInfo);
yield return Instruction.Create(OpCodes.Call, getInvariant);
yield return Instruction.Create(OpCodes.Ldloca, vardef);
var tryParseInfo =
Context.Body.Method.Module.Import(typeof (decimal))
.Resolve()
.Methods.FirstOrDefault(md => md.Name == "TryParse" && md.Parameters.Count == 4);
var tryParse = Context.Body.Method.Module.Import(tryParseInfo);
yield return Instruction.Create(OpCodes.Call, tryParse);
yield return Instruction.Create(OpCodes.Pop);
yield return Instruction.Create(OpCodes.Ldloc, vardef);
}
else
{
yield return Instruction.Create(OpCodes.Ldc_I4_0);
var decimalctorinfo =
Context.Body.Method.Module.Import(typeof (decimal))
.Resolve()
.Methods.FirstOrDefault(
md => md.IsConstructor && md.Parameters.Count == 1 && md.Parameters[0].ParameterType.FullName == "System.Int32");
var decimalctor = Context.Body.Method.Module.Import(decimalctorinfo);
yield return Instruction.Create(OpCodes.Newobj, decimalctor);
}
break;
case "System.Single":
float outfloat;
if (hasValue && float.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outfloat))
yield return Instruction.Create(OpCodes.Ldc_R4, outfloat);
else
yield return Instruction.Create(OpCodes.Ldc_R4, 0f);
break;
case "System.Double":
double outdouble;
if (hasValue && double.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outdouble))
yield return Instruction.Create(OpCodes.Ldc_R8, outdouble);
else
yield return Instruction.Create(OpCodes.Ldc_R8, 0d);
break;
case "System.Byte":
byte outbyte;
if (hasValue && byte.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outbyte))
yield return Instruction.Create(OpCodes.Ldc_I4, (int)outbyte);
else
yield return Instruction.Create(OpCodes.Ldc_I4, 0x00);
break;
case "System.Int16":
short outshort;
if (hasValue && short.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outshort))
yield return Instruction.Create(OpCodes.Ldc_I4, outshort);
else
yield return Instruction.Create(OpCodes.Ldc_I4, 0x00);
break;
case "System.Int32":
int outint;
if (hasValue && int.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outint))
yield return Instruction.Create(OpCodes.Ldc_I4, outint);
else
yield return Instruction.Create(OpCodes.Ldc_I4, 0x00);
break;
case "System.Int64":
long outlong;
if (hasValue && long.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outlong))
yield return Instruction.Create(OpCodes.Ldc_I8, outlong);
else
yield return Instruction.Create(OpCodes.Ldc_I8, 0L);
break;
case "System.TimeSpan":
TimeSpan outspan;
if (hasValue && TimeSpan.TryParse(valueString, CultureInfo.InvariantCulture, out outspan))
{
var vardef = new VariableDefinition(Context.Body.Method.Module.Import(typeof (TimeSpan)));
Context.Body.Variables.Add(vardef);
//Use an extra temp var so we can push the value to the stack, just like other cases
yield return Instruction.Create(OpCodes.Ldstr, valueString);
var getInvariantInfo =
Context.Body.Method.Module.Import(typeof (CultureInfo))
.Resolve()
.Properties.FirstOrDefault(pd => pd.Name == "InvariantCulture")
.GetMethod;
var getInvariant = Context.Body.Method.Module.Import(getInvariantInfo);
yield return Instruction.Create(OpCodes.Call, getInvariant);
yield return Instruction.Create(OpCodes.Ldloca, vardef);
var tryParseInfo =
Context.Body.Method.Module.Import(typeof (TimeSpan))
.Resolve()
.Methods.FirstOrDefault(md => md.Name == "TryParse" && md.Parameters.Count == 3);
var tryParse = Context.Body.Method.Module.Import(tryParseInfo);
yield return Instruction.Create(OpCodes.Call, tryParse);
yield return Instruction.Create(OpCodes.Pop);
yield return Instruction.Create(OpCodes.Ldloc, vardef);
}
else
{
yield return Instruction.Create(OpCodes.Ldc_I8, 0L);
var timespanctorinfo =
Context.Body.Method.Module.Import(typeof (TimeSpan))
.Resolve()
.Methods.FirstOrDefault(
md => md.IsConstructor && md.Parameters.Count == 1 && md.Parameters[0].ParameterType.FullName == "System.Int64");
var timespanctor = Context.Body.Method.Module.Import(timespanctorinfo);
yield return Instruction.Create(OpCodes.Newobj, timespanctor);
}
break;
case "System.Uri":
Uri outuri;
if (hasValue && Uri.TryCreate(valueString, UriKind.RelativeOrAbsolute, out outuri))
{
var vardef = new VariableDefinition(Context.Body.Method.Module.Import(typeof (Uri)));
Context.Body.Variables.Add(vardef);
//Use an extra temp var so we can push the value to the stack, just like other cases
yield return Instruction.Create(OpCodes.Ldstr, valueString);
yield return Instruction.Create(OpCodes.Ldc_I4, (int)UriKind.RelativeOrAbsolute);
yield return Instruction.Create(OpCodes.Ldloca, vardef);
var tryCreateInfo =
Context.Body.Method.Module.Import(typeof (Uri))
.Resolve()
.Methods.FirstOrDefault(md => md.Name == "TryCreate" && md.Parameters.Count == 3);
var tryCreate = Context.Body.Method.Module.Import(tryCreateInfo);
yield return Instruction.Create(OpCodes.Call, tryCreate);
yield return Instruction.Create(OpCodes.Pop);
yield return Instruction.Create(OpCodes.Ldloc, vardef);
}
else
yield return Instruction.Create(OpCodes.Ldnull);
break;
default:
var defaultctorinfo = typedef.Methods.FirstOrDefault(md => md.IsConstructor && !md.HasParameters);
if (defaultctorinfo != null)
{
var defaultctor = Context.Body.Method.Module.Import(defaultctorinfo);
yield return Instruction.Create(OpCodes.Newobj, defaultctor);
}
else
{
//should never happen. but if it does, this prevents corrupting the IL stack
yield return Instruction.Create(OpCodes.Ldnull);
}
break;
}
}
}
}
| |
using Bridge.Contract;
using Bridge.Contract.Constants;
using ICSharpCode.NRefactory.CSharp;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
namespace Bridge.Translator
{
public class SwitchBlock : AbstractEmitterBlock
{
public SwitchBlock(IEmitter emitter, SwitchStatement switchStatement)
: base(emitter, switchStatement)
{
this.Emitter = emitter;
this.SwitchStatement = switchStatement;
}
public SwitchBlock(IEmitter emitter, SwitchSection switchSection)
: base(emitter, switchSection)
{
this.Emitter = emitter;
this.SwitchSection = switchSection;
}
public SwitchBlock(IEmitter emitter, CaseLabel caseLabel)
: base(emitter, caseLabel)
{
this.Emitter = emitter;
this.CaseLabel = caseLabel;
}
public SwitchStatement SwitchStatement
{
get;
set;
}
public SwitchSection SwitchSection
{
get;
set;
}
public CaseLabel CaseLabel
{
get;
set;
}
public SwitchStatement ParentAsyncSwitch
{
get;
set;
}
protected override void DoEmit()
{
if (this.SwitchStatement != null)
{
var awaiters = this.Emitter.IsAsync ? this.GetAwaiters(this.SwitchStatement) : null;
if (awaiters != null && awaiters.Length > 0)
{
this.VisitAsyncSwitchStatement();
}
else
{
this.VisitSwitchStatement();
}
}
else if (this.SwitchSection != null)
{
if (this.Emitter.AsyncSwitch != null)
{
throw new EmitterException(this.SwitchSection, "Async switch section must be handled by VisitAsyncSwitchStatement method");
}
else
{
this.VisitSwitchSection();
}
}
else
{
if (this.Emitter.AsyncSwitch != null)
{
throw new EmitterException(this.CaseLabel, "Async case label must be handled by VisitAsyncSwitchStatement method");
}
else
{
this.VisitCaseLabel();
}
}
}
protected void VisitAsyncSwitchStatement()
{
SwitchStatement switchStatement = this.SwitchStatement;
this.ParentAsyncSwitch = this.Emitter.AsyncSwitch;
this.Emitter.AsyncSwitch = switchStatement;
this.WriteAwaiters(switchStatement.Expression);
var oldValue = this.Emitter.ReplaceAwaiterByVar;
this.Emitter.ReplaceAwaiterByVar = true;
string key = null;
if (switchStatement.Expression is IdentifierExpression)
{
var oldBuilder = this.Emitter.Output;
this.Emitter.Output = new StringBuilder();
switchStatement.Expression.AcceptVisitor(this.Emitter);
key = this.Emitter.Output.ToString().Trim();
this.Emitter.Output = oldBuilder;
}
else
{
key = this.AddLocal(this.GetTempVarName(), null, AstType.Null);
this.Write(key);
this.Write(" = ");
switchStatement.Expression.AcceptVisitor(this.Emitter);
this.WriteSemiColon();
this.WriteNewLine();
}
this.Emitter.ReplaceAwaiterByVar = oldValue;
var list = switchStatement.SwitchSections.ToList();
list.Sort((s1, s2) =>
{
var lbl = s1.CaseLabels.FirstOrDefault(l => l.Expression.IsNull);
if (lbl != null)
{
return 1;
}
lbl = s2.CaseLabels.FirstOrDefault(l => l.Expression.IsNull);
if (lbl != null)
{
return -1;
}
return 0;
});
var jumpStatements = this.Emitter.JumpStatements;
this.Emitter.JumpStatements = new List<IJumpInfo>();
bool writeElse = false;
var thisStep = this.Emitter.AsyncBlock.Steps.Last();
var rr = this.Emitter.Resolver.ResolveNode(switchStatement.Expression, this.Emitter);
bool is64Bit = Helpers.Is64Type(rr.Type, this.Emitter.Resolver);
foreach (var switchSection in list)
{
this.VisitAsyncSwitchSection(switchSection, writeElse, key, is64Bit);
writeElse = true;
}
var nextStep = this.Emitter.AsyncBlock.AddAsyncStep();
thisStep.JumpToStep = nextStep.Step;
if (this.Emitter.JumpStatements.Count > 0)
{
this.Emitter.JumpStatements.Sort((j1, j2) => -j1.Position.CompareTo(j2.Position));
foreach (var jump in this.Emitter.JumpStatements)
{
if (jump.Break)
{
jump.Output.Insert(jump.Position, nextStep.Step);
}
else if (jumpStatements != null)
{
jumpStatements.Add(jump);
}
}
}
this.Emitter.JumpStatements = jumpStatements;
this.Emitter.AsyncSwitch = this.ParentAsyncSwitch;
}
protected void VisitAsyncSwitchSection(SwitchSection switchSection, bool writeElse, string switchKey, bool is64Bit)
{
var list = switchSection.CaseLabels.ToList();
list.Sort((l1, l2) =>
{
if (l1.Expression.IsNull)
{
return 1;
}
if (l2.Expression.IsNull)
{
return -1;
}
return 0;
});
if (writeElse)
{
this.WriteElse();
}
if (list.Any(l => l.Expression.IsNull))
{
if (!writeElse)
{
this.WriteElse();
}
}
else
{
this.WriteIf();
this.WriteOpenParentheses();
var oldValue = this.Emitter.ReplaceAwaiterByVar;
this.Emitter.ReplaceAwaiterByVar = true;
bool writeOr = false;
foreach (var label in list)
{
if (writeOr)
{
this.WriteSpace();
this.Write("||");
this.WriteSpace();
}
this.Write(switchKey);
if (is64Bit)
{
this.WriteDot();
this.Write(JS.Funcs.Math.EQ);
this.WriteOpenParentheses();
}
else
{
this.Write(" === ");
}
label.Expression.AcceptVisitor(this.Emitter);
if (is64Bit)
{
this.Write(")");
}
if (label.Expression is NullReferenceExpression)
{
this.WriteSpace();
this.Write("||");
this.WriteSpace();
this.Write(switchKey);
this.Write(" === undefined");
}
writeOr = true;
}
this.WriteCloseParentheses();
this.Emitter.ReplaceAwaiterByVar = oldValue;
}
var isBlock = false;
if (switchSection.Statements.Count == 1 && switchSection.Statements.First() is BlockStatement)
{
isBlock = true;
this.Emitter.IgnoreBlock = switchSection.Statements.First();
}
this.WriteSpace();
this.BeginBlock();
this.Write(JS.Vars.ASYNC_STEP + " = " + this.Emitter.AsyncBlock.Step + ";");
this.WriteNewLine();
this.Write("continue;");
var writer = this.SaveWriter();
var step = this.Emitter.AsyncBlock.AddAsyncStep();
step.Node = switchSection;
if (!isBlock)
{
this.PushLocals();
}
switchSection.Statements.AcceptVisitor(this.Emitter);
if (!isBlock)
{
this.PopLocals();
}
if (this.RestoreWriter(writer) && !this.IsOnlyWhitespaceOnPenultimateLine(true))
{
this.WriteNewLine();
}
this.EndBlock();
this.WriteNewLine();
}
protected void VisitSwitchStatement()
{
SwitchStatement switchStatement = this.SwitchStatement;
this.ParentAsyncSwitch = this.Emitter.AsyncSwitch;
this.Emitter.AsyncSwitch = null;
var jumpStatements = this.Emitter.JumpStatements;
this.Emitter.JumpStatements = null;
this.WriteSwitch();
this.WriteOpenParentheses();
var rr = this.Emitter.Resolver.ResolveNode(switchStatement.Expression, this.Emitter);
bool is64Bit = false;
bool wrap = true;
if (Helpers.Is64Type(rr.Type, this.Emitter.Resolver))
{
is64Bit = true;
wrap = !(rr is LocalResolveResult || rr is MemberResolveResult);
}
if (is64Bit && wrap)
{
this.WriteOpenParentheses();
}
switchStatement.Expression.AcceptVisitor(this.Emitter);
if (is64Bit)
{
if (wrap)
{
this.WriteCloseParentheses();
}
this.WriteDot();
this.Write(JS.Funcs.TOSTIRNG);
this.WriteOpenCloseParentheses();
}
this.WriteCloseParentheses();
this.WriteSpace();
this.BeginBlock();
switchStatement.SwitchSections.ToList().ForEach(s => s.AcceptVisitor(this.Emitter));
this.EndBlock();
this.WriteNewLine();
this.Emitter.JumpStatements = jumpStatements;
this.Emitter.AsyncSwitch = this.ParentAsyncSwitch;
}
protected void VisitSwitchSection()
{
SwitchSection switchSection = this.SwitchSection;
switchSection.CaseLabels.ToList().ForEach(l => l.AcceptVisitor(this.Emitter));
this.Indent();
var isBlock = switchSection.Statements.Count == 1 && switchSection.Statements.First() is BlockStatement;
if (!isBlock)
{
this.PushLocals();
}
var children = switchSection.Children.Where(c => c.Role == Roles.EmbeddedStatement || c.Role == Roles.Comment);
children.ToList().ForEach(s => s.AcceptVisitor(this.Emitter));
if (!isBlock)
{
this.PopLocals();
}
this.Outdent();
}
protected void VisitCaseLabel()
{
CaseLabel caseLabel = this.CaseLabel;
if (caseLabel.Expression.IsNull)
{
this.Write("default");
}
else
{
this.Write("case ");
var rr = this.Emitter.Resolver.ResolveNode(caseLabel.Expression.GetParent<SwitchStatement>().Expression, this.Emitter);
var caserr = this.Emitter.Resolver.ResolveNode(caseLabel.Expression, this.Emitter);
if (Helpers.Is64Type(rr.Type, this.Emitter.Resolver))
{
if (caserr is ConstantResolveResult)
{
this.WriteScript(caserr.ConstantValue.ToString());
}
else
{
caseLabel.Expression.AcceptVisitor(this.Emitter);
this.WriteDot();
this.Write(JS.Funcs.TOSTIRNG);
this.WriteOpenCloseParentheses();
}
}
else
{
caseLabel.Expression.AcceptVisitor(this.Emitter);
}
if (caserr.Type.Kind == TypeKind.Null)
{
this.WriteColon();
this.WriteNewLine();
this.Write("case undefined");
}
}
this.WriteColon();
this.WriteNewLine();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Text
{
using System;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
[Serializable]
public sealed class EncoderExceptionFallback : EncoderFallback
{
// Construction
public EncoderExceptionFallback()
{
}
public override EncoderFallbackBuffer CreateFallbackBuffer()
{
return new EncoderExceptionFallbackBuffer();
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return 0;
}
}
public override bool Equals(Object value)
{
EncoderExceptionFallback that = value as EncoderExceptionFallback;
if (that != null)
{
return (true);
}
return (false);
}
public override int GetHashCode()
{
return 654;
}
}
public sealed class EncoderExceptionFallbackBuffer : EncoderFallbackBuffer
{
public EncoderExceptionFallbackBuffer(){}
public override bool Fallback(char charUnknown, int index)
{
// Fall back our char
throw new EncoderFallbackException(
Environment.GetResourceString("Argument_InvalidCodePageConversionIndex",
(int)charUnknown, index), charUnknown, index);
}
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
{
if (!Char.IsHighSurrogate(charUnknownHigh))
{
throw new ArgumentOutOfRangeException("charUnknownHigh",
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xD800, 0xDBFF));
}
if (!Char.IsLowSurrogate(charUnknownLow))
{
throw new ArgumentOutOfRangeException("CharUnknownLow",
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xDC00, 0xDFFF));
}
Contract.EndContractBlock();
int iTemp = Char.ConvertToUtf32(charUnknownHigh, charUnknownLow);
// Fall back our char
throw new EncoderFallbackException(
Environment.GetResourceString("Argument_InvalidCodePageConversionIndex",
iTemp, index), charUnknownHigh, charUnknownLow, index);
}
public override char GetNextChar()
{
return (char)0;
}
public override bool MovePrevious()
{
// Exception fallback doesn't have anywhere to back up to.
return false;
}
// Exceptions are always empty
public override int Remaining
{
get
{
return 0;
}
}
}
[Serializable]
public sealed class EncoderFallbackException : ArgumentException
{
char charUnknown;
char charUnknownHigh;
char charUnknownLow;
int index;
public EncoderFallbackException()
: base(Environment.GetResourceString("Arg_ArgumentException"))
{
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
public EncoderFallbackException(String message)
: base(message)
{
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
public EncoderFallbackException(String message, Exception innerException)
: base(message, innerException)
{
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
internal EncoderFallbackException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
internal EncoderFallbackException(
String message, char charUnknown, int index) : base(message)
{
this.charUnknown = charUnknown;
this.index = index;
}
internal EncoderFallbackException(
String message, char charUnknownHigh, char charUnknownLow, int index) : base(message)
{
if (!Char.IsHighSurrogate(charUnknownHigh))
{
throw new ArgumentOutOfRangeException("charUnknownHigh",
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xD800, 0xDBFF));
}
if (!Char.IsLowSurrogate(charUnknownLow))
{
throw new ArgumentOutOfRangeException("CharUnknownLow",
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xDC00, 0xDFFF));
}
Contract.EndContractBlock();
this.charUnknownHigh = charUnknownHigh;
this.charUnknownLow = charUnknownLow;
this.index = index;
}
public char CharUnknown
{
get
{
return (charUnknown);
}
}
public char CharUnknownHigh
{
get
{
return (charUnknownHigh);
}
}
public char CharUnknownLow
{
get
{
return (charUnknownLow);
}
}
public int Index
{
get
{
return index;
}
}
// Return true if the unknown character is a surrogate pair.
public bool IsUnknownSurrogate()
{
return (this.charUnknownHigh != '\0');
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// Describes the storage that is available to a PVS site for caching purposes
/// First published in XenServer 7.1.
/// </summary>
public partial class PVS_cache_storage : XenObject<PVS_cache_storage>
{
#region Constructors
public PVS_cache_storage()
{
}
public PVS_cache_storage(string uuid,
XenRef<Host> host,
XenRef<SR> SR,
XenRef<PVS_site> site,
long size,
XenRef<VDI> VDI)
{
this.uuid = uuid;
this.host = host;
this.SR = SR;
this.site = site;
this.size = size;
this.VDI = VDI;
}
/// <summary>
/// Creates a new PVS_cache_storage from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public PVS_cache_storage(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new PVS_cache_storage from a Proxy_PVS_cache_storage.
/// </summary>
/// <param name="proxy"></param>
public PVS_cache_storage(Proxy_PVS_cache_storage proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given PVS_cache_storage.
/// </summary>
public override void UpdateFrom(PVS_cache_storage update)
{
uuid = update.uuid;
host = update.host;
SR = update.SR;
site = update.site;
size = update.size;
VDI = update.VDI;
}
internal void UpdateFrom(Proxy_PVS_cache_storage proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
SR = proxy.SR == null ? null : XenRef<SR>.Create(proxy.SR);
site = proxy.site == null ? null : XenRef<PVS_site>.Create(proxy.site);
size = proxy.size == null ? 0 : long.Parse(proxy.size);
VDI = proxy.VDI == null ? null : XenRef<VDI>.Create(proxy.VDI);
}
public Proxy_PVS_cache_storage ToProxy()
{
Proxy_PVS_cache_storage result_ = new Proxy_PVS_cache_storage();
result_.uuid = uuid ?? "";
result_.host = host ?? "";
result_.SR = SR ?? "";
result_.site = site ?? "";
result_.size = size.ToString();
result_.VDI = VDI ?? "";
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this PVS_cache_storage
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("host"))
host = Marshalling.ParseRef<Host>(table, "host");
if (table.ContainsKey("SR"))
SR = Marshalling.ParseRef<SR>(table, "SR");
if (table.ContainsKey("site"))
site = Marshalling.ParseRef<PVS_site>(table, "site");
if (table.ContainsKey("size"))
size = Marshalling.ParseLong(table, "size");
if (table.ContainsKey("VDI"))
VDI = Marshalling.ParseRef<VDI>(table, "VDI");
}
public bool DeepEquals(PVS_cache_storage other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._SR, other._SR) &&
Helper.AreEqual2(this._site, other._site) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._VDI, other._VDI);
}
internal static List<PVS_cache_storage> ProxyArrayToObjectList(Proxy_PVS_cache_storage[] input)
{
var result = new List<PVS_cache_storage>();
foreach (var item in input)
result.Add(new PVS_cache_storage(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, PVS_cache_storage server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static PVS_cache_storage get_record(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_record(session.opaque_ref, _pvs_cache_storage);
else
return new PVS_cache_storage(session.proxy.pvs_cache_storage_get_record(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get a reference to the PVS_cache_storage instance with the specified UUID.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PVS_cache_storage> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<PVS_cache_storage>.Create(session.proxy.pvs_cache_storage_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new PVS_cache_storage instance, and return its handle.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<PVS_cache_storage> create(Session session, PVS_cache_storage _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_create(session.opaque_ref, _record);
else
return XenRef<PVS_cache_storage>.Create(session.proxy.pvs_cache_storage_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new PVS_cache_storage instance, and return its handle.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, PVS_cache_storage _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pvs_cache_storage_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.proxy.async_pvs_cache_storage_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified PVS_cache_storage instance.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static void destroy(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pvs_cache_storage_destroy(session.opaque_ref, _pvs_cache_storage);
else
session.proxy.pvs_cache_storage_destroy(session.opaque_ref, _pvs_cache_storage ?? "").parse();
}
/// <summary>
/// Destroy the specified PVS_cache_storage instance.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<Task> async_destroy(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pvs_cache_storage_destroy(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<Task>.Create(session.proxy.async_pvs_cache_storage_destroy(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static string get_uuid(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_uuid(session.opaque_ref, _pvs_cache_storage);
else
return session.proxy.pvs_cache_storage_get_uuid(session.opaque_ref, _pvs_cache_storage ?? "").parse();
}
/// <summary>
/// Get the host field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<Host> get_host(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_host(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<Host>.Create(session.proxy.pvs_cache_storage_get_host(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the SR field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<SR> get_SR(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_sr(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<SR>.Create(session.proxy.pvs_cache_storage_get_sr(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the site field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<PVS_site> get_site(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_site(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<PVS_site>.Create(session.proxy.pvs_cache_storage_get_site(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the size field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static long get_size(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_size(session.opaque_ref, _pvs_cache_storage);
else
return long.Parse(session.proxy.pvs_cache_storage_get_size(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the VDI field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<VDI> get_VDI(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_vdi(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<VDI>.Create(session.proxy.pvs_cache_storage_get_vdi(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Return a list of all the PVS_cache_storages known to the system.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PVS_cache_storage>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_all(session.opaque_ref);
else
return XenRef<PVS_cache_storage>.Create(session.proxy.pvs_cache_storage_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the PVS_cache_storage Records at once, in a single XML RPC call
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PVS_cache_storage>, PVS_cache_storage> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_all_records(session.opaque_ref);
else
return XenRef<PVS_cache_storage>.Create<Proxy_PVS_cache_storage>(session.proxy.pvs_cache_storage_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// The host on which this object defines PVS cache storage
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host>))]
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host = new XenRef<Host>("OpaqueRef:NULL");
/// <summary>
/// SR providing storage for the PVS cache
/// </summary>
[JsonConverter(typeof(XenRefConverter<SR>))]
public virtual XenRef<SR> SR
{
get { return _SR; }
set
{
if (!Helper.AreEqual(value, _SR))
{
_SR = value;
Changed = true;
NotifyPropertyChanged("SR");
}
}
}
private XenRef<SR> _SR = new XenRef<SR>("OpaqueRef:NULL");
/// <summary>
/// The PVS_site for which this object defines the storage
/// </summary>
[JsonConverter(typeof(XenRefConverter<PVS_site>))]
public virtual XenRef<PVS_site> site
{
get { return _site; }
set
{
if (!Helper.AreEqual(value, _site))
{
_site = value;
Changed = true;
NotifyPropertyChanged("site");
}
}
}
private XenRef<PVS_site> _site = new XenRef<PVS_site>("OpaqueRef:NULL");
/// <summary>
/// The size of the cache VDI (in bytes)
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
Changed = true;
NotifyPropertyChanged("size");
}
}
}
private long _size = 21474836480;
/// <summary>
/// The VDI used for caching
/// </summary>
[JsonConverter(typeof(XenRefConverter<VDI>))]
public virtual XenRef<VDI> VDI
{
get { return _VDI; }
set
{
if (!Helper.AreEqual(value, _VDI))
{
_VDI = value;
Changed = true;
NotifyPropertyChanged("VDI");
}
}
}
private XenRef<VDI> _VDI = new XenRef<VDI>("OpaqueRef:NULL");
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// 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 Alachisoft.NCache.Common.Pooling.Lease;
using Alachisoft.NCache.Common.Pooling.Extension;
namespace Alachisoft.NCache.Common.Protobuf
{
public partial class Command : SimpleLease
{
#region ILeasable
public override sealed void ResetLeasable()
{
switch (type)
{
case Type.ADD:
addCommand = null;
break;
case Type.ADD_BULK:
bulkAddCommand = null;
break;
case Type.GET_BULK:
bulkGetCommand = null;
break;
case Type.INSERT_BULK:
bulkInsertCommand = null;
break;
case Type.REMOVE_BULK:
bulkRemoveCommand = null;
break;
case Type.CLEAR:
clearCommand = null;
break;
case Type.CONTAINS:
containsCommand = null;
break;
case Type.COUNT:
countCommand = null;
break;
case Type.DISPOSE:
disposeCommand = null;
break;
case Type.GET_CACHE_ITEM:
getCacheItemCommand = null;
break;
case Type.GET:
getCommand = null;
break;
case Type.GET_COMPACT_TYPES:
getCompactTypesCommand = null;
break;
case Type.GET_ENUMERATOR:
getEnumeratorCommand = null;
break;
case Type.GET_HASHMAP:
getHashmapCommand = null;
break;
case Type.GET_OPTIMAL_SERVER:
getOptimalServerCommand = null;
break;
case Type.GET_TYPEINFO_MAP:
getTypeInfoMapCommand = null;
break;
case Type.INIT:
initCommand = null;
break;
case Type.INSERT:
insertCommand = null;
break;
case Type.RAISE_CUSTOM_EVENT:
raiseCustomEventCommand = null;
break;
case Type.REGISTER_KEY_NOTIF:
registerKeyNotifCommand = null;
break;
case Type.REGISTER_NOTIF:
registerNotifCommand = null;
break;
case Type.REMOVE:
removeCommand = null;
break;
case Type.LOCK:
lockCommand = null;
break;
case Type.UNLOCK:
unlockCommand = null;
break;
case Type.ISLOCKED:
isLockedCommand = null;
break;
case Type.LOCK_VERIFY:
lockVerifyCommand = null;
break;
case Type.UNREGISTER_KEY_NOTIF:
unRegisterKeyNotifCommand = null;
break;
case Type.UNREGISTER_BULK_KEY_NOTIF:
unRegisterBulkKeyNotifCommand = null;
break;
case Type.REGISTER_BULK_KEY_NOTIF:
registerBulkKeyNotifCommand = null;
break;
case Type.GET_LOGGING_INFO:
getLoggingInfoCommand = null;
break;
case Type.DELETE_BULK:
bulkDeleteCommand = null;
break;
case Type.DELETE:
deleteCommand = null;
break;
case Type.GET_NEXT_CHUNK:
getNextChunkCommand = null;
break;
case Type.GET_GROUP_NEXT_CHUNK:
getGroupNextChunkCommand = null;
break;
case Type.ADD_ATTRIBUTE:
addAttributeCommand = null;
break;
case Type.GET_RUNNING_SERVERS:
getRunningServersCommand = null;
break;
case Type.SYNC_EVENTS:
syncEventsCommand = null;
break;
case Type.DELETEQUERY:
deleteQueryCommand = null;
break;
case Type.GET_PRODUCT_VERSION:
getProductVersionCommand = null;
break;
case Type.GET_SERVER_MAPPING:
getServerMappingCommand = null;
break;
case Type.INQUIRY_REQUEST:
inquiryRequestCommand = null;
break;
case Type.GET_CACHE_BINDING:
getCacheBindingCommand = null;
break;
case Type.GET_READER_CHUNK:
getReaderNextChunkCommand = null;
break;
case Type.DISPOSE_READER:
disposeReaderCommand = null;
break;
case Type.GET_EXPIRATION:
getExpirationCommand = null;
break;
case Type.GET_LC_DATA:
getLCCommand = null;
break;
case Type.POLL:
pollCommand = null;
break;
case Type.REGISTER_POLLING_NOTIFICATION:
registerPollNotifCommand = null;
break;
case Type.GET_CONNECTED_CLIENTS:
getConnectedClientsCommand = null;
break;
case Type.TOUCH:
touchCommand = null;
break;
case Type.GET_CACHE_MANAGEMENT_PORT:
getCacheManagementPortCommand = null;
break;
case Type.GET_TOPIC:
getTopicCommand = null;
break;
case Type.SUBSCRIBE_TOPIC:
subscribeTopicCommand = null;
break;
case Type.REMOVE_TOPIC:
removeTopicCommand = null;
break;
case Type.UNSUBSCRIBE_TOPIC:
unSubscribeTopicCommand = null;
break;
case Type.MESSAGE_PUBLISH:
messagePublishCommand = null;
break;
case Type.GET_MESSAGE:
getMessageCommand = null;
break;
case Type.MESSAGE_ACKNOWLEDGMENT:
mesasgeAcknowledgmentCommand = null;
break;
case Type.PING:
pingCommand = null;
break;
case Type.MESSAGE_COUNT:
messageCountCommand = null;
break;
case Type.GET_SERIALIZATION_FORMAT:
getSerializationFormatCommand = null;
break;
case Type.GET_BULK_CACHEITEM:
bulkGetCacheItemCommand = null;
break;
case Type.CONTAINS_BULK:
containsBulkCommand = null;
break;
default:
throw new System.Exception($"Case not handled for command type '{type}' in order to reset it.");
}
commandID = -1;
type = Type.ADD;
commandVersion = 0;
MethodOverload = 0;
clientLastViewId = -1;
version = string.Empty;
isRetryCommand = false;
requestID = default(long);
intendedRecipient = string.Empty;
extensionObject = default(ProtoBuf.IExtension);
}
public override sealed void ReturnLeasableToPool()
{
switch (type)
{
case Type.ADD:
(addCommand as SimpleLease)?.ReturnLeasableToPool();
break;
case Type.ADD_DEPENDENCY:
break;
case Type.ADD_SYNC_DEPENDENCY:
break;
case Type.ADD_BULK:
break;
case Type.GET_BULK:
break;
case Type.INSERT_BULK:
break;
case Type.REMOVE_BULK:
break;
case Type.CLEAR:
break;
case Type.CONTAINS:
break;
case Type.COUNT:
break;
case Type.DISPOSE:
break;
case Type.GET_CACHE_ITEM:
break;
case Type.GET:
(getCommand as SimpleLease)?.ReturnLeasableToPool();
break;
case Type.GET_COMPACT_TYPES:
break;
case Type.GET_ENUMERATOR:
break;
case Type.GET_HASHMAP:
break;
case Type.GET_OPTIMAL_SERVER:
break;
case Type.GET_TYPEINFO_MAP:
break;
case Type.INIT:
break;
case Type.INSERT:
(insertCommand as SimpleLease)?.ReturnLeasableToPool();
break;
case Type.RAISE_CUSTOM_EVENT:
break;
case Type.REGISTER_KEY_NOTIF:
break;
case Type.REGISTER_NOTIF:
break;
case Type.REMOVE:
(removeCommand as SimpleLease)?.ReturnLeasableToPool();
break;
case Type.SEARCH:
break;
case Type.LOCK:
break;
case Type.UNLOCK:
break;
case Type.ISLOCKED:
break;
case Type.LOCK_VERIFY:
break;
case Type.UNREGISTER_KEY_NOTIF:
break;
case Type.UNREGISTER_BULK_KEY_NOTIF:
break;
case Type.REGISTER_BULK_KEY_NOTIF:
break;
case Type.GET_LOGGING_INFO:
break;
case Type.UNREGISTER_CQ:
break;
case Type.SEARCH_CQ:
break;
case Type.REGISTER_CQ:
break;
case Type.DELETE_BULK:
break;
case Type.DELETE:
break;
case Type.GET_NEXT_CHUNK:
break;
case Type.GET_GROUP_NEXT_CHUNK:
break;
case Type.ADD_ATTRIBUTE:
break;
case Type.GET_RUNNING_SERVERS:
break;
case Type.SYNC_EVENTS:
break;
case Type.DELETEQUERY:
break;
case Type.GET_PRODUCT_VERSION:
break;
case Type.GET_SERVER_MAPPING:
break;
case Type.INQUIRY_REQUEST:
break;
case Type.GET_CACHE_BINDING:
break;
case Type.EXECUTE_READER:
break;
case Type.GET_READER_CHUNK:
break;
case Type.DISPOSE_READER:
break;
case Type.EXECUTE_READER_CQ:
break;
case Type.GET_EXPIRATION:
break;
case Type.GET_LC_DATA:
break;
case Type.POLL:
break;
case Type.REGISTER_POLLING_NOTIFICATION:
break;
case Type.GET_CONNECTED_CLIENTS:
break;
case Type.TOUCH:
break;
case Type.GET_CACHE_MANAGEMENT_PORT:
break;
case Type.GET_TOPIC:
break;
case Type.SUBSCRIBE_TOPIC:
break;
case Type.REMOVE_TOPIC:
break;
case Type.UNSUBSCRIBE_TOPIC:
break;
case Type.MESSAGE_PUBLISH:
break;
case Type.GET_MESSAGE:
break;
case Type.MESSAGE_ACKNOWLEDGMENT:
break;
case Type.PING:
break;
case Type.MESSAGE_COUNT:
break;
case Type.GET_SERIALIZATION_FORMAT:
break;
case Type.GET_BULK_CACHEITEM:
break;
case Type.CONTAINS_BULK:
break;
default:
throw new System.Exception($"Case not handled for command type '{type}' in order to return to pool.");
}
PoolManager.GetProtobufCommandPool()?.Return(this);
}
#endregion
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT 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.
*
* SharpNEAT 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 SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* Changed (well hacked ...) by Christoph Kutza for Unity support.
*
*/
using System;
using System.Collections.Generic;
using System.Threading;
using SharpNeat.Core;
#if NET4
using log4net;
#endif
// Disable missing comment warnings for non-private variables.
#pragma warning disable 1591
namespace SharpNeat.EvolutionAlgorithms
{
/// <summary>
/// Abstract class providing some common/baseline data and methods for implementions of IEvolutionAlgorithm.
/// </summary>
/// <typeparam name="TGenome">The genome type that the algorithm will operate on.</typeparam>
public abstract class AbstractGenerationalAlgorithm<TGenome> : IEvolutionAlgorithm<TGenome>
where TGenome : class, IGenome<TGenome>
{
#if NET4
private static readonly ILog __log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endif
#region Instance Fields
protected IGenomeListEvaluator<TGenome> _genomeListEvaluator;
protected IGenomeFactory<TGenome> _genomeFactory;
protected List<TGenome> _genomeList;
protected int _populationSize;
protected TGenome _currentBestGenome;
// Algorithm state data.
RunState _runState = RunState.NotReady;
protected uint _currentGeneration;
// Update event scheme / data.
UpdateScheme _updateScheme;
uint _prevUpdateGeneration;
long _prevUpdateTimeTick;
// Misc working variables.
Thread _algorithmThread;
bool _pauseRequestFlag;
readonly AutoResetEvent _awaitPauseEvent = new AutoResetEvent(false);
readonly AutoResetEvent _awaitRestartEvent = new AutoResetEvent(false);
#endregion
#region Events
/// <summary>
/// Notifies listeners that some state change has occured.
/// </summary>
public event EventHandler UpdateEvent;
/// <summary>
/// Notifies listeners that the algorithm has paused.
/// </summary>
public event EventHandler PausedEvent;
#endregion
#region Properties
/// <summary>
/// Gets the current generation.
/// </summary>
public uint CurrentGeneration
{
get { return _currentGeneration; }
}
#endregion
#region IEvolutionAlgorithm<TGenome> Members
/// <summary>
/// Gets or sets the algorithm's update scheme.
/// </summary>
public UpdateScheme UpdateScheme
{
get { return _updateScheme; }
set { _updateScheme = value; }
}
/// <summary>
/// Gets the current execution/run state of the IEvolutionAlgorithm.
/// </summary>
public RunState RunState
{
get { return _runState; }
}
/// <summary>
/// Gets the population's current champion genome.
/// </summary>
public TGenome CurrentChampGenome
{
get { return _currentBestGenome; }
}
/// <summary>
/// Gets a value indicating whether some goal fitness has been achieved and that the algorithm has therefore stopped.
/// </summary>
public bool StopConditionSatisfied
{
get { return _genomeListEvaluator.StopConditionSatisfied; }
}
/// <summary>
/// Initializes the evolution algorithm with the provided IGenomeListEvaluator, IGenomeFactory
/// and an initial population of genomes.
/// </summary>
/// <param name="genomeListEvaluator">The genome evaluation scheme for the evolution algorithm.</param>
/// <param name="genomeFactory">The factory that was used to create the genomeList and which is therefore referenced by the genomes.</param>
/// <param name="genomeList">An initial genome population.</param>
public virtual void Initialize(IGenomeListEvaluator<TGenome> genomeListEvaluator,
IGenomeFactory<TGenome> genomeFactory,
List<TGenome> genomeList)
{
_currentGeneration = 0;
_genomeListEvaluator = genomeListEvaluator;
_genomeFactory = genomeFactory;
_genomeList = genomeList;
_populationSize = _genomeList.Count;
_runState = RunState.Ready;
_updateScheme = new UpdateScheme(new TimeSpan(0, 0, 1));
}
/// <summary>
/// Initializes the evolution algorithm with the provided IGenomeListEvaluator
/// and an IGenomeFactory that can be used to create an initial population of genomes.
/// </summary>
/// <param name="genomeListEvaluator">The genome evaluation scheme for the evolution algorithm.</param>
/// <param name="genomeFactory">The factory that was used to create the genomeList and which is therefore referenced by the genomes.</param>
/// <param name="populationSize">The number of genomes to create for the initial population.</param>
public virtual void Initialize(IGenomeListEvaluator<TGenome> genomeListEvaluator,
IGenomeFactory<TGenome> genomeFactory,
int populationSize)
{
_currentGeneration = 0;
_genomeListEvaluator = genomeListEvaluator;
_genomeFactory = genomeFactory;
_genomeList = genomeFactory.CreateGenomeList(populationSize, _currentGeneration);
_populationSize = populationSize;
_runState = RunState.Ready;
_updateScheme = new UpdateScheme(new TimeSpan(0, 0, 1));
}
/// <summary>
/// Starts the algorithm running. The algorithm will switch to the Running state from either
/// the Ready or Paused states.
/// </summary>
public void StartContinue()
{
// RunState must be Ready or Paused.
if(RunState.Ready == _runState)
{ // Create a new thread and start it running.
_algorithmThread = new Thread(AlgorithmThreadMethod);
_algorithmThread.IsBackground = true;
_algorithmThread.Priority = ThreadPriority.BelowNormal;
_runState = RunState.Running;
OnUpdateEvent();
_algorithmThread.Start();
}
else if(RunState.Paused == _runState)
{ // Thread is paused. Resume execution.
_runState = RunState.Running;
OnUpdateEvent();
_awaitRestartEvent.Set();
}
else if(RunState.Running == _runState)
{ // Already running. Log a warning.
#if NET4
__log.Warn("StartContinue() called but algorithm is already running.");
#endif
}
else
{
throw new SharpNeatException(string.Format("StartContinue() call failed. Unexpected RunState [{0}]", _runState));
}
}
/// <summary>
/// Alias for RequestPause().
/// </summary>
public void Stop()
{
RequestPause();
}
/// <summary>
/// Requests that the algorithm pauses but doesn't wait for the algorithm thread to stop.
/// The algorithm thread will pause when it is next convenient to do so, and will notify
/// listeners via an UpdateEvent.
/// </summary>
public void RequestPause()
{
if(RunState.Running == _runState) {
_pauseRequestFlag = true;
}
else
{
#if NET4
__log.Warn("RequestPause() called but algorithm is not running.");
#endif
}
}
/// <summary>
/// Request that the algorithm pause and waits for the algorithm to do so. The algorithm
/// thread will pause when it is next convenient to do so and notifies any UpdateEvent
/// listeners prior to returning control to the caller. Therefore it's generally a bad idea
/// to call this method from a GUI thread that also has code that may be called by the
/// UpdateEvent - doing so will result in deadlocked threads.
/// </summary>
public void RequestPauseAndWait()
{
if(RunState.Running == _runState)
{ // Set a flag that tells the algorithm thread to enter the paused state and wait
// for a signal that tells us the thread has paused.
_pauseRequestFlag = true;
_awaitPauseEvent.WaitOne();
}
else
{
#if NET4
__log.Warn("RequestPauseAndWait() called but algorithm is not running.");
#endif
}
}
#endregion
#region Private/Protected Methods [Evolution Algorithm]
private void AlgorithmThreadMethod()
{
try
{
_prevUpdateGeneration = 0;
_prevUpdateTimeTick = DateTime.Now.Ticks;
for(;;)
{
_currentGeneration++;
PerformOneGeneration();
if(UpdateTest())
{
_prevUpdateGeneration = _currentGeneration;
_prevUpdateTimeTick = DateTime.Now.Ticks;
OnUpdateEvent();
}
// Check if a pause has been requested.
// Access to the flag is not thread synchronized, but it doesn't really matter if
// we miss it being set and perform one other generation before pausing.
if(_pauseRequestFlag || _genomeListEvaluator.StopConditionSatisfied)
{
// Signal to any waiting thread that we are pausing
_awaitPauseEvent.Set();
// Reset the flag. Update RunState and notify any listeners of the state change.
_pauseRequestFlag = false;
_runState = RunState.Paused;
OnUpdateEvent();
OnPausedEvent();
// Wait indefinitely for a signal to wake up and continue.
_awaitRestartEvent.WaitOne();
}
}
}
catch(ThreadAbortException)
{ // Quietly exit thread.
}
}
/// <summary>
/// Returns true if it is time to raise an update event.
/// </summary>
private bool UpdateTest()
{
if(UpdateMode.Generational == _updateScheme.UpdateMode) {
return (_currentGeneration - _prevUpdateGeneration) >= _updateScheme.Generations;
}
return (DateTime.Now.Ticks - _prevUpdateTimeTick) >= _updateScheme.TimeSpan.Ticks;
}
private void OnUpdateEvent()
{
if(null != UpdateEvent)
{
// Catch exceptions thrown by even listeners. This prevents listener exceptions from terminating the algorithm thread.
try {
UpdateEvent(this, EventArgs.Empty);
}
catch(Exception ex) {
#if NET4
__log.Error("UpdateEvent listener threw exception", ex);
#endif
}
}
}
private void OnPausedEvent()
{
if(null != PausedEvent)
{
// Catch exceptions thrown by even listeners. This prevents listener exceptions from terminating the algorithm thread.
try {
PausedEvent(this, EventArgs.Empty);
}
catch(Exception ex)
{
#if NET4
__log.Error("PausedEvent listener threw exception", ex);
#endif
}
}
}
/// <summary>
/// Progress forward by one generation. Perform one generation/cycle of the evolution algorithm.
/// </summary>
protected abstract void PerformOneGeneration();
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmEmergencyProcedures.
/// </summary>
public partial class frmProcTasks : System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
protected System.Web.UI.WebControls.Label Label2;
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
Load_Procedures();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.processCommand);
this.DataGrid1.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.deleteRow);
}
#endregion
private void Load_Procedures()
{
//if (Convert.IsDBNull(Session["OrgNamet"]) == false)
if (!IsPostBack)
{
lblOrg.Text=Session["OrgNamet"].ToString();
loadData();
}
}
private void loadData ()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_RetrieveProcTasks";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Caller",SqlDbType.NVarChar);
cmd.Parameters["@Caller"].Value=Session["CallerTasks"].ToString();
cmd.Parameters.Add ("@LocId",SqlDbType.Int);
cmd.Parameters["@LocId"].Value=Session["LocId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"Tasks");
Session["ds"] = ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
}
private void deleteRow(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_DeleteTask";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value=Int32.Parse (e.Item.Cells[0].Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
private void processCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == "Update")
{
Session["CallerUpdTask"]="frmTasks";
Response.Redirect (strURL + "frmUpdTask.aspx?"
+ "&btnAction=" + "Update"
+ "&Id=" + e.Item.Cells[0].Text
+ "&Name=" + e.Item.Cells[1].Text
+ "&Desc=" + e.Item.Cells[2].Text
+ "&Status=" + e.Item.Cells[3].Text
+ "&StartTime=" + e.Item.Cells[4].Text
+ "&EndTime=" + e.Item.Cells[5].Text
+ "&LocId=" + e.Item.Cells[9].Text
+ "&ProcId=" + e.Item.Cells[13].Text);
}
else if (e.CommandName == "Plan")
{
Session["CallerTaskSteps"]="frmTasks";
Session["TaskName"]=e.Item.Cells[1].Text;
Session["ServiceName"]=e.Item.Cells[7].Text;
Session["TaskId"]=e.Item.Cells[0].Text;
Session["LocId"]=e.Item.Cells[9].Text;
Session["StepType"]="na";
Response.Redirect (strURL + "frmTaskSteps.aspx?");
}
else if (e.CommandName == "Register")
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_UpdateTaskPeople";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@PeopleId", SqlDbType.Int);
cmd.Parameters["@PeopleId"].Value=Session["PeopleId"].ToString();
cmd.Parameters.Add ("@TaskId", SqlDbType.Int);
cmd.Parameters["@TaskId"].Value=e.Item.Cells[0].Text;
cmd.Parameters.Add ("@Type", SqlDbType.NVarChar);
if (Session["startForm"].ToString() == "frmMainStaff")
{
cmd.Parameters["@Type"].Value="Client";
}
else
{
cmd.Parameters["@Type"].Value="Staff";
}
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
if (Session["startForm"].ToString() == "frmMainOrgs")
{
Response.Redirect (strURL + Session["CallerServices"].ToString() + ".aspx?");
}
else if ((Session["startForm"].ToString() == "frmMainStaff")
|| (Session["startForm"].ToString() == "frmMainTrg"))
{
Response.Redirect (strURL + Session["CallerTasks"].ToString() + ".aspx?");
}
}
else if (e.CommandName == "Clients")
{
Session["CallerTaskPeople"]="frmTasks";
Session["ServiceName"]=e.Item.Cells[7].Text;
Session["TaskName"]=e.Item.Cells[1].Text;
Session["Type"]="Client";
Session["TaskId"]=e.Item.Cells[0].Text;
//["ParentRoleId"]=12;//12=Roles.ParentId for Students
Response.Redirect (strURL + "frmTaskPeople.aspx?"
+ "&LocName=" + e.Item.Cells[6].Text
+ "&StartTime=" + e.Item.Cells[4].Text);
}
else if (e.CommandName == "Staff")
{
Session["CallerTaskPeople"]="frmTasks";
Session["ServiceName"]=e.Item.Cells[7].Text;
Session["TaskName"]=e.Item.Cells[1].Text;
Session["Type"]="Staff";
Session["TaskId"]=e.Item.Cells[0].Text;
//["ParentRoleId"]=12;//12=Roles.ParentId for Students
Response.Redirect (strURL + "frmTaskPeople.aspx?"
+ "&LocName=" + e.Item.Cells[6].Text
+ "&StartTime=" + e.Item.Cells[4].Text);
}
else if (e.CommandName == "Details")
{
Session["CallerTaskDetail"]="frmTasks";
Response.Redirect (strURL + "frmTaskDetail.aspx?"
//+ "&ServiceName=" + e.Item.Cells[1].Text
//+ "&Start=" + e.Item.Cells[2].Text
//+ "&End=" + e.Item.Cells[3].Text
//+ "&RegStatus=" + e.Item.Cells[4].Text
+ "&Desc=" + e.Item.Cells[2].Text
//+ "&StaffClient=" + e.Item.Cells[8].Text
//+ "&TaskName=" + e.Item.Cells[10].Text
//+ "&EventName=" + e.Item.Cells[11].Text
//+ "&LicOrg=" + e.Item.Cells[12].Text
//+ "&MgrOrg=" + e.Item.Cells[13].Text
//+ "&LicId=" + e.Item.Cells[14].Text
//+ "&Status=" + e.Item.Cells[15].Text //
//+ "&Loc=" + e.Item.Cells[16].Text
//+ "&LocAddress=" + e.Item.Cells[17].Text
//+ "&Comment=" + e.Item.Cells[18].Text
);
}
}
protected void btnAdd_Click(object sender, System.EventArgs e)
{
Session["CallerUpdTask"]="frmTasks";
Response.Redirect (strURL + "frmUpdTask.aspx?"
+ "&btnAction=" + "Add");
}
protected void btnExit_Click(object sender, System.EventArgs e)
{
Response.Redirect (strURL + Session["CallerProcTasks"].ToString() + ".aspx?");
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using System.Linq;
using MindTouch.Deki.Data;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Deki.Logic {
public static class BanningBL {
// -- Constants --
private const string BANTOKEN = "bantoken";
public static void PerformBanCheck() {
string[] clientIPs = DetermineSourceIPs();
ulong banMask = 0;
List<string> banReasons = new List<string>();
ulong? cachedBanMask = GetBanMaskFromCache(DekiContext.Current.User.ID, clientIPs);
if (cachedBanMask != null) {
//TODO MaxM: Ban reeasons isn't currently cached (or used)
banMask = cachedBanMask.Value;
} else {
IList<BanBE> bans = DbUtils.CurrentSession.Bans_GetByRequest(DekiContext.Current.User.ID, clientIPs.ToList());
foreach (BanBE ban in bans) {
if ((ban.Expires ?? DateTime.MaxValue) >= DateTime.UtcNow) {
banMask |= ban.RevokeMask;
banReasons.Add(ban.Reason);
}
}
CacheBanMask(DekiContext.Current.User.ID, clientIPs, banMask);
}
DekiContext.Current.BanPermissionRevokeMask = banMask;
DekiContext.Current.BanReasons = banReasons.ToArray();
}
public static XDoc RetrieveBans() {
IList<BanBE> bans = DbUtils.CurrentSession.Bans_GetAll();
return GetBanListXml(bans);
}
public static BanBE GetById(uint id) {
return DbUtils.CurrentSession.Bans_GetAll().FirstOrDefault(e => e.Id == id);
}
public static BanBE SaveBan(XDoc doc) {
BanBE ban = ReadBanXml(doc);
if(ArrayUtil.IsNullOrEmpty(ban.BanAddresses) && ArrayUtil.IsNullOrEmpty(ban.BanUserIds)) {
throw new Exceptions.BanEmptyException();
}
if(ban.RevokeMask == 0) {
throw new Exceptions.BanNoPermsException();
}
TokenReset();
uint banId = DbUtils.CurrentSession.Bans_Insert(ban);
if (banId == 0) {
return null;
} else {
ban.Id = banId;
return ban;
}
}
public static void DeleteBan(BanBE ban) {
if (ban != null) {
DbUtils.CurrentSession.Bans_Delete(ban.Id);
TokenReset();
}
}
#region XML Helpers
private static BanBE ReadBanXml(XDoc doc) {
BanBE b = new BanBE();
b.BanAddresses = new List<string>();
b.BanUserIds = new List<uint>();
try {
b.Reason = doc["description"].AsText;
b.RevokeMask = PermissionsBL.MaskFromPermissionList(PermissionsBL.PermissionListFromString(doc["permissions.revoked/operations"].AsText ?? string.Empty));
b.LastEdit = DateTime.UtcNow;
b.Expires = doc["date.expires"].AsDate;
b.ByUserId = DekiContext.Current.User.ID;
foreach (XDoc val in doc["ban.addresses/address"]) {
if (!val.IsEmpty) {
b.BanAddresses.Add(val.AsText);
}
}
foreach (XDoc val in doc["ban.users/user"]) {
uint? id = val["@id"].AsUInt;
if (id != null) {
b.BanUserIds.Add(id ?? 0);
}
}
} catch (Exception x) {
throw new DreamAbortException(DreamMessage.BadRequest(x.Message));
}
return b;
}
public static XDoc GetBanXml(BanBE ban) {
return AppendBanXml(new XDoc("ban"), ban);
}
public static XDoc GetBanListXml(IList<BanBE> bans) {
XDoc doc = new XDoc("bans");
foreach (BanBE b in bans) {
doc.Start("ban");
doc = AppendBanXml(doc, b);
doc.End();
}
return doc;
}
private static XDoc AppendBanXml(XDoc doc, BanBE ban) {
UserBE createdBy = UserBL.GetUserById(ban.ByUserId);
doc.Attr("id", ban.Id);
doc.Attr("href", DekiContext.Current.ApiUri.At("site", "bans", ban.Id.ToString()));
if (createdBy != null) {
doc.Add(UserBL.GetUserXml(createdBy, "createdby", Utils.ShowPrivateUserInfo(createdBy)));
}
doc.Elem("date.modified", ban.LastEdit);
doc.Elem("description", ban.Reason);
doc.Elem("date.expires", ban.Expires);
doc.Add(PermissionsBL.GetPermissionXml(ban.RevokeMask, "revoked"));
doc.Start("ban.addresses");
if (ban.BanAddresses != null) {
foreach (string address in ban.BanAddresses) {
doc.Elem("address", address);
}
}
doc.End();
doc.Start("ban.users");
if (ban.BanUserIds != null) {
IList<UserBE> banUsers = DbUtils.CurrentSession.Users_GetByIds(ban.BanUserIds);
foreach(UserBE u in banUsers){
doc.Add(UserBL.GetUserXml(u, null, Utils.ShowPrivateUserInfo(createdBy)));
}
}
doc.End();
return doc;
}
#endregion
#region Private helper methods
private static string[] DetermineSourceIPs() {
return DreamContext.Current.Request.Headers.GetValues(DreamHeaders.DREAM_CLIENTIP);
}
private static string BuildCacheKey(string token, uint userid, string[] clientips) {
return string.Format("{0}.{1}|{2}", token, userid, string.Join(",", clientips));
}
private static void CacheBanMask(uint userid, string[] clientips, ulong banMask) {
if (DekiContext.Current.Instance.CacheBans) {
string token = TokenGet();
DekiContext.Current.Instance.Cache.Set(BuildCacheKey(token, userid, clientips), banMask, DateTime.UtcNow.AddSeconds(30));
}
}
private static ulong? GetBanMaskFromCache(uint userid, string[] clientips) {
ulong? banmask = null;
if (DekiContext.Current.Instance.CacheBans) {
string token = TokenGet();
banmask = DekiContext.Current.Instance.Cache.Get<ulong?>(BuildCacheKey(token, userid, clientips), null);
}
return banmask;
}
private static string TokenReset() {
if(!DekiContext.Current.Instance.CacheBans) {
return string.Empty;
}
string token = DateTime.UtcNow.Ticks.ToString();
DekiContext.Current.Instance.Cache.Set(BANTOKEN, token);
return token;
}
private static string TokenGet() {
string token = DekiContext.Current.Instance.Cache.Get<string>(BANTOKEN, null);
if(token == null) {
token = TokenReset();
}
return token;
}
#endregion
}
}
| |
using YAF.Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace YAF.Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/// <summary>
/// A simple append only random-access <see cref="BytesRef"/> array that stores full
/// copies of the appended bytes in a <see cref="ByteBlockPool"/>.
/// <para/>
/// <b>Note: this class is not Thread-Safe!</b>
/// <para/>
/// @lucene.internal
/// @lucene.experimental
/// </summary>
public sealed class BytesRefArray
{
private readonly ByteBlockPool pool;
private int[] offsets = new int[1];
private int lastElement = 0;
private int currentOffset = 0;
private readonly Counter bytesUsed;
/// <summary>
/// Creates a new <see cref="BytesRefArray"/> with a counter to track allocated bytes
/// </summary>
public BytesRefArray(Counter bytesUsed)
{
this.pool = new ByteBlockPool(new ByteBlockPool.DirectTrackingAllocator(bytesUsed));
pool.NextBuffer();
bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + RamUsageEstimator.NUM_BYTES_INT32);
this.bytesUsed = bytesUsed;
}
/// <summary>
/// Clears this <see cref="BytesRefArray"/>
/// </summary>
public void Clear()
{
lastElement = 0;
currentOffset = 0;
Array.Clear(offsets, 0, offsets.Length);
pool.Reset(false, true); // no need to 0 fill the buffers we control the allocator
}
/// <summary>
/// Appends a copy of the given <see cref="BytesRef"/> to this <see cref="BytesRefArray"/>. </summary>
/// <param name="bytes"> The bytes to append </param>
/// <returns> The index of the appended bytes </returns>
public int Append(BytesRef bytes)
{
if (lastElement >= offsets.Length)
{
int oldLen = offsets.Length;
offsets = ArrayUtil.Grow(offsets, offsets.Length + 1);
bytesUsed.AddAndGet((offsets.Length - oldLen) * RamUsageEstimator.NUM_BYTES_INT32);
}
pool.Append(bytes);
offsets[lastElement++] = currentOffset;
currentOffset += bytes.Length;
return lastElement - 1;
}
/// <summary>
/// Returns the current size of this <see cref="BytesRefArray"/>.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
/// <returns> The current size of this <see cref="BytesRefArray"/> </returns>
public int Length => lastElement;
/// <summary>
/// Returns the <i>n'th</i> element of this <see cref="BytesRefArray"/> </summary>
/// <param name="spare"> A spare <see cref="BytesRef"/> instance </param>
/// <param name="index"> The elements index to retrieve </param>
/// <returns> The <i>n'th</i> element of this <see cref="BytesRefArray"/> </returns>
public BytesRef Get(BytesRef spare, int index)
{
if (lastElement > index)
{
int offset = offsets[index];
int length = index == lastElement - 1 ? currentOffset - offset : offsets[index + 1] - offset;
if (Debugging.AssertsEnabled) Debugging.Assert(spare.Offset == 0);
spare.Grow(length);
spare.Length = length;
pool.ReadBytes(offset, spare.Bytes, spare.Offset, spare.Length);
return spare;
}
throw new IndexOutOfRangeException("index " + index + " must be less than the size: " + lastElement);
}
private int[] Sort(IComparer<BytesRef> comp)
{
int[] orderedEntries = new int[Length];
for (int i = 0; i < orderedEntries.Length; i++)
{
orderedEntries[i] = i;
}
new IntroSorterAnonymousClass(this, comp, orderedEntries).Sort(0, Length);
return orderedEntries;
}
private class IntroSorterAnonymousClass : IntroSorter
{
private readonly BytesRefArray outerInstance;
private readonly IComparer<BytesRef> comp;
private readonly int[] orderedEntries;
public IntroSorterAnonymousClass(BytesRefArray outerInstance, IComparer<BytesRef> comp, int[] orderedEntries)
{
this.outerInstance = outerInstance;
this.comp = comp;
this.orderedEntries = orderedEntries;
pivot = new BytesRef();
scratch1 = new BytesRef();
scratch2 = new BytesRef();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void Swap(int i, int j)
{
int o = orderedEntries[i];
orderedEntries[i] = orderedEntries[j];
orderedEntries[j] = o;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override int Compare(int i, int j)
{
int idx1 = orderedEntries[i], idx2 = orderedEntries[j];
return comp.Compare(outerInstance.Get(scratch1, idx1), outerInstance.Get(scratch2, idx2));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void SetPivot(int i)
{
int index = orderedEntries[i];
outerInstance.Get(pivot, index);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override int ComparePivot(int j)
{
int index = orderedEntries[j];
return comp.Compare(pivot, outerInstance.Get(scratch2, index));
}
private readonly BytesRef pivot;
private readonly BytesRef scratch1;
private readonly BytesRef scratch2;
}
/// <summary>
/// Sugar for <see cref="GetIterator(IComparer{BytesRef})"/> with a <c>null</c> comparer
/// </summary>
[Obsolete("Use GetEnumerator() instead. This method will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public IBytesRefIterator GetIterator()
{
return GetIterator(null);
}
/// <summary>
/// <para>
/// Returns a <see cref="IBytesRefIterator"/> with point in time semantics. The
/// iterator provides access to all so far appended <see cref="BytesRef"/> instances.
/// </para>
/// <para>
/// If a non <c>null</c> <see cref="T:IComparer{BytesRef}"/> is provided the iterator will
/// iterate the byte values in the order specified by the comparer. Otherwise
/// the order is the same as the values were appended.
/// </para>
/// <para>
/// This is a non-destructive operation.
/// </para>
/// </summary>
[Obsolete("Use GetEnumerator(IComparer<BytesRef>) instead. This method will be removed in 4.8.0 release candidate"), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public IBytesRefIterator GetIterator(IComparer<BytesRef> comp)
{
BytesRef spare = new BytesRef();
int size = Length;
int[] indices = comp is null ? null : Sort(comp);
return new BytesRefIteratorAnonymousClass(this, comp, spare, size, indices);
}
[Obsolete("This class will be removed in 4.8.0 release candidate"), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
private class BytesRefIteratorAnonymousClass : IBytesRefIterator
{
private readonly BytesRefArray outerInstance;
private readonly IComparer<BytesRef> comp;
private readonly BytesRef spare;
private readonly int size;
private readonly int[] indices;
public BytesRefIteratorAnonymousClass(BytesRefArray outerInstance, IComparer<BytesRef> comp, BytesRef spare, int size, int[] indices)
{
this.outerInstance = outerInstance;
this.comp = comp;
this.spare = spare;
this.size = size;
this.indices = indices;
pos = 0;
}
internal int pos;
public virtual BytesRef Next()
{
if (pos < size)
{
return outerInstance.Get(spare, indices is null ? pos++ : indices[pos++]);
}
return null;
}
public virtual IComparer<BytesRef> Comparer => comp;
}
/// <summary>
/// Sugar for <see cref="GetEnumerator(IComparer{BytesRef})"/> with a <c>null</c> comparer.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public IBytesRefEnumerator GetEnumerator()
=> GetEnumerator(null);
/// <summary>
/// <para>
/// Returns a <see cref="IBytesRefEnumerator"/> with point in time semantics. The
/// enumerator provides access to all so far appended <see cref="BytesRef"/> instances.
/// </para>
/// <para>
/// If a non <c>null</c> <see cref="T:IComparer{BytesRef}"/> is provided the enumerator will
/// iterate the byte values in the order specified by the comparer. Otherwise
/// the order is the same as the values were appended.
/// </para>
/// <para>
/// This is a non-destructive operation.
/// </para>
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public IBytesRefEnumerator GetEnumerator(IComparer<BytesRef> comparer)
{
int[] indices = comparer is null ? null : Sort(comparer);
return new Enumerator(this, comparer, this.Length, indices);
}
private struct Enumerator : IBytesRefEnumerator
{
private readonly IComparer<BytesRef> comparer;
private readonly BytesRef spare;
private readonly int size;
private readonly int[] indices;
private readonly BytesRefArray bytesRefArray;
private int pos;
public Enumerator(BytesRefArray bytesRefArray, IComparer<BytesRef> comparer, int size, int[] indices)
{
this.spare = new BytesRef();
this.pos = 0;
this.Current = null;
this.bytesRefArray = bytesRefArray;
this.comparer = comparer;
this.size = size;
this.indices = indices;
}
public BytesRef Current { get; private set; }
public bool MoveNext()
{
if (pos < size)
{
Current = bytesRefArray.Get(spare, indices is null ? pos++ : indices[pos++]);
return true;
}
Current = null;
return false;
}
public IComparer<BytesRef> Comparer => comparer;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Text;
using Epi;
using Epi.Collections;
using Epi.Windows;
using Epi.Analysis;
using Epi.Windows.Dialogs;
using Epi.Windows.Analysis;
using Epi.Data.Services;
namespace Epi.Windows.Analysis.Dialogs
{
/// <summary>
/// Set Dialog
/// </summary>
public partial class SetDialog : CommandDesignDialog
{
/// <summary>
/// Boolean isDialogMode
/// </summary>
public bool isDialogMode = false;
#region Public Interface
#region Constructor
/// <summary>
/// Default constructor - NOT TO BE USED FOR INSTANTIATION
/// </summary>
[Obsolete("Use of default constructor not allowed", true)]
public SetDialog()
{
InitializeComponent();
}
/// <summary>
/// Constructor for SetDialog
/// </summary>
/// <param name="frm">Main form</param>
public SetDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm)
: base(frm)
{
InitializeComponent();
Construct();
}
#endregion Constructors
#endregion Public Interface
#region Protected Interface
/// <summary>
/// Builds the command text
/// </summary>
protected override void GenerateCommand()
{
Configuration config = Configuration.GetNewInstance();
KeyValuePairCollection kvPairs = new KeyValuePairCollection();
kvPairs.Delimiter = CharLiterals.SPACE;
if ((cmbYesAs.Text != config.Settings.RepresentationOfYes) || (hasYesAsChanged))
{
kvPairs.Add(new KeyValuePair(ShortHands.YES, Util.InsertInDoubleQuotes(cmbYesAs.Text)));
}
if ((cmbNoAs.Text != config.Settings.RepresentationOfNo) || (hasNoAsChanged))
{
kvPairs.Add(new KeyValuePair(ShortHands.NO, Util.InsertInDoubleQuotes(cmbNoAs.Text)));
}
if ((cmbMissingAs.Text != config.Settings.RepresentationOfMissing) || (hasMissingAsChanged))
{
kvPairs.Add(new KeyValuePair(ShortHands.MISSING, Util.InsertInDoubleQuotes(cmbMissingAs.Text)));
}
if ((cbxGraphics.Checked != config.Settings.ShowGraphics) || (hasShowGraphicChanged))
{
kvPairs.Add(new KeyValuePair(CommandNames.FREQGRAPH,
Epi.Util.GetShortHand(cbxGraphics.Checked)));
}
if ((cbxHyperlinks.Checked != config.Settings.ShowHyperlinks) || (hasShowHyperlinkChanged))
{
kvPairs.Add(new KeyValuePair(CommandNames.HYPERLINKS,
Epi.Util.GetShortHand(cbxHyperlinks.Checked)));
}
if ((cbxPercents.Checked != config.Settings.ShowPercents) || (hasShowPercentsChanged))
{
kvPairs.Add(new KeyValuePair(CommandNames.PERCENTS,
Epi.Util.GetShortHand(cbxPercents.Checked)));
}
if ((cbxSelectCriteria.Checked != config.Settings.ShowSelection) || (hasShowSelectChanged))
{
kvPairs.Add(new KeyValuePair(CommandNames.SELECT,
Epi.Util.GetShortHand(cbxSelectCriteria.Checked)));
}
if ((cbxShowPrompt.Checked != config.Settings.ShowCompletePrompt) || (hasShowPromptChanged))
{
kvPairs.Add(new KeyValuePair(CommandNames.SHOWPROMPTS,
Epi.Util.GetShortHand(cbxShowPrompt.Checked)));
}
if ((cbxTablesOutput.Checked != config.Settings.ShowTables) || (hasShowTablesChanged))
{
kvPairs.Add(new KeyValuePair(CommandNames.TABLES,
Epi.Util.GetShortHand(cbxTablesOutput.Checked)));
}
if ((cbxIncludeMissing.Checked != config.Settings.IncludeMissingValues) || (hasIncludeMissingChanged))
{
kvPairs.Add(new KeyValuePair(CommandNames.MISSING,
Epi.Util.GetShortHand(cbxIncludeMissing.Checked)));
}
if (hasStatisticsLevelChanged)
{
StatisticsLevel levelIdSelected = (StatisticsLevel)short.Parse(WinUtil.GetSelectedRadioButton(gbxStatistics).Tag.ToString());
string levelTagSelected = AppData.Instance.GetStatisticsLevelById(levelIdSelected).Tag;
kvPairs.Add(new KeyValuePair(CommandNames.STATISTICS, levelTagSelected));
}
if (hasProcessRecordsChanged)
{
RecordProcessingScope scopeIdSelected = (RecordProcessingScope)short.Parse(WinUtil.GetSelectedRadioButton(gbxProcessRecords).Tag.ToString());
string scopeTagSelected = AppData.Instance.GetRecordProcessessingScopeById(scopeIdSelected).Tag;
kvPairs.Add(new KeyValuePair(CommandNames.PROCESS, scopeTagSelected));
}
WordBuilder command = new WordBuilder();
//Generate command only if there are key value pairs
if (kvPairs.Count > 0)
{
if (!this.isDialogMode)
{
command.Append(CommandNames.SET);
}
command.Append(kvPairs.ToString());
if (!this.isDialogMode)
{
command.Append(" END-SET\n");
}
this.CommandText = command.ToString();
}
else
{
this.CommandText = string.Empty;
}
}
/// <summary>
/// Validates user input
/// </summary>
/// <returns>True/False depending upon whether errors were generated</returns>
protected override bool ValidateInput()
{
return base.ValidateInput();
}
#endregion Protected Interface
#region Private Attributes
private bool hasYesAsChanged;
private bool hasNoAsChanged;
private bool hasMissingAsChanged;
private bool hasShowPromptChanged;
private bool hasShowGraphicChanged;
private bool hasShowHyperlinkChanged;
private bool hasShowSelectChanged;
private bool hasShowPercentsChanged;
private bool hasShowTablesChanged;
private bool hasStatisticsLevelChanged;
private bool hasIncludeMissingChanged;
private bool hasProcessRecordsChanged;
#endregion Private Attributes
#region Public Methods
/// <summary>
/// Loads the settings from the configuration file.
/// </summary>
public void ShowSettings(Configuration pConfig = null)
{
Configuration config = null;
if (pConfig == null)
{
config = Configuration.GetNewInstance();
}
else
{
config = pConfig;
}
Epi.DataSets.Config.SettingsRow settings = config.Settings;
// Representation of boolean values ...
cmbYesAs.SelectedItem = settings.RepresentationOfYes;
cmbNoAs.SelectedItem = settings.RepresentationOfNo;
cmbMissingAs.SelectedItem = settings.RepresentationOfMissing;
// HTML output options ...
cbxShowPrompt.Checked = settings.ShowCompletePrompt;
cbxSelectCriteria.Checked = settings.ShowSelection;
cbxPercents.Checked = settings.ShowPercents;
cbxGraphics.Checked = settings.ShowGraphics;
cbxHyperlinks.Checked = settings.ShowHyperlinks;
cbxTablesOutput.Checked = settings.ShowTables;
// Statistics Options
WinUtil.SetSelectedRadioButton(settings.StatisticsLevel.ToString(), gbxStatistics);
numericUpDownPrecision.Value = settings.PrecisionForStatistics;
// Record Processing
WinUtil.SetSelectedRadioButton(settings.RecordProcessingScope.ToString(), gbxProcessRecords);
cbxIncludeMissing.Checked = settings.IncludeMissingValues;
}
#endregion //Public Methods
#region Private Methods
private void Construct()
{
if (!this.DesignMode) // designer throws an error
{
this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click);
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
}
}
/// <summary>
/// Reset hasChanged values
/// </summary>
private void ResetHasChangedValues(bool changed)
{
hasIncludeMissingChanged = changed;
hasMissingAsChanged = changed;
hasNoAsChanged = changed;
hasYesAsChanged = changed;
hasShowGraphicChanged = changed;
hasShowHyperlinkChanged = changed;
hasShowPercentsChanged = changed;
hasShowPromptChanged = changed;
hasShowSelectChanged = changed;
hasShowTablesChanged = changed;
hasStatisticsLevelChanged = changed;
hasProcessRecordsChanged = changed;
}
#region Private Methods
/// <summary>
/// Loads combobox with values for RepresentationsOfYes from application data file
/// </summary>
private void LoadRepresentionsOfYes()
{
string currentRepresentationOfYes = Configuration.GetNewInstance().Settings.RepresentationOfYes;
DataView dv = AppData.Instance.RepresentationsOfYesDataTable.DefaultView;
cmbYesAs.Items.Clear();
if (!string.IsNullOrEmpty(currentRepresentationOfYes))
{
cmbYesAs.Items.Add(currentRepresentationOfYes);
}
dv.Sort = ColumnNames.POSITION;
foreach (DataRowView row in dv)
{
string name = row[ColumnNames.NAME].ToString();
if (name != currentRepresentationOfYes)
{
cmbYesAs.Items.Add(row[ColumnNames.NAME]);
}
}
cmbYesAs.SelectedIndex = 0;
}
/// <summary>
/// Loads combobox with values for RepresentationsOfNo from application data file
/// </summary>
private void LoadRepresentionsOfNo()
{
string currentRepresentationOfNo = Configuration.GetNewInstance().Settings.RepresentationOfNo;
DataView dv = AppData.Instance.RepresentationsOfNoDataTable.DefaultView;
cmbNoAs.Items.Clear();
if (!string.IsNullOrEmpty(currentRepresentationOfNo))
{
cmbNoAs.Items.Add(currentRepresentationOfNo);
}
dv.Sort = ColumnNames.POSITION;
foreach (DataRowView row in dv)
{
string name = row[ColumnNames.NAME].ToString();
if (name != currentRepresentationOfNo)
{
cmbNoAs.Items.Add(name);
}
}
cmbNoAs.SelectedIndex = 0;
}
/// <summary>
/// Loads combobox with values for RepresentationsOfMissing from application data file
/// </summary>
private void LoadRepresentionsOfMissing()
{
string currentRepresentationOfMissing = Configuration.GetNewInstance().Settings.RepresentationOfMissing;
DataView dv = AppData.Instance.RepresentationsOfMissingDataTable.DefaultView;
cmbMissingAs.Items.Clear();
if (!string.IsNullOrEmpty(currentRepresentationOfMissing))
{
cmbMissingAs.Items.Add(currentRepresentationOfMissing);
}
dv.Sort = ColumnNames.POSITION;
foreach (DataRowView row in dv)
{
string name = row[ColumnNames.NAME].ToString();
if (name != currentRepresentationOfMissing)
{
cmbMissingAs.Items.Add(name);
}
}
cmbMissingAs.SelectedIndex = 0;
}
#endregion Private Methods
#endregion //Private Methods
#region Event Handlers
/// <summary>
/// Handles Attach event of dialog
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void Set_Load(object sender, System.EventArgs e)
{
Configuration config = Configuration.GetNewInstance();
this.EpiInterpreter.Context.ApplyOverridenConfigSettings(config);
this.LoadRepresentionsOfYes();
this.LoadRepresentionsOfNo();
this.LoadRepresentionsOfMissing();
this.ShowSettings(config);
ResetHasChangedValues(false);
}
//##########################################################
/// <summary>
/// Occurs when RepresentationOfYes property changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbYesAs_SelectedIndexChanged(object sender, System.EventArgs e)
{
hasYesAsChanged = true;
}
/// <summary>
/// Occurs when RepresentationOfYes Text property changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbYesAs_TextChanged(object sender, System.EventArgs e)
{
hasYesAsChanged = true;
}
/// <summary>
///Occurs when RepresentationOfNoproperty changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbNoAs_SelectedIndexChanged(object sender, System.EventArgs e)
{
hasNoAsChanged = true;
}
private void cmbNoAs_TextChanged(object sender, EventArgs e)
{
hasNoAsChanged = true;
}
/// <summary>
/// Occurs when RepresentationOfMissing property changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbMissingAs_SelectedIndexChanged(object sender, System.EventArgs e)
{
hasMissingAsChanged = true;
}
/// <summary>
/// Occurs when RepresentationOfMssing property changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbMissingAs_TextChanged(object sender, EventArgs e)
{
hasMissingAsChanged = true;
}
/// <summary>
/// Occurs when ShowPrompt property changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cbxShowPrompt_CheckedChanged(object sender, System.EventArgs e)
{
hasShowPromptChanged = true;
}
/// <summary>
/// Occurs when ShowSelectCriteria property changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cbxSelectCriteria_CheckedChanged(object sender, System.EventArgs e)
{
hasShowSelectChanged = true;
}
/// <summary>
/// Occurs when ShowGraphics property changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cbxGraphics_CheckedChanged(object sender, System.EventArgs e)
{
hasShowGraphicChanged = true;
}
/// <summary>
/// Occurs when ShowPercents property changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cbxPercents_CheckedChanged(object sender, System.EventArgs e)
{
hasShowPercentsChanged = true;
}
/// <summary>
/// Occurs when ShowHyperlinks property changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cbxHyperlinks_CheckedChanged(object sender, System.EventArgs e)
{
hasShowHyperlinkChanged = true;
}
/// <summary>
/// Occurs when ShowTablesOutput property changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cbxTablesOutput_CheckedChanged(object sender, System.EventArgs e)
{
hasShowTablesChanged = true;
}
/// <summary>
/// Occurs when the value of StatisticsLevel property changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void StatisticsRadioButtonClick(object sender, System.EventArgs e)
{
hasStatisticsLevelChanged = true;
}
/// <summary>
///Occures when the value of ProcessRecords changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void ProcessRecordsRadioButtonClick(object sender, System.EventArgs e)
{
hasProcessRecordsChanged = true;
}
/// <summary>
/// Occurs when ShowIncludeMissinge property changes.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cbxIncludeMissing_CheckedChanged(object sender, System.EventArgs e)
{
hasIncludeMissingChanged = true;
}
/// <summary>
/// Opens a process to show the related help topic
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
protected override void btnHelp_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/command-reference/analysis-commands-set.html");
}
private void btnClear_Click(object sender, EventArgs e)
{
ShowSettings();
}
/// <summary>
/// Occurs when the OK button is clicked
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
protected override void btnOK_Click(object sender, EventArgs e)
{
if (!this.isDialogMode)
{
base.btnOK_Click(sender, e);
}
else
{
base.btnSaveOnly_Click(sender, e);
}
}
#endregion //Event Handlers
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData.Metadata
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Data.Services.Common;
using System.Diagnostics;
using System.Linq;
using Microsoft.Data.Edm;
using Microsoft.Data.Edm.Library;
using o = Microsoft.Data.OData;
#endregion Namespaces
/// <summary>
/// Tree representing the sourceName properties in all the EntityPropertyMappingAttributes for a type.
/// </summary>
internal sealed class EpmSourceTree
{
#region Fields
/// <summary>
/// Root of the tree.
/// </summary>
private readonly EpmSourcePathSegment root;
/// <summary>
/// <see cref="EpmTargetTree"/> corresponding to this tree.
/// </summary>
private readonly EpmTargetTree epmTargetTree;
#endregion
/// <summary>
/// Constructor which creates an empty root.
/// </summary>
/// <param name="epmTargetTree">Target xml tree</param>
internal EpmSourceTree(EpmTargetTree epmTargetTree)
{
DebugUtils.CheckNoExternalCallers();
this.root = new EpmSourcePathSegment();
this.epmTargetTree = epmTargetTree;
}
#region Properties
/// <summary>
/// Root of the tree
/// </summary>
internal EpmSourcePathSegment Root
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.root;
}
}
#endregion
/// <summary>
/// Adds a path to the source and target tree which is obtained by looking at the EntityPropertyMappingAttribute in the <paramref name="epmInfo"/>
/// </summary>
/// <param name="epmInfo">EnitityPropertyMappingInfo holding the source path</param>
internal void Add(EntityPropertyMappingInfo epmInfo)
{
DebugUtils.CheckNoExternalCallers();
List<EpmSourcePathSegment> pathToCurrentSegment = new List<EpmSourcePathSegment>();
EpmSourcePathSegment currentSourceSegment = this.Root;
EpmSourcePathSegment foundSourceSegment = null;
IEdmType currentType = epmInfo.ActualPropertyType;
Debug.Assert(!string.IsNullOrEmpty(epmInfo.Attribute.SourcePath), "Invalid source path");
string[] propertyPath = epmInfo.Attribute.SourcePath.Split('/');
int propertyPathLength = propertyPath.Length;
Debug.Assert(propertyPathLength > 0, "Must have been validated during EntityPropertyMappingAttribute construction");
for (int sourcePropertyIndex = 0; sourcePropertyIndex < propertyPathLength; sourcePropertyIndex++)
{
string propertyName = propertyPath[sourcePropertyIndex];
if (propertyName.Length == 0)
{
throw new ODataException(o.Strings.EpmSourceTree_InvalidSourcePath(epmInfo.DefiningType.ODataFullName(), epmInfo.Attribute.SourcePath));
}
IEdmTypeReference nextPropertyTypeReference = GetPropertyType(currentType, propertyName);
IEdmType nextPropertyType = nextPropertyTypeReference == null ? null : nextPropertyTypeReference.Definition;
// If we don't find a property type this is an open property; check whether this is the last segment in the path
// since otherwise this would not be an open primitive property and only open primitive properties are allowed.
if (nextPropertyType == null && sourcePropertyIndex < propertyPathLength - 1)
{
throw new ODataException(o.Strings.EpmSourceTree_OpenComplexPropertyCannotBeMapped(propertyName, currentType.ODataFullName()));
}
currentType = nextPropertyType;
foundSourceSegment = currentSourceSegment.SubProperties.SingleOrDefault(e => e.PropertyName == propertyName);
if (foundSourceSegment != null)
{
currentSourceSegment = foundSourceSegment;
}
else
{
EpmSourcePathSegment newSourceSegment = new EpmSourcePathSegment(propertyName);
currentSourceSegment.SubProperties.Add(newSourceSegment);
currentSourceSegment = newSourceSegment;
}
pathToCurrentSegment.Add(currentSourceSegment);
}
// The last segment is the one being mapped from by the user specified attribute.
// It must be a primitive type - we don't allow mappings of anything else than primitive properties directly.
// Note that we can only verify this for non-open properties, for open properties we must assume it's a primitive type
// and we will make this check later during serialization again when we actually have the value of the property.
if (currentType != null)
{
if (!currentType.IsODataPrimitiveTypeKind())
{
throw new ODataException(o.Strings.EpmSourceTree_EndsWithNonPrimitiveType(currentSourceSegment.PropertyName));
}
}
Debug.Assert(foundSourceSegment == null || foundSourceSegment.EpmInfo != null, "Can't have a leaf node in the tree without EpmInfo.");
// Two EpmAttributes with same PropertyName in the same type, this could be a result of inheritance
if (foundSourceSegment != null)
{
Debug.Assert(object.ReferenceEquals(foundSourceSegment, currentSourceSegment), "currentSourceSegment variable should have been updated already to foundSourceSegment");
// Check for duplicates on the same entity type
Debug.Assert(foundSourceSegment.SubProperties.Count == 0, "If non-leaf, it means we allowed complex type to be a leaf node");
if (foundSourceSegment.EpmInfo.DefiningTypesAreEqual(epmInfo))
{
throw new ODataException(o.Strings.EpmSourceTree_DuplicateEpmAttributesWithSameSourceName(epmInfo.DefiningType.ODataFullName(), epmInfo.Attribute.SourcePath));
}
// In case of inheritance, we need to remove the node from target tree which was mapped to base type property
this.epmTargetTree.Remove(foundSourceSegment.EpmInfo);
}
epmInfo.SetPropertyValuePath(pathToCurrentSegment.ToArray());
currentSourceSegment.EpmInfo = epmInfo;
this.epmTargetTree.Add(epmInfo);
}
/// <summary>
/// Validates the source tree.
/// </summary>
/// <param name="entityType">The entity type for which the validation is performed.</param>
internal void Validate(IEdmEntityType entityType)
{
DebugUtils.CheckNoExternalCallers();
Validate(this.Root, entityType);
}
/// <summary>
/// Validates the specified segment and all its subsegments.
/// </summary>
/// <param name="pathSegment">The path segment to validate.</param>
/// <param name="type">The type of the property represented by this segment (null for open properties).</param>
private static void Validate(EpmSourcePathSegment pathSegment, IEdmType type)
{
Debug.Assert(pathSegment != null, "pathSegment != null");
foreach (EpmSourcePathSegment subSegment in pathSegment.SubProperties)
{
IEdmTypeReference subSegmentTypeReference = GetPropertyType(type, subSegment.PropertyName);
IEdmType subSegmentType = subSegmentTypeReference == null ? null : subSegmentTypeReference.Definition;
Validate(subSegment, subSegmentType);
}
}
/// <summary>
/// Returns the type of the property on the specified type.
/// </summary>
/// <param name="type">The type to look for the property on.</param>
/// <param name="propertyName">The name of the property to look for.</param>
/// <returns>The type of the property specified.</returns>
private static IEdmTypeReference GetPropertyType(IEdmType type, string propertyName)
{
Debug.Assert(propertyName != null, "propertyName != null");
IEdmStructuredType structuredType = type as IEdmStructuredType;
IEdmProperty property = structuredType == null ? null : structuredType.FindProperty(propertyName);
if (property != null)
{
IEdmTypeReference propertyType = property.Type;
if (propertyType.IsNonEntityODataCollectionTypeKind())
{
throw new ODataException(o.Strings.EpmSourceTree_CollectionPropertyCannotBeMapped(propertyName, type.ODataFullName()));
}
if (propertyType.IsStream())
{
throw new ODataException(o.Strings.EpmSourceTree_StreamPropertyCannotBeMapped(propertyName, type.ODataFullName()));
}
if (propertyType.IsSpatial())
{
throw new ODataException(o.Strings.EpmSourceTree_SpatialTypeCannotBeMapped(propertyName, type.ODataFullName()));
}
return property.Type;
}
if (type != null && !type.IsOpenType())
{
throw new ODataException(o.Strings.EpmSourceTree_MissingPropertyOnType(propertyName, type.ODataFullName()));
}
return null;
}
}
}
| |
using System;
using FM;
using FM.IceLink;
using FM.IceLink.WebRTC;
namespace Xamarin.Conference.WebRTC.Opus
{
public class OpusCodec : AudioCodec
{
private BasicAudioPadep _Padep;
private Encoder _Encoder;
private Decoder _Decoder;
public OpusEchoCanceller EchoCanceller { get; set; }
public int PercentLossToTriggerFEC { get; set; }
public bool DisableFEC { get; set; }
public bool FecActive { get; private set; }
public OpusCodec()
: this(null)
{ }
public OpusCodec(OpusEchoCanceller echoCanceller)
: base(20)
{
EchoCanceller = echoCanceller;
DisableFEC = false;
PercentLossToTriggerFEC = 5;
_Padep = new BasicAudioPadep();
}
/// <summary>
/// Encodes a frame.
/// </summary>
/// <param name="frame">The frame.</param>
/// <returns></returns>
public override byte[] Encode(AudioBuffer frame)
{
if (_Encoder == null)
{
_Encoder = new Encoder(ClockRate, Channels, PacketTime);
_Encoder.Quality = 1.0;
_Encoder.Bitrate = 125;
}
byte[] data; int index; int length;
var echoCanceller = EchoCanceller;
if (echoCanceller == null)
{
data = frame.Data;
index = frame.Index;
length = frame.Length;
}
else
{
data = echoCanceller.capture(frame);
index = 0;
length = data.Length;
}
return _Encoder.Encode(data, index, length);
}
private int _CurrentRTPSequenceNumber = -1;
private int _LastRTPSequenceNumber = -1;
/// <summary>
/// Decodes an encoded frame.
/// </summary>
/// <param name="encodedFrame">The encoded frame.</param>
/// <returns></returns>
public override AudioBuffer Decode(byte[] encodedFrame)
{
if (_Decoder == null)
{
_Decoder = new Decoder(ClockRate, Channels, PacketTime);
Link.GetRemoteStream().DisablePLC = true;
}
if (_LastRTPSequenceNumber == -1)
{
_LastRTPSequenceNumber = _CurrentRTPSequenceNumber;
return DecodeNormal(encodedFrame);
}
else
{
var sequenceNumberDelta = RTPPacket.GetSequenceNumberDelta(_CurrentRTPSequenceNumber, _LastRTPSequenceNumber);
_LastRTPSequenceNumber = _CurrentRTPSequenceNumber;
var missingPacketCount = sequenceNumberDelta - 1;
var previousFrames = new AudioBuffer[missingPacketCount];
var plcFrameCount = (missingPacketCount > 1) ? missingPacketCount - 1 : 0;
if (plcFrameCount > 0)
{
Log.InfoFormat("Adding {0} frames of loss concealment to incoming audio stream. Packet sequence violated.", plcFrameCount.ToString());
for (var i = 0; i < plcFrameCount; i++)
{
previousFrames[i] = DecodePLC();
}
}
var fecFrameCount = (missingPacketCount > 0) ? 1 : 0;
if (fecFrameCount > 0)
{
var fecFrame = DecodeFEC(encodedFrame);
var fecFrameIndex = missingPacketCount - 1;
if (fecFrame == null)
{
previousFrames[fecFrameIndex] = DecodePLC();
}
else
{
previousFrames[fecFrameIndex] = fecFrame;
}
}
var frame = DecodeNormal(encodedFrame);
frame.PreviousBuffers = previousFrames;
return frame;
}
}
private AudioBuffer DecodePLC()
{
return Decode(null, false);
}
private AudioBuffer DecodeFEC(byte[] encodedFrame)
{
return Decode(encodedFrame, true);
}
private AudioBuffer DecodeNormal(byte[] encodedFrame)
{
return Decode(encodedFrame, false);
}
private AudioBuffer Decode(byte[] encodedFrame, bool fec)
{
var data = _Decoder.Decode(encodedFrame, fec);
if (data == null)
{
return null;
}
var frame = new AudioBuffer(data, 0, data.Length);
var echoCanceller = EchoCanceller;
if (echoCanceller != null)
{
echoCanceller.render(PeerId, frame);
}
return frame;
}
/// <summary>
/// Packetizes an encoded frame.
/// </summary>
/// <param name="encodedFrame">The encoded frame.</param>
/// <returns></returns>
public override RTPPacket[] Packetize(byte[] encodedFrame)
{
return _Padep.Packetize(encodedFrame, ClockRate, PacketTime, ResetTimestamp);
}
/// <summary>
/// Depacketizes a packet.
/// </summary>
/// <param name="packet">The packet.</param>
/// <returns></returns>
public override byte[] Depacketize(RTPPacket packet)
{
_CurrentRTPSequenceNumber = packet.SequenceNumber;
return _Padep.Depacketize(packet);
}
private int _LossyCount = 0;
private int _LosslessCount = 0;
private int _MinimumReportsBeforeFEC = 1;
private long _ReportsReceived = 0;
/// <summary>
/// Processes RTCP packets.
/// </summary>
/// <param name="packets">The packets to process.</param>
public override void ProcessRTCP(RTCPPacket[] packets)
{
if (_Encoder != null)
{
foreach (var packet in packets)
{
if (packet is RTCPReportPacket)
{
_ReportsReceived++;
var report = (RTCPReportPacket)packet;
foreach (var block in report.ReportBlocks)
{
Log.DebugFormat("Opus report: {0} packet loss ({1} cumulative packets lost)", block.PercentLost.ToString("P2"), block.CumulativeNumberOfPacketsLost.ToString());
if (block.PercentLost > 0)
{
_LosslessCount = 0;
_LossyCount++;
if (_LossyCount > 5 && _Encoder.Quality > 0.0)
{
_LossyCount = 0;
_Encoder.Quality = MathAssistant.Max(0.0, _Encoder.Quality - 0.1);
Log.InfoFormat("Decreasing Opus encoder quality to {0}.", _Encoder.Quality.ToString("P2"));
}
}
else
{
_LossyCount = 0;
_LosslessCount++;
if (_LosslessCount > 5 && _Encoder.Quality < 1.0)
{
_LosslessCount = 0;
_Encoder.Quality = MathAssistant.Min(1.0, _Encoder.Quality + 0.1);
Log.InfoFormat("Increasing Opus encoder quality to {0}.", _Encoder.Quality.ToString("P2"));
}
}
if (!DisableFEC && !FecActive && _ReportsReceived > _MinimumReportsBeforeFEC)
{
if ((block.PercentLost * 100) > PercentLossToTriggerFEC)
{
Log.Info("Activating FEC for Opus audio stream.");
_Encoder.ActivateFEC(PercentLossToTriggerFEC);
FecActive = true;
}
}
}
}
}
}
}
/// <summary>
/// Destroys the codec.
/// </summary>
public override void Destroy()
{
if (_Encoder != null)
{
_Encoder.Destroy();
_Encoder = null;
}
if (_Decoder != null)
{
_Decoder.Destroy();
_Decoder = null;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
/// <summary>
/// Synthesized method that represents an intrinsic debugger method.
/// </summary>
internal sealed class PlaceholderMethodSymbol : MethodSymbol, Cci.ISignature
{
internal delegate ImmutableArray<TypeParameterSymbol> GetTypeParameters(PlaceholderMethodSymbol method);
internal delegate ImmutableArray<ParameterSymbol> GetParameters(PlaceholderMethodSymbol method);
internal delegate TypeSymbol GetReturnType(PlaceholderMethodSymbol method);
private readonly NamedTypeSymbol _container;
private readonly CSharpSyntaxNode _syntax;
private readonly string _name;
private readonly ImmutableArray<Location> _locations;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly ImmutableArray<ParameterSymbol> _parameters;
private readonly TypeSymbol _returnType;
private readonly bool _returnValueIsByRef;
internal PlaceholderMethodSymbol(
NamedTypeSymbol container,
CSharpSyntaxNode syntax,
string name,
TypeSymbol returnType,
GetParameters getParameters) :
this(container, syntax, name)
{
Debug.Assert(
(returnType.SpecialType == SpecialType.System_Void) ||
(returnType.SpecialType == SpecialType.System_Object) ||
(returnType.Name == "Exception"));
_typeParameters = ImmutableArray<TypeParameterSymbol>.Empty;
_returnType = returnType;
_parameters = getParameters(this);
}
internal PlaceholderMethodSymbol(
NamedTypeSymbol container,
CSharpSyntaxNode syntax,
string name,
GetTypeParameters getTypeParameters,
GetReturnType getReturnType,
GetParameters getParameters,
bool returnValueIsByRef) :
this(container, syntax, name)
{
_typeParameters = getTypeParameters(this);
_returnType = getReturnType(this);
_parameters = getParameters(this);
_returnValueIsByRef = returnValueIsByRef;
}
private PlaceholderMethodSymbol(
NamedTypeSymbol container,
CSharpSyntaxNode syntax,
string name)
{
_container = container;
_syntax = syntax;
_name = name;
_locations = ImmutableArray.Create(syntax.Location);
}
public override int Arity
{
get { return _typeParameters.Length; }
}
public override Symbol AssociatedSymbol
{
get { return null; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Internal; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<MethodSymbol>.Empty; }
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsAsync
{
get { return false; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsStatic
{
get { return true; }
}
public override bool IsVararg
{
get { return false; }
}
public override bool IsVirtual
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { return _locations; }
}
public override MethodKind MethodKind
{
get { return MethodKind.Ordinary; }
}
public override string Name
{
get { return _name; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return _parameters; }
}
public override bool ReturnsVoid
{
get { return _returnType.SpecialType == SpecialType.System_Void; }
}
public override TypeSymbol ReturnType
{
get { return _returnType; }
}
bool Cci.ISignature.ReturnValueIsByRef
{
get { return _returnValueIsByRef; }
}
public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
public override ImmutableArray<TypeSymbol> TypeArguments
{
get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
internal override Cci.CallingConvention CallingConvention
{
get
{
Debug.Assert(this.IsStatic);
return this.IsGenericMethod ? Cci.CallingConvention.Generic : Cci.CallingConvention.Default;
}
}
internal override bool GenerateDebugInfo
{
get { return false; }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
internal override bool HasSpecialName
{
get { return true; }
}
internal override System.Reflection.MethodImplAttributes ImplementationAttributes
{
get { return default(System.Reflection.MethodImplAttributes); }
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool RequiresSecurityObject
{
get { return false; }
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { return null; }
}
public override DllImportData GetDllImportData()
{
return null;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsMetadataFinal
{
get
{
return false;
}
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override void GenerateMethodBody(TypeCompilationState compilationState, DiagnosticBag diagnostics)
{
var factory = new SyntheticBoundNodeFactory(this, _syntax, compilationState, diagnostics);
factory.CurrentMethod = this;
// The method body is "throw null;" although the body
// is arbitrary since the method will not be invoked.
var body = factory.Block(factory.ThrowNull());
factory.CloseMethod(body);
}
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| |
using System;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
namespace Domain.Data.Query
{
public partial class Node
{
public static WorkOrderRoutingNode WorkOrderRouting { get { return new WorkOrderRoutingNode(); } }
}
public partial class WorkOrderRoutingNode : Blueprint41.Query.Node
{
protected override string GetNeo4jLabel()
{
return "WorkOrderRouting";
}
internal WorkOrderRoutingNode() { }
internal WorkOrderRoutingNode(WorkOrderRoutingAlias alias, bool isReference = false)
{
NodeAlias = alias;
IsReference = isReference;
}
internal WorkOrderRoutingNode(RELATIONSHIP relationship, DirectionEnum direction, string neo4jLabel = null) : base(relationship, direction, neo4jLabel) { }
public WorkOrderRoutingNode Alias(out WorkOrderRoutingAlias alias)
{
alias = new WorkOrderRoutingAlias(this);
NodeAlias = alias;
return this;
}
public WorkOrderRoutingNode UseExistingAlias(AliasResult alias)
{
NodeAlias = alias;
return this;
}
public WorkOrderRoutingIn In { get { return new WorkOrderRoutingIn(this); } }
public class WorkOrderRoutingIn
{
private WorkOrderRoutingNode Parent;
internal WorkOrderRoutingIn(WorkOrderRoutingNode parent)
{
Parent = parent;
}
public IFromIn_WORKORDERROUTING_HAS_LOCATION_REL WORKORDERROUTING_HAS_LOCATION { get { return new WORKORDERROUTING_HAS_LOCATION_REL(Parent, DirectionEnum.In); } }
public IFromIn_WORKORDERROUTING_HAS_PRODUCT_REL WORKORDERROUTING_HAS_PRODUCT { get { return new WORKORDERROUTING_HAS_PRODUCT_REL(Parent, DirectionEnum.In); } }
public IFromIn_WORKORDERROUTING_HAS_WORKORDER_REL WORKORDERROUTING_HAS_WORKORDER { get { return new WORKORDERROUTING_HAS_WORKORDER_REL(Parent, DirectionEnum.In); } }
}
}
public class WorkOrderRoutingAlias : AliasResult
{
internal WorkOrderRoutingAlias(WorkOrderRoutingNode parent)
{
Node = parent;
}
public override IReadOnlyDictionary<string, FieldResult> AliasFields
{
get
{
if (m_AliasFields == null)
{
m_AliasFields = new Dictionary<string, FieldResult>()
{
{ "OperationSequence", new StringResult(this, "OperationSequence", Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"], Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"].Properties["OperationSequence"]) },
{ "ScheduledStartDate", new DateTimeResult(this, "ScheduledStartDate", Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"], Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"].Properties["ScheduledStartDate"]) },
{ "ScheduledEndDate", new DateTimeResult(this, "ScheduledEndDate", Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"], Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"].Properties["ScheduledEndDate"]) },
{ "ActualStartDate", new DateTimeResult(this, "ActualStartDate", Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"], Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"].Properties["ActualStartDate"]) },
{ "ActualEndDate", new DateTimeResult(this, "ActualEndDate", Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"], Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"].Properties["ActualEndDate"]) },
{ "ActualResourceHrs", new StringResult(this, "ActualResourceHrs", Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"], Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"].Properties["ActualResourceHrs"]) },
{ "PlannedCost", new StringResult(this, "PlannedCost", Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"], Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"].Properties["PlannedCost"]) },
{ "ActualCost", new StringResult(this, "ActualCost", Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"], Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"].Properties["ActualCost"]) },
{ "ModifiedDate", new DateTimeResult(this, "ModifiedDate", Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"], Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]) },
{ "Uid", new StringResult(this, "Uid", Datastore.AdventureWorks.Model.Entities["WorkOrderRouting"], Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]) },
};
}
return m_AliasFields;
}
}
private IReadOnlyDictionary<string, FieldResult> m_AliasFields = null;
public WorkOrderRoutingNode.WorkOrderRoutingIn In { get { return new WorkOrderRoutingNode.WorkOrderRoutingIn(new WorkOrderRoutingNode(this, true)); } }
public StringResult OperationSequence
{
get
{
if ((object)m_OperationSequence == null)
m_OperationSequence = (StringResult)AliasFields["OperationSequence"];
return m_OperationSequence;
}
}
private StringResult m_OperationSequence = null;
public DateTimeResult ScheduledStartDate
{
get
{
if ((object)m_ScheduledStartDate == null)
m_ScheduledStartDate = (DateTimeResult)AliasFields["ScheduledStartDate"];
return m_ScheduledStartDate;
}
}
private DateTimeResult m_ScheduledStartDate = null;
public DateTimeResult ScheduledEndDate
{
get
{
if ((object)m_ScheduledEndDate == null)
m_ScheduledEndDate = (DateTimeResult)AliasFields["ScheduledEndDate"];
return m_ScheduledEndDate;
}
}
private DateTimeResult m_ScheduledEndDate = null;
public DateTimeResult ActualStartDate
{
get
{
if ((object)m_ActualStartDate == null)
m_ActualStartDate = (DateTimeResult)AliasFields["ActualStartDate"];
return m_ActualStartDate;
}
}
private DateTimeResult m_ActualStartDate = null;
public DateTimeResult ActualEndDate
{
get
{
if ((object)m_ActualEndDate == null)
m_ActualEndDate = (DateTimeResult)AliasFields["ActualEndDate"];
return m_ActualEndDate;
}
}
private DateTimeResult m_ActualEndDate = null;
public StringResult ActualResourceHrs
{
get
{
if ((object)m_ActualResourceHrs == null)
m_ActualResourceHrs = (StringResult)AliasFields["ActualResourceHrs"];
return m_ActualResourceHrs;
}
}
private StringResult m_ActualResourceHrs = null;
public StringResult PlannedCost
{
get
{
if ((object)m_PlannedCost == null)
m_PlannedCost = (StringResult)AliasFields["PlannedCost"];
return m_PlannedCost;
}
}
private StringResult m_PlannedCost = null;
public StringResult ActualCost
{
get
{
if ((object)m_ActualCost == null)
m_ActualCost = (StringResult)AliasFields["ActualCost"];
return m_ActualCost;
}
}
private StringResult m_ActualCost = null;
public DateTimeResult ModifiedDate
{
get
{
if ((object)m_ModifiedDate == null)
m_ModifiedDate = (DateTimeResult)AliasFields["ModifiedDate"];
return m_ModifiedDate;
}
}
private DateTimeResult m_ModifiedDate = null;
public StringResult Uid
{
get
{
if ((object)m_Uid == null)
m_Uid = (StringResult)AliasFields["Uid"];
return m_Uid;
}
}
private StringResult m_Uid = null;
}
}
| |
using System;
namespace C5
{
/// <summary>
/// A read-only wrapper for an <see cref="T:C5.ICollection`1"/>,
/// <para>
/// <i>Suitable for wrapping hash tables, <see cref="T:C5.HashSet`1"/>
/// and <see cref="T:C5.HashBag`1"/> </i></para>
/// </summary>
[Serializable]
public class GuardedCollection<T> : GuardedCollectionValue<T>, ICollection<T>
{
#region Fields
private readonly ICollection<T> collection;
#endregion
#region Constructor
/// <summary>
/// Wrap an ICollection<T> in a read-only wrapper
/// </summary>
/// <param name="collection">the collection to wrap</param>
public GuardedCollection(ICollection<T> collection)
: base(collection)
{
this.collection = collection;
}
#endregion
#region ICollection<T> Members
/// <summary>
/// (This is a read-only wrapper)
/// </summary>
/// <value>True</value>
public virtual bool IsReadOnly => true;
/// <summary> </summary>
/// <value>Speed of wrapped collection</value>
public virtual Speed ContainsSpeed => collection.ContainsSpeed;
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual int GetUnsequencedHashCode()
{ return collection.GetUnsequencedHashCode(); }
/// <summary>
///
/// </summary>
/// <param name="that"></param>
/// <returns></returns>
public virtual bool UnsequencedEquals(ICollection<T> that)
{ return collection.UnsequencedEquals(that); }
/// <summary>
/// Check if an item is in the wrapped collection
/// </summary>
/// <param name="item">The item</param>
/// <returns>True if found</returns>
public virtual bool Contains(T item) { return collection.Contains(item); }
/// <summary>
/// Count the number of times an item appears in the wrapped collection
/// </summary>
/// <param name="item">The item</param>
/// <returns>The number of copies</returns>
public virtual int ContainsCount(T item) { return collection.ContainsCount(item); }
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<T> UniqueItems() { return new GuardedCollectionValue<T>(collection.UniqueItems()); }
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<System.Collections.Generic.KeyValuePair<T, int>> ItemMultiplicities() { return new GuardedCollectionValue<System.Collections.Generic.KeyValuePair<T, int>>(collection.ItemMultiplicities()); }
/// <summary>
/// Check if all items in the argument is in the wrapped collection
/// </summary>
/// <param name="items">The items</param>
/// <returns>True if so</returns>
public virtual bool ContainsAll(System.Collections.Generic.IEnumerable<T> items) { return collection.ContainsAll(items); }
/// <summary>
/// Search for an item in the wrapped collection
/// </summary>
/// <param name="item">On entry the item to look for, on exit the equivalent item found (if any)</param>
/// <returns></returns>
public virtual bool Find(ref T item) { return collection.Find(ref item); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
/// <returns></returns>
public virtual bool FindOrAdd(ref T item)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
/// <returns></returns>
public virtual bool Update(T item)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
/// <param name="olditem"></param>
/// <returns></returns>
public virtual bool Update(T item, out T olditem)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
/// <returns></returns>
public virtual bool UpdateOrAdd(T item)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
/// <param name="olditem"></param>
/// <returns></returns>
public virtual bool UpdateOrAdd(T item, out T olditem)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
/// <returns></returns>
public virtual bool Remove(T item)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item">The value to remove.</param>
/// <param name="removeditem">The removed value.</param>
/// <returns></returns>
public virtual bool Remove(T item, out T removeditem)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
public virtual void RemoveAllCopies(T item)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="items"></param>
public virtual void RemoveAll(System.Collections.Generic.IEnumerable<T> items)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
public virtual void Clear()
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="items"></param>
public virtual void RetainAll(System.Collections.Generic.IEnumerable<T> items)
{ throw new ReadOnlyCollectionException("Collection cannot be modified through this guard object"); }
/// <summary>
/// Check wrapped collection for internal consistency
/// </summary>
/// <returns>True if check passed</returns>
public virtual bool Check() { return collection.Check(); }
#endregion
#region IExtensible<T> Members
/// <summary> </summary>
/// <value>False if wrapped collection has set semantics</value>
public virtual bool AllowsDuplicates => collection.AllowsDuplicates;
//TODO: the equalityComparer should be guarded
/// <summary>
///
/// </summary>
/// <value></value>
public virtual System.Collections.Generic.IEqualityComparer<T> EqualityComparer => collection.EqualityComparer;
/// <summary>
/// By convention this is true for any collection with set semantics.
/// </summary>
/// <value>True if only one representative of a group of equal items
/// is kept in the collection together with the total count.</value>
public virtual bool DuplicatesByCounting => collection.DuplicatesByCounting;
/// <summary> </summary>
/// <value>True if wrapped collection is empty</value>
public override bool IsEmpty => collection.IsEmpty;
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
/// <returns></returns>
public virtual bool Add(T item)
{ throw new ReadOnlyCollectionException(); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="item"></param>
void System.Collections.Generic.ICollection<T>.Add(T item)
{ throw new ReadOnlyCollectionException(); }
/// <summary>
/// </summary>
/// <exception cref="ReadOnlyCollectionException"> since this is a read-only wrapper</exception>
/// <param name="items"></param>
public virtual void AddAll(System.Collections.Generic.IEnumerable<T> items)
{ throw new ReadOnlyCollectionException(); }
#endregion
}
}
| |
using System;
using Lucene.Net.Documents;
using Lucene.Net.Support;
namespace Lucene.Net.Index
{
using NUnit.Framework;
using BytesRef = Lucene.Net.Util.BytesRef;
using CollectionStatistics = Lucene.Net.Search.CollectionStatistics;
using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using LineFileDocs = Lucene.Net.Util.LineFileDocs;
//using Slow = Lucene.Net.Util.LuceneTestCase.Slow;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using PerFieldSimilarityWrapper = Lucene.Net.Search.Similarities.PerFieldSimilarityWrapper;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using TermStatistics = Lucene.Net.Search.TermStatistics;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
using TFIDFSimilarity = Lucene.Net.Search.Similarities.TFIDFSimilarity;
/// <summary>
/// Test that norms info is preserved during index life - including
/// separate norms, addDocument, addIndexes, forceMerge.
/// </summary>
[SuppressCodecs("Memory", "Direct", "SimpleText")]
[TestFixture]
public class TestNorms : LuceneTestCase
{
internal readonly string ByteTestField = "normsTestByte";
internal class CustomNormEncodingSimilarity : TFIDFSimilarity
{
private readonly TestNorms OuterInstance;
public CustomNormEncodingSimilarity(TestNorms outerInstance)
{
this.OuterInstance = outerInstance;
}
public override long EncodeNormValue(float f)
{
return (long)f;
}
public override float DecodeNormValue(long norm)
{
return norm;
}
public override float LengthNorm(FieldInvertState state)
{
return state.Length;
}
public override float Coord(int overlap, int maxOverlap)
{
return 0;
}
public override float QueryNorm(float sumOfSquaredWeights)
{
return 0;
}
public override float Tf(float freq)
{
return 0;
}
public override float Idf(long docFreq, long numDocs)
{
return 0;
}
public override float SloppyFreq(int distance)
{
return 0;
}
public override float ScorePayload(int doc, int start, int end, BytesRef payload)
{
return 0;
}
}
// LUCENE-1260
[Test]
public virtual void TestCustomEncoder()
{
Directory dir = NewDirectory();
MockAnalyzer analyzer = new MockAnalyzer(Random());
IndexWriterConfig config = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
config.SetSimilarity(new CustomNormEncodingSimilarity(this));
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, config);
Document doc = new Document();
Field foo = NewTextField("foo", "", Field.Store.NO);
Field bar = NewTextField("bar", "", Field.Store.NO);
doc.Add(foo);
doc.Add(bar);
for (int i = 0; i < 100; i++)
{
bar.SetStringValue("singleton");
writer.AddDocument(doc);
}
IndexReader reader = writer.Reader;
writer.Dispose();
NumericDocValues fooNorms = MultiDocValues.GetNormValues(reader, "foo");
for (int i = 0; i < reader.MaxDoc; i++)
{
Assert.AreEqual(0, fooNorms.Get(i));
}
NumericDocValues barNorms = MultiDocValues.GetNormValues(reader, "bar");
for (int i = 0; i < reader.MaxDoc; i++)
{
Assert.AreEqual(1, barNorms.Get(i));
}
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestMaxByteNorms()
{
Directory dir = NewFSDirectory(CreateTempDir("TestNorms.testMaxByteNorms"));
BuildIndex(dir);
AtomicReader open = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir));
NumericDocValues normValues = open.GetNormValues(ByteTestField);
Assert.IsNotNull(normValues);
for (int i = 0; i < open.MaxDoc; i++)
{
Document document = open.Document(i);
int expected = Convert.ToInt32(document.Get(ByteTestField));
Assert.AreEqual(expected, normValues.Get(i) & 0xff);
}
open.Dispose();
dir.Dispose();
}
// TODO: create a testNormsNotPresent ourselves by adding/deleting/merging docs
public virtual void BuildIndex(Directory dir)
{
Random random = Random();
MockAnalyzer analyzer = new MockAnalyzer(Random());
analyzer.MaxTokenLength = TestUtil.NextInt(Random(), 1, IndexWriter.MAX_TERM_LENGTH);
IndexWriterConfig config = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
Similarity provider = new MySimProvider(this);
config.SetSimilarity(provider);
RandomIndexWriter writer = new RandomIndexWriter(random, dir, config);
LineFileDocs docs = new LineFileDocs(random, DefaultCodecSupportsDocValues());
int num = AtLeast(100);
for (int i = 0; i < num; i++)
{
Document doc = docs.NextDoc();
int boost = Random().Next(255);
Field f = new TextField(ByteTestField, "" + boost, Field.Store.YES);
f.Boost = boost;
doc.Add(f);
writer.AddDocument(doc);
doc.RemoveField(ByteTestField);
if (Rarely())
{
writer.Commit();
}
}
writer.Commit();
writer.Dispose();
docs.Dispose();
}
public class MySimProvider : PerFieldSimilarityWrapper
{
private readonly TestNorms OuterInstance;
public MySimProvider(TestNorms outerInstance)
{
this.OuterInstance = outerInstance;
}
internal Similarity @delegate = new DefaultSimilarity();
public override float QueryNorm(float sumOfSquaredWeights)
{
return @delegate.QueryNorm(sumOfSquaredWeights);
}
public override Similarity Get(string field)
{
if (OuterInstance.ByteTestField.Equals(field))
{
return new ByteEncodingBoostSimilarity();
}
else
{
return @delegate;
}
}
public override float Coord(int overlap, int maxOverlap)
{
return @delegate.Coord(overlap, maxOverlap);
}
}
public class ByteEncodingBoostSimilarity : Similarity
{
public override long ComputeNorm(FieldInvertState state)
{
int boost = (int)state.Boost;
return (sbyte)boost;
}
public override SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats)
{
throw new System.NotSupportedException();
}
public override SimScorer GetSimScorer(SimWeight weight, AtomicReaderContext context)
{
throw new System.NotSupportedException();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using EPiServer;
using EPiServer.Configuration;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Filters;
using EPiServer.Logging;
using EPiServer.ServiceLocation;
using EPiServer.Web;
namespace MyEpiserverSite.Business.ContentProviders
{
/// <summary>
/// Used to clone a part of the page tree
/// </summary>
/// <remarks>The current implementation only supports cloning of <see cref="PageData"/> content</remarks>
/// <code>
/// // Example of programmatically registering a cloned content provider
///
/// var rootPageOfContentToClone = new PageReference(10);
///
/// var pageWhereClonedContentShouldAppear = new PageReference(20);
///
/// var provider = new ClonedContentProvider(rootPageOfContentToClone, pageWhereClonedContentShouldAppear);
///
/// var providerManager = ServiceLocator.Current.GetInstance<IContentProviderManager>();
///
/// providerManager.ProviderMap.AddProvider(provider);
/// </code>
public class ClonedContentProvider : ContentProvider, IPageCriteriaQueryService
{
private static readonly ILogger Logger = LogManager.GetLogger();
private readonly NameValueCollection _parameters = new NameValueCollection(1);
public ClonedContentProvider(PageReference cloneRoot, PageReference entryRoot) : this(cloneRoot, entryRoot, null) { }
public ClonedContentProvider(PageReference cloneRoot, PageReference entryRoot, CategoryList categoryFilter)
{
if (cloneRoot.CompareToIgnoreWorkID(entryRoot))
{
throw new NotSupportedException("Entry root and clone root cannot be set to the same content reference");
}
if (ServiceLocator.Current.GetInstance<IContentLoader>().GetChildren<IContent>(entryRoot).Any())
{
throw new NotSupportedException("Unable to create ClonedContentProvider, the EntryRoot property must point to leaf content (without children)");
}
CloneRoot = cloneRoot;
EntryRoot = entryRoot;
Category = categoryFilter;
// Set the entry point parameter
Parameters.Add(ContentProviderElement.EntryPointString, EntryRoot.ID.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Clones a page to make it appear to come from where the content provider is attached
/// </summary>
private PageData ClonePage(PageData originalPage)
{
if (originalPage == null)
{
throw new ArgumentNullException("originalPage", "No page to clone specified");
}
Logger.Debug("Cloning page {0}...", originalPage.PageLink);
var clone = originalPage.CreateWritableClone();
// If original page was under the clone root, we make it appear to be under the entry root instead
if (originalPage.ParentLink.CompareToIgnoreWorkID(CloneRoot))
{
clone.ParentLink = EntryRoot;
}
// All pages but the entry root should appear to come from this content provider
if (!clone.PageLink.CompareToIgnoreWorkID(EntryRoot))
{
clone.ContentLink.ProviderName = ProviderKey;
}
// Unless the parent is the entry root, it should appear to come from this content provider
if (!clone.ParentLink.CompareToIgnoreWorkID(EntryRoot))
{
var parentLinkClone = clone.ParentLink.CreateWritableClone();
parentLinkClone.ProviderName = ProviderKey;
clone.ParentLink = parentLinkClone;
}
// This is integral to map the cloned page to this content provider
clone.LinkURL = ConstructContentUri(originalPage.PageTypeID, clone.ContentLink, clone.ContentGuid).ToString();
return clone;
}
/// <summary>
/// Filters out content references to content that does not match current category filters, if any
/// </summary>
/// <param name="contentReferences"></param>
/// <returns></returns>
private IList<T> FilterByCategory<T>(IEnumerable<T> contentReferences)
{
if (Category == null || !Category.Any())
{
return contentReferences.ToList();
}
// Filter by category if a category filter has been set
var filteredChildren = new List<T>();
foreach (var contentReference in contentReferences)
{
ICategorizable content = null;
if (contentReference is ContentReference)
{
content = (contentReference as ContentReference).Get<IContent>() as ICategorizable;
} else if (typeof(T) == typeof(GetChildrenReferenceResult))
{
content = (contentReference as GetChildrenReferenceResult).ContentLink.Get<IContent>() as ICategorizable;
}
if (content != null)
{
var atLeastOneMatchingCategory = content.Category.Any(c => Category.Contains(c));
if (atLeastOneMatchingCategory)
{
filteredChildren.Add(contentReference);
}
}
else // Non-categorizable content will also be included
{
filteredChildren.Add(contentReference);
}
}
return filteredChildren;
}
protected override IContent LoadContent(ContentReference contentLink, ILanguageSelector languageSelector)
{
if (ContentReference.IsNullOrEmpty(contentLink) || contentLink.ID == 0)
{
throw new ArgumentNullException("contentLink");
}
if (contentLink.WorkID > 0)
{
return ContentStore.LoadVersion(contentLink, -1);
}
var languageBranchRepository = ServiceLocator.Current.GetInstance<ILanguageBranchRepository>();
LanguageBranch langBr = null;
if (languageSelector.Language != null)
{
langBr = languageBranchRepository.Load(languageSelector.Language);
}
if (contentLink.GetPublishedOrLatest)
{
return ContentStore.LoadVersion(contentLink, langBr != null ? langBr.ID : -1);
}
// Get published version of Content
var originalContent = ContentStore.Load(contentLink, langBr != null ? langBr.ID : -1);
var page = originalContent as PageData;
if (page == null)
{
throw new NotSupportedException("Only cloning of pages is supported");
}
return ClonePage(page);
}
protected override ContentResolveResult ResolveContent(ContentReference contentLink)
{
var contentData = ContentCoreDataLoader.Service.Load(contentLink.ID);
// All pages but the entry root should appear to come from this content provider
if (!contentLink.CompareToIgnoreWorkID(EntryRoot))
{
contentData.ContentReference.ProviderName = ProviderKey;
}
var result = CreateContentResolveResult(contentData);
if (!result.ContentLink.CompareToIgnoreWorkID(EntryRoot))
{
result.ContentLink.ProviderName = ProviderKey;
}
return result;
}
protected override Uri ConstructContentUri(int contentTypeId, ContentReference contentLink, Guid contentGuid)
{
if (!contentLink.CompareToIgnoreWorkID(EntryRoot))
{
contentLink.ProviderName = ProviderKey;
}
return base.ConstructContentUri(contentTypeId, contentLink, contentGuid);
}
protected override IList<GetChildrenReferenceResult> LoadChildrenReferencesAndTypes(ContentReference contentLink, string languageID, out bool languageSpecific)
{
// If retrieving children for the entry point, we retrieve pages from the clone root
contentLink = contentLink.CompareToIgnoreWorkID(EntryRoot) ? CloneRoot : contentLink;
FilterSortOrder sortOrder;
var children = ContentStore.LoadChildrenReferencesAndTypes(contentLink.ID, languageID, out sortOrder);
languageSpecific = sortOrder == FilterSortOrder.Alphabetical;
foreach (var contentReference in children.Where(contentReference => !contentReference.ContentLink.CompareToIgnoreWorkID(EntryRoot)))
{
contentReference.ContentLink.ProviderName = ProviderKey;
}
return FilterByCategory <GetChildrenReferenceResult>(children);
}
protected override IEnumerable<IContent> LoadContents(IList<ContentReference> contentReferences, ILanguageSelector selector)
{
return contentReferences
.Select(contentReference => ClonePage(ContentLoader.Get<PageData>(contentReference.ToReferenceWithoutVersion())))
.Cast<IContent>()
.ToList();
}
protected override void SetCacheSettings(IContent content, CacheSettings cacheSettings)
{
// Make the cache of this content provider depend on the original content
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(content.ContentLink.ID)));
}
protected override void SetCacheSettings(ContentReference contentReference, IEnumerable<GetChildrenReferenceResult> children, CacheSettings cacheSettings)
{
// Make the cache of this content provider depend on the original content
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(contentReference.ID)));
foreach (var child in children)
{
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(child.ContentLink.ID)));
}
}
public override IList<ContentReference> GetDescendentReferences(ContentReference contentLink)
{
// If retrieving children for the entry point, we retrieve pages from the clone root
contentLink = contentLink.CompareToIgnoreWorkID(EntryRoot) ? CloneRoot : contentLink;
var descendents = ContentStore.ListAll(contentLink);
foreach (var contentReference in descendents.Where(contentReference => !contentReference.CompareToIgnoreWorkID(EntryRoot)))
{
contentReference.ProviderName = ProviderKey;
}
return FilterByCategory<ContentReference>(descendents);
}
public PageDataCollection FindAllPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias, string languageBranch, ILanguageSelector selector)
{
// Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
if (pageLink.CompareToIgnoreWorkID(EntryRoot))
{
pageLink = CloneRoot;
}
else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName)) // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
{
pageLink = new PageReference(pageLink.ID);
}
var pages = PageQueryService.FindAllPagesWithCriteria(pageLink, criterias, languageBranch, selector);
// Return cloned search result set
return new PageDataCollection(pages.Select(ClonePage));
}
public PageDataCollection FindPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias, string languageBranch, ILanguageSelector selector)
{
// Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
if (pageLink.CompareToIgnoreWorkID(EntryRoot))
{
pageLink = CloneRoot;
}
else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName)) // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
{
pageLink = new PageReference(pageLink.ID);
}
var pages = PageQueryService.FindPagesWithCriteria(pageLink, criterias, languageBranch, selector);
// Return cloned search result set
return new PageDataCollection(pages.Select(ClonePage));
}
/// <summary>
/// Gets the content store used to get original content
/// </summary>
protected virtual ContentStore ContentStore
{
get { return ServiceLocator.Current.GetInstance<ContentStore>(); }
}
/// <summary>
/// Gets the content loader used to get content
/// </summary>
protected virtual IContentLoader ContentLoader
{
get { return ServiceLocator.Current.GetInstance<IContentLoader>(); }
}
/// <summary>
/// Gets the service used to query for pages using criterias
/// </summary>
protected virtual IPageCriteriaQueryService PageQueryService
{
get { return ServiceLocator.Current.GetInstance<IPageCriteriaQueryService>(); }
}
/// <summary>
/// Content that should be cloned at the entry point
/// </summary>
public PageReference CloneRoot { get; protected set; }
/// <summary>
/// Gets the page where the cloned content will appear
/// </summary>
public PageReference EntryRoot { get; protected set; }
/// <summary>
/// Gets the category filters used for this content provider
/// </summary>
/// <remarks>If set, pages not matching at least one of these categories will be excluded from this content provider</remarks>
public CategoryList Category { get; protected set; }
/// <summary>
/// Gets a unique key for this content provider instance
/// </summary>
public override string ProviderKey
{
get
{
return string.Format("ClonedContent-{0}-{1}", CloneRoot.ID, EntryRoot.ID);
}
}
/// <summary>
/// Gets capabilities indicating no content editing can be performed through this provider
/// </summary>
public override ContentProviderCapabilities ProviderCapabilities { get { return ContentProviderCapabilities.Search; } }
/// <summary>
/// Gets configuration parameters for this content provider instance
/// </summary>
public override NameValueCollection Parameters { get { return _parameters; } }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
namespace Signum.Engine.Linq
{
internal sealed class ProjectedColumns
{
public readonly Expression Projector;
public readonly ReadOnlyCollection<ColumnDeclaration> Columns;
internal ProjectedColumns(Expression projector, ReadOnlyCollection<ColumnDeclaration> columns)
{
this.Projector = projector;
this.Columns = columns;
}
}
/// <summary>
/// ColumnProjection is a visitor that splits an expression representing the result of a query into
/// two parts, a list of column declarations of expressions that must be evaluated on the server
/// and a projector expression that describes how to combine the columns back into the result object
/// </summary>
internal class ColumnProjector : DbExpressionVisitor
{
ColumnGenerator generator = new ColumnGenerator();
Dictionary<ColumnExpression, ColumnExpression> map = new Dictionary<ColumnExpression, ColumnExpression>();
HashSet<Expression> candidates;
Alias newAlias;
bool projectTrivialColumns;
public ColumnProjector(HashSet<Expression> candidates, Alias newAlias, bool projectTrivialColumns)
{
this.candidates = candidates;
this.newAlias = newAlias;
this.projectTrivialColumns = projectTrivialColumns;
}
static internal ColumnExpression SingleProjection(ColumnDeclaration declaration, Alias newAlias, Type columnType)
{
return new ColumnExpression(columnType, newAlias, declaration.Name);
}
static internal ProjectedColumns ProjectColumns(Expression projector, Alias newAlias, bool isGroupKey = false, bool selectTrivialColumns = false)
{
var candidates = DbExpressionNominator.Nominate(projector, out Expression newProj, isGroupKey: isGroupKey);
ColumnProjector cp = new ColumnProjector(candidates, newAlias, selectTrivialColumns);
Expression e = cp.Visit(newProj);
return new ProjectedColumns(e, cp.generator.Columns.NotNull().ToReadOnly());
}
public override Expression Visit(Expression expression)
{
if (this.candidates.Contains(expression))
{
if (expression is ColumnExpression)
{
if (!projectTrivialColumns)
return expression;
ColumnExpression column = (ColumnExpression)expression;
if (this.map.TryGetValue(column, out var mapped))
{
return mapped;
}
mapped = generator.MapColumn(column).GetReference(newAlias);
this.map[column] = mapped;
return mapped;
}
else
{
if (expression.Type.UnNullify().IsEnum)
{
var convert = expression.TryConvert(expression.Type.IsNullable() ? typeof(int?) : typeof(int));
return generator.NewColumn(convert).GetReference(newAlias).TryConvert(expression.Type);
}
else
{
return generator.NewColumn(expression).GetReference(newAlias);
}
}
}
else
{
return base.Visit(expression);
}
}
}
internal class ColumnUnionProjector : DbExpressionVisitor
{
Dictionary<ColumnExpression, ColumnExpression> map = new Dictionary<ColumnExpression, ColumnExpression>();
HashSet<Expression> candidates;
UnionAllRequest request;
Type implementation;
public ColumnUnionProjector(HashSet<Expression> candidates, UnionAllRequest request, Type implementation)
{
this.candidates = candidates;
this.request = request;
this.implementation = implementation;
}
static internal Expression Project(Expression projector, HashSet<Expression> candidates, UnionAllRequest request, Type implementation)
{
ColumnUnionProjector cp = new ColumnUnionProjector(candidates, request, implementation);
return cp.Visit(projector);
}
public override Expression Visit(Expression expression)
{
if (this.candidates.Contains(expression))
{
if (expression is ColumnExpression column)
{
if (this.map.TryGetValue(column, out var mapped))
{
return mapped;
}
mapped = request.AddIndependentColumn(column.Type, column.Name!, implementation, column);
this.map[column] = mapped;
return mapped;
}
else
{
if (expression.Type.UnNullify().IsEnum)
{
var convert = expression.TryConvert(expression.Type.IsNullable() ? typeof(int?) : typeof(int));
return request.AddIndependentColumn(convert.Type, "v", implementation, convert).TryConvert(expression.Type);
}
else
{
return request.AddIndependentColumn(expression.Type, "v", implementation, expression);
}
}
}
else
{
return base.Visit(expression);
}
}
}
internal class ColumnGenerator
{
public ColumnGenerator()
{
}
public ColumnGenerator(IEnumerable<ColumnDeclaration> columns)
{
foreach (var item in columns)
this.columns.Add(item.Name ?? "-", item);
}
public IEnumerable<ColumnDeclaration?> Columns { get { return columns.Values; } }
Dictionary<string, ColumnDeclaration?> columns = new Dictionary<string, ColumnDeclaration?>(StringComparer.InvariantCultureIgnoreCase);
int iColumn;
public string GetUniqueColumnName(string name)
{
string baseName = name;
int suffix = 1;
while (this.columns.ContainsKey(name))
name = baseName + (suffix++);
return name;
}
public string GetNextColumnName()
{
return this.GetUniqueColumnName("c" + (iColumn++));
}
public ColumnDeclaration MapColumn(ColumnExpression ce)
{
string columnName = GetUniqueColumnName(ce.Name!);
var result = new ColumnDeclaration(columnName, ce);
columns.Add(result.Name, result);
return result;
}
public ColumnDeclaration NewColumn(Expression exp)
{
string columnName = GetNextColumnName();
var result = new ColumnDeclaration(columnName, exp);
columns.Add(result.Name, result);
return result;
}
public void AddUsedName(string name)
{
columns.Add(name, null);
}
}
}
| |
//
// TextBlock.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright 2009 Aaron Bockover
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using Cairo;
using Hyena.Gui;
using Hyena.Gui.Theming;
namespace Hyena.Gui.Canvas
{
public class TextBlock : CanvasItem
{
private Pango.Layout layout;
private Pango.FontDescription font_desc;
private Rect text_alloc = Rect.Empty;
private Rect invalidation_rect = Rect.Empty;
public TextBlock ()
{
FontWeight = FontWeight.Normal;
TextWrap = TextWrap.None;
EllipsizeMode = Pango.EllipsizeMode.End;
}
private bool EnsureLayout ()
{
layout = Manager.Host.PangoLayout;
font_desc = Manager.Host.FontDescription;
return layout != null;
}
public override Size Measure (Size available)
{
if (!EnsureLayout ()) {
return new Size (0, 0);
}
available = base.Measure (available);
int text_w, text_h;
// Update layout
UpdateLayout (GetText (), available.Width - Margin.X, null, false);
layout.GetPixelSize (out text_w, out text_h);
double width = text_w;
if (!available.IsEmpty && available.Width > 0) {
width = available.Width;
}
//DesiredSize = new Size (width, text_h);
var size = DesiredSize = new Size (width, text_h);
// Hack, as this prevents the TextBlock from
// being flexible in a Vertical StackPanel
Height = size.Height;
if (ForceSize) {
Width = DesiredSize.Width;
}
return size;
}
private void UpdateLayout (string text, double width, double? height, bool forceWidth)
{
if (text != last_text) {
last_formatted_text = GetFormattedText (text) ?? "";
last_text = text;
if (TextWrap == TextWrap.None && last_formatted_text.IndexOfAny (lfcr) >= 0) {
last_formatted_text = last_formatted_text.Replace ("\r\n", "\x20").Replace ('\n', '\x20').Replace ('\r', '\x20');
}
}
TextWrap wrap = TextWrap;
layout.Width = wrap != TextWrap.None || forceWidth ? (int)(Pango.Scale.PangoScale * width) : -1;
layout.Wrap = GetPangoWrapMode (wrap);
if (height != null && wrap != TextWrap.None) {
layout.SetHeight ((int)(Pango.Scale.PangoScale * height.Value));
}
font_desc.Weight = GetPangoFontWeight (FontWeight);
layout.SingleParagraphMode = wrap == TextWrap.None;
layout.Ellipsize = EllipsizeMode;
if (UseMarkup) {
layout.SetMarkup (last_formatted_text);
} else {
layout.SetText (last_formatted_text);
}
}
private string GetText ()
{
if (TextGenerator != null) {
return TextGenerator (BoundObject);
} else {
var so = BoundObject;
return so == null ? Text : so.ToString ();
}
}
private string GetFormattedText (string text)
{
if (String.IsNullOrEmpty (TextFormat)) {
return text;
}
return String.Format (TextFormat, UseMarkup ? GLib.Markup.EscapeText (text) : text);
}
public override void Arrange ()
{
if (!EnsureLayout ()) {
return;
}
UpdateLayout (GetText (), RenderSize.Width, RenderSize.Height, true);
int text_width, text_height;
layout.GetPixelSize (out text_width, out text_height);
Rect new_alloc = new Rect (
Math.Round ((RenderSize.Width - text_width) * HorizontalAlignment),
Math.Round ((RenderSize.Height - text_height) * VerticalAlignment),
text_width,
text_height);
if (text_alloc.IsEmpty) {
InvalidateRender (text_alloc);
} else {
invalidation_rect = text_alloc;
invalidation_rect.Union (new_alloc);
// Some padding, likely because of the pen size for
// showing the actual text layout in the render pass
invalidation_rect.X -= 2;
invalidation_rect.Y -= 2;
invalidation_rect.Width += 4;
invalidation_rect.Height += 4;
InvalidateRender (invalidation_rect);
}
text_alloc = new_alloc;
}
protected override void ClippedRender (Hyena.Data.Gui.CellContext context)
{
if (!EnsureLayout ()) {
return;
}
var cr = context.Context;
Foreground = new Brush (context.Theme.Colors.GetWidgetColor (
context.TextAsForeground ? GtkColorClass.Foreground : GtkColorClass.Text, context.State));
Brush foreground = Foreground;
if (!foreground.IsValid) {
return;
}
cr.Rectangle (0, 0, RenderSize.Width, RenderSize.Height);
cr.Clip ();
bool fade = Fade && text_alloc.Width > RenderSize.Width;
if (fade) {
cr.PushGroup ();
}
cr.MoveTo (text_alloc.X, text_alloc.Y);
Foreground.Apply (cr);
UpdateLayout (GetText (), RenderSize.Width, RenderSize.Height, true);
if (Hyena.PlatformDetection.IsWindows) {
// FIXME windows; working around some unknown issue with ShowLayout; bgo#644311
cr.Antialias = Cairo.Antialias.None;
PangoCairoHelper.LayoutPath (cr, layout, true);
} else {
PangoCairoHelper.ShowLayout (cr, layout);
}
cr.Fill ();
TooltipMarkup = layout.IsEllipsized ? last_formatted_text : null;
if (fade) {
LinearGradient mask = new LinearGradient (RenderSize.Width - 20, 0, RenderSize.Width, 0);
mask.AddColorStop (0, new Color (0, 0, 0, 1));
mask.AddColorStop (1, new Color (0, 0, 0, 0));
cr.PopGroupToSource ();
cr.Mask (mask);
mask.Dispose ();
}
cr.ResetClip ();
}
private Pango.Weight GetPangoFontWeight (FontWeight weight)
{
switch (weight) {
case FontWeight.Bold: return Pango.Weight.Bold;
default: return Pango.Weight.Normal;
}
}
private Pango.WrapMode GetPangoWrapMode (TextWrap wrap)
{
switch (wrap) {
case TextWrap.Char: return Pango.WrapMode.Char;
case TextWrap.WordChar: return Pango.WrapMode.WordChar;
case TextWrap.None:
case TextWrap.Word:
default:
return Pango.WrapMode.Word;
}
}
protected override Rect InvalidationRect {
get { return invalidation_rect; }
}
public override string ToString ()
{
return String.Format ("<TextBlock Text='{0}' Allocation={1}>", last_formatted_text, Allocation);
}
public string Text { get; set; }
public string TextFormat { get; set; }
public FontWeight FontWeight { get; set; }
public TextWrap TextWrap { get; set; }
public bool Fade { get; set; }
public bool ForceSize { get; set; }
public Pango.EllipsizeMode EllipsizeMode { get; set; }
public Func<object, string> TextGenerator { get; set; }
public bool UseMarkup { get; set; }
public double HorizontalAlignment { get; set; }
public double VerticalAlignment { get; set; }
private static char[] lfcr = new char[] {'\n', '\r'};
private string last_text;
private string last_formatted_text = "";
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Tests
{
public static class QueueTests
{
[Fact]
public static void Ctor_Empty()
{
const int DefaultCapactiy = 32;
var queue = new Queue();
Assert.Equal(0, queue.Count);
for (int i = 0; i <= DefaultCapactiy; i++)
{
queue.Enqueue(i);
}
Assert.Equal(DefaultCapactiy + 1, queue.Count);
}
[Theory]
[InlineData(1)]
[InlineData(32)]
[InlineData(77)]
public static void Ctor_Int(int capacity)
{
var queue = new Queue(capacity);
for (int i = 0; i <= capacity; i++)
{
queue.Enqueue(i);
}
Assert.Equal(capacity + 1, queue.Count);
}
[Fact]
public static void Ctor_Int_NegativeCapacity_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Queue(-1)); // Capacity < 0
}
[Theory]
[InlineData(1, 2.0)]
[InlineData(32, 1.0)]
[InlineData(77, 5.0)]
public static void Ctor_Int_Int(int capacity, float growFactor)
{
var queue = new Queue(capacity, growFactor);
for (int i = 0; i <= capacity; i++)
{
queue.Enqueue(i);
}
Assert.Equal(capacity + 1, queue.Count);
}
[Fact]
public static void Ctor_Int_Int_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Queue(-1, 1)); // Capacity < 0
Assert.Throws<ArgumentOutOfRangeException>("growFactor", () => new Queue(1, (float)0.99)); // Grow factor < 1
Assert.Throws<ArgumentOutOfRangeException>("growFactor", () => new Queue(1, (float)10.01)); // Grow factor > 10
}
[Fact]
public static void Ctor_ICollection()
{
ArrayList arrList = Helpers.CreateIntArrayList(100);
var queue = new Queue(arrList);
Assert.Equal(arrList.Count, queue.Count);
for (int i = 0; i < queue.Count; i++)
{
Assert.Equal(i, queue.Dequeue());
}
}
[Fact]
public static void Ctor_ICollection_NullCollection_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("col", () => new Queue(null)); // Collection is null
}
[Fact]
public static void DebuggerAttribute()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new Queue());
var testQueue = new Queue();
testQueue.Enqueue("a");
testQueue.Enqueue(1);
testQueue.Enqueue("b");
testQueue.Enqueue(2);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(testQueue);
bool threwNull = false;
try
{
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Queue), null);
}
catch (TargetInvocationException ex)
{
threwNull = ex.InnerException is ArgumentNullException;
}
Assert.True(threwNull);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(32)]
public static void Clear(int capacity)
{
var queue1 = new Queue(capacity);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
queue2.Enqueue(1);
queue2.Clear();
Assert.Equal(0, queue2.Count);
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(32)]
public static void Clear_Empty(int capacity)
{
var queue1 = new Queue(capacity);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
queue2.Clear();
Assert.Equal(0, queue2.Count);
queue2.Clear();
Assert.Equal(0, queue2.Count);
});
}
[Fact]
public static void Clone()
{
Queue queue1 = Helpers.CreateIntQueue(100);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
Queue clone = (Queue)queue2.Clone();
Assert.Equal(queue2.IsSynchronized, clone.IsSynchronized);
Assert.Equal(queue2.Count, clone.Count);
for (int i = 0; i < queue2.Count; i++)
{
Assert.True(clone.Contains(i));
}
});
}
[Fact]
public static void Clone_IsShallowCopy()
{
var queue1 = new Queue();
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
queue2.Enqueue(new Foo(10));
Queue clone = (Queue)queue2.Clone();
var foo = (Foo)queue2.Dequeue();
foo.IntValue = 50;
var fooClone = (Foo)clone.Dequeue();
Assert.Equal(50, fooClone.IntValue);
});
}
[Fact]
public static void Clone_Empty()
{
var queue1 = new Queue();
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
Queue clone = (Queue)queue2.Clone();
Assert.Equal(0, clone.Count);
// Can change the clone queue
clone.Enqueue(500);
Assert.Equal(500, clone.Dequeue());
});
}
[Fact]
public static void Clone_Clear()
{
Queue queue1 = Helpers.CreateIntQueue(100);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
queue2.Clear();
Queue clone = (Queue)queue2.Clone();
Assert.Equal(0, clone.Count);
// Can change clone queue
clone.Enqueue(500);
Assert.Equal(500, clone.Dequeue());
});
}
[Fact]
public static void Clone_DequeueUntilEmpty()
{
Queue queue1 = Helpers.CreateIntQueue(100);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
for (int i = 0; i < 100; i++)
{
queue2.Dequeue();
}
Queue clone = (Queue)queue2.Clone();
Assert.Equal(0, queue2.Count);
// Can change clone the queue
clone.Enqueue(500);
Assert.Equal(500, clone.Dequeue());
});
}
[Fact]
public static void Clone_DequeueThenEnqueue()
{
var queue1 = new Queue(100);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
// Insert 50 items in the Queue
for (int i = 0; i < 50; i++)
{
queue2.Enqueue(i);
}
// Insert and Remove 75 items in the Queue. This should wrap the queue
// where there is 25 at the end of the array and 25 at the beginning
for (int i = 0; i < 75; i++)
{
queue2.Enqueue(i + 50);
queue2.Dequeue();
}
Queue queClone = (Queue)queue2.Clone();
Assert.Equal(50, queClone.Count);
Assert.Equal(75, queClone.Dequeue());
// Add an item to the Queue
queClone.Enqueue(100);
Assert.Equal(50, queClone.Count);
Assert.Equal(76, queClone.Dequeue());
});
}
[Fact]
public static void Contains()
{
Queue queue1 = Helpers.CreateIntQueue(100);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
for (int i = 0; i < queue2.Count; i++)
{
Assert.True(queue2.Contains(i));
}
queue2.Enqueue(null);
Assert.True(queue2.Contains(null));
});
}
[Fact]
public static void Contains_NonExistentObject()
{
Queue queue1 = Helpers.CreateIntQueue(100);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
Assert.False(queue2.Contains(101));
Assert.False(queue2.Contains("hello world"));
Assert.False(queue2.Contains(null));
queue2.Enqueue(null);
Assert.False(queue2.Contains(-1)); // We have a null item in the list, so the algorithm may use a different branch
});
}
[Fact]
public static void Contains_EmptyQueue()
{
var queue1 = new Queue();
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
Assert.False(queue2.Contains(101));
Assert.False(queue2.Contains("hello world"));
Assert.False(queue2.Contains(null));
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(1000, 0)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
[InlineData(1000, 50)]
public static void CopyTo(int count, int index)
{
Queue queue1 = Helpers.CreateIntQueue(count);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
var array = new object[count + index];
queue2.CopyTo(array, index);
Assert.Equal(count + index, array.Length);
for (int i = index; i < index + count; i++)
{
Assert.Equal(queue2.Dequeue(), array[i]);
}
});
}
[Fact]
public static void CopyTo_DequeueThenEnqueue()
{
var queue1 = new Queue(100);
// Insert 50 items in the Queue
for (int i = 0; i < 50; i++)
{
queue1.Enqueue(i);
}
// Insert and Remove 75 items in the Queue. This should wrap the queue
// where there is 25 at the end of the array and 25 at the beginning
for (int i = 0; i < 75; i++)
{
queue1.Enqueue(i + 50);
queue1.Dequeue();
}
var array = new object[queue1.Count];
queue1.CopyTo(array, 0);
Assert.Equal(queue1.Count, array.Length);
for (int i = 0; i < queue1.Count; i++)
{
Assert.Equal(queue1.Dequeue(), array[i]);
}
}
[Fact]
public static void CopyTo_Invalid()
{
Queue queue1 = Helpers.CreateIntQueue(100);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
Assert.Throws<ArgumentNullException>("array", () => queue2.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>("array", () => queue2.CopyTo(new object[150, 150], 0)); // Array is multidimensional
Assert.Throws<ArgumentOutOfRangeException>("index", () => queue2.CopyTo(new object[150], -1)); // Index < 0
Assert.Throws<ArgumentException>(null, () => queue2.CopyTo(new object[150], 51)); // Index + queue.Count > array.Length
});
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void Dequeue(int count)
{
Queue queue1 = Helpers.CreateIntQueue(count);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
for (int i = 1; i <= count; i++)
{
int obj = (int)queue2.Dequeue();
Assert.Equal(i - 1, obj);
Assert.Equal(count - i, queue2.Count);
}
});
}
[Fact]
public static void Dequeue_EmptyQueue_ThrowsInvalidOperationException()
{
var queue1 = new Queue();
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
Assert.Throws<InvalidOperationException>(() => queue2.Dequeue()); // Queue is empty
});
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void Dequeue_UntilEmpty(int count)
{
Queue queue1 = Helpers.CreateIntQueue(count);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
for (int i = 0; i < count; i++)
{
queue2.Dequeue();
}
Assert.Throws<InvalidOperationException>(() => queue2.Dequeue());
});
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(10000)]
public static void Enqueue(int count)
{
var queue1 = new Queue();
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
for (int i = 1; i <= count; i++)
{
queue2.Enqueue(i);
Assert.Equal(i, queue2.Count);
}
Assert.Equal(count, queue2.Count);
});
}
[Fact]
public static void Enqueue_Null()
{
var queue1 = new Queue();
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
queue2.Enqueue(null);
Assert.Equal(1, queue2.Count);
});
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void GetEnumerator(int count)
{
var queue1 = Helpers.CreateIntQueue(count);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
Assert.NotSame(queue2.GetEnumerator(), queue2.GetEnumerator());
IEnumerator enumerator = queue2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
Assert.Equal(counter, enumerator.Current);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public static void GetEnumerator_Invalid()
{
var queue1 = Helpers.CreateIntQueue(100);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
IEnumerator enumerator = queue2.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// If the underlying collection is modified, MoveNext and Reset throw, but Current doesn't
enumerator.MoveNext();
object dequeued = queue2.Dequeue();
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.Equal(dequeued, enumerator.Current);
// Current throws if the current index is < 0 or >= count
enumerator = queue2.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current throws after resetting
enumerator = queue2.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.True(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
});
}
[Fact]
public static void Peek()
{
string s1 = "hello";
string s2 = "world";
char c = '\0';
bool b = false;
byte i8 = 0;
short i16 = 0;
int i32 = 0;
long i64 = 0L;
float f = (float)0.0;
double d = 0.0;
var queue1 = new Queue();
queue1.Enqueue(s1);
queue1.Enqueue(s2);
queue1.Enqueue(c);
queue1.Enqueue(b);
queue1.Enqueue(i8);
queue1.Enqueue(i16);
queue1.Enqueue(i32);
queue1.Enqueue(i64);
queue1.Enqueue(f);
queue1.Enqueue(d);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
Assert.Same(s1, queue2.Peek());
queue2.Dequeue();
Assert.Same(s2, queue2.Peek());
queue2.Dequeue();
Assert.Equal(c, queue2.Peek());
queue2.Dequeue();
Assert.Equal(b, queue2.Peek());
queue2.Dequeue();
Assert.Equal(i8, queue2.Peek());
queue2.Dequeue();
Assert.Equal(i16, queue2.Peek());
queue2.Dequeue();
Assert.Equal(i32, queue2.Peek());
queue2.Dequeue();
Assert.Equal(i64, queue2.Peek());
queue2.Dequeue();
Assert.Equal(f, queue2.Peek());
queue2.Dequeue();
Assert.Equal(d, queue2.Peek());
queue2.Dequeue();
});
}
[Fact]
public static void Peek_EmptyQueue_ThrowsInvalidOperationException()
{
var queue1 = new Queue();
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
Assert.Throws<InvalidOperationException>(() => queue2.Peek()); // Queue is empty
});
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void ToArray(int count)
{
Queue queue1 = Helpers.CreateIntQueue(count);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
object[] arr = queue2.ToArray();
Assert.Equal(count, arr.Length);
for (int i = 0; i < count; i++)
{
Assert.Equal(queue2.Dequeue(), arr[i]);
}
});
}
[Fact]
public static void ToArray_Wrapped()
{
var queue1 = new Queue(1);
queue1.Enqueue(1);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
object[] arr = queue2.ToArray();
Assert.Equal(1, arr.Length);
Assert.Equal(1, arr[0]);
});
}
[Fact]
public static void ToArrayDiffentObjectTypes()
{
string s1 = "hello";
string s2 = "world";
char c = '\0';
bool b = false;
byte i8 = 0;
short i16 = 0;
int i32 = 0;
long i64 = 0L;
float f = (float)0.0;
double d = 0.0;
var queue1 = new Queue();
queue1.Enqueue(s1);
queue1.Enqueue(s2);
queue1.Enqueue(c);
queue1.Enqueue(b);
queue1.Enqueue(i8);
queue1.Enqueue(i16);
queue1.Enqueue(i32);
queue1.Enqueue(i64);
queue1.Enqueue(f);
queue1.Enqueue(d);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
object[] arr = queue2.ToArray();
Assert.Same(s1, arr[0]);
Assert.Same(s2, arr[1]);
Assert.Equal(c, arr[2]);
Assert.Equal(b, arr[3]);
Assert.Equal(i8, arr[4]);
Assert.Equal(i16, arr[5]);
Assert.Equal(i32, arr[6]);
Assert.Equal(i64, arr[7]);
Assert.Equal(f, arr[8]);
Assert.Equal(d, arr[9]);
});
}
[Fact]
public static void ToArray_EmptyQueue()
{
var queue1 = new Queue();
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
object[] arr = queue2.ToArray();
Assert.Equal(0, arr.Length);
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void TrimToSize(int count)
{
Queue queue1 = Helpers.CreateIntQueue(count);
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
queue2.TrimToSize();
Assert.Equal(count, queue2.Count);
// Can change the queue after trimming
queue2.Enqueue(100);
Assert.Equal(count + 1, queue2.Count);
if (count == 0)
{
Assert.Equal(100, queue2.Dequeue());
}
else
{
Assert.Equal(0, queue2.Dequeue());
}
});
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void TrimToSize_DequeueAll(int count)
{
Queue queue1 = Helpers.CreateIntQueue(count);
for (int i = 0; i < count; i++)
{
queue1.Dequeue();
}
Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>
{
queue2.TrimToSize();
Assert.Equal(0, queue2.Count);
// Can change the queue after trimming
queue2.Enqueue(1);
Assert.Equal(1, queue2.Dequeue());
});
}
[Fact]
public static void TrimToSize_Wrapped()
{
var queue = new Queue(100);
// Insert 50 items in the Queue
for (int i = 0; i < 50; i++)
{
queue.Enqueue(i);
}
// Insert and Remove 75 items in the Queue. This should wrap the queue
// where there is 25 at the end of the array and 25 at the beginning
for (int i = 0; i < 75; i++)
{
queue.Enqueue(i + 50);
queue.Dequeue();
}
queue.TrimToSize();
Assert.Equal(50, queue.Count);
Assert.Equal(75, queue.Dequeue());
queue.Enqueue(100);
Assert.Equal(50, queue.Count);
Assert.Equal(76, queue.Dequeue());
}
private class Foo
{
public Foo(int intValue)
{
IntValue = intValue;
}
public int IntValue { get; set; }
}
}
public class Queue_SyncRootTests
{
private const int NumberOfElements = 1000;
private const int NumberOfWorkers = 1000;
private Queue _queueDaughter;
private Queue _queueGrandDaughter;
[Fact]
public void SyncRoot()
{
var queueMother = new Queue();
for (int i = 0; i < NumberOfElements; i++)
{
queueMother.Enqueue(i);
}
Assert.Equal(queueMother.SyncRoot.GetType(), typeof(object));
var queueSon = Queue.Synchronized(queueMother);
_queueGrandDaughter = Queue.Synchronized(queueSon);
_queueDaughter = Queue.Synchronized(queueMother);
Assert.Equal(queueMother.SyncRoot, queueSon.SyncRoot);
Assert.Equal(queueSon.SyncRoot, queueMother.SyncRoot);
Assert.Equal(queueMother.SyncRoot, _queueGrandDaughter.SyncRoot);
Assert.Equal(queueMother.SyncRoot, _queueDaughter.SyncRoot);
Task[] workers = new Task[NumberOfWorkers];
Action action1 = SortElements;
Action action2 = ReverseElements;
for (int i = 0; i < NumberOfWorkers; i += 2)
{
workers[i] = Task.Run(action1);
workers[i + 1] = Task.Run(action2);
}
Task.WaitAll(workers);
}
private void SortElements()
{
_queueGrandDaughter.Clear();
for (int i = 0; i < NumberOfElements; i++)
{
_queueGrandDaughter.Enqueue(i);
}
}
private void ReverseElements()
{
_queueDaughter.Clear();
for (int i = 0; i < NumberOfElements; i++)
{
_queueDaughter.Enqueue(i);
}
}
}
public class Queue_SynchronizedTests
{
public Queue _queue;
public int _threadsToUse = 8;
public int _threadAge = 5; // 5000;
public int _threadCount;
[Fact]
public static void Synchronized()
{
Queue queue = Helpers.CreateIntQueue(100);
Queue syncQueue = Queue.Synchronized(queue);
Assert.True(syncQueue.IsSynchronized);
Assert.Equal(queue.Count, syncQueue.Count);
for (int i = 0; i < queue.Count; i++)
{
Assert.True(syncQueue.Contains(i));
}
}
[Fact]
public void SynchronizedEnqueue()
{
// Enqueue
_queue = Queue.Synchronized(new Queue());
PerformTest(StartEnqueueThread, 40);
// Dequeue
Queue queue = Helpers.CreateIntQueue(_threadAge);
_queue = Queue.Synchronized(queue);
PerformTest(StartDequeueThread, 0);
// Enqueue, dequeue
_queue = Queue.Synchronized(new Queue());
PerformTest(StartEnqueueDequeueThread, 0);
// Dequeue, enqueue
queue = Helpers.CreateIntQueue(_threadAge);
_queue = Queue.Synchronized(queue);
PerformTest(StartDequeueEnqueueThread, _threadAge);
}
private void PerformTest(Action action, int expected)
{
var tasks = new Task[_threadsToUse];
for (int i = 0; i < _threadsToUse; i++)
{
tasks[i] = Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
_threadCount = _threadsToUse;
Task.WaitAll(tasks);
Assert.Equal(expected, _queue.Count);
}
[Fact]
public static void Synchronized_NullQueue_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("queue", () => Queue.Synchronized(null)); // Queue is null
}
public void StartEnqueueThread()
{
int t_age = _threadAge;
while (t_age > 0)
{
_queue.Enqueue(t_age);
Interlocked.Decrement(ref t_age);
}
Interlocked.Decrement(ref _threadCount);
}
private void StartDequeueThread()
{
int t_age = _threadAge;
while (t_age > 0)
{
try
{
_queue.Dequeue();
}
catch { }
Interlocked.Decrement(ref t_age);
}
Interlocked.Decrement(ref _threadCount);
}
private void StartEnqueueDequeueThread()
{
int t_age = _threadAge;
while (t_age > 0)
{
_queue.Enqueue(2);
_queue.Dequeue();
Interlocked.Decrement(ref t_age);
}
Interlocked.Decrement(ref _threadCount);
}
private void StartDequeueEnqueueThread()
{
int t_age = _threadAge;
while (t_age > 0)
{
_queue.Dequeue();
_queue.Enqueue(2);
Interlocked.Decrement(ref t_age);
}
Interlocked.Decrement(ref _threadCount);
}
}
}
| |
// 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;
/// <summary>
/// System.Text.StringBuilder.Remove
/// </summary>
public class StringBuilderRemove
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
public static int Main()
{
StringBuilderRemove test = new StringBuilderRemove();
TestLibrary.TestFramework.BeginTestCase("for Method:System.Text.StringBuilder.Remove(indexStart,length)");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int startIndex = TestLibrary.Generator.GetInt32(-55) % Math.Max(1,oldString.Length);
int removedLength = TestLibrary.Generator.GetInt32(-55) % Math.Max(1,(oldString.Length-startIndex-1));
string newString = oldString.Remove(startIndex, removedLength);
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify Remove subString form a StringBuilder ...");
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
System.Text.StringBuilder removedStringBuilder = new System.Text.StringBuilder(newString);
try
{
stringBuilder.Remove(startIndex,removedLength);
int compareResult = string.CompareOrdinal(stringBuilder.ToString(), removedStringBuilder.ToString());
if (compareResult != 0)
{
TestLibrary.TestFramework.LogError("001", "StringBuilder can't corrently remove");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2:Verify StringBuilder Remove itself ");
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int startIndex = 0;
int removedLength = oldString.Length;
try
{
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
stringBuilder.Remove(startIndex, removedLength);
if (stringBuilder.Length != 0)
{
TestLibrary.TestFramework.LogError("003", "StringBuilder can't corrently remove itself");
retVal = false;
}
}
catch(Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int startIndex = 0;
int removedLength = TestLibrary.Generator.GetInt32(-55) % (oldString.Length - startIndex);
string newString = oldString.Remove(startIndex, removedLength);
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify StringBuilder Remove form posization of 0 index ...");
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
System.Text.StringBuilder removedStringBuilder = new System.Text.StringBuilder(newString);
try
{
stringBuilder.Remove(startIndex, removedLength);
int compareResult = string.CompareOrdinal(stringBuilder.ToString(), removedStringBuilder.ToString());
if (compareResult != 0)
{
TestLibrary.TestFramework.LogError("005", "StringBuilder can't corrently remove from posization of 0 index");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int startIndex = TestLibrary.Generator.GetInt32(-55) % oldString.Length;
int removedLength = 0;
string newString = oldString.Remove(startIndex, removedLength);
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify StringBuilder Remove 0 length ...");
try
{
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
System.Text.StringBuilder removedStringBuilder = new System.Text.StringBuilder(newString);
stringBuilder.Remove(startIndex, removedLength);
if (stringBuilder.ToString() != removedStringBuilder.ToString())
{
TestLibrary.TestFramework.LogError("007", "StringBuilder can't corrently Remove 0 length");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: StingBuilder length is 0 and length of removed larger than 0";
const string c_TEST_ID = "N001";
string oldString = TestLibrary.Generator.GetString(-55, false, 0, 0);
int startIndex = 0;
int removedLength = 0;
while (removedLength == 0)
{
removedLength = TestLibrary.Generator.GetInt32(-55);
}
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Remove(startIndex, removedLength);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." );
retVal = false;
}
catch (ArgumentException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: StingBuilder length is 0 and started index larger than 0";
const string c_TEST_ID = "N002";
int startIndex = 0;
int removedLength = 0;
while (startIndex == 0)
{
startIndex = TestLibrary.Generator.GetInt32(-55);
}
string oldString = TestLibrary.Generator.GetString(-55, false, 0, 0);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Remove(startIndex, removedLength);
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected.");
retVal = false;
}
catch (ArgumentException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: length of Removed is larger than length of StringBuilder ";
const string c_TEST_ID = "N003";
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int startIndex = TestLibrary.Generator.GetInt32(-55);
int removedLength = TestLibrary.Generator.GetInt32(-55);
while (startIndex <= oldString.Length )
{
startIndex = TestLibrary.Generator.GetInt32(-55);
}
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Remove(startIndex, removedLength);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected.");
retVal = false;
}
catch (ArgumentException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest4: Sum of length of Removed and index of started is larger than length of StringBuilder ";
const string c_TEST_ID = "N004";
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int removedLength = TestLibrary.Generator.GetInt32(-55);
int startIndex = TestLibrary.Generator.GetInt32(-55) % (oldString.Length-removedLength);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Remove(startIndex, removedLength);
TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
| |
using System;
namespace Eto.Forms
{
/// <summary>
/// Represents a document that can be printed
/// </summary>
/// <remarks>
/// A print document uses the <see cref="Drawing.Graphics"/> to render its output via the
/// <see cref="PrintPage"/> event.
/// </remarks>
[Handler(typeof(PrintDocument.IHandler))]
public class PrintDocument : Widget
{
new IHandler Handler { get { return (IHandler)base.Handler; } }
#region Events
/// <summary>
/// Identifier for handlers when attaching the <see cref="Printing"/> event
/// </summary>
public const string PrintingEvent = "PrintDocument.Printing";
/// <summary>
/// Occurs before printing has started
/// </summary>
public event EventHandler<EventArgs> Printing
{
add { Properties.AddHandlerEvent(PrintingEvent, value); }
remove { Properties.RemoveEvent(PrintingEvent, value); }
}
/// <summary>
/// Raises the <see cref="Printing"/> event.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnPrinting(EventArgs e)
{
Properties.TriggerEvent(PrintingEvent, this, e);
}
/// <summary>
/// Identifier for handlers when attaching the <see cref="Printed"/> event
/// </summary>
public const string PrintedEvent = "PrintDocument.Printed";
/// <summary>
/// Occurs after the document has been printed
/// </summary>
public event EventHandler<EventArgs> Printed
{
add { Properties.AddHandlerEvent(PrintedEvent, value); }
remove { Properties.RemoveEvent(PrintedEvent, value); }
}
/// <summary>
/// Raises the <see cref="Printed"/> event.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnPrinted(EventArgs e)
{
Properties.TriggerEvent(PrintedEvent, this, e);
}
/// <summary>
/// Identifier for handlers when attaching the <see cref="PrintPage"/> event
/// </summary>
public const string PrintPageEvent = "PrintDocument.PrintPage";
/// <summary>
/// Occurs for each printed page
/// </summary>
public event EventHandler<PrintPageEventArgs> PrintPage
{
add { Properties.AddHandlerEvent(PrintPageEvent, value); }
remove { Properties.RemoveEvent(PrintPageEvent, value); }
}
/// <summary>
/// Raises the <see cref="PrintPage"/> event.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnPrintPage(PrintPageEventArgs e)
{
Properties.TriggerEvent(PrintPageEvent, this, e);
}
#endregion
static PrintDocument()
{
EventLookup.Register<PrintDocument>(c => c.OnPrinting(null), PrintDocument.PrintingEvent);
EventLookup.Register<PrintDocument>(c => c.OnPrinted(null), PrintDocument.PrintedEvent);
EventLookup.Register<PrintDocument>(c => c.OnPrintPage(null), PrintDocument.PrintPageEvent);
}
/// <summary>
/// Gets or sets the name of the document to show in the printer queue
/// </summary>
/// <value>The name of the document</value>
public string Name
{
get { return Handler.Name; }
set { Handler.Name = value; }
}
/// <summary>
/// Prints this document immediately using the current <see cref="PrintSettings"/>
/// </summary>
/// <remarks>
/// This skips the print dialog, so if you want the user to adjust settings before printing, use
/// <see cref="PrintDialog.ShowDialog(Control,PrintDocument)"/>.
/// </remarks>
public void Print()
{
Handler.Print();
}
/// <summary>
/// Gets or sets the print settings for the document when printing.
/// </summary>
/// <remarks>
/// You can adjust the settings using the <see cref="PrintDialog"/>, or use <see cref="PrintDialog.ShowDialog(Control,PrintDocument)"/>
/// to allow the user to adjust the settings before printing.
/// </remarks>
/// <value>The print settings.</value>
public PrintSettings PrintSettings
{
get { return Handler.PrintSettings; }
set { Handler.PrintSettings = value; }
}
/// <summary>
/// Gets or sets the total number of pages available to be printed in this document.
/// </summary>
/// <remarks>
/// This must be set to the number of pages your document contains before printing or showing the print dialog.
/// </remarks>
/// <value>The page count.</value>
public virtual int PageCount
{
get { return Handler.PageCount; }
set { Handler.PageCount = value; }
}
#region Callback
static readonly object callback = new Callback();
/// <summary>
/// Gets an instance of an object used to perform callbacks to the widget from handler implementations
/// </summary>
/// <returns>The callback instance to use for this widget</returns>
protected override object GetCallback() { return callback; }
/// <summary>
/// Interface for handlers to trigger events
/// </summary>
public new interface ICallback : Widget.ICallback
{
/// <summary>
/// Raises the printing event, which should occur before the document is printed.
/// </summary>
void OnPrinting(PrintDocument widget, EventArgs e);
/// <summary>
/// Raises the printed event, which should occur after the document is fully printed.
/// </summary>
void OnPrinted(PrintDocument widget, EventArgs e);
/// <summary>
/// Raises the print page event, which should be called for each page in the selected page range to render its contents.
/// </summary>
void OnPrintPage(PrintDocument widget, PrintPageEventArgs e);
}
/// <summary>
/// Callback methods for handlers of <see cref="PrintDocument"/>
/// </summary>
protected class Callback : ICallback
{
/// <summary>
/// Raises the printing event.
/// </summary>
public void OnPrinting(PrintDocument widget, EventArgs e)
{
widget.Platform.Invoke(() => widget.OnPrinting(e));
}
/// <summary>
/// Raises the printed event.
/// </summary>
public void OnPrinted(PrintDocument widget, EventArgs e)
{
widget.Platform.Invoke(() => widget.OnPrinted(e));
}
/// <summary>
/// Raises the print page event.
/// </summary>
public void OnPrintPage(PrintDocument widget, PrintPageEventArgs e)
{
widget.Platform.Invoke(() => widget.OnPrintPage(e));
}
}
#endregion
#region Handler
/// <summary>
/// Handler interface for the <see cref="PrintDocument"/> widget
/// </summary>
public new interface IHandler : Widget.IHandler
{
/// <summary>
/// Prints this document immediately using the current <see cref="PrintSettings"/>
/// </summary>
/// <remarks>
/// This should not show a print dialog, and should add the document to the print queue immediately using
/// the current <see cref="PrintSettings"/>
/// </remarks>
void Print();
/// <summary>
/// Gets or sets the name of the document to show in the printer queue
/// </summary>
/// <value>The name of the document</value>
string Name { get; set; }
/// <summary>
/// Gets or sets the print settings for the document when printing.
/// </summary>
/// <value>The print settings.</value>
PrintSettings PrintSettings { get; set; }
/// <summary>
/// Gets or sets the total number of pages available to be printed in this document.
/// </summary>
/// <remarks>
/// This will be set to the number of pages your document contains before printing or showing the print dialog.
/// </remarks>
/// <value>The page count.</value>
int PageCount { get; set; }
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.