context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* Copyright (c) 2006-2008, openmetaverse.org
* 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.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Utilities;
namespace VoiceTest
{
public class VoiceException: Exception
{
public bool LoggedIn = false;
public VoiceException(string msg): base(msg)
{
}
public VoiceException(string msg, bool loggedIn): base(msg)
{
LoggedIn = loggedIn;
}
}
class VoiceTest
{
static AutoResetEvent EventQueueRunningEvent = new AutoResetEvent(false);
static AutoResetEvent ProvisionEvent = new AutoResetEvent(false);
static AutoResetEvent ParcelVoiceInfoEvent = new AutoResetEvent(false);
static string VoiceAccount = String.Empty;
static string VoicePassword = String.Empty;
static string VoiceRegionName = String.Empty;
static int VoiceLocalID = 0;
static string VoiceChannelURI = String.Empty;
static void Main(string[] args)
{
if (args.Length < 3)
{
Console.WriteLine("Usage: VoiceTest.exe [firstname] [lastname] [password]");
return;
}
string firstName = args[0];
string lastName = args[1];
string password = args[2];
GridClient client = new GridClient();
client.Settings.MULTIPLE_SIMS = false;
Settings.LOG_LEVEL = Helpers.LogLevel.None;
client.Settings.LOG_RESENDS = false;
client.Settings.STORE_LAND_PATCHES = true;
client.Settings.ALWAYS_DECODE_OBJECTS = true;
client.Settings.ALWAYS_REQUEST_OBJECTS = true;
client.Settings.SEND_AGENT_UPDATES = true;
string loginURI = client.Settings.LOGIN_SERVER;
if (4 == args.Length) {
loginURI = args[3];
}
VoiceManager voice = new VoiceManager(client);
voice.OnProvisionAccount += voice_OnProvisionAccount;
voice.OnParcelVoiceInfo += voice_OnParcelVoiceInfo;
client.Network.OnEventQueueRunning += client_OnEventQueueRunning;
try {
if (!voice.ConnectToDaemon()) throw new VoiceException("Failed to connect to the voice daemon");
List<string> captureDevices = voice.CaptureDevices();
Console.WriteLine("Capture Devices:");
for (int i = 0; i < captureDevices.Count; i++)
Console.WriteLine(String.Format("{0}. \"{1}\"", i, captureDevices[i]));
Console.WriteLine();
List<string> renderDevices = voice.RenderDevices();
Console.WriteLine("Render Devices:");
for (int i = 0; i < renderDevices.Count; i++)
Console.WriteLine(String.Format("{0}. \"{1}\"", i, renderDevices[i]));
Console.WriteLine();
// Login
Console.WriteLine("Logging into the grid as " + firstName + " " + lastName + "...");
LoginParams loginParams =
client.Network.DefaultLoginParams(firstName, lastName, password, "Voice Test", "1.0.0");
loginParams.URI = loginURI;
if (!client.Network.Login(loginParams))
throw new VoiceException("Login to SL failed: " + client.Network.LoginMessage);
Console.WriteLine("Logged in: " + client.Network.LoginMessage);
Console.WriteLine("Creating voice connector...");
int status;
string connectorHandle = voice.CreateConnector(out status);
if (String.IsNullOrEmpty(connectorHandle))
throw new VoiceException("Failed to create a voice connector, error code: " + status, true);
Console.WriteLine("Voice connector handle: " + connectorHandle);
Console.WriteLine("Waiting for OnEventQueueRunning");
if (!EventQueueRunningEvent.WaitOne(45 * 1000, false))
throw new VoiceException("EventQueueRunning event did not occur", true);
Console.WriteLine("EventQueue running");
Console.WriteLine("Asking the current simulator to create a provisional account...");
if (!voice.RequestProvisionAccount())
throw new VoiceException("Failed to request a provisional account", true);
if (!ProvisionEvent.WaitOne(120 * 1000, false))
throw new VoiceException("Failed to create a provisional account", true);
Console.WriteLine("Provisional account created. Username: " + VoiceAccount +
", Password: " + VoicePassword);
Console.WriteLine("Logging in to voice server " + voice.VoiceServer);
string accountHandle = voice.Login(VoiceAccount, VoicePassword, connectorHandle, out status);
if (String.IsNullOrEmpty(accountHandle))
throw new VoiceException("Login failed, error code: " + status, true);
Console.WriteLine("Login succeeded, account handle: " + accountHandle);
if (!voice.RequestParcelVoiceInfo())
throw new Exception("Failed to request parcel voice info");
if (!ParcelVoiceInfoEvent.WaitOne(45 * 1000, false))
throw new VoiceException("Failed to obtain parcel info voice", true);
Console.WriteLine("Parcel Voice Info obtained. Region name {0}, local parcel ID {1}, channel URI {2}",
VoiceRegionName, VoiceLocalID, VoiceChannelURI);
client.Network.Logout();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
if (e is VoiceException && (e as VoiceException).LoggedIn)
{
client.Network.Logout();
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
static void client_OnEventQueueRunning(Simulator sim) {
EventQueueRunningEvent.Set();
}
static void client_OnLogMessage(string message, Helpers.LogLevel level)
{
if (level == Helpers.LogLevel.Warning || level == Helpers.LogLevel.Error)
Console.WriteLine(level.ToString() + ": " + message);
}
static void voice_OnProvisionAccount(string username, string password)
{
VoiceAccount = username;
VoicePassword = password;
ProvisionEvent.Set();
}
static void voice_OnParcelVoiceInfo(string regionName, int localID, string channelURI)
{
VoiceRegionName = regionName;
VoiceLocalID = localID;
VoiceChannelURI = channelURI;
ParcelVoiceInfoEvent.Set();
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools;
using TestUtilities;
using TestUtilities.Mocks;
using TestUtilities.Python;
namespace PythonToolsTests {
[TestClass]
public class ReplEvaluatorTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
}
[TestMethod, Priority(UnitTestPriority.P1_FAILING)]
public void ExecuteTest() {
using (var evaluator = MakeEvaluator()) {
var window = new MockReplWindow(evaluator);
evaluator._Initialize(window);
TestOutput(window, evaluator, "print 'hello'", true, "hello");
TestOutput(window, evaluator, "42", true, "42");
TestOutput(window, evaluator, "for i in xrange(2): print i\n", true, "0", "1");
TestOutput(window, evaluator, "raise Exception()\n", false, "Traceback (most recent call last):", " File \"<stdin>\", line 1, in <module>", "Exception");
TestOutput(window, evaluator, "try:\r\n print 'hello'\r\nexcept:\r\n print 'goodbye'\r\n \r\n ", true, "hello");
TestOutput(window, evaluator, "try:\r\n print 'hello'\r\nfinally:\r\n print 'goodbye'\r\n \r\n ", true, "hello", "goodbye");
TestOutput(window, evaluator, "import sys", true);
TestOutput(window, evaluator, "sys.exit(0)", false);
}
}
[TestMethod, Priority(UnitTestPriority.P3_FAILING)]
public void TestAbort() {
using (var evaluator = MakeEvaluator()) {
var window = new MockReplWindow(evaluator);
evaluator._Initialize(window);
TestOutput(
window,
evaluator,
"while True: pass\n",
false,
(completed) => {
Assert.IsTrue(!completed);
Thread.Sleep(1000);
evaluator.AbortExecution();
},
false,
20000,
"KeyboardInterrupt"
);
}
}
[TestMethod, Priority(UnitTestPriority.P1_FAILING)]
public void TestCanExecute() {
using (var evaluator = MakeEvaluator()) {
Assert.IsTrue(evaluator.CanExecuteCode("print 'hello'"));
Assert.IsTrue(evaluator.CanExecuteCode("42"));
Assert.IsTrue(evaluator.CanExecuteCode("for i in xrange(2): print i\r\n\r\n"));
Assert.IsTrue(evaluator.CanExecuteCode("raise Exception()\n"));
Assert.IsFalse(evaluator.CanExecuteCode("try:\r\n print 'hello'\r\nexcept:\r\n print 'goodbye'\r\n "));
Assert.IsTrue(evaluator.CanExecuteCode("try:\r\n print 'hello'\r\nexcept:\r\n print 'goodbye'\r\n \r\n"));
Assert.IsFalse(evaluator.CanExecuteCode("try:\r\n print 'hello'\r\nfinally:\r\n print 'goodbye'\r\n "));
Assert.IsTrue(evaluator.CanExecuteCode("try:\r\n print 'hello'\r\nfinally:\r\n print 'goodbye'\r\n \r\n"));
Assert.IsFalse(evaluator.CanExecuteCode("x = \\"));
Assert.IsTrue(evaluator.CanExecuteCode("x = \\\r\n42\r\n\r\n"));
Assert.IsTrue(evaluator.CanExecuteCode(""));
Assert.IsFalse(evaluator.CanExecuteCode(" "));
Assert.IsFalse(evaluator.CanExecuteCode("# Comment"));
Assert.IsTrue(evaluator.CanExecuteCode("\r\n"));
Assert.IsFalse(evaluator.CanExecuteCode("\r\n#Comment"));
Assert.IsTrue(evaluator.CanExecuteCode("# hello\r\n#world\r\n"));
}
}
[TestMethod, Priority(UnitTestPriority.P3_FAILING)]
public async Task TestGetAllMembers() {
using (var evaluator = MakeEvaluator()) {
var window = new MockReplWindow(evaluator);
await evaluator._Initialize(window);
// Run the ExecuteText on another thread so that we don't continue
// onto the REPL evaluation thread, which leads to GetMemberNames being
// blocked as it's hogging the event loop.
AutoResetEvent are = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(async (x) => {
await evaluator.ExecuteText("globals()['my_new_value'] = 123");
are.Set();
}
);
are.WaitOne(10000);
var names = evaluator.GetMemberNames("");
Assert.IsNotNull(names);
AssertUtil.ContainsAtLeast(names.Select(m => m.Name), "my_new_value");
}
}
[TestMethod, Priority(UnitTestPriority.P1_FAILING)]
public void ReplSplitCodeTest() {
// http://pytools.codeplex.com/workitem/606
var testCases = new[] {
new {
Code = @"def f():
pass
def g():
pass
f()
g()",
Expected = new[] { "def f():\r\n pass\r\n", "def g():\r\n pass\r\n", "f()", "g()" }
},
new {
Code = @"def f():
pass
f()
def g():
pass
f()
g()",
Expected = new[] { "def f():\r\n pass\r\n", "f()", "def g():\r\n pass\r\n", "f()", "g()" }
},
new {
Code = @"def f():
pass
f()
f()
def g():
pass
f()
g()",
Expected = new[] { "def f():\r\n pass\r\n", "f()", "f()", "def g():\r\n pass\r\n", "f()", "g()" }
},
new {
Code = @" def f():
pass
f()
f()
def g():
pass
f()
g()",
Expected = new[] { "def f():\r\n pass\r\n", "f()", "f()", "def g():\r\n pass\r\n", "f()", "g()" }
},
new {
Code = @"# Comment
f()
f()",
Expected = new[] { "# Comment\r\n\r\nf()\r\n", "f()" }
}
};
using (var evaluator = MakeEvaluator()) {
int counter = 0;
foreach (var testCase in testCases) {
Console.WriteLine("Test case {0}", ++counter);
AssertUtil.AreEqual(ReplEditFilter.JoinToCompleteStatements(ReplEditFilter.SplitAndDedent(testCase.Code), Microsoft.PythonTools.Parsing.PythonLanguageVersion.V35), testCase.Expected);
}
}
}
private static PythonInteractiveEvaluator MakeEvaluator() {
var python = PythonPaths.Python27_x64 ?? PythonPaths.Python27;
python.AssertInstalled();
var provider = new SimpleFactoryProvider(python.InterpreterPath, python.InterpreterPath);
var eval = new PythonInteractiveEvaluator(PythonToolsTestUtilities.CreateMockServiceProvider()) {
Configuration = new LaunchConfiguration(python.Configuration)
};
Assert.IsTrue(eval._Initialize(new MockReplWindow(eval)).Result.IsSuccessful);
return eval;
}
class SimpleFactoryProvider : IPythonInterpreterFactoryProvider {
private readonly string _pythonExe;
private readonly string _pythonWinExe;
private readonly string _pythonLib;
public SimpleFactoryProvider(string pythonExe, string pythonWinExe) {
_pythonExe = pythonExe;
_pythonWinExe = pythonWinExe;
_pythonLib = Path.Combine(Path.GetDirectoryName(pythonExe), "Lib");
}
public IEnumerable<IPythonInterpreterFactory> GetInterpreterFactories() {
yield return InterpreterFactoryCreator.CreateInterpreterFactory(new VisualStudioInterpreterConfiguration(
"Test Interpreter",
"Python 2.6 32-bit",
PathUtils.GetParent(_pythonExe),
_pythonExe,
_pythonWinExe,
"PYTHONPATH",
InterpreterArchitecture.x86,
new Version(2, 6),
InterpreterUIMode.CannotBeDefault
), new InterpreterFactoryCreationOptions {
WatchFileSystem = false
});
}
public IEnumerable<InterpreterConfiguration> GetInterpreterConfigurations() {
return GetInterpreterFactories().Select(x => x.Configuration);
}
public IPythonInterpreterFactory GetInterpreterFactory(string id) {
return GetInterpreterFactories()
.Where(x => x.Configuration.Id == id)
.FirstOrDefault();
}
public object GetProperty(string id, string propName) => null;
public event EventHandler InterpreterFactoriesChanged { add { } remove { } }
}
private static void TestOutput(MockReplWindow window, PythonInteractiveEvaluator evaluator, string code, bool success, params string[] expectedOutput) {
TestOutput(window, evaluator, code, success, null, true, 3000, expectedOutput);
}
private static void TestOutput(MockReplWindow window, PythonInteractiveEvaluator evaluator, string code, bool success, Action<bool> afterExecute, bool equalOutput, int timeout = 3000, params string[] expectedOutput) {
window.ClearScreen();
bool completed = false;
var task = evaluator.ExecuteText(code).ContinueWith(completedTask => {
Assert.AreEqual(success, completedTask.Result.IsSuccessful);
var output = success ? window.Output : window.Error;
if (equalOutput) {
if (output.Length == 0) {
Assert.IsTrue(expectedOutput.Length == 0);
} else {
// don't count ending \n as new empty line
output = output.Replace("\r\n", "\n");
if (output[output.Length - 1] == '\n') {
output = output.Remove(output.Length - 1, 1);
}
var lines = output.Split('\n');
if (lines.Length != expectedOutput.Length) {
for (int i = 0; i < lines.Length; i++) {
Console.WriteLine("{0}: {1}", i, lines[i].ToString());
}
}
Assert.AreEqual(lines.Length, expectedOutput.Length);
for (int i = 0; i < expectedOutput.Length; i++) {
Assert.AreEqual(lines[i], expectedOutput[i]);
}
}
} else {
foreach (var line in expectedOutput) {
Assert.IsTrue(output.Contains(line), string.Format("'{0}' does not contain '{1}'", output, line));
}
}
completed = true;
});
if (afterExecute != null) {
afterExecute(completed);
}
try {
task.Wait(timeout);
} catch (AggregateException ex) {
if (ex.InnerException != null) {
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
throw;
}
if (!completed) {
Assert.Fail(string.Format("command didn't complete in {0} seconds", timeout / 1000.0));
}
}
[TestMethod, Priority(UnitTestPriority.P1_FAILING)]
public async Task NoInterpreterPath() {
// http://pytools.codeplex.com/workitem/662
var replEval = new PythonInteractiveEvaluator(PythonToolsTestUtilities.CreateMockServiceProvider()) {
DisplayName = "Test Interpreter"
};
var replWindow = new MockReplWindow(replEval);
await replEval._Initialize(replWindow);
await replEval.ExecuteText("42");
Console.WriteLine(replWindow.Error);
Assert.IsTrue(
replWindow.Error.Contains("Test Interpreter cannot be started"),
"Expected: <Test Interpreter cannot be started>\r\nActual: <" + replWindow.Error + ">"
);
}
[TestMethod, Priority(UnitTestPriority.P1_FAILING)]
public void BadInterpreterPath() {
// http://pytools.codeplex.com/workitem/662
var replEval = new PythonInteractiveEvaluator(PythonToolsTestUtilities.CreateMockServiceProvider()) {
DisplayName = "Test Interpreter",
Configuration = new LaunchConfiguration(new VisualStudioInterpreterConfiguration("InvalidInterpreter", "Test Interpreter", pythonExePath: "C:\\Does\\Not\\Exist\\Some\\Interpreter.exe"))
};
var replWindow = new MockReplWindow(replEval);
replEval._Initialize(replWindow);
var execute = replEval.ExecuteText("42");
var errorText = replWindow.Error;
const string expected = "the associated Python environment could not be found.";
if (!errorText.Contains(expected)) {
Assert.Fail(string.Format(
"Did not find:\n{0}\n\nin:\n{1}",
expected,
errorText
));
}
}
}
}
| |
// 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.Diagnostics;
using System.Runtime.Versioning;
namespace System.Xml
{
// XmlReaderSettings class specifies basic features of an XmlReader.
public sealed class XmlReaderSettings
{
//
// Fields
//
private bool _useAsync;
// Nametable
private XmlNameTable _nameTable;
// XmlResolver
private XmlResolver _xmlResolver = null;
// Text settings
private int _lineNumberOffset;
private int _linePositionOffset;
// Conformance settings
private ConformanceLevel _conformanceLevel;
private bool _checkCharacters;
private long _maxCharactersInDocument;
private long _maxCharactersFromEntities;
// Filtering settings
private bool _ignoreWhitespace;
private bool _ignorePIs;
private bool _ignoreComments;
// security settings
private DtdProcessing _dtdProcessing;
// other settings
private bool _closeInput;
// read-only flag
private bool _isReadOnly;
//
// Constructor
//
public XmlReaderSettings()
{
Initialize();
}
//
// Properties
//
public bool Async
{
get
{
return _useAsync;
}
set
{
CheckReadOnly("Async");
_useAsync = value;
}
}
// Nametable
public XmlNameTable NameTable
{
get
{
return _nameTable;
}
set
{
CheckReadOnly("NameTable");
_nameTable = value;
}
}
internal XmlResolver GetXmlResolver()
{
return _xmlResolver;
}
// Text settings
public int LineNumberOffset
{
get
{
return _lineNumberOffset;
}
set
{
CheckReadOnly("LineNumberOffset");
_lineNumberOffset = value;
}
}
public int LinePositionOffset
{
get
{
return _linePositionOffset;
}
set
{
CheckReadOnly("LinePositionOffset");
_linePositionOffset = value;
}
}
// Conformance settings
public ConformanceLevel ConformanceLevel
{
get
{
return _conformanceLevel;
}
set
{
CheckReadOnly("ConformanceLevel");
if ((uint)value > (uint)ConformanceLevel.Document)
{
throw new ArgumentOutOfRangeException("value");
}
_conformanceLevel = value;
}
}
public bool CheckCharacters
{
get
{
return _checkCharacters;
}
set
{
CheckReadOnly("CheckCharacters");
_checkCharacters = value;
}
}
public long MaxCharactersInDocument
{
get
{
return _maxCharactersInDocument;
}
set
{
CheckReadOnly("MaxCharactersInDocument");
if (value < 0)
{
throw new ArgumentOutOfRangeException("value");
}
_maxCharactersInDocument = value;
}
}
public long MaxCharactersFromEntities
{
get
{
return _maxCharactersFromEntities;
}
set
{
CheckReadOnly("MaxCharactersFromEntities");
if (value < 0)
{
throw new ArgumentOutOfRangeException("value");
}
_maxCharactersFromEntities = value;
}
}
// Filtering settings
public bool IgnoreWhitespace
{
get
{
return _ignoreWhitespace;
}
set
{
CheckReadOnly("IgnoreWhitespace");
_ignoreWhitespace = value;
}
}
public bool IgnoreProcessingInstructions
{
get
{
return _ignorePIs;
}
set
{
CheckReadOnly("IgnoreProcessingInstructions");
_ignorePIs = value;
}
}
public bool IgnoreComments
{
get
{
return _ignoreComments;
}
set
{
CheckReadOnly("IgnoreComments");
_ignoreComments = value;
}
}
public DtdProcessing DtdProcessing
{
get
{
return _dtdProcessing;
}
set
{
CheckReadOnly("DtdProcessing");
if ((uint)value > (uint)DtdProcessing.Parse)
{
throw new ArgumentOutOfRangeException("value");
}
_dtdProcessing = value;
}
}
public bool CloseInput
{
get
{
return _closeInput;
}
set
{
CheckReadOnly("CloseInput");
_closeInput = value;
}
}
//
// Public methods
//
public void Reset()
{
CheckReadOnly("Reset");
Initialize();
}
public XmlReaderSettings Clone()
{
XmlReaderSettings clonedSettings = this.MemberwiseClone() as XmlReaderSettings;
clonedSettings.ReadOnly = false;
return clonedSettings;
}
//
// Internal methods
//
internal XmlReader CreateReader(String inputUri, XmlParserContext inputContext)
{
if (inputUri == null)
{
throw new ArgumentNullException("inputUri");
}
if (inputUri.Length == 0)
{
throw new ArgumentException(SR.XmlConvert_BadUri, "inputUri");
}
// resolve and open the url
XmlResolver tmpResolver = this.GetXmlResolver();
if (tmpResolver == null)
{
tmpResolver = CreateDefaultResolver();
}
// create text XML reader
XmlReader reader = new XmlTextReaderImpl(inputUri, this, inputContext, tmpResolver);
if (_useAsync)
{
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
internal XmlReader CreateReader(Stream input, Uri baseUri, string baseUriString, XmlParserContext inputContext)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
if (baseUriString == null)
{
if (baseUri == null)
{
baseUriString = string.Empty;
}
else
{
baseUriString = baseUri.ToString();
}
}
// create text XML reader
XmlReader reader = new XmlTextReaderImpl(input, null, 0, this, baseUri, baseUriString, inputContext, _closeInput);
if (_useAsync)
{
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
internal XmlReader CreateReader(TextReader input, string baseUriString, XmlParserContext inputContext)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
if (baseUriString == null)
{
baseUriString = string.Empty;
}
// create xml text reader
XmlReader reader = new XmlTextReaderImpl(input, this, baseUriString, inputContext);
if (_useAsync)
{
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
internal XmlReader CreateReader(XmlReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
// wrap with conformance layer (if needed)
return AddConformanceWrapper(reader);
}
internal bool ReadOnly
{
get
{
return _isReadOnly;
}
set
{
_isReadOnly = value;
}
}
private void CheckReadOnly(string propertyName)
{
if (_isReadOnly)
{
throw new XmlException(SR.Xml_ReadOnlyProperty, this.GetType().ToString() + '.' + propertyName);
}
}
//
// Private methods
//
private void Initialize()
{
_nameTable = null;
_lineNumberOffset = 0;
_linePositionOffset = 0;
_checkCharacters = true;
_conformanceLevel = ConformanceLevel.Document;
_ignoreWhitespace = false;
_ignorePIs = false;
_ignoreComments = false;
_dtdProcessing = DtdProcessing.Prohibit;
_closeInput = false;
_maxCharactersFromEntities = 0;
_maxCharactersInDocument = 0;
_useAsync = false;
_isReadOnly = false;
}
private static XmlResolver CreateDefaultResolver()
{
return new XmlSystemPathResolver();
}
internal XmlReader AddConformanceWrapper(XmlReader baseReader)
{
XmlReaderSettings baseReaderSettings = baseReader.Settings;
bool checkChars = false;
bool noWhitespace = false;
bool noComments = false;
bool noPIs = false;
DtdProcessing dtdProc = (DtdProcessing)(-1);
bool needWrap = false;
if (baseReaderSettings == null)
{
#pragma warning disable 618
if (_conformanceLevel != ConformanceLevel.Auto && _conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader))
{
throw new InvalidOperationException(SR.Format(SR.Xml_IncompatibleConformanceLevel, _conformanceLevel.ToString()));
}
// assume the V1 readers already do all conformance checking;
// wrap only if IgnoreWhitespace, IgnoreComments, IgnoreProcessingInstructions or ProhibitDtd is true;
if (_ignoreWhitespace)
{
WhitespaceHandling wh = WhitespaceHandling.All;
if (wh == WhitespaceHandling.All)
{
noWhitespace = true;
needWrap = true;
}
}
if (_ignoreComments)
{
noComments = true;
needWrap = true;
}
if (_ignorePIs)
{
noPIs = true;
needWrap = true;
}
dtdProc = _dtdProcessing;
needWrap = true;
#pragma warning restore 618
}
else
{
if (_conformanceLevel != baseReaderSettings.ConformanceLevel && _conformanceLevel != ConformanceLevel.Auto)
{
throw new InvalidOperationException(SR.Format(SR.Xml_IncompatibleConformanceLevel, _conformanceLevel.ToString()));
}
if (_checkCharacters && !baseReaderSettings.CheckCharacters)
{
checkChars = true;
needWrap = true;
}
if (_ignoreWhitespace && !baseReaderSettings.IgnoreWhitespace)
{
noWhitespace = true;
needWrap = true;
}
if (_ignoreComments && !baseReaderSettings.IgnoreComments)
{
noComments = true;
needWrap = true;
}
if (_ignorePIs && !baseReaderSettings.IgnoreProcessingInstructions)
{
noPIs = true;
needWrap = true;
}
if (_dtdProcessing == DtdProcessing.Prohibit && baseReaderSettings.DtdProcessing != DtdProcessing.Prohibit)
{
dtdProc = _dtdProcessing;
needWrap = true;
}
}
if (needWrap)
{
IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver;
if (readerAsNSResolver != null)
{
return new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc);
}
else
{
return new XmlCharCheckingReader(baseReader, checkChars, noWhitespace, noComments, noPIs, dtdProc);
}
}
else
{
return baseReader;
}
}
}
}
| |
// <copyright file=WorkingStep.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// 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.
// </copyright>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:59 PM</date>
using System.Collections.ObjectModel;
using System.ComponentModel;
using HciLab.motionEAP.InterfacesAndDataModel;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System;
using System.Linq;
namespace motionEAPAdmin.Model.Process
{
/// <summary>
/// This class represents a working step. A working step is a task that the user has to perform in order
/// to create a product. Usually a workflow consists of 1..n working steps.
/// </summary>
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
[Serializable()]
public class WorkingStep : ISerializable, INotifyPropertyChanged
{
// Version
private int m_SerVersion = 6;
// members
private int m_StepNumber; // the position of this Workingstep in the workflow
private string m_Name; // a descriptive name of the workingstep
private string m_WithDrawel;
private AllEnums.PBD_Mode m_Mode;
private ObservableCollection<AdaptiveScene> m_AdaptiveScenes = new ObservableCollection<AdaptiveScene>(); // represents the adaptive scenes belonging to this workingstep
private readonly ObservableCollection<WorkflowFailState> m_FailStates = new ObservableCollection<WorkflowFailState>();
// endcondition
private string m_EndConditionObjectName; //Name of the object to be recognized at the end of the workingstep
//TODO: Change this to some Condition object to allow for more complex conditions.
//time after which workingstep is skipped automatically in milliseconds
private int m_TimeOut = 0;
private int m_ExpectedDuration = 0;
private bool m_IsManualStep;
private bool m_IsQSStep = false;
public event PropertyChangedEventHandler PropertyChanged; // event for the databinding
// constructor
public WorkingStep()
{
createAdaptiveScenesAccordingToAdaptivityLevels();
}
public WorkingStep(string pName, string pWithDrawel, string pEndCondition, int pStepNumber, int pTimeOut = 0)
{
m_Name = pName;
m_EndConditionObjectName = pEndCondition;
m_StepNumber = pStepNumber;
m_WithDrawel = pWithDrawel;
createAdaptiveScenesAccordingToAdaptivityLevels();
m_FailStates = new ObservableCollection<WorkflowFailState>();
}
protected WorkingStep(SerializationInfo info, StreamingContext context)
{
if (info.MemberCount > 6) m_SerVersion = info.GetInt32("m_SerVersion");
else m_SerVersion = 1;
m_StepNumber = info.GetInt32("m_StepNumber");
m_Name = info.GetString("m_Name");
m_WithDrawel = info.GetString("m_WithDrawel");
m_Mode = (AllEnums.PBD_Mode)info.GetValue("m_Mode", typeof(AllEnums.PBD_Mode));
m_AdaptiveScenes = (ObservableCollection<AdaptiveScene>)info.GetValue("m_AdaptiveScenes", typeof(ObservableCollection<AdaptiveScene>));
m_EndConditionObjectName = info.GetString("m_EndConditionObjectName");
if (SerVersion < 2)
return;
m_FailStates = (ObservableCollection<WorkflowFailState>)info.GetValue("m_FailStates", typeof(ObservableCollection<WorkflowFailState>));
if (SerVersion < 3)
return;
m_TimeOut = info.GetInt32("m_TimeOut");
if (SerVersion < 3)
return;
m_ExpectedDuration = info.GetInt32("m_ExpectedDuration");
if (SerVersion < 5)
return;
m_IsManualStep = info.GetBoolean("m_IsManualStep");
if (SerVersion < 6)
return;
m_IsQSStep = info.GetBoolean("m_IsQSStep");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("m_SerVersion", m_SerVersion);
info.AddValue("m_StepNumber", m_StepNumber);
info.AddValue("m_Name", m_Name);
info.AddValue("m_WithDrawel", m_WithDrawel);
info.AddValue("m_Mode", m_Mode);
info.AddValue("m_AdaptiveScenes", m_AdaptiveScenes);
info.AddValue("m_EndConditionObjectName", m_EndConditionObjectName);
info.AddValue("m_FailStates", m_FailStates);
info.AddValue("m_TimeOut", m_TimeOut);
info.AddValue("m_ExpectedDuration", m_ExpectedDuration);
info.AddValue("m_IsManualStep", m_IsManualStep);
info.AddValue("m_IsQSStep", m_IsQSStep);
}
public void createNewName(AllEnums.PBD_Mode mode)
{
if (mode == AllEnums.PBD_Mode.BOX_WITHDRAWEL)
{
string newName = "Step " + m_StepNumber + ": Entnahme " + m_WithDrawel;
Name = newName;
}
else if (mode == AllEnums.PBD_Mode.ASSEMBLY_DONE)
{
string newName = "Step " + m_StepNumber + ": Assembly ";
Name = newName;
}
if (mode == AllEnums.PBD_Mode.END_CONDITION)
{
string newName = "Fertig";
Name = newName;
}
}
/// <summary>
/// This method checks adaptive scenes if all adaptivitylevels have a adaptivescene
/// </summary>
///
///
private void createAdaptiveScenesAccordingToAdaptivityLevels()
{
foreach( AdaptivityLevel level in AdaptivityLevel.AdaptivityLevels)
{
bool found = false;
foreach (AdaptiveScene scene in m_AdaptiveScenes)
{
if(scene.Level.Id == level.Id)
{
found = true;
break;
}
}
if (!found)
{
// create a default adaptive scene
m_AdaptiveScenes.Add(new AdaptiveScene(null, level));
}
}
}
public void CreateFailState(string pTriggerMessage)
{
m_FailStates.Add(new WorkflowFailState("Error "+ (m_FailStates.Count+1), pTriggerMessage, new Scene.Scene()));
NotifyPropertyChanged("ErrorConditionObjectName");
}
public void ChangeFailStateTriggerMessage(string pTriggerMessage)
{
GetFirstFailState().Conditions.FirstOrDefault().CheckMessage = pTriggerMessage;
NotifyPropertyChanged("ErrorConditionObjectName");
}
public Boolean HasFailState()
{
return HasFailstate(0);
}
public Boolean HasFailstate(int index)
{
if (m_FailStates.Count > index) return true;
else return false;
}
public WorkflowFailState GetFirstFailState()
{
if (m_FailStates.Count > 0) return m_FailStates.FirstOrDefault();
else return null;
}
public Scene.Scene GetFirstFailStateScene()
{
if (m_FailStates.Count > 0) return m_FailStates.FirstOrDefault().Scene;
else return null;
}
public WorkflowFailState GetFailState(int index)
{
if (m_FailStates.Count > index) return m_FailStates.ElementAt(index);
else return null;
}
public Scene.Scene GetFailStateScene(int index)
{
if (m_FailStates.Count > index) return m_FailStates.ElementAt(index).Scene;
else return null;
}
public AdaptiveScene getAdaptiveScene(int pLevelId)
{
AdaptiveScene aScene = null;
foreach (AdaptiveScene scene in m_AdaptiveScenes)
{
//Legacy Support: Set Scene AdaptivityLevel if none is defined
if (scene.Level == null)
{
scene.Level = AdaptivityLevel.AdaptivityLevels.ToArray()[0];
}
if (scene.Level.Id == pLevelId)
{
aScene = scene;
}
}
if (aScene == null)
{
// create a default adaptive scene
aScene = new AdaptiveScene(new Scene.Scene(), AdaptivityLevel.AdaptivityLevels.Find(al => al.Id == pLevelId));
m_AdaptiveScenes.Add(aScene);
}
return aScene;
}
// getter/setter
public int SerVersion
{
get { return m_SerVersion; }
set { m_SerVersion = value; }
}
public int StepNumber
{
get
{
return m_StepNumber;
}
set
{
m_StepNumber = value;
NotifyPropertyChanged("STEPNUMBER");
}
}
public string Name
{
get
{
return m_Name;
}
set
{
m_Name = value;
NotifyPropertyChanged("NAME");
}
}
public string Withdrawel
{
get
{
return m_WithDrawel;
}
set
{
m_WithDrawel = value;
NotifyPropertyChanged("WITHDRAWEL");
}
}
public AllEnums.PBD_Mode Mode
{
get
{
return m_Mode;
}
set
{
m_Mode = value;
NotifyPropertyChanged("WITHDRAWEL");
}
}
public ObservableCollection<AdaptiveScene> AdaptiveScenes
{
get
{
return m_AdaptiveScenes;
}
set
{
m_AdaptiveScenes = value;
NotifyPropertyChanged("ADAPTIVESCENES");
}
}
public string EndConditionObjectName
{
get
{
return m_EndConditionObjectName;
}
set
{
m_EndConditionObjectName = value;
NotifyPropertyChanged("ENDCONDITIONOBJECTNAME");
}
}
public ObservableCollection<WorkflowFailState> FailStates
{
get
{
return m_FailStates;
}
}
public string ErrorConditionObjectName
{
get
{
if (m_FailStates.Count > 0) return m_FailStates.FirstOrDefault().Conditions.FirstOrDefault().CheckMessage;
else return "";
}
set
{
throw new Exception("Only for testing purposes. Have a look at fail states collection");
}
}
public int TimeOut
{
get { return m_TimeOut; }
set { m_TimeOut = value; NotifyPropertyChanged("TimeOut"); }
}
public int ExpectedDuration
{
get { return m_ExpectedDuration; }
set { m_ExpectedDuration = value; NotifyPropertyChanged("ExpectedDuration"); }
}
public bool IsManualStep
{
get { return m_IsManualStep; }
set { m_IsManualStep = value; NotifyPropertyChanged("IsManualStep"); }
}
public bool IsQSStep
{
get { return m_IsQSStep; }
set
{
if (CanBeQSStep)
{
m_IsQSStep = value;
NotifyPropertyChanged("IsQSStep");
}
else
{
m_IsQSStep = false;
NotifyPropertyChanged("IsQSStep");
}
}
}
public bool CanBeQSStep
{
get { return EndConditionObjectName != "end"; }
}
private void NotifyPropertyChanged(string Obj)
{
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(Obj));
}
}
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
namespace AmplifyShaderEditor
{
public enum MenuAnchor
{
TOP_LEFT = 0,
TOP_CENTER,
TOP_RIGHT,
MIDDLE_LEFT,
MIDDLE_CENTER,
MIDDLE_RIGHT,
BOTTOM_LEFT,
BOTTOM_CENTER,
BOTTOM_RIGHT,
NONE
}
public enum MenuAutoSize
{
MATCH_VERTICAL = 0,
MATCH_HORIZONTAL,
NONE
}
public class MenuParent
{
protected const float MinimizeButtonXSpacing = 5;
protected const float MinimizeButtonYSpacing = 5.5f;
protected const float ResizeAreaWidth = 5;
protected const float MinimizeCollisionAdjust = 5;
protected GUIStyle m_style;
protected GUIContent m_content;
protected Rect m_maximizedArea;
protected Rect m_transformedArea;
protected Rect m_resizeArea;
protected MenuAnchor m_anchor;
protected MenuAutoSize m_autoSize;
protected bool m_isActive = true;
protected bool m_isMaximized = true;
protected bool m_lockOnMinimize = false;
protected bool m_preLockState = false;
protected Rect m_minimizedArea;
protected Rect m_minimizeButtonPos;
protected float m_realWidth;
protected GUIStyle m_empty = new GUIStyle();
protected float m_resizeDelta;
protected bool m_isResizing = false;
protected bool m_resizable = false;
protected GUIStyle m_resizeAreaStyle;
protected bool m_isMouseInside = false;
protected Vector2 m_currentScrollPos;
public MenuParent( float x, float y, float width, float height, string name, MenuAnchor anchor = MenuAnchor.NONE, MenuAutoSize autoSize = MenuAutoSize.NONE )
{
m_anchor = anchor;
m_autoSize = autoSize;
m_maximizedArea = new Rect( x, y, width, height );
m_content = new GUIContent( GUIContent.none );
m_content.text = name;
m_transformedArea = new Rect();
m_resizeArea = new Rect();
m_resizeArea.width = ResizeAreaWidth;
m_resizeAreaStyle = GUIStyle.none;
m_currentScrollPos = Vector2.zero;
}
public void SetMinimizedArea( float x, float y, float width, float height )
{
m_minimizedArea = new Rect( x, y, width, height );
}
protected void InitDraw( Rect parentPosition, Vector2 mousePosition, int mouseButtonId )
{
if ( m_style == null )
{
m_style = new GUIStyle( UIUtils.CurrentWindow.CustomStylesInstance.TextArea );
m_style.stretchHeight = true;
m_style.stretchWidth = true;
m_style.fontSize = ( int ) Constants.DefaultTitleFontSize;
m_style.fontStyle = FontStyle.Normal;
Texture minimizeTex = UIUtils.GetCustomStyle( CustomStyle.MaximizeButton ).normal.background;
m_minimizeButtonPos = new Rect( 0, 0, minimizeTex.width, minimizeTex.height );
}
Rect currentArea = m_isMaximized ? m_maximizedArea : m_minimizedArea;
if ( m_isMaximized )
{
if ( m_resizable )
{
if ( m_isResizing )
{
float delta = Event.current.delta.x;
m_resizeDelta += delta;
}
}
m_realWidth = m_maximizedArea.width;
if ( m_resizable )
{
if ( m_anchor == MenuAnchor.TOP_LEFT )
{
currentArea.width += m_resizeDelta;
m_realWidth += m_resizeDelta;
}
else if ( m_anchor == MenuAnchor.TOP_RIGHT )
{
currentArea.width -= m_resizeDelta;
m_realWidth -= m_resizeDelta;
}
}
}
else
{
if ( currentArea.x < 0 )
{
m_realWidth = currentArea.width + currentArea.x;
}
else if ( ( currentArea.x + currentArea.width ) > parentPosition.width )
{
m_realWidth = parentPosition.width - currentArea.x;
}
if ( m_realWidth < 0 )
m_realWidth = 0;
}
switch ( m_anchor )
{
case MenuAnchor.TOP_LEFT:
{
m_transformedArea.x = currentArea.x;
m_transformedArea.y = currentArea.y;
if ( m_isMaximized )
{
m_minimizeButtonPos.x = m_transformedArea.x + m_transformedArea.width - m_minimizeButtonPos.width - MinimizeButtonXSpacing;
m_minimizeButtonPos.y = m_transformedArea.y + MinimizeButtonYSpacing;
m_resizeArea.x = m_transformedArea.x + m_transformedArea.width;
m_resizeArea.y = m_minimizeButtonPos.y;
m_resizeArea.height = m_transformedArea.height;
}
else
{
float width = ( m_transformedArea.width - m_transformedArea.x );
m_minimizeButtonPos.x = m_transformedArea.x + width * 0.5f - m_minimizeButtonPos.width * 0.5f;
m_minimizeButtonPos.y = m_transformedArea.height * 0.5f - m_minimizeButtonPos.height * 0.5f;
}
}
break;
case MenuAnchor.TOP_CENTER:
{
m_transformedArea.x = parentPosition.width * 0.5f + currentArea.x;
m_transformedArea.y = currentArea.y;
}
break;
case MenuAnchor.TOP_RIGHT:
{
m_transformedArea.x = parentPosition.width - currentArea.x - currentArea.width;
m_transformedArea.y = currentArea.y;
if ( m_isMaximized )
{
m_minimizeButtonPos.x = m_transformedArea.x + MinimizeButtonXSpacing;
m_minimizeButtonPos.y = m_transformedArea.y + MinimizeButtonYSpacing;
m_resizeArea.x = m_transformedArea.x - ResizeAreaWidth;
m_resizeArea.y = m_minimizeButtonPos.y;
m_resizeArea.height = m_transformedArea.height;
}
else
{
float width = ( parentPosition.width - m_transformedArea.x );
m_minimizeButtonPos.x = m_transformedArea.x + width * 0.5f - m_minimizeButtonPos.width * 0.5f;
m_minimizeButtonPos.y = m_transformedArea.height * 0.5f - m_minimizeButtonPos.height * 0.5f;
}
}
break;
case MenuAnchor.MIDDLE_LEFT:
{
m_transformedArea.x = currentArea.x;
m_transformedArea.y = parentPosition.height * 0.5f + currentArea.y;
}
break;
case MenuAnchor.MIDDLE_CENTER:
{
m_transformedArea.x = parentPosition.width * 0.5f + currentArea.x;
m_transformedArea.y = parentPosition.height * 0.5f + currentArea.y;
}
break;
case MenuAnchor.MIDDLE_RIGHT:
{
m_transformedArea.x = parentPosition.width - currentArea.x - currentArea.width;
m_transformedArea.y = parentPosition.height * 0.5f + currentArea.y;
}
break;
case MenuAnchor.BOTTOM_LEFT:
{
m_transformedArea.x = currentArea.x;
m_transformedArea.y = parentPosition.height - currentArea.y - currentArea.height;
}
break;
case MenuAnchor.BOTTOM_CENTER:
{
m_transformedArea.x = parentPosition.width * 0.5f + currentArea.x;
m_transformedArea.y = parentPosition.height - currentArea.y - currentArea.height;
}
break;
case MenuAnchor.BOTTOM_RIGHT:
{
m_transformedArea.x = parentPosition.width - currentArea.x - currentArea.width;
m_transformedArea.y = parentPosition.height - currentArea.y - currentArea.height;
}
break;
case MenuAnchor.NONE:
{
m_transformedArea.x = currentArea.x;
m_transformedArea.y = currentArea.y;
}
break;
}
switch ( m_autoSize )
{
case MenuAutoSize.MATCH_HORIZONTAL:
{
m_transformedArea.width = parentPosition.width - m_transformedArea.x;
m_transformedArea.height = currentArea.height;
}
break;
case MenuAutoSize.MATCH_VERTICAL:
{
m_transformedArea.width = currentArea.width;
m_transformedArea.height = parentPosition.height - m_transformedArea.y;
}
break;
case MenuAutoSize.NONE:
{
m_transformedArea.width = currentArea.width;
m_transformedArea.height = currentArea.height;
}
break;
}
}
public virtual void Draw( Rect parentPosition, Vector2 mousePosition, int mouseButtonId, bool hasKeyboadFocus )
{
InitDraw( parentPosition, mousePosition, mouseButtonId );
m_isMouseInside = IsInside( mousePosition );
if ( m_isMouseInside )
{
if ( Event.current.type == EventType.MouseDrag && Event.current.button > 0 /*catches both middle and right mouse button*/ )
{
m_currentScrollPos.x += Constants.MenuDragSpeed*Event.current.delta.x;
if ( m_currentScrollPos.x < 0 )
m_currentScrollPos.x = 0;
m_currentScrollPos.y += Constants.MenuDragSpeed * Event.current.delta.y;
if ( m_currentScrollPos.y < 0 )
m_currentScrollPos.y = 0;
}
}
}
public void PostDraw()
{
if ( !m_isMaximized )
{
m_transformedArea.height = 35;
GUI.Box( m_transformedArea, m_content, m_style );
}
Color colorBuffer = GUI.color;
GUI.color = EditorGUIUtility.isProSkin ? Color.white : Color.black;
bool guiEnabledBuffer = GUI.enabled;
GUI.enabled = !m_lockOnMinimize;
Rect buttonArea = m_minimizeButtonPos;
buttonArea.x -= MinimizeCollisionAdjust;
buttonArea.width += 2 * MinimizeCollisionAdjust;
buttonArea.y -= MinimizeCollisionAdjust;
buttonArea.height += 2 * MinimizeCollisionAdjust;
GUI.Box( m_minimizeButtonPos, string.Empty, UIUtils.GetCustomStyle( m_isMaximized ? CustomStyle.MinimizeButton : CustomStyle.MaximizeButton ) );
if ( GUI.Button( buttonArea, string.Empty, m_empty ) )
{
m_isMaximized = !m_isMaximized;
m_resizeDelta = 0;
}
if ( m_resizable && m_isMaximized )
{
EditorGUIUtility.AddCursorRect( m_resizeArea, MouseCursor.ResizeHorizontal );
if ( !m_isResizing && GUI.RepeatButton( m_resizeArea, string.Empty, m_resizeAreaStyle ) )
{
m_isResizing = true;
}
else
{
if ( m_isResizing )
{
if ( Event.current.isMouse && Event.current.type != EventType.MouseDrag )
{
m_isResizing = false;
}
}
}
if ( m_realWidth < buttonArea.width )
{
// Auto-minimize
m_isMaximized = false;
m_resizeDelta = 0;
m_isResizing = false;
}
else
{
float halfSizeWindow = 0.5f * UIUtils.CurrentWindow.position.width;
if ( m_realWidth > halfSizeWindow )
{
m_realWidth = 0.5f * UIUtils.CurrentWindow.position.width;
if ( m_resizeDelta > 0 )
{
m_resizeDelta = m_realWidth - m_maximizedArea.width;
}
else
{
m_resizeDelta = m_maximizedArea.width - m_realWidth;
}
}
}
}
GUI.enabled = guiEnabledBuffer;
GUI.color = colorBuffer;
}
public void OnLostFocus()
{
if ( m_isResizing )
{
m_isResizing = false;
}
}
virtual public void Destroy()
{
m_empty = null;
m_resizeAreaStyle = null;
}
public float InitialX
{
get { return m_maximizedArea.x; }
set { m_maximizedArea.x = value; }
}
public float Width
{
get { return m_maximizedArea.width; }
set { m_maximizedArea.width = value; }
}
public float RealWidth
{
get { return m_realWidth; }
}
public float Height
{
get { return m_maximizedArea.height; }
set { m_maximizedArea.height = value; }
}
public Rect Size
{
get { return m_maximizedArea; }
}
public virtual bool IsInside( Vector2 position )
{
if ( !m_isActive )
return false;
return m_transformedArea.Contains( position );
}
public bool IsMaximized
{
get { return m_isMaximized; }
set { m_isMaximized = value; }
}
public Rect TransformedArea
{
get { return m_transformedArea; }
}
public bool Resizable { set { m_resizable = value; } }
public bool IsResizing { get { return m_isResizing; } }
public bool LockOnMinimize
{
set
{
if ( m_lockOnMinimize == value )
return;
m_lockOnMinimize = value;
if ( value )
{
m_preLockState = m_isMaximized;
m_isMaximized = false;
}
else
{
m_isMaximized = m_preLockState;
}
}
}
}
}
| |
/* ====================================================================
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 NUnit.Framework;
using NPOI.OpenXmlFormats.Spreadsheet;
using System.Collections.Generic;
using System;
using NPOI.SS.UserModel;
namespace NPOI.XSSF.UserModel
{
/**
* Tests functionality of the XSSFRichTextRun object
*
* @author Yegor Kozlov
*/
[TestFixture]
public class TestXSSFRichTextString
{
[Test]
public void TestCreate()
{
XSSFRichTextString rt = new XSSFRichTextString("Apache POI");
Assert.AreEqual("Apache POI", rt.String);
CT_Rst st = rt.GetCTRst();
Assert.IsTrue(st.IsSetT());
Assert.AreEqual("Apache POI", st.t);
rt.Append(" is cool stuff");
Assert.AreEqual(2, st.sizeOfRArray());
Assert.IsFalse(st.IsSetT());
Assert.AreEqual("Apache POI is cool stuff", rt.String);
}
[Test]
public void TestApplyFont()
{
XSSFRichTextString rt = new XSSFRichTextString();
rt.Append("123");
rt.Append("4567");
rt.Append("89");
Assert.AreEqual("123456789", rt.String);
XSSFFont font1 = new XSSFFont();
font1.IsBold = (true);
rt.ApplyFont(2, 5, font1);
Assert.AreEqual(4, rt.NumFormattingRuns);
Assert.AreEqual(0, rt.GetIndexOfFormattingRun(0));
Assert.AreEqual("12", rt.GetCTRst().GetRArray(0).t);
Assert.AreEqual(2, rt.GetIndexOfFormattingRun(1));
Assert.AreEqual("345", rt.GetCTRst().GetRArray(1).t);
Assert.AreEqual(5, rt.GetIndexOfFormattingRun(2));
Assert.AreEqual(2, rt.GetLengthOfFormattingRun(2));
Assert.AreEqual("67", rt.GetCTRst().GetRArray(2).t);
Assert.AreEqual(7, rt.GetIndexOfFormattingRun(3));
Assert.AreEqual(2, rt.GetLengthOfFormattingRun(3));
Assert.AreEqual("89", rt.GetCTRst().GetRArray(3).t);
}
[Test]
public void TestClearFormatting()
{
XSSFRichTextString rt = new XSSFRichTextString("Apache POI");
Assert.AreEqual("Apache POI", rt.String);
rt.ClearFormatting();
CT_Rst st = rt.GetCTRst();
Assert.IsTrue(st.IsSetT());
Assert.AreEqual("Apache POI", rt.String);
Assert.AreEqual(0, rt.NumFormattingRuns);
XSSFFont font = new XSSFFont();
font.IsBold = true;
rt.ApplyFont(7, 10, font);
Assert.AreEqual(2, rt.NumFormattingRuns);
rt.ClearFormatting();
Assert.AreEqual("Apache POI", rt.String);
Assert.AreEqual(0, rt.NumFormattingRuns);
}
[Test]
public void TestGetFonts()
{
XSSFRichTextString rt = new XSSFRichTextString();
XSSFFont font1 = new XSSFFont();
font1.FontName = ("Arial");
font1.IsItalic = (true);
rt.Append("The quick", font1);
XSSFFont font1FR = (XSSFFont)rt.GetFontOfFormattingRun(0);
Assert.AreEqual(font1.IsItalic, font1FR.IsItalic);
Assert.AreEqual(font1.FontName, font1FR.FontName);
XSSFFont font2 = new XSSFFont();
font2.FontName = ("Courier");
font2.IsBold = (true);
rt.Append(" brown fox", font2);
XSSFFont font2FR = (XSSFFont)rt.GetFontOfFormattingRun(1);
Assert.AreEqual(font2.IsBold, font2FR.IsBold);
Assert.AreEqual(font2.FontName, font2FR.FontName);
}
/**
* make sure we insert xml:space="preserve" attribute
* if a string has leading or trailing white spaces
*/
// [Test]
//public void TestPreserveSpaces()
//{
// XSSFRichTextString rt = new XSSFRichTextString("Apache");
// CT_Rst ct = rt.GetCTRst();
// STXstring xs = ct.xgetT();
// Assert.AreEqual("<xml-fragment>Apache</xml-fragment>", xs.xmlText());
// rt.String = (" Apache");
// Assert.AreEqual("<xml-fragment xml:space=\"preserve\"> Apache</xml-fragment>", xs.xmlText());
//rt.Append(" POI");
//rt.Append(" ");
//Assert.AreEqual(" Apache POI ", rt.getString());
//Assert.AreEqual("<xml-fragment xml:space=\"preserve\"> Apache</xml-fragment>", rt.getCTRst().getRArray(0).xgetT().xmlText());
//Assert.AreEqual("<xml-fragment xml:space=\"preserve\"> POI</xml-fragment>", rt.getCTRst().getRArray(1).xgetT().xmlText());
//Assert.AreEqual("<xml-fragment xml:space=\"preserve\"> </xml-fragment>", rt.getCTRst().getRArray(2).xgetT().xmlText());
//}
/**
* Test that unicode representation_ xHHHH_ is properly Processed
*/
[Test]
public void TestUtfDecode()
{
CT_Rst st = new CT_Rst();
st.t = ("abc_x000D_2ef_x000D_");
XSSFRichTextString rt = new XSSFRichTextString(st);
//_x000D_ is Converted into carriage return
Assert.AreEqual("abc\r2ef\r", rt.String);
}
//[Test]
//public void TestApplyFont_lowlevel()
//{
// CT_Rst st = new CT_Rst();
// String text = "Apache Software Foundation";
// XSSFRichTextString str = new XSSFRichTextString(text);
// Assert.AreEqual(26, text.Length);
// st.AddNewR().t = (text);
// Dictionary<int, CT_RPrElt> formats = str.GetFormatMap(st);
// Assert.AreEqual(1, formats.Count);
// Assert.AreEqual(26, (int)formats.firstKey());
// Assert.IsNull(formats.Get(formats.firstKey()));
// CT_RPrElt fmt1 = new CT_RPrElt();
// str.ApplyFont(formats, 0, 6, fmt1);
// Assert.AreEqual(2, formats.Count);
// Assert.AreEqual("[6, 26]", formats.Keys.ToString());
// Object[] Runs1 = formats.Values.ToArray();
// Assert.AreSame(fmt1, Runs1[0]);
// Assert.AreSame(null, Runs1[1]);
// CT_RPrElt fmt2 = new CT_RPrElt();
// str.ApplyFont(formats, 7, 15, fmt2);
// Assert.AreEqual(4, formats.Count);
// Assert.AreEqual("[6, 7, 15, 26]", formats.Keys.ToString());
// Object[] Runs2 = formats.Values.ToArray();
// Assert.AreSame(fmt1, Runs2[0]);
// Assert.AreSame(null, Runs2[1]);
// Assert.AreSame(fmt2, Runs2[2]);
// Assert.AreSame(null, Runs2[3]);
// CT_RPrElt fmt3 = new CT_RPrElt();
// str.ApplyFont(formats, 6, 7, fmt3);
// Assert.AreEqual(4, formats.Count);
// Assert.AreEqual("[6, 7, 15, 26]", formats.Keys.ToString());
// Object[] Runs3 = formats.Values.ToArray();
// Assert.AreSame(fmt1, Runs3[0]);
// Assert.AreSame(fmt3, Runs3[1]);
// Assert.AreSame(fmt2, Runs3[2]);
// Assert.AreSame(null, Runs3[3]);
// CT_RPrElt fmt4 = new CT_RPrElt();
// str.ApplyFont(formats, 0, 7, fmt4);
// Assert.AreEqual(3, formats.Count);
// Assert.AreEqual("[7, 15, 26]", formats.Keys.ToString());
// Object[] Runs4 = formats.Values.ToArray();
// Assert.AreSame(fmt4, Runs4[0]);
// Assert.AreSame(fmt2, Runs4[1]);
// Assert.AreSame(null, Runs4[2]);
// CT_RPrElt fmt5 = new CT_RPrElt();
// str.ApplyFont(formats, 0, 26, fmt5);
// Assert.AreEqual(1, formats.Count);
// Assert.AreEqual("[26]", formats.Keys.ToString());
// Object[] Runs5 = formats.Values.ToArray();
// Assert.AreSame(fmt5, Runs5[0]);
// CT_RPrElt fmt6 = new CT_RPrElt();
// str.ApplyFont(formats, 15, 26, fmt6);
// Assert.AreEqual(2, formats.Count);
// Assert.AreEqual("[15, 26]", formats.Keys.ToString());
// Object[] Runs6 = formats.Values.ToArray();
// Assert.AreSame(fmt5, Runs6[0]);
// Assert.AreSame(fmt6, Runs6[1]);
// str.ApplyFont(formats, 0, 26, null);
// Assert.AreEqual(1, formats.Count);
// Assert.AreEqual("[26]", formats.Keys.ToString());
// Object[] Runs7 = formats.Values.ToArray();
// Assert.AreSame(null, Runs7[0]);
// str.ApplyFont(formats, 15, 26, fmt6);
// Assert.AreEqual(2, formats.Count);
// Assert.AreEqual("[15, 26]", formats.Keys.ToString());
// Object[] Runs8 = formats.Values.ToArray();
// Assert.AreSame(null, Runs8[0]);
// Assert.AreSame(fmt6, Runs8[1]);
// str.ApplyFont(formats, 15, 26, fmt5);
// Assert.AreEqual(2, formats.Count);
// Assert.AreEqual("[15, 26]", formats.Keys.ToString());
// Object[] Runs9 = formats.Values.ToArray();
// Assert.AreSame(null, Runs9[0]);
// Assert.AreSame(fmt5, Runs9[1]);
// str.ApplyFont(formats, 2, 20, fmt6);
// Assert.AreEqual(3, formats.Count);
// Assert.AreEqual("[2, 20, 26]", formats.Keys.ToString());
// Object[] Runs10 = formats.Values.ToArray();
// Assert.AreSame(null, Runs10[0]);
// Assert.AreSame(fmt6, Runs10[1]);
// Assert.AreSame(fmt5, Runs10[2]);
// str.ApplyFont(formats, 22, 24, fmt4);
// Assert.AreEqual(5, formats.Count);
// Assert.AreEqual("[2, 20, 22, 24, 26]", formats.Keys.ToString());
// Object[] Runs11 = formats.Values.ToArray();
// Assert.AreSame(null, Runs11[0]);
// Assert.AreSame(fmt6, Runs11[1]);
// Assert.AreSame(fmt5, Runs11[2]);
// Assert.AreSame(fmt4, Runs11[3]);
// Assert.AreSame(fmt5, Runs11[4]);
// str.ApplyFont(formats, 0, 10, fmt1);
// Assert.AreEqual(5, formats.Count);
// Assert.AreEqual("[10, 20, 22, 24, 26]", formats.Keys.ToString());
// Object[] Runs12 = formats.Values.ToArray();
// Assert.AreSame(fmt1, Runs12[0]);
// Assert.AreSame(fmt6, Runs12[1]);
// Assert.AreSame(fmt5, Runs12[2]);
// Assert.AreSame(fmt4, Runs12[3]);
// Assert.AreSame(fmt5, Runs12[4]);
//}
[Test]
public void TestApplyFont_usermodel()
{
String text = "Apache Software Foundation";
XSSFRichTextString str = new XSSFRichTextString(text);
XSSFFont font1 = new XSSFFont();
XSSFFont font2 = new XSSFFont();
XSSFFont font3 = new XSSFFont();
str.ApplyFont(font1);
Assert.AreEqual(1, str.NumFormattingRuns);
str.ApplyFont(0, 6, font1);
str.ApplyFont(6, text.Length, font2);
Assert.AreEqual(2, str.NumFormattingRuns);
Assert.AreEqual("Apache", str.GetCTRst().GetRArray(0).t);
Assert.AreEqual(" Software Foundation", str.GetCTRst().GetRArray(1).t);
str.ApplyFont(15, 26, font3);
Assert.AreEqual(3, str.NumFormattingRuns);
Assert.AreEqual("Apache", str.GetCTRst().GetRArray(0).t);
Assert.AreEqual(" Software", str.GetCTRst().GetRArray(1).t);
Assert.AreEqual(" Foundation", str.GetCTRst().GetRArray(2).t);
str.ApplyFont(6, text.Length, font2);
Assert.AreEqual(2, str.NumFormattingRuns);
Assert.AreEqual("Apache", str.GetCTRst().GetRArray(0).t);
Assert.AreEqual(" Software Foundation", str.GetCTRst().GetRArray(1).t);
}
//[Test]
//public void TestLineBreaks_bug48877()
//{
// XSSFFont font = new XSSFFont();
// font.Boldweight = (short)FontBoldWeight.BOLD;
// font.FontHeightInPoints = ((short)14);
// XSSFRichTextString str;
// STXstring t1, t2, t3;
// str = new XSSFRichTextString("Incorrect\nLine-Breaking");
// str.ApplyFont(0, 8, font);
// t1 = str.GetCTRst().r[0].xgetT();
// t2 = str.GetCTRst().r[1].xgetT();
// Assert.AreEqual("<xml-fragment>Incorrec</xml-fragment>", t1.xmlText());
// Assert.AreEqual("<xml-fragment>t\nLine-Breaking</xml-fragment>", t2.xmlText());
// str = new XSSFRichTextString("Incorrect\nLine-Breaking");
// str.ApplyFont(0, 9, font);
// t1 = str.GetCTRst().r[0].xgetT();
// t2 = str.GetCTRst().r[1].xgetT();
// Assert.AreEqual("<xml-fragment>Incorrect</xml-fragment>", t1.xmlText());
// Assert.AreEqual("<xml-fragment xml:space=\"preserve\">\nLine-Breaking</xml-fragment>", t2.xmlText());
// str = new XSSFRichTextString("Incorrect\n Line-Breaking");
// str.ApplyFont(0, 9, font);
// t1 = str.GetCTRst().r[0].xgetT();
// t2 = str.GetCTRst().r[1].xgetT();
// Assert.AreEqual("<xml-fragment>Incorrect</xml-fragment>", t1.xmlText());
// Assert.AreEqual("<xml-fragment xml:space=\"preserve\">\n Line-Breaking</xml-fragment>", t2.xmlText());
// str = new XSSFRichTextString("Tab\tSeparated\n");
// t1 = str.GetCTRst().xgetT();
// // trailing \n causes must be preserved
// Assert.AreEqual("<xml-fragment xml:space=\"preserve\">Tab\tSeparated\n</xml-fragment>", t1.xmlText());
// str.ApplyFont(0, 3, font);
// t1 = str.GetCTRst().r[0].xgetT();
// t2 = str.GetCTRst().r[1].xgetT();
// Assert.AreEqual("<xml-fragment>Tab</xml-fragment>", t1.xmlText());
// Assert.AreEqual("<xml-fragment xml:space=\"preserve\">\tSeparated\n</xml-fragment>", t2.xmlText());
// str = new XSSFRichTextString("Tab\tSeparated\n");
// str.ApplyFont(0, 4, font);
// t1 = str.GetCTRst().r[0].xgetT();
// t2 = str.GetCTRst().r[1].xgetT();
// // YK: don't know why, but XmlBeans Converts leading tab characters to spaces
// //Assert.AreEqual("<xml-fragment>Tab\t</xml-fragment>", t1.xmlText());
// Assert.AreEqual("<xml-fragment xml:space=\"preserve\">Separated\n</xml-fragment>", t2.xmlText());
// str = new XSSFRichTextString("\n\n\nNew Line\n\n");
// str.ApplyFont(0, 3, font);
// str.ApplyFont(11, 13, font);
// t1 = str.GetCTRst().r[0].xgetT();
// t2 = str.GetCTRst().r[1].xgetT();
// t3 = str.GetCTRst().r[2].xgetT();
// // YK: don't know why, but XmlBeans Converts leading tab characters to spaces
// Assert.AreEqual("<xml-fragment xml:space=\"preserve\">\n\n\n</xml-fragment>", t1.xmlText());
// Assert.AreEqual("<xml-fragment>New Line</xml-fragment>", t2.xmlText());
// Assert.AreEqual("<xml-fragment xml:space=\"preserve\">\n\n</xml-fragment>", t3.xmlText());
//}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DataHubServicesAddin.LocatorHub;
namespace DataHubServicesAddin.Dialogs
{
public partial class LocatorPopupForm : Form
{
#region "Variables"
String _Query;
String _MatchType;
bool _UseFuzzy;
Stack<MatchResult> _MatchCache = new Stack<MatchResult>();
DataTable _CurrentDataTable;
string _LocatorId;
int _SpatialReference = -1;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LocatorPopupForm"/> class.
/// </summary>
public LocatorPopupForm(LocatorHub.LocatorHub client)
{
InitializeComponent();
this.Client = client;
}
#endregion
#region Properties
/// <summary>
/// Gets the client.
/// </summary>
/// <value>
/// The client.
/// </value>
public LocatorHub.LocatorHub Client { get; private set; }
/// <summary>
/// Gets the found record.
/// </summary>
/// <value>
/// The found record.
/// </value>
public MatchResult FoundRecord
{
get;
private set;
}
/// <summary>
/// Gets the fail reason.
/// </summary>
/// <value>
/// The fail reason.
/// </value>
public MatchResultCodes FailReason
{
get;
private set;
}
/// <summary>
/// Gets the column lookup.
/// </summary>
/// <value>
/// The column lookup.
/// </value>
public Dictionary<String, int> ColumnLookup
{
get;
private set;
}
#endregion
#region Functions
/// <summary>
/// Setups the specified in match type.
/// </summary>
/// <param name="inMatchType">Type of the in match.</param>
/// <param name="inQuery">The in query.</param>
/// <param name="inLocatorId">The in locator id.</param>
/// <param name="inFuzzy">if set to <c>true</c> [in fuzzy].</param>
/// <param name="inName">Name of the in.</param>
/// <param name="spref">The spref.</param>
public void Setup(string inMatchType, string inQuery, string inLocatorId, bool inFuzzy, string inName, int spref)
{
//Setup Values for Selection
_Query = inQuery;
_MatchType = inMatchType;
_UseFuzzy = inFuzzy;
_SpatialReference = spref;
this._LocatorId = inLocatorId;
//set caption
this.Text = "Select " + inName;
//Run Match without drill down and no item selected
RunMatch(inLocatorId, inMatchType, inQuery, inFuzzy, false, -1);
}
/// <summary>
/// Runs the match.
/// </summary>
/// <param name="inLocatorId">The in locator id.</param>
/// <param name="inMatchType">Type of the in match.</param>
/// <param name="inQuery">The in query.</param>
/// <param name="inFuzzy">if set to <c>true</c> [in fuzzy].</param>
/// <param name="indrillDown">if set to <c>true</c> [indrill down].</param>
/// <param name="inSelectedItem">The in selected item.</param>
private void RunMatch(string inLocatorId, String inMatchType, String inQuery, bool inFuzzy, bool indrillDown, int inSelectedItem)
{
try
{
//set RoecordID & CacheID to be empty
String RecordID = "";
String CacheID = "";
//if its a drill down then grab the RecordId and CacheID
if (indrillDown)
{
RecordID = _MatchCache.Peek().PickListItems[inSelectedItem].RecordId.ToString();
CacheID = _MatchCache.Peek().CacheIdentifier;
}
//Run First Query and Pop results onto stack
MatchResult matchResult = this.Client.Match(inLocatorId, inMatchType, inQuery, inFuzzy, RecordID, _SpatialReference, CacheID);
switch (matchResult.TypeOfResult)
{
case MatchResultCodes.PickList:
//Produce a DataTable for the Datagrid to show
_CurrentDataTable = ConvertToDataTable(matchResult);
//cache query for drilldown
_MatchCache.Push(matchResult);
break;
case MatchResultCodes.SingleMatch:
//code for case where show if parent haschildren but Singlerecord is returned
if (_MatchCache.Count != 0)
{
if (_MatchCache.Peek().PickListItems[inSelectedItem].HasChildren)
{
//show in datgrid as a single record
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Drill", typeof(Bitmap));
dataTable.Columns.Add("Score");
dataTable.Columns.Add("Description");
DataRow dataRow = dataTable.NewRow();
Bitmap bitmap = new Bitmap(GetType().Assembly.GetManifestResourceStream("DataHubServicesAddin.Images.Search.bmp"));
dataRow[0] = bitmap;
dataRow[1] = matchResult.MatchedRecordScore;
dataRow[2] = matchResult.MatchedRecord.R.V[2/*"LOCATOR_DESCRIPTION"*/].Replace("|LOCATOR_SEPARATOR|", ",");
dataTable.Rows.Add(dataRow);
_CurrentDataTable = dataTable;
_MatchCache.Push(matchResult);
}
else
{
//set the found item
this.FoundRecord = matchResult;
BuildColumnLookup();
//inform all that the dialog has been closed with OK
DialogResult = DialogResult.OK;
}
}
else
{
//set the found item
this.FoundRecord = matchResult;
BuildColumnLookup();
//inform all that the dialog has been closed with OK
DialogResult = DialogResult.OK;
}
break;
default:
this.FailReason = matchResult.TypeOfResult;
this.DialogResult = DialogResult.Abort;
break;
}
}
catch (Exception ex)
{
DataHubExtension.ShowError(ex);
}
}
private void BuildColumnLookup()
{
this.ColumnLookup = new Dictionary<string, int>();
//Build a dictionary of Column name to ordinal for easy lookup
for (int i = 0; i < this.FoundRecord.MatchedRecord.C.Length; i++)
{
LocatorColumn locatorColumn = this.FoundRecord.MatchedRecord.C[i];
this.ColumnLookup.Add(locatorColumn.n, i);
}
}
private DataTable ConvertToDataTable(MatchResult matchResult)
{
//Create a new Datatable
DataTable dataTable = new DataTable();
try
{
//Add Columns
dataTable.Columns.Add("Drill", typeof(Bitmap));
dataTable.Columns.Add("Score");
dataTable.Columns.Add("Description");
//add a new row for each item in the picklist
foreach (PickItem pickItem in matchResult.PickListItems)
{
//Create a new DataRow
DataRow dataRow = dataTable.NewRow();
//Add Data To Row
if (pickItem.HasChildren)
{
Bitmap bitmap = new Bitmap(GetType().Assembly.GetManifestResourceStream("DataHubServicesAddin.Images.Drill.bmp"));
dataRow[0] = bitmap;
}
else
{
Bitmap bitmap = new Bitmap(GetType().Assembly.GetManifestResourceStream("DataHubServicesAddin.Images.Search.bmp"));
dataRow[0] = bitmap;
}
dataRow[1] = pickItem.Score;
dataRow[2] = pickItem.Description;
//Add Row to Datatable
dataTable.Rows.Add(dataRow);
}
}
catch (Exception ex)
{
DataHubExtension.ShowError(ex);
}
//return the Datatable - all filled up and ready to bind
return dataTable;
}
#endregion
#region "Events"
private void butBack_Click(object sender, EventArgs e)
{
//pop the current item off the stack as we are moving back an iteration
_MatchCache.Pop();
//Convert the last Cache to a datatable
_CurrentDataTable = ConvertToDataTable(_MatchCache.Peek());
//Display datatable in GridView
DGResults.DataSource = _CurrentDataTable;
DGResults.Refresh();
//If there is only one cache then disable the back button as we can go back no further
if (_MatchCache.Count <= 1)
{
butBack.Enabled = false;
}
}
private void butCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
private void DGResults_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
//Catch Any singlerecords displayed as picklists
if (_MatchCache.Count > 0)
{
if (_MatchCache.Peek().TypeOfResult == MatchResultCodes.SingleMatch)
{
this.FoundRecord = _MatchCache.Peek();
BuildColumnLookup();
this.DialogResult = DialogResult.OK;
return;
}
}
RunMatch(_LocatorId, _MatchType, _Query, _UseFuzzy, true, DGResults.CurrentRow.Index);
DGResults.DataSource = _CurrentDataTable;
DGResults.Refresh();
//enable the back button as now we are 1 step down the results tree
butBack.Enabled = true;
}
private void LocatorPopupForm_Shown(object sender, EventArgs e)
{
//disable back button as nothing to return to
butBack.Enabled = false;
//Bing DataTable to DataGridView When Form is shown
DGResults.DataSource = _CurrentDataTable;
DGResults.Columns["Drill"].HeaderText = "";
//Set first to columns to set size and freeze them so that they dont move
DGResults.Columns[0].Width = 25;
DGResults.Columns[0].Resizable = DataGridViewTriState.False;
DGResults.Columns[1].Width = 40;
DGResults.Columns[1].Resizable = DataGridViewTriState.False;
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
namespace StartApp {
public class StartAppWrapper : MonoBehaviour {
#if UNITY_ANDROID
private static string developerId;
private static string applicatonId;
private static AndroidJavaClass unityClass;
private static AndroidJavaObject currentActivity;
private static AndroidJavaObject wrapper;
public interface AdEventListener{
void onReceiveAd();
void onFailedToReceiveAd();
}
public interface AdDisplayListener{
void adHidden();
void adDisplayed();
void adClicked();
}
/* Implementation of Ad Event Listener for Unity */
private class ImplementationAdEventListener : AndroidJavaProxy{
private AdEventListener listener = null;
public ImplementationAdEventListener(AdEventListener listener) : base("com.startapp.android.publish.AdEventListener"){
this.listener = listener;
}
void onReceiveAd(AndroidJavaObject ad){
if (listener != null){
listener.onReceiveAd();
}
}
void onFailedToReceiveAd(AndroidJavaObject ad){
if (listener != null){
listener.onFailedToReceiveAd();
}
}
int hashCode() {
return GetHashCode ();
}
}
/* Implementation of Ad Display Listener for Unity */
private class ImplementationAdDisplayListener : AndroidJavaProxy{
private AdDisplayListener listener = null;
public ImplementationAdDisplayListener(AdDisplayListener listener) : base("com.startapp.android.publish.AdDisplayListener"){
this.listener = listener;
}
void adHidden(AndroidJavaObject ad){
if (listener != null){
listener.adHidden();
}
}
void adDisplayed(AndroidJavaObject ad){
if (listener != null){
listener.adDisplayed();
}
}
void adClicked(AndroidJavaObject ad){
if (listener != null){
listener.adClicked();
}
}
}
/* Implementation of Ad Display Listener for Unity */
private class OnBackPressedAdDisplayListener : AndroidJavaProxy{
private string gameObjectName = null;
private bool clicked = false;
public OnBackPressedAdDisplayListener(string gameObjectName) : base("com.startapp.android.publish.AdDisplayListener"){
this.gameObjectName = gameObjectName;
}
void adHidden(AndroidJavaObject ad){
Debug.Log("ad hidden - quitting application");
if (!clicked) {
init();
wrapper.Call ("quit", gameObjectName);
}
}
void adDisplayed(AndroidJavaObject ad){
}
void adClicked(AndroidJavaObject ad){
clicked = true;
}
}
public enum BannerPosition{
BOTTOM,
TOP
};
public enum BannerType{
AUTOMATIC,
STANDARD,
THREED
};
public static void loadAd(AdEventListener listener) {
init();
wrapper.Call("loadAd", new []{new ImplementationAdEventListener(listener)});
}
public static void loadAd() {
loadAd (null);
}
public static bool showAd(AdDisplayListener listener) {
init();
return wrapper.Call<bool>("showAd", new object[] {new ImplementationAdDisplayListener(listener)});
}
public static bool showAd() {
init();
return wrapper.Call<bool>("showAd");
}
public static bool onBackPressed(string gameObjectName) {
init();
return wrapper.Call<bool>("onBackPressed", new object[] {new OnBackPressedAdDisplayListener(gameObjectName)});
}
public static void addBanner() {
addBanner(BannerType.AUTOMATIC, BannerPosition.BOTTOM);
}
public static void addBanner(BannerType bannerType, BannerPosition position) {
int pos = 1;
int type = 1;
// Select position
switch(position){
case BannerPosition.BOTTOM:
pos = 1;
break;
case BannerPosition.TOP:
pos = 2;
break;
}
AndroidJavaObject objPosition = new AndroidJavaObject("java.lang.Integer", pos);
// Select type
switch(bannerType){
case BannerType.AUTOMATIC:
type = 1;
break;
case BannerType.STANDARD:
type = 2;
break;
case BannerType.THREED:
type = 3;
break;
}
AndroidJavaObject objType = new AndroidJavaObject("java.lang.Integer", type);
init();
wrapper.Call("addBanner", new []{ objType, objPosition });
}
public static void removeBanner() {
removeBanner(BannerPosition.BOTTOM);
}
public static void removeBanner(BannerPosition position) {
int pos = 1;
// Select position
switch(position){
case BannerPosition.BOTTOM:
pos = 1;
break;
case BannerPosition.TOP:
pos = 2;
break;
}
AndroidJavaObject objPosition = new AndroidJavaObject("java.lang.Integer", pos);
init();
wrapper.Call("removeBanner", objPosition);
}
public static void init(){
if (wrapper == null) {
initWrapper (false);
}
}
private static void initWrapper(bool enableReturnAds) {
unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
currentActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
wrapper = new AndroidJavaObject("com.apperhand.unity.wrapper.InAppWrapper", currentActivity);
if (!initUserData()){
throw new System.ArgumentException("Error in initializing Application ID or Developer ID, Verify you initialized them in StartAppData in resources");
}
AndroidJavaObject jAppId = new AndroidJavaObject("java.lang.String", applicatonId);
AndroidJavaObject jDevId = new AndroidJavaObject("java.lang.String", developerId);
AndroidJavaObject jEnableReturnAds = new AndroidJavaObject("java.lang.Boolean", enableReturnAds);
wrapper.Call("init", jDevId, jAppId, jEnableReturnAds);
}
private static bool initUserData(){
bool result = false;
int assigned = 0;
TextAsset data = (TextAsset)Resources.Load("StartAppData");
string userData = data.ToString();
string[] splitData = userData.Split('\n');
string[] singleData;
for (int i = 0; i < splitData.Length; i++){
singleData = splitData[i].Split('=');
if (singleData[0].ToLower().CompareTo("applicationid") == 0){
assigned++;
applicatonId = singleData[1].ToString().Trim();
}
if (singleData[0].ToLower().CompareTo("developerid") == 0){
assigned++;
developerId = singleData[1].ToString().Trim();
}
}
if (assigned == 2){
result = true;
}
return result;
}
#elif UNITY_IPHONE
public interface AdEventListener{
void onReceiveAd();
void onFailedToReceiveAd();
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class OfTypeTests
{
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_AllValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (int i in query.Select(x => (object)x).OfType<int>())
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_AllValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_Unordered_AllValid(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))]
public static void OfType_AllValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
foreach (int i in query.Select(x => (object)x).OfType<int>())
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(Sources))]
public static void OfType_AllValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_AllValid(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_AllValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(query.Select(x => (object)x).OfType<int>().ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_AllValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_Unordered_AllValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))]
public static void OfType_AllValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.Select(x => (object)x).OfType<int>().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(Sources))]
public static void OfType_AllValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_AllValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void OfType_NoneValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Empty(query.OfType<long>());
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(Sources))]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(UnorderedSources))]
public static void OfType_NoneValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_NoneValid(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void OfType_NoneValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Empty(query.OfType<long>().ToList());
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(Sources))]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(UnorderedSources))]
public static void OfType_NoneValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_NoneValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_SomeValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(count / 2, (count + 1) / 2);
foreach (int i in query.Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>())
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_SomeValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_Unordered_SomeValid(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))]
public static void OfType_SomeValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = count / 2;
foreach (int i in query.Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>())
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(Sources))]
public static void OfType_SomeValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeValid(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_SomeValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(count / 2, (count + 1) / 2);
Assert.All(query.Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>().ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_SomeValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_Unordered_SomeValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))]
public static void OfType_SomeValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(Sources))]
public static void OfType_SomeValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))]
public static void OfType_SomeInvalidNull(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)x : null).OfType<int>(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(Sources))]
public static void OfType_SomeInvalidNull_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeInvalidNull(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))]
public static void OfType_SomeValidNull(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int nullCount = 0;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)(x.ToString()) : (object)(string)null).OfType<string>(),
x =>
{
if (string.IsNullOrEmpty(x)) nullCount++;
else Assert.Equal(seen++, int.Parse(x));
});
Assert.Equal(count, seen);
Assert.Equal(0, nullCount);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(Sources))]
public static void OfType_SomeValidNull_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeValidNull(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))]
public static void OfType_SomeNull(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int nullCount = 0;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)(int?)x : (int?)null).OfType<int?>(),
x =>
{
if (!x.HasValue) nullCount++;
else Assert.Equal(seen++, x.Value);
});
Assert.Equal(count, seen);
Assert.Equal(0, nullCount);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 256 }), MemberType = typeof(Sources))]
public static void OfType_SomeNull_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeNull(labeled, count);
}
[Fact]
public static void OfType_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<object>)null).OfType<int>());
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Text;
using Internal.Runtime.Augments;
using Internal.Reflection.Core.NonPortable;
namespace System
{
public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible
{
public int CompareTo(Object target)
{
if (target == null)
return 1;
if (target == this)
return 0;
if (this.EETypePtr != target.EETypePtr)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, target.GetType().ToString(), this.GetType().ToString()));
}
ref byte pThisValue = ref this.GetRawData();
ref byte pTargetValue = ref target.GetRawData();
switch (this.EETypePtr.CorElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1:
return (Unsafe.As<byte, sbyte>(ref pThisValue) == Unsafe.As<byte, sbyte>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, sbyte>(ref pThisValue) < Unsafe.As<byte, sbyte>(ref pTargetValue)) ? -1 : 1;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN:
return (Unsafe.As<byte, byte>(ref pThisValue) == Unsafe.As<byte, byte>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, byte>(ref pThisValue) < Unsafe.As<byte, byte>(ref pTargetValue)) ? -1 : 1;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
return (Unsafe.As<byte, short>(ref pThisValue) == Unsafe.As<byte, short>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, short>(ref pThisValue) < Unsafe.As<byte, short>(ref pTargetValue)) ? -1 : 1;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR:
return (Unsafe.As<byte, ushort>(ref pThisValue) == Unsafe.As<byte, ushort>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, ushort>(ref pThisValue) < Unsafe.As<byte, ushort>(ref pTargetValue)) ? -1 : 1;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
return (Unsafe.As<byte, int>(ref pThisValue) == Unsafe.As<byte, int>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, int>(ref pThisValue) < Unsafe.As<byte, int>(ref pTargetValue)) ? -1 : 1;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
return (Unsafe.As<byte, uint>(ref pThisValue) == Unsafe.As<byte, uint>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, uint>(ref pThisValue) < Unsafe.As<byte, uint>(ref pTargetValue)) ? -1 : 1;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
return (Unsafe.As<byte, long>(ref pThisValue) == Unsafe.As<byte, long>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, long>(ref pThisValue) < Unsafe.As<byte, long>(ref pTargetValue)) ? -1 : 1;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
return (Unsafe.As<byte, ulong>(ref pThisValue) == Unsafe.As<byte, ulong>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, ulong>(ref pThisValue) < Unsafe.As<byte, ulong>(ref pTargetValue)) ? -1 : 1;
default:
Environment.FailFast("Unexpected enum underlying type");
return 0;
}
}
public override bool Equals(Object obj)
{
if (obj == null)
return false;
EETypePtr eeType = this.EETypePtr;
if (!eeType.FastEquals(obj.EETypePtr))
return false;
ref byte pThisValue = ref this.GetRawData();
ref byte pOtherValue = ref obj.GetRawData();
RuntimeImports.RhCorElementTypeInfo corElementTypeInfo = eeType.CorElementTypeInfo;
switch (corElementTypeInfo.Log2OfSize)
{
case 0:
return Unsafe.As<byte, byte>(ref pThisValue) == Unsafe.As<byte, byte>(ref pOtherValue);
case 1:
return Unsafe.As<byte, ushort>(ref pThisValue) == Unsafe.As<byte, ushort>(ref pOtherValue);
case 2:
return Unsafe.As<byte, uint>(ref pThisValue) == Unsafe.As<byte, uint>(ref pOtherValue);
case 3:
return Unsafe.As<byte, ulong>(ref pThisValue) == Unsafe.As<byte, ulong>(ref pOtherValue);
default:
Environment.FailFast("Unexpected enum underlying type");
return false;
}
}
public override int GetHashCode()
{
ref byte pValue = ref this.GetRawData();
switch (this.EETypePtr.CorElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN:
return Unsafe.As<byte, bool>(ref pValue).GetHashCode();
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR:
return Unsafe.As<byte, char>(ref pValue).GetHashCode();
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1:
return Unsafe.As<byte, sbyte>(ref pValue).GetHashCode();
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1:
return Unsafe.As<byte, byte>(ref pValue).GetHashCode();
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
return Unsafe.As<byte, short>(ref pValue).GetHashCode();
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
return Unsafe.As<byte, ushort>(ref pValue).GetHashCode();
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
return Unsafe.As<byte, int>(ref pValue).GetHashCode();
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
return Unsafe.As<byte, uint>(ref pValue).GetHashCode();
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
return Unsafe.As<byte, long>(ref pValue).GetHashCode();
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
return Unsafe.As<byte, ulong>(ref pValue).GetHashCode();
default:
Environment.FailFast("Unexpected enum underlying type");
return 0;
}
}
public static String Format(Type enumType, Object value, String format)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
EnumInfo enumInfo = GetEnumInfo(enumType);
if (value == null)
throw new ArgumentNullException(nameof(value));
if (format == null)
throw new ArgumentNullException(nameof(format));
Contract.EndContractBlock();
if (value.EETypePtr.IsEnum)
{
EETypePtr enumTypeEEType;
if ((!enumType.TryGetEEType(out enumTypeEEType)) || enumTypeEEType != value.EETypePtr)
throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, value.GetType().ToString(), enumType.ToString()));
}
else
{
if (value.EETypePtr != enumInfo.UnderlyingType.TypeHandle.ToEETypePtr())
throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, value.GetType().ToString(), enumInfo.UnderlyingType.ToString()));
}
return Format(enumInfo, value, format);
}
private static String Format(EnumInfo enumInfo, Object value, String format)
{
ulong rawValue;
if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue))
{
Debug.Assert(false, "Caller was expected to do enough validation to avoid reaching this.");
throw new ArgumentException();
}
if (format.Length != 1)
{
// all acceptable format string are of length 1
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd')
{
return DoFormatD(rawValue, value.EETypePtr.CorElementType);
}
if (formatCh == 'X' || formatCh == 'x')
{
return DoFormatX(rawValue, value.EETypePtr.CorElementType);
}
if (formatCh == 'G' || formatCh == 'g')
{
return DoFormatG(enumInfo, rawValue);
}
if (formatCh == 'F' || formatCh == 'f')
{
return DoFormatF(enumInfo, rawValue);
}
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
//
// Helper for Enum.Format(,,"d")
//
private static String DoFormatD(ulong rawValue, RuntimeImports.RhCorElementType corElementType)
{
switch (corElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1:
{
SByte result = (SByte)rawValue;
return result.ToString();
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1:
{
Byte result = (Byte)rawValue;
return result.ToString();
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN:
{
// direct cast from bool to byte is not allowed
bool b = (rawValue != 0);
return b.ToString();
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
{
Int16 result = (Int16)rawValue;
return result.ToString();
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
{
UInt16 result = (UInt16)rawValue;
return result.ToString();
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR:
{
Char result = (Char)rawValue;
return result.ToString();
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
{
UInt32 result = (UInt32)rawValue;
return result.ToString();
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
{
Int32 result = (Int32)rawValue;
return result.ToString();
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
{
UInt64 result = (UInt64)rawValue;
return result.ToString();
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
{
Int64 result = (Int64)rawValue;
return result.ToString();
}
default:
Debug.Assert(false, "Invalid Object type in Format");
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
//
// Helper for Enum.Format(,,"x")
//
private static String DoFormatX(ulong rawValue, RuntimeImports.RhCorElementType corElementType)
{
switch (corElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1:
{
Byte result = (byte)(sbyte)rawValue;
return result.ToString("X2", null);
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1:
{
Byte result = (byte)rawValue;
return result.ToString("X2", null);
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN:
{
// direct cast from bool to byte is not allowed
Byte result = (byte)rawValue;
return result.ToString("X2", null);
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
{
UInt16 result = (UInt16)(Int16)rawValue;
return result.ToString("X4", null);
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
{
UInt16 result = (UInt16)rawValue;
return result.ToString("X4", null);
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR:
{
UInt16 result = (UInt16)(Char)rawValue;
return result.ToString("X4", null);
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
{
UInt32 result = (UInt32)rawValue;
return result.ToString("X8", null);
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
{
UInt32 result = (UInt32)(int)rawValue;
return result.ToString("X8", null);
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
{
UInt64 result = (UInt64)rawValue;
return result.ToString("X16", null);
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
{
UInt64 result = (UInt64)(Int64)rawValue;
return result.ToString("X16", null);
}
default:
Debug.Assert(false, "Invalid Object type in Format");
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
//
// Helper for Enum.Format(,,"g")
//
private static String DoFormatG(EnumInfo enumInfo, ulong rawValue)
{
Debug.Assert(enumInfo != null);
if (!enumInfo.HasFlagsAttribute) // Not marked with Flags attribute
{
// Try to see if its one of the enum values, then we return a String back else the value
String name = GetNameIfAny(enumInfo, rawValue);
if (name == null)
return DoFormatD(rawValue, enumInfo.UnderlyingType.TypeHandle.ToEETypePtr().CorElementType);
else
return name;
}
else // These are flags OR'ed together (We treat everything as unsigned types)
{
return DoFormatF(enumInfo, rawValue);
}
}
//
// Helper for Enum.Format(,,"f")
//
private static String DoFormatF(EnumInfo enumInfo, ulong rawValue)
{
Debug.Assert(enumInfo != null);
// These values are sorted by value. Don't change this
KeyValuePair<String, ulong>[] namesAndValues = enumInfo.NamesAndValues;
int index = namesAndValues.Length - 1;
StringBuilder retval = new StringBuilder();
bool firstTime = true;
ulong result = rawValue;
// We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied
// to minimize the comparsions required. This code works the same for the best/worst case. In general the number of
// items in an enum are sufficiently small and not worth the optimization.
while (index >= 0)
{
if ((index == 0) && (namesAndValues[index].Value == 0))
break;
if ((result & namesAndValues[index].Value) == namesAndValues[index].Value)
{
result -= namesAndValues[index].Value;
if (!firstTime)
retval.Insert(0, ", ");
retval.Insert(0, namesAndValues[index].Key);
firstTime = false;
}
index--;
}
// We were unable to represent this number as a bitwise or of valid flags
if (result != 0)
return DoFormatD(rawValue, enumInfo.UnderlyingType.TypeHandle.ToEETypePtr().CorElementType);
// For the case when we have zero
if (rawValue == 0)
{
if (namesAndValues.Length > 0 && namesAndValues[0].Value == 0)
return namesAndValues[0].Key; // Zero was one of the enum values.
else
return "0";
}
else
return retval.ToString(); // Built a list of matching names. Return it.
}
internal Object GetValue()
{
ref byte pValue = ref this.GetRawData();
switch (this.EETypePtr.CorElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN:
return Unsafe.As<byte, bool>(ref pValue);
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR:
return Unsafe.As<byte, char>(ref pValue);
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1:
return Unsafe.As<byte, sbyte>(ref pValue);
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1:
return Unsafe.As<byte, byte>(ref pValue);
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
return Unsafe.As<byte, short>(ref pValue);
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
return Unsafe.As<byte, ushort>(ref pValue);
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
return Unsafe.As<byte, int>(ref pValue);
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
return Unsafe.As<byte, uint>(ref pValue);
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
return Unsafe.As<byte, long>(ref pValue);
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
return Unsafe.As<byte, ulong>(ref pValue);
default:
Environment.FailFast("Unexpected enum underlying type");
return 0;
}
}
public static String GetName(Type enumType, Object value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsRuntimeImplemented())
return enumType.GetEnumName(value);
if (value == null)
throw new ArgumentNullException(nameof(value));
ulong rawValue;
if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue))
throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value));
// For desktop compatibility, do not bounce an incoming integer that's the wrong size.
// Do a value-preserving cast of both it and the enum values and do a 64-bit compare.
EnumInfo enumInfo = GetEnumInfo(enumType);
String nameOrNull = GetNameIfAny(enumInfo, rawValue);
return nameOrNull;
}
public static String[] GetNames(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsRuntimeImplemented())
return enumType.GetEnumNames();
KeyValuePair<String, ulong>[] namesAndValues = GetEnumInfo(enumType).NamesAndValues;
String[] names = new String[namesAndValues.Length];
for (int i = 0; i < namesAndValues.Length; i++)
names[i] = namesAndValues[i].Key;
return names;
}
public static Type GetUnderlyingType(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
RuntimeTypeHandle runtimeTypeHandle = enumType.TypeHandle;
EETypePtr eeType = runtimeTypeHandle.ToEETypePtr();
if (!eeType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
switch (eeType.CorElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN:
return CommonRuntimeTypes.Boolean;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR:
return CommonRuntimeTypes.Char;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1:
return CommonRuntimeTypes.SByte;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1:
return CommonRuntimeTypes.Byte;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
return CommonRuntimeTypes.Int16;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
return CommonRuntimeTypes.UInt16;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
return CommonRuntimeTypes.Int32;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
return CommonRuntimeTypes.UInt32;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
return CommonRuntimeTypes.Int64;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
return CommonRuntimeTypes.UInt64;
default:
throw new ArgumentException();
}
}
public static Array GetValues(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
Array values = GetEnumInfo(enumType).Values;
int count = values.Length;
EETypePtr enumArrayType = enumType.MakeArrayType().TypeHandle.ToEETypePtr();
Array result = RuntimeImports.RhNewArray(enumArrayType, count);
Array.CopyImplValueTypeArrayNoInnerGcRefs(values, 0, result, 0, count);
return result;
}
public Boolean HasFlag(Enum flag)
{
if (flag == null)
throw new ArgumentNullException(nameof(flag));
Contract.EndContractBlock();
if (!(this.EETypePtr == flag.EETypePtr))
throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), this.GetType()));
ref byte pThisValue = ref this.GetRawData();
ref byte pFlagValue = ref flag.GetRawData();
switch (this.EETypePtr.CorElementTypeInfo.Log2OfSize)
{
case 0:
return (Unsafe.As<byte, byte>(ref pThisValue) & Unsafe.As<byte, byte>(ref pFlagValue)) == Unsafe.As<byte, byte>(ref pFlagValue);
case 1:
return (Unsafe.As<byte, ushort>(ref pThisValue) & Unsafe.As<byte, ushort>(ref pFlagValue)) == Unsafe.As<byte, ushort>(ref pFlagValue);
case 2:
return (Unsafe.As<byte, uint>(ref pThisValue) & Unsafe.As<byte, uint>(ref pFlagValue)) == Unsafe.As<byte, uint>(ref pFlagValue);
case 3:
return (Unsafe.As<byte, ulong>(ref pThisValue) & Unsafe.As<byte, ulong>(ref pFlagValue)) == Unsafe.As<byte, ulong>(ref pFlagValue);
default:
Environment.FailFast("Unexpected enum underlying type");
return false;
}
}
public static bool IsDefined(Type enumType, Object value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsRuntimeImplemented())
return enumType.IsEnumDefined(value);
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.EETypePtr == EETypePtr.EETypePtrOf<string>())
{
EnumInfo enumInfo = GetEnumInfo(enumType);
foreach (KeyValuePair<String, ulong> kv in enumInfo.NamesAndValues)
{
if (value.Equals(kv.Key))
return true;
}
return false;
}
else
{
ulong rawValue;
if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue))
{
if (Type.IsIntegerType(value.GetType()))
throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, value.GetType(), Enum.GetUnderlyingType(enumType)));
else
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
EnumInfo enumInfo = null;
if (value.EETypePtr.IsEnum)
{
if (!ValueTypeMatchesEnumType(enumType, value))
throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, value.GetType(), enumType));
}
else
{
enumInfo = GetEnumInfo(enumType);
if (!(enumInfo.UnderlyingType.TypeHandle.ToEETypePtr() == value.EETypePtr))
throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, value.GetType(), enumInfo.UnderlyingType));
}
if (enumInfo == null)
enumInfo = GetEnumInfo(enumType);
String nameOrNull = GetNameIfAny(enumInfo, rawValue);
return nameOrNull != null;
}
}
public static Object Parse(Type enumType, String value)
{
return Parse(enumType, value, ignoreCase: false);
}
public static Object Parse(Type enumType, String value, bool ignoreCase)
{
Object result;
Exception exception;
if (!TryParseEnum(enumType, value, ignoreCase, out result, out exception))
throw exception;
return result;
}
public static TEnum Parse<TEnum>(String value) where TEnum : struct
{
return Parse<TEnum>(value, ignoreCase: false);
}
public static TEnum Parse<TEnum>(String value, bool ignoreCase) where TEnum : struct
{
Object result;
Exception exception;
if (!TryParseEnum(typeof(TEnum), value, ignoreCase, out result, out exception))
throw exception;
return (TEnum)result;
}
//
// Non-boxing overloads for Enum.ToObject().
//
// The underlying integer type of the enum does not have to match the type of "value." If
// the enum type is larger, this api does a value-preserving widening if possible (or a 2's complement
// conversion if not.) If the enum type is smaller, the api discards the higher order bits.
// Either way, no exception is thrown upon overflow.
//
[CLSCompliant(false)]
public static object ToObject(Type enumType, sbyte value) => ToObjectWorker(enumType, value);
public static object ToObject(Type enumType, byte value) => ToObjectWorker(enumType, value);
[CLSCompliant(false)]
public static object ToObject(Type enumType, ushort value) => ToObjectWorker(enumType, value);
public static object ToObject(Type enumType, short value) => ToObjectWorker(enumType, value);
[CLSCompliant(false)]
public static object ToObject(Type enumType, uint value) => ToObjectWorker(enumType, value);
public static object ToObject(Type enumType, int value) => ToObjectWorker(enumType, value);
[CLSCompliant(false)]
public static object ToObject(Type enumType, ulong value) => ToObjectWorker(enumType, (long)value);
public static object ToObject(Type enumType, long value) => ToObjectWorker(enumType, value);
// These are needed to service ToObject(Type, Object).
private static object ToObject(Type enumType, char value) => ToObjectWorker(enumType, value);
private static object ToObject(Type enumType, bool value) => ToObjectWorker(enumType, value ? 1 : 0);
// Common helper for the non-boxing Enum.ToObject() overloads.
private static object ToObjectWorker(Type enumType, long value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsRuntimeImplemented())
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
EETypePtr enumEEType = enumType.TypeHandle.ToEETypePtr();
if (!enumEEType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
unsafe
{
byte* pValue = (byte*)&value;
AdjustForEndianness(ref pValue, enumEEType);
return RuntimeImports.RhBox(enumEEType, pValue);
}
}
public static Object ToObject(Type enumType, Object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Delegate rest of error checking to the other functions
TypeCode typeCode = Convert.GetTypeCode(value);
switch (typeCode)
{
case TypeCode.Int32:
return ToObject(enumType, (int)value);
case TypeCode.SByte:
return ToObject(enumType, (sbyte)value);
case TypeCode.Int16:
return ToObject(enumType, (short)value);
case TypeCode.Int64:
return ToObject(enumType, (long)value);
case TypeCode.UInt32:
return ToObject(enumType, (uint)value);
case TypeCode.Byte:
return ToObject(enumType, (byte)value);
case TypeCode.UInt16:
return ToObject(enumType, (ushort)value);
case TypeCode.UInt64:
return ToObject(enumType, (ulong)value);
case TypeCode.Char:
return ToObject(enumType, (char)value);
case TypeCode.Boolean:
return ToObject(enumType, (bool)value);
default:
// All unsigned types will be directly cast
throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value));
}
}
public static bool TryParse(Type enumType, String value, bool ignoreCase, out Object result)
{
Exception exception;
return TryParseEnum(enumType, value, ignoreCase, out result, out exception);
}
public static bool TryParse(Type enumType, String value, out Object result)
{
Exception exception;
return TryParseEnum(enumType, value, false, out result, out exception);
}
public static bool TryParse<TEnum>(String value, bool ignoreCase, out TEnum result) where TEnum : struct
{
Exception exception;
Object tempResult;
if (!TryParseEnum(typeof(TEnum), value, ignoreCase, out tempResult, out exception))
{
result = default(TEnum);
return false;
}
result = (TEnum)tempResult;
return true;
}
public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct
{
return TryParse<TEnum>(value, false, out result);
}
public override String ToString()
{
try
{
return this.ToString("G");
}
catch (Exception)
{
return this.LastResortToString;
}
}
public String ToString(String format)
{
if (format == null || format.Length == 0)
format = "G";
EnumInfo enumInfo = GetEnumInfoIfAvailable(this.GetType());
// Project N port note: If Reflection info isn't available, fallback to ToString() which will substitute a numeric value for the "correct" output.
// This scenario has been hit frequently when throwing exceptions formatted with error strings containing enum substitations.
// To avoid replacing the masking the actual exception with an uninteresting MissingMetadataException, we choose instead
// to return a base-effort string.
if (enumInfo == null)
return this.LastResortToString;
return Format(enumInfo, this, format);
}
public String ToString(String format, IFormatProvider provider)
{
return ToString(format);
}
[Obsolete("The provider argument is not used. Please use ToString().")]
public String ToString(IFormatProvider provider)
{
return ToString();
}
//
// Note: this helper also checks if the enumType is in fact an Enum and throws an user-visible ArgumentException if it's not.
//
private static EnumInfo GetEnumInfo(Type enumType)
{
EnumInfo enumInfo = GetEnumInfoIfAvailable(enumType);
if (enumInfo == null)
throw RuntimeAugments.Callbacks.CreateMissingMetadataException(enumType);
return enumInfo;
}
//
// Note: this helper also checks if the enumType is in fact an Enum and throws an user-visible ArgumentException if it's not.
//
private static EnumInfo GetEnumInfoIfAvailable(Type enumType)
{
RuntimeTypeHandle runtimeTypeHandle = enumType.TypeHandle;
if (!runtimeTypeHandle.ToEETypePtr().IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum);
return s_enumInfoCache.GetOrAdd(new TypeUnificationKey(enumType));
}
//
// Checks if value.GetType() matches enumType exactly.
//
private static bool ValueTypeMatchesEnumType(Type enumType, Object value)
{
EETypePtr enumEEType;
if (!enumType.TryGetEEType(out enumEEType))
return false;
if (!(enumEEType == value.EETypePtr))
return false;
return true;
}
// Exported for use by legacy user-defined Type Enum apis.
internal static ulong ToUInt64(object value)
{
ulong result;
if (!TryGetUnboxedValueOfEnumOrInteger(value, out result))
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
return result;
}
//
// Note: This works on both Enum's and underlying integer values.
//
//
// This returns the underlying enum values as "ulong" regardless of the actual underlying type. Signed integral
// types get sign-extended into the 64-bit value, unsigned types get zero-extended.
//
// The return value is "bool" if "value" is not an enum or an "integer type" as defined by the BCL Enum apis.
//
private static bool TryGetUnboxedValueOfEnumOrInteger(Object value, out ulong result)
{
EETypePtr eeType = value.EETypePtr;
// For now, this check is required to flush out pointers.
if (!eeType.IsDefType)
{
result = 0;
return false;
}
RuntimeImports.RhCorElementType corElementType = eeType.CorElementType;
ref byte pValue = ref value.GetRawData();
switch (corElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN:
result = Unsafe.As<byte, bool>(ref pValue) ? 1UL : 0UL;
return true;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR:
result = (ulong)(long)Unsafe.As<byte, char>(ref pValue);
return true;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1:
result = (ulong)(long)Unsafe.As<byte, sbyte>(ref pValue);
return true;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1:
result = (ulong)(long)Unsafe.As<byte, byte>(ref pValue);
return true;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
result = (ulong)(long)Unsafe.As<byte, short>(ref pValue);
return true;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
result = (ulong)(long)Unsafe.As<byte, ushort>(ref pValue);
return true;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
result = (ulong)(long)Unsafe.As<byte, int>(ref pValue);
return true;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
result = (ulong)(long)Unsafe.As<byte, uint>(ref pValue);
return true;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
result = (ulong)(long)Unsafe.As<byte, long>(ref pValue);
return true;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
result = (ulong)(long)Unsafe.As<byte, ulong>(ref pValue);
return true;
default:
result = 0;
return false;
}
}
//
// Look up a name for rawValue if a matching one exists. Returns null if no matching name exists.
//
private static String GetNameIfAny(EnumInfo enumInfo, ulong rawValue)
{
KeyValuePair<String, ulong>[] namesAndValues = enumInfo.NamesAndValues;
KeyValuePair<String, ulong> searchKey = new KeyValuePair<String, ulong>(null, rawValue);
int index = Array.BinarySearch<KeyValuePair<String, ulong>>(namesAndValues, searchKey, s_nameAndValueComparer);
if (index < 0)
return null;
return namesAndValues[index].Key;
}
//
// Common funnel for Enum.Parse methods.
//
private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, out Object result, out Exception exception)
{
exception = null;
result = null;
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsRuntimeImplemented())
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
if (value == null)
{
exception = new ArgumentNullException(nameof(value));
return false;
}
int firstNonWhitespaceIndex = -1;
for (int i = 0; i < value.Length; i++)
{
if (!char.IsWhiteSpace(value[i]))
{
firstNonWhitespaceIndex = i;
break;
}
}
if (firstNonWhitespaceIndex == -1)
{
exception = new ArgumentException(SR.Arg_MustContainEnumInfo);
return false;
}
EETypePtr enumEEType = enumType.TypeHandle.ToEETypePtr();
if (!enumEEType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
if (TryParseAsInteger(enumEEType, value, firstNonWhitespaceIndex, out result))
return true;
if (StillLooksLikeInteger(value, firstNonWhitespaceIndex))
{
exception = new OverflowException();
return false;
}
// Parse as string. Now (and only now) do we look for metadata information.
EnumInfo enumInfo = RuntimeAugments.Callbacks.GetEnumInfoIfAvailable(enumType);
if (enumInfo == null)
throw RuntimeAugments.Callbacks.CreateMissingMetadataException(enumType);
ulong v = 0;
// Port note: The docs are silent on how multiple matches are resolved when doing case-insensitive parses.
// The desktop's ad-hoc behavior is to pick the one with the smallest value after doing a value-preserving cast
// to a ulong, so we'll follow that here.
StringComparison comparison = ignoreCase ?
StringComparison.OrdinalIgnoreCase :
StringComparison.Ordinal;
KeyValuePair<String, ulong>[] actualNamesAndValues = enumInfo.NamesAndValues;
int valueIndex = firstNonWhitespaceIndex;
while (valueIndex <= value.Length) // '=' is to handle invalid case of an ending comma
{
// Find the next separator, if there is one, otherwise the end of the string.
int endIndex = value.IndexOf(',', valueIndex);
if (endIndex == -1)
{
endIndex = value.Length;
}
// Shift the starting and ending indices to eliminate whitespace
int endIndexNoWhitespace = endIndex;
while (valueIndex < endIndex && char.IsWhiteSpace(value[valueIndex])) valueIndex++;
while (endIndexNoWhitespace > valueIndex && char.IsWhiteSpace(value[endIndexNoWhitespace - 1])) endIndexNoWhitespace--;
int valueSubstringLength = endIndexNoWhitespace - valueIndex;
// Try to match this substring against each enum name
bool foundMatch = false;
foreach (KeyValuePair<String, ulong> kv in actualNamesAndValues)
{
String actualName = kv.Key;
if (actualName.Length == valueSubstringLength &&
String.Compare(actualName, 0, value, valueIndex, valueSubstringLength, comparison) == 0)
{
v |= kv.Value;
foundMatch = true;
break;
}
}
if (!foundMatch)
{
exception = new ArgumentException(SR.Format(SR.Arg_EnumValueNotFound, value));
return false;
}
// Move our pointer to the ending index to go again.
valueIndex = endIndex + 1;
}
unsafe
{
result = RuntimeImports.RhBox(enumEEType, &v); //@todo: Not compatible with big-endian platforms.
}
return true;
}
private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int valueOffset, out Object result)
{
Debug.Assert(value != null, "Expected non-null value");
Debug.Assert(value.Length > 0, "Expected non-empty value");
Debug.Assert(valueOffset >= 0 && valueOffset < value.Length, "Expected valueOffset to be within value");
result = null;
char firstNonWhitespaceChar = value[valueOffset];
if (!(Char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '+' || firstNonWhitespaceChar == '-'))
return false;
RuntimeImports.RhCorElementType corElementType = enumEEType.CorElementType;
value = value.Trim();
unsafe
{
switch (corElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN:
{
Boolean v;
if (!Boolean.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR:
{
Char v;
if (!Char.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1:
{
SByte v;
if (!SByte.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1:
{
Byte v;
if (!Byte.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
{
Int16 v;
if (!Int16.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
{
UInt16 v;
if (!UInt16.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
{
Int32 v;
if (!Int32.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
{
UInt32 v;
if (!UInt32.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
{
Int64 v;
if (!Int64.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
{
UInt64 v;
if (!UInt64.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
default:
throw new NotSupportedException();
}
}
}
private static bool StillLooksLikeInteger(String value, int index)
{
if (index != value.Length && (value[index] == '-' || value[index] == '+'))
{
index++;
}
if (index == value.Length || !char.IsDigit(value[index]))
return false;
index++;
while (index != value.Length && char.IsDigit(value[index]))
{
index++;
}
while (index != value.Length && char.IsWhiteSpace(value[index]))
{
index++;
}
return index == value.Length;
}
[Conditional("BIGENDIAN")]
private static unsafe void AdjustForEndianness(ref byte* pValue, EETypePtr enumEEType)
{
// On Debug builds, include the big-endian code to help deter bitrot (the "Conditional("BIGENDIAN")" will prevent it from executing on little-endian).
// On Release builds, exclude code to deter IL bloat and toolchain work.
#if BIGENDIAN || DEBUG
RuntimeImports.RhCorElementType corElementType = enumEEType.CorElementType;
switch (corElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1:
pValue += sizeof(long) - sizeof(byte);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
pValue += sizeof(long) - sizeof(short);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
pValue += sizeof(long) - sizeof(int);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
break;
default:
throw new NotSupportedException();
}
#endif //BIGENDIAN || DEBUG
}
//
// Sort comparer for NamesAndValues
//
private class NamesAndValueComparer : IComparer<KeyValuePair<String, ulong>>
{
public int Compare(KeyValuePair<String, ulong> kv1, KeyValuePair<String, ulong> kv2)
{
ulong x = kv1.Value;
ulong y = kv2.Value;
if (x < y)
return -1;
else if (x > y)
return 1;
else
return 0;
}
}
private static NamesAndValueComparer s_nameAndValueComparer = new NamesAndValueComparer();
private String LastResortToString
{
get
{
return String.Format("{0}", GetValue());
}
}
private sealed class EnumInfoUnifier : ConcurrentUnifierW<TypeUnificationKey, EnumInfo>
{
protected override EnumInfo Factory(TypeUnificationKey key)
{
return RuntimeAugments.Callbacks.GetEnumInfoIfAvailable(key.Type);
}
}
private static EnumInfoUnifier s_enumInfoCache = new EnumInfoUnifier();
#region IConvertible
public TypeCode GetTypeCode()
{
Type enumType = this.GetType();
Type underlyingType = GetUnderlyingType(enumType);
if (underlyingType == typeof(Int32))
{
return TypeCode.Int32;
}
if (underlyingType == typeof(sbyte))
{
return TypeCode.SByte;
}
if (underlyingType == typeof(Int16))
{
return TypeCode.Int16;
}
if (underlyingType == typeof(Int64))
{
return TypeCode.Int64;
}
if (underlyingType == typeof(UInt32))
{
return TypeCode.UInt32;
}
if (underlyingType == typeof(byte))
{
return TypeCode.Byte;
}
if (underlyingType == typeof(UInt16))
{
return TypeCode.UInt16;
}
if (underlyingType == typeof(UInt64))
{
return TypeCode.UInt64;
}
if (underlyingType == typeof(Boolean))
{
return TypeCode.Boolean;
}
if (underlyingType == typeof(Char))
{
return TypeCode.Char;
}
Debug.Assert(false, "Unknown underlying type.");
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Enum", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
#endregion
}
}
| |
using Raven.Client.ServerWide;
using Raven.Client.ServerWide.Commands;
using Raven.Client.ServerWide.Operations;
using Raven.Client.ServerWide.Operations.Certificates;
using System;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
namespace DaaSDemo.Data
{
/// <summary>
/// Extension methods for the RavenDB client's <see cref="ServerOperationExecutor"/> and friends.
/// </summary>
public static class RavenServerOperationExtensions
{
/// <summary>
/// Get the names of all databases present on the server.
/// </summary>
/// <param name="serverOperations">
/// The server operations client.
/// </param>
/// <param name="start">
/// The index of the first name to return.
/// </param>
/// <param name="count">
/// The number of names to return.
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// An array of database names.
/// </returns>
public static Task<string[]> GetDatabaseNames(this ServerOperationExecutor serverOperations, int start, int count, CancellationToken cancellationToken = default)
{
if (serverOperations == null)
throw new ArgumentNullException(nameof(serverOperations));
return serverOperations.SendAsync(
new GetDatabaseNamesOperation(start, count),
cancellationToken
);
}
/// <summary>
/// Create a database.
/// </summary>
/// <param name="serverOperations">
/// The server operations client.
/// </param>
/// <param name="name">
/// The name of the database to create.
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// A <see cref="DatabasePutResult"/> representing the operation result.
/// </returns>
public static Task<DatabasePutResult> CreateDatabase(this ServerOperationExecutor serverOperations, string name, CancellationToken cancellationToken = default)
{
if (serverOperations == null)
throw new ArgumentNullException(nameof(serverOperations));
if (String.IsNullOrWhiteSpace(name))
throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'name'.", nameof(name));
return serverOperations.SendAsync(
new CreateDatabaseOperation(new DatabaseRecord
{
DatabaseName = name
}),
cancellationToken
);
}
/// <summary>
/// Delete a database.
/// </summary>
/// <param name="serverOperations">
/// The server operations client.
/// </param>
/// <param name="name">
/// The name of the database to delete.
/// </param>
/// <param name="hardDelete">
/// Delete the physical database files, too?
/// </param>
/// <param name="waitForConfirmation">
/// If specified, wait this long at most for confirmation of deletion.
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// A <see cref="DeleteDatabaseResult"/> representing the operation result.
/// </returns>
public static Task<DeleteDatabaseResult> DeleteDatabase(this ServerOperationExecutor serverOperations, string name, bool hardDelete = false, TimeSpan? waitForConfirmation = null, CancellationToken cancellationToken = default)
{
if (serverOperations == null)
throw new ArgumentNullException(nameof(serverOperations));
if (String.IsNullOrWhiteSpace(name))
throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'name'.", nameof(name));
return serverOperations.SendAsync(
new DeleteDatabasesOperation(name, hardDelete, timeToWaitForConfirmation: waitForConfirmation),
cancellationToken
);
}
/// <summary>
/// Request creation of a client certificate for the specified user.
/// </summary>
/// <param name="serverOperations">
/// The server operations client.
/// </param>
/// <param name="subjectName">
/// The name of the security principal that the certificate will represent.
/// </param>
/// <param name="protectedWithPassword">
/// The password that the certificate will be protected with.
/// </param>
/// <param name="clearance">
/// Rights assigned to the user.
/// </param>
/// <param name="permissions">
/// Database-level permissions assigned to the user.
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// A byte array containing the PKCS12-encoded (i.e. PFX) certificate and private key.
/// </returns>
public static async Task<byte[]> CreateClientCertificate(this ServerOperationExecutor serverOperations, string subjectName, string protectedWithPassword, SecurityClearance clearance, Dictionary<string, DatabaseAccess> permissions = null, CancellationToken cancellationToken = default)
{
if (serverOperations == null)
throw new ArgumentNullException(nameof(serverOperations));
if (String.IsNullOrWhiteSpace(subjectName))
throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'userName'.", nameof(subjectName));
CertificateRawData clientCertificatePfx = await serverOperations.SendAsync(
new CreateClientCertificateOperation(
subjectName,
permissions ?? new Dictionary<string, DatabaseAccess>(),
clearance,
protectedWithPassword
),
cancellationToken
);
return clientCertificatePfx.RawData;
}
/// <summary>
/// Register a client certificate for the specified user.
/// </summary>
/// <param name="serverOperations">
/// The server operations client.
/// </param>
/// <param name="subjectName">
/// The name of the security principal that the certificate will represent.
/// </param>
/// <param name="certificate">
/// The client certificate to register.
/// </param>
/// <param name="clearance">
/// Rights assigned to the user.
/// </param>
/// <param name="permissions">
/// Database-level permissions assigned to the user.
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// A <see cref="Task"/> representing the operation.
/// </returns>
public static async Task PutClientCertificate(this ServerOperationExecutor serverOperations, string subjectName, X509Certificate2 certificate, SecurityClearance clearance, Dictionary<string, DatabaseAccess> permissions = null, CancellationToken cancellationToken = default)
{
if (serverOperations == null)
throw new ArgumentNullException(nameof(serverOperations));
if (String.IsNullOrWhiteSpace(subjectName))
throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'userName'.", nameof(subjectName));
if (certificate == null)
throw new ArgumentNullException(nameof(certificate));
await serverOperations.SendAsync(
new PutClientCertificateOperation(
subjectName,
certificate,
permissions ?? new Dictionary<string, DatabaseAccess>(),
clearance
),
cancellationToken
);
}
/// <summary>
/// Retrieve details for a specific client certificate.
/// </summary>
/// <param name="serverOperations">
/// The server operations client.
/// </param>
/// <param name="thumbprint">
/// The thumbprint of the certificate to retrieve.
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// A <see cref="CertificateDefinition"/> representing the certificate, or <c>null</c> if no certificate was found with the specified thumbprint.
/// </returns>
public static Task<CertificateDefinition> GetClientCertificate(this ServerOperationExecutor serverOperations, string thumbprint, CancellationToken cancellationToken = default)
{
if (serverOperations == null)
throw new ArgumentNullException(nameof(serverOperations));
if (String.IsNullOrWhiteSpace(thumbprint))
throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'userName'.", nameof(thumbprint));
return serverOperations.SendAsync(
new GetCertificateOperation(thumbprint),
cancellationToken
);
}
/// <summary>
/// Retrieve details for all client certificates.
/// </summary>
/// <param name="serverOperations">
/// The server operations client.
/// </param>
/// <param name="start">
/// The index of the first certificate to return.
/// </param>
/// <param name="count">
/// The number of certificates to return.
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// An array of <see cref="CertificateDefinition"/>s representing the certificates.
/// </returns>
public static Task<CertificateDefinition[]> GetClientCertificates(this ServerOperationExecutor serverOperations, int start, int count, CancellationToken cancellationToken = default)
{
if (serverOperations == null)
throw new ArgumentNullException(nameof(serverOperations));
return serverOperations.SendAsync(
new GetCertificatesOperation(start, count),
cancellationToken
);
}
/// <summary>
/// Delete a client certificate.
/// </summary>
/// <param name="serverOperations">
/// The server operations client.
/// </param>
/// <param name="thumbprint">
/// The thumbprint of the certificate to delete.
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// A <see cref="Task"/> representing the operation.
/// </returns>
public static Task DeleteClientCertificate(this ServerOperationExecutor serverOperations, string thumbprint, CancellationToken cancellationToken = default)
{
if (serverOperations == null)
throw new ArgumentNullException(nameof(serverOperations));
if (String.IsNullOrWhiteSpace(thumbprint))
throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'userName'.", nameof(thumbprint));
return serverOperations.SendAsync(
new DeleteCertificateOperation(thumbprint),
cancellationToken
);
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using System.Linq;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Api.V2010.Account
{
/// <summary>
/// Send a message from the account used to make the request
/// </summary>
public class CreateMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The SID of the Account that will create the resource
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The destination phone number
/// </summary>
public Types.PhoneNumber To { get; }
/// <summary>
/// The phone number that initiated the message
/// </summary>
public Types.PhoneNumber From { get; set; }
/// <summary>
/// The SID of the Messaging Service you want to associate with the message.
/// </summary>
public string MessagingServiceSid { get; set; }
/// <summary>
/// The text of the message you want to send. Can be up to 1,600 characters in length.
/// </summary>
public string Body { get; set; }
/// <summary>
/// The URL of the media to send with the message
/// </summary>
public List<Uri> MediaUrl { get; set; }
/// <summary>
/// The URL we should call to send status information to your application
/// </summary>
public Uri StatusCallback { get; set; }
/// <summary>
/// The application to use for callbacks
/// </summary>
public string ApplicationSid { get; set; }
/// <summary>
/// The total maximum price up to 4 decimal places in US dollars acceptable for the message to be delivered.
/// </summary>
public decimal? MaxPrice { get; set; }
/// <summary>
/// Whether to confirm delivery of the message
/// </summary>
public bool? ProvideFeedback { get; set; }
/// <summary>
/// Total numer of attempts made , this inclusive to send out the message
/// </summary>
public int? Attempt { get; set; }
/// <summary>
/// The number of seconds that the message can remain in our outgoing queue.
/// </summary>
public int? ValidityPeriod { get; set; }
/// <summary>
/// Reserved
/// </summary>
public bool? ForceDelivery { get; set; }
/// <summary>
/// Determines if the message content can be stored or redacted based on privacy settings
/// </summary>
public MessageResource.ContentRetentionEnum ContentRetention { get; set; }
/// <summary>
/// Determines if the address can be stored or obfuscated based on privacy settings
/// </summary>
public MessageResource.AddressRetentionEnum AddressRetention { get; set; }
/// <summary>
/// Whether to detect Unicode characters that have a similar GSM-7 character and replace them
/// </summary>
public bool? SmartEncoded { get; set; }
/// <summary>
/// Rich actions for Channels Messages.
/// </summary>
public List<string> PersistentAction { get; set; }
/// <summary>
/// Pass the value `fixed` to schedule a message at a fixed time.
/// </summary>
public MessageResource.ScheduleTypeEnum ScheduleType { get; set; }
/// <summary>
/// The time that Twilio will send the message. Must be in ISO 8601 format.
/// </summary>
public DateTime? SendAt { get; set; }
/// <summary>
/// If set to True, Twilio will deliver the message as a single MMS message, regardless of the presence of media
/// </summary>
public bool? SendAsMms { get; set; }
/// <summary>
/// Construct a new CreateMessageOptions
/// </summary>
/// <param name="to"> The destination phone number </param>
public CreateMessageOptions(Types.PhoneNumber to)
{
To = to;
MediaUrl = new List<Uri>();
PersistentAction = new List<string>();
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (To != null)
{
p.Add(new KeyValuePair<string, string>("To", To.ToString()));
}
if (From != null)
{
p.Add(new KeyValuePair<string, string>("From", From.ToString()));
}
if (MessagingServiceSid != null)
{
p.Add(new KeyValuePair<string, string>("MessagingServiceSid", MessagingServiceSid.ToString()));
}
if (Body != null)
{
p.Add(new KeyValuePair<string, string>("Body", Body));
}
if (MediaUrl != null)
{
p.AddRange(MediaUrl.Select(prop => new KeyValuePair<string, string>("MediaUrl", Serializers.Url(prop))));
}
if (StatusCallback != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallback", Serializers.Url(StatusCallback)));
}
if (ApplicationSid != null)
{
p.Add(new KeyValuePair<string, string>("ApplicationSid", ApplicationSid.ToString()));
}
if (MaxPrice != null)
{
p.Add(new KeyValuePair<string, string>("MaxPrice", MaxPrice.Value.ToString()));
}
if (ProvideFeedback != null)
{
p.Add(new KeyValuePair<string, string>("ProvideFeedback", ProvideFeedback.Value.ToString().ToLower()));
}
if (Attempt != null)
{
p.Add(new KeyValuePair<string, string>("Attempt", Attempt.ToString()));
}
if (ValidityPeriod != null)
{
p.Add(new KeyValuePair<string, string>("ValidityPeriod", ValidityPeriod.ToString()));
}
if (ForceDelivery != null)
{
p.Add(new KeyValuePair<string, string>("ForceDelivery", ForceDelivery.Value.ToString().ToLower()));
}
if (ContentRetention != null)
{
p.Add(new KeyValuePair<string, string>("ContentRetention", ContentRetention.ToString()));
}
if (AddressRetention != null)
{
p.Add(new KeyValuePair<string, string>("AddressRetention", AddressRetention.ToString()));
}
if (SmartEncoded != null)
{
p.Add(new KeyValuePair<string, string>("SmartEncoded", SmartEncoded.Value.ToString().ToLower()));
}
if (PersistentAction != null)
{
p.AddRange(PersistentAction.Select(prop => new KeyValuePair<string, string>("PersistentAction", prop)));
}
if (ScheduleType != null)
{
p.Add(new KeyValuePair<string, string>("ScheduleType", ScheduleType.ToString()));
}
if (SendAt != null)
{
p.Add(new KeyValuePair<string, string>("SendAt", Serializers.DateTimeIso8601(SendAt)));
}
if (SendAsMms != null)
{
p.Add(new KeyValuePair<string, string>("SendAsMms", SendAsMms.Value.ToString().ToLower()));
}
return p;
}
}
/// <summary>
/// Deletes a message record from your account
/// </summary>
public class DeleteMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The SID of the Account that created the resources to delete
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteMessageOptions
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
public DeleteMessageOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Fetch a message belonging to the account used to make the request
/// </summary>
public class FetchMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The SID of the Account that created the resource to fetch
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchMessageOptions
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
public FetchMessageOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Retrieve a list of messages belonging to the account used to make the request
/// </summary>
public class ReadMessageOptions : ReadOptions<MessageResource>
{
/// <summary>
/// The SID of the Account that created the resources to read
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// Filter by messages sent to this number
/// </summary>
public Types.PhoneNumber To { get; set; }
/// <summary>
/// Filter by from number
/// </summary>
public Types.PhoneNumber From { get; set; }
/// <summary>
/// Filter by date sent
/// </summary>
public DateTime? DateSentBefore { get; set; }
/// <summary>
/// Filter by date sent
/// </summary>
public DateTime? DateSent { get; set; }
/// <summary>
/// Filter by date sent
/// </summary>
public DateTime? DateSentAfter { get; set; }
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (To != null)
{
p.Add(new KeyValuePair<string, string>("To", To.ToString()));
}
if (From != null)
{
p.Add(new KeyValuePair<string, string>("From", From.ToString()));
}
if (DateSent != null)
{
p.Add(new KeyValuePair<string, string>("DateSent", Serializers.DateTimeIso8601(DateSent)));
}
else
{
if (DateSentBefore != null)
{
p.Add(new KeyValuePair<string, string>("DateSent<", Serializers.DateTimeIso8601(DateSentBefore)));
}
if (DateSentAfter != null)
{
p.Add(new KeyValuePair<string, string>("DateSent>", Serializers.DateTimeIso8601(DateSentAfter)));
}
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// To redact a message-body from a post-flight message record, post to the message instance resource with an empty body
/// </summary>
public class UpdateMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The SID of the Account that created the resources to update
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// The text of the message you want to send
/// </summary>
public string Body { get; set; }
/// <summary>
/// Set as `canceled` to cancel a message from being sent.
/// </summary>
public MessageResource.UpdateStatusEnum Status { get; set; }
/// <summary>
/// Construct a new UpdateMessageOptions
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
public UpdateMessageOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Body != null)
{
p.Add(new KeyValuePair<string, string>("Body", Body));
}
if (Status != null)
{
p.Add(new KeyValuePair<string, string>("Status", Status.ToString()));
}
return p;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace TheBigCatProject.Server.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);
}
}
}
}
| |
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using RestSharp.Authenticators.OAuth.Extensions;
namespace RestSharp.Authenticators.OAuth
{
#if !SILVERLIGHT && !WINDOWS_PHONE
[Serializable]
#endif
internal static class OAuthTools
{
private const string AlphaNumeric = Upper + Lower + Digit;
private const string Digit = "1234567890";
private const string Lower = "abcdefghijklmnopqrstuvwxyz";
private const string Unreserved = AlphaNumeric + "-._~";
private const string Upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static readonly Random _random;
private static readonly object _randomLock = new object();
#if !SILVERLIGHT && !WINDOWS_PHONE
private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create();
#endif
static OAuthTools()
{
#if !SILVERLIGHT && !WINDOWS_PHONE
var bytes = new byte[4];
_rng.GetNonZeroBytes(bytes);
_random = new Random(BitConverter.ToInt32(bytes, 0));
#else
_random = new Random();
#endif
}
/// <summary>
/// All text parameters are UTF-8 encoded (per section 5.1).
/// </summary>
/// <seealso cref="http://www.hueniverse.com/hueniverse/2008/10/beginners-gui-1.html"/>
private static readonly Encoding _encoding = Encoding.UTF8;
/// <summary>
/// Generates a random 16-byte lowercase alphanumeric string.
/// </summary>
/// <seealso cref="http://oauth.net/core/1.0#nonce"/>
/// <returns></returns>
public static string GetNonce()
{
const string chars = (Lower + Digit);
var nonce = new char[16];
lock (_randomLock)
{
for (var i = 0; i < nonce.Length; i++)
{
nonce[i] = chars[_random.Next(0, chars.Length)];
}
}
return new string(nonce);
}
/// <summary>
/// Generates a timestamp based on the current elapsed seconds since '01/01/1970 0000 GMT"
/// </summary>
/// <seealso cref="http://oauth.net/core/1.0#nonce"/>
/// <returns></returns>
public static string GetTimestamp()
{
return GetTimestamp(DateTime.UtcNow);
}
/// <summary>
/// Generates a timestamp based on the elapsed seconds of a given time since '01/01/1970 0000 GMT"
/// </summary>
/// <seealso cref="http://oauth.net/core/1.0#nonce"/>
/// <param name="dateTime">A specified point in time.</param>
/// <returns></returns>
public static string GetTimestamp(DateTime dateTime)
{
var timestamp = dateTime.ToUnixTime();
return timestamp.ToString();
}
/// <summary>
/// URL encodes a string based on section 5.1 of the OAuth spec.
/// Namely, percent encoding with [RFC3986], avoiding unreserved characters,
/// upper-casing hexadecimal characters, and UTF-8 encoding for text value pairs.
/// </summary>
/// <param name="value"></param>
/// <seealso cref="http://oauth.net/core/1.0#encoding_parameters" />
public static string UrlEncodeRelaxed(string value)
{
return Uri.EscapeDataString(value);
}
/// <summary>
/// URL encodes a string based on section 5.1 of the OAuth spec.
/// Namely, percent encoding with [RFC3986], avoiding unreserved characters,
/// upper-casing hexadecimal characters, and UTF-8 encoding for text value pairs.
/// </summary>
/// <param name="value"></param>
/// <seealso cref="http://oauth.net/core/1.0#encoding_parameters" />
public static string UrlEncodeStrict(string value)
{
// [JD]: We need to escape the apostrophe as well or the signature will fail
var original = value;
var ret = original.Where(
c => !Unreserved.Contains(c) && c != '%').Aggregate(
value, (current, c) => current.Replace(
c.ToString(), c.ToString().PercentEncode()
));
return ret.Replace("%%", "%25%"); // Revisit to encode actual %'s
}
/// <summary>
/// Sorts a collection of key-value pairs by name, and then value if equal,
/// concatenating them into a single string. This string should be encoded
/// prior to, or after normalization is run.
/// </summary>
/// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.1.1"/>
/// <param name="parameters"></param>
/// <returns></returns>
public static string NormalizeRequestParameters(WebParameterCollection parameters)
{
var copy = SortParametersExcludingSignature(parameters);
var concatenated = copy.Concatenate("=", "&");
return concatenated;
}
/// <summary>
/// Sorts a <see cref="WebParameterCollection"/> by name, and then value if equal.
/// </summary>
/// <param name="parameters">A collection of parameters to sort</param>
/// <returns>A sorted parameter collection</returns>
public static WebParameterCollection SortParametersExcludingSignature(WebParameterCollection parameters)
{
var copy = new WebParameterCollection(parameters);
var exclusions = copy.Where(n => n.Name.EqualsIgnoreCase("oauth_signature"));
copy.RemoveAll(exclusions);
copy.ForEach(p => { p.Name = UrlEncodeStrict(p.Name); p.Value = UrlEncodeStrict(p.Value); });
copy.Sort(
(x, y) =>
string.CompareOrdinal(x.Name, y.Name) != 0
? string.CompareOrdinal(x.Name, y.Name)
: string.CompareOrdinal(x.Value, y.Value));
return copy;
}
/// <summary>
/// Creates a request URL suitable for making OAuth requests.
/// Resulting URLs must exclude port 80 or port 443 when accompanied by HTTP and HTTPS, respectively.
/// Resulting URLs must be lower case.
/// </summary>
/// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.1.2"/>
/// <param name="url">The original request URL</param>
/// <returns></returns>
public static string ConstructRequestUrl(Uri url)
{
if (url == null)
{
throw new ArgumentNullException("url");
}
var sb = new StringBuilder();
var requestUrl = "{0}://{1}".FormatWith(url.Scheme, url.Host);
var qualified = ":{0}".FormatWith(url.Port);
var basic = url.Scheme == "http" && url.Port == 80;
var secure = url.Scheme == "https" && url.Port == 443;
sb.Append(requestUrl);
sb.Append(!basic && !secure ? qualified : "");
sb.Append(url.AbsolutePath);
return sb.ToString(); //.ToLower();
}
/// <summary>
/// Creates a request elements concatentation value to send with a request.
/// This is also known as the signature base.
/// </summary>
/// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.1.3"/>
/// <seealso cref="http://oauth.net/core/1.0#sig_base_example"/>
/// <param name="method">The request's HTTP method type</param>
/// <param name="url">The request URL</param>
/// <param name="parameters">The request's parameters</param>
/// <returns>A signature base string</returns>
public static string ConcatenateRequestElements(string method, string url, WebParameterCollection parameters)
{
var sb = new StringBuilder();
// Separating &'s are not URL encoded
var requestMethod = method.ToUpper().Then("&");
var requestUrl = UrlEncodeRelaxed(ConstructRequestUrl(url.AsUri())).Then("&");
var requestParameters = UrlEncodeRelaxed(NormalizeRequestParameters(parameters));
sb.Append(requestMethod);
sb.Append(requestUrl);
sb.Append(requestParameters);
return sb.ToString();
}
/// <summary>
/// Creates a signature value given a signature base and the consumer secret.
/// This method is used when the token secret is currently unknown.
/// </summary>
/// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.2"/>
/// <param name="signatureMethod">The hashing method</param>
/// <param name="signatureBase">The signature base</param>
/// <param name="consumerSecret">The consumer key</param>
/// <returns></returns>
public static string GetSignature(OAuthSignatureMethod signatureMethod, string signatureBase, string consumerSecret)
{
return GetSignature(signatureMethod, OAuthSignatureTreatment.Escaped, signatureBase, consumerSecret, null);
}
/// <summary>
/// Creates a signature value given a signature base and the consumer secret.
/// This method is used when the token secret is currently unknown.
/// </summary>
/// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.2"/>
/// <param name="signatureMethod">The hashing method</param>
/// <param name="signatureTreatment">The treatment to use on a signature value</param>
/// <param name="signatureBase">The signature base</param>
/// <param name="consumerSecret">The consumer key</param>
/// <returns></returns>
public static string GetSignature(OAuthSignatureMethod signatureMethod, OAuthSignatureTreatment signatureTreatment, string signatureBase, string consumerSecret)
{
return GetSignature(signatureMethod, signatureTreatment, signatureBase, consumerSecret, null);
}
/// <summary>
/// Creates a signature value given a signature base and the consumer secret and a known token secret.
/// </summary>
/// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.2"/>
/// <param name="signatureMethod">The hashing method</param>
/// <param name="signatureBase">The signature base</param>
/// <param name="consumerSecret">The consumer secret</param>
/// <param name="tokenSecret">The token secret</param>
/// <returns></returns>
public static string GetSignature(OAuthSignatureMethod signatureMethod, string signatureBase, string consumerSecret, string tokenSecret)
{
return GetSignature(signatureMethod, OAuthSignatureTreatment.Escaped, consumerSecret, tokenSecret);
}
/// <summary>
/// Creates a signature value given a signature base and the consumer secret and a known token secret.
/// </summary>
/// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.2"/>
/// <param name="signatureMethod">The hashing method</param>
/// <param name="signatureTreatment">The treatment to use on a signature value</param>
/// <param name="signatureBase">The signature base</param>
/// <param name="consumerSecret">The consumer secret</param>
/// <param name="tokenSecret">The token secret</param>
/// <returns></returns>
public static string GetSignature(OAuthSignatureMethod signatureMethod,
OAuthSignatureTreatment signatureTreatment,
string signatureBase,
string consumerSecret,
string tokenSecret)
{
if (tokenSecret.IsNullOrBlank())
{
tokenSecret = String.Empty;
}
consumerSecret = UrlEncodeRelaxed(consumerSecret);
tokenSecret = UrlEncodeRelaxed(tokenSecret);
string signature;
switch (signatureMethod)
{
case OAuthSignatureMethod.HmacSha1:
{
var crypto = new HMACSHA1();
var key = "{0}&{1}".FormatWith(consumerSecret, tokenSecret);
crypto.Key = _encoding.GetBytes(key);
signature = signatureBase.HashWith(crypto);
break;
}
default:
throw new NotImplementedException("Only HMAC-SHA1 is currently supported.");
}
var result = signatureTreatment == OAuthSignatureTreatment.Escaped
? UrlEncodeRelaxed(signature)
: signature;
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Utilities class for working with configuration.
/// </summary>
public static class ConfigUtilities
{
// Time spans are entered as a string of decimal digits, optionally followed by a unit string: "ms", "s", "m", "hr"
internal static TimeSpan ParseTimeSpan(string input, string errorMessage)
{
long unitSize;
string numberInput;
var trimmedInput = input.Trim().ToLowerInvariant();
if (trimmedInput.EndsWith("ms", StringComparison.Ordinal))
{
unitSize = 10000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 2).Trim();
}
else if (trimmedInput.EndsWith('s'))
{
unitSize = 1000 * 10000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 1).Trim();
}
else if (trimmedInput.EndsWith('m'))
{
unitSize = 60 * 1000 * 10000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 1).Trim();
}
else if (trimmedInput.EndsWith("hr", StringComparison.Ordinal))
{
unitSize = 60 * 60 * 1000 * 10000L;
numberInput = trimmedInput.Remove(trimmedInput.Length - 2).Trim();
}
else
{
unitSize = 1000 * 10000; // Default is seconds
numberInput = trimmedInput;
}
decimal rawTimeSpan;
if (!decimal.TryParse(numberInput, NumberStyles.Any, CultureInfo.InvariantCulture, out rawTimeSpan))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return TimeSpan.FromTicks((long)(rawTimeSpan * unitSize));
}
internal static IPAddress ResolveIPAddressOrDefault(byte[] subnet, AddressFamily family)
{
IList<IPAddress> nodeIps = NetworkInterface.GetAllNetworkInterfaces()
.Where(iface => iface.OperationalStatus == OperationalStatus.Up)
.SelectMany(iface => iface.GetIPProperties().UnicastAddresses)
.Select(addr => addr.Address)
.Where(addr => addr.AddressFamily == family && !IPAddress.IsLoopback(addr))
.ToList();
var ipAddress = PickIPAddress(nodeIps, subnet, family);
return ipAddress;
}
internal static IPAddress ResolveIPAddressOrDefault(string addrOrHost, byte[] subnet, AddressFamily family)
{
var loopback = family == AddressFamily.InterNetwork ? IPAddress.Loopback : IPAddress.IPv6Loopback;
// if the address is an empty string, just enumerate all ip addresses available
// on this node
if (string.IsNullOrEmpty(addrOrHost))
{
return ResolveIPAddressOrDefault(subnet, family);
}
else
{
// Fix StreamFilteringTests_SMS tests
if (addrOrHost.Equals("loopback", StringComparison.OrdinalIgnoreCase))
{
return loopback;
}
// check if addrOrHost is a valid IP address including loopback (127.0.0.0/8, ::1) and any (0.0.0.0/0, ::) addresses
if (IPAddress.TryParse(addrOrHost, out var address))
{
return address;
}
// Get IP address from DNS. If addrOrHost is localhost will
// return loopback IPv4 address (or IPv4 and IPv6 addresses if OS is supported IPv6)
var nodeIps = Dns.GetHostAddresses(addrOrHost);
return PickIPAddress(nodeIps, subnet, family);
}
}
private static IPAddress PickIPAddress(IList<IPAddress> nodeIps, byte[] subnet, AddressFamily family)
{
var candidates = new List<IPAddress>();
foreach (var nodeIp in nodeIps.Where(x => x.AddressFamily == family))
{
// If the subnet does not match - we can't resolve this address.
// If subnet is not specified - pick smallest address deterministically.
if (subnet == null)
{
candidates.Add(nodeIp);
}
else
{
var ip = nodeIp;
if (subnet.Select((b, i) => ip.GetAddressBytes()[i] == b).All(x => x))
{
candidates.Add(nodeIp);
}
}
}
return candidates.Count > 0 ? PickIPAddress(candidates) : null;
}
private static IPAddress PickIPAddress(IReadOnlyList<IPAddress> candidates)
{
IPAddress chosen = null;
foreach (IPAddress addr in candidates)
{
if (chosen == null)
{
chosen = addr;
}
else
{
if (CompareIPAddresses(addr, chosen)) // pick smallest address deterministically
chosen = addr;
}
}
return chosen;
// returns true if lhs is "less" (in some repeatable sense) than rhs
static bool CompareIPAddresses(IPAddress lhs, IPAddress rhs)
{
byte[] lbytes = lhs.GetAddressBytes();
byte[] rbytes = rhs.GetAddressBytes();
if (lbytes.Length != rbytes.Length) return lbytes.Length < rbytes.Length;
// compare starting from most significant octet.
// 10.68.20.21 < 10.98.05.04
for (int i = 0; i < lbytes.Length; i++)
{
if (lbytes[i] != rbytes[i])
{
return lbytes[i] < rbytes[i];
}
}
// They're equal
return false;
}
}
/// <summary>
/// Gets the address of the local server.
/// If there are multiple addresses in the correct family in the server's DNS record, the first will be returned.
/// </summary>
/// <returns>The server's IPv4 address.</returns>
internal static IPAddress GetLocalIPAddress(AddressFamily family = AddressFamily.InterNetwork, string interfaceName = null)
{
var loopback = (family == AddressFamily.InterNetwork) ? IPAddress.Loopback : IPAddress.IPv6Loopback;
// get list of all network interfaces
NetworkInterface[] netInterfaces = NetworkInterface.GetAllNetworkInterfaces();
var candidates = new List<IPAddress>();
// loop through interfaces
for (int i = 0; i < netInterfaces.Length; i++)
{
NetworkInterface netInterface = netInterfaces[i];
if (netInterface.OperationalStatus != OperationalStatus.Up)
{
// Skip network interfaces that are not operational
continue;
}
if (!string.IsNullOrWhiteSpace(interfaceName) &&
!netInterface.Name.StartsWith(interfaceName, StringComparison.Ordinal)) continue;
bool isLoopbackInterface = (netInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback);
// get list of all unicast IPs from current interface
UnicastIPAddressInformationCollection ipAddresses = netInterface.GetIPProperties().UnicastAddresses;
// loop through IP address collection
foreach (UnicastIPAddressInformation ip in ipAddresses)
{
if (ip.Address.AddressFamily == family) // Picking the first address of the requested family for now. Will need to revisit later
{
//don't pick loopback address, unless we were asked for a loopback interface
if (!(isLoopbackInterface && ip.Address.Equals(loopback)))
{
candidates.Add(ip.Address); // collect all candidates.
}
}
}
}
if (candidates.Count > 0) return PickIPAddress(candidates);
throw new OrleansException("Failed to get a local IP address.");
}
/// <summary>
/// Prints the DataConnectionString,
/// without disclosing any credential info
/// such as the Azure Storage AccountKey, SqlServer password or AWS SecretKey.
/// </summary>
/// <param name="connectionString">The connection string to print.</param>
/// <returns>The string representation of the DataConnectionString with account credential info redacted.</returns>
public static string RedactConnectionStringInfo(string connectionString)
{
string[] secretKeys =
{
"AccountKey=", // Azure Storage
"SharedAccessSignature=", // Many Azure services
"SharedAccessKey=", "SharedSecretValue=", // ServiceBus
"Password=", // SQL
"SecretKey=", "SessionToken=", // DynamoDb
};
var mark = "<--SNIP-->";
if (String.IsNullOrEmpty(connectionString)) return "null";
//if connection string format doesn't contain any secretKey, then return just <--SNIP-->
if (!secretKeys.Any(key => connectionString.Contains(key))) return mark;
string connectionInfo = connectionString;
// Remove any secret keys from connection string info written to log files
foreach (var secretKey in secretKeys)
{
int keyPos = connectionInfo.IndexOf(secretKey, StringComparison.OrdinalIgnoreCase);
if (keyPos >= 0)
{
connectionInfo = connectionInfo.Remove(keyPos + secretKey.Length) + mark;
}
}
return connectionInfo;
}
}
}
| |
// 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.Net.Sockets;
using Xunit;
namespace System.Net.Primitives.Functional.Tests
{
public class IPEndPointParsing
{
[Theory]
[MemberData(nameof(IPAddressParsing.ValidIpv4Addresses), MemberType = typeof(IPAddressParsing))] // Just borrow the list from IPAddressParsing
public void Parse_ValidEndPoint_IPv4_Success(string address, string expectedAddress)
{
Parse_ValidEndPoint_Success(address, expectedAddress, true);
}
[Theory]
[MemberData(nameof(ValidIpv6AddressesNoPort))] // We need our own list here to explicitly exclude port numbers and brackets without making the test overly complicated (and less valid)
public void Parse_ValidEndPoint_IPv6_Success(string address, string expectedAddress)
{
Parse_ValidEndPoint_Success(address, expectedAddress, false);
}
private void Parse_ValidEndPoint_Success(string address, string expectedAddress, bool isIPv4)
{
// We'll parse just the address alone followed by the address with various port numbers
expectedAddress = expectedAddress.ToLowerInvariant(); // This is done in the IP parse routines
// TryParse should return true
Assert.True(IPEndPoint.TryParse(address, out IPEndPoint result));
Assert.Equal(expectedAddress, result.Address.ToString());
Assert.Equal(0, result.Port);
// Parse should give us the same result
result = IPEndPoint.Parse(address);
Assert.Equal(expectedAddress, result.Address.ToString());
Assert.Equal(0, result.Port);
// Cover varying lengths of port number
int portNumber = 1;
for (int i = 0; i < 5; i++)
{
var addressAndPort = isIPv4 ? $"{address}:{portNumber}" : $"[{address}]:{portNumber}";
// TryParse should return true
Assert.True(IPEndPoint.TryParse(addressAndPort, out result));
Assert.Equal(expectedAddress, result.Address.ToString());
Assert.Equal(portNumber, result.Port);
// Parse should give us the same result
result = IPEndPoint.Parse(addressAndPort);
Assert.Equal(expectedAddress, result.Address.ToString());
Assert.Equal(portNumber, result.Port);
// i.e.: 1; 12; 123; 1234; 12345
portNumber *= 10;
portNumber += i + 2;
}
}
[Theory]
[MemberData(nameof(IPAddressParsing.InvalidIpv4Addresses), MemberType = typeof(IPAddressParsing))]
[MemberData(nameof(IPAddressParsing.InvalidIpv4AddressesStandalone), MemberType = typeof(IPAddressParsing))]
public void Parse_InvalidAddress_IPv4_Throws(string address)
{
Parse_InvalidAddress_Throws(address, true);
}
[Theory]
[MemberData(nameof(IPAddressParsing.InvalidIpv6Addresses), MemberType = typeof(IPAddressParsing))]
[MemberData(nameof(IPAddressParsing.InvalidIpv6AddressesNoInner), MemberType = typeof(IPAddressParsing))]
public void Parse_InvalidAddress_IPv6_Throws(string address)
{
Parse_InvalidAddress_Throws(address, false);
}
private void Parse_InvalidAddress_Throws(string address, bool isIPv4)
{
// TryParse should return false and set result to null
Assert.False(IPEndPoint.TryParse(address, out IPEndPoint result));
Assert.Null(result);
// Parse should throw
Assert.Throws<FormatException>(() => IPEndPoint.Parse(address));
int portNumber = 1;
for (int i = 0; i < 5; i++)
{
string addressAndPort = isIPv4 ? $"{address}:{portNumber}" : $"[{address}]:{portNumber}";
// TryParse should return false and set result to null
result = new IPEndPoint(IPAddress.Parse("0"), 25);
Assert.False(IPEndPoint.TryParse(addressAndPort, out result));
Assert.Null(result);
// Parse should throw
Assert.Throws<FormatException>(() => IPEndPoint.Parse(addressAndPort));
// i.e.: 1; 12; 123; 1234; 12345
portNumber *= 10;
portNumber += i + 2;
}
}
[Theory]
[MemberData(nameof(IPAddressParsing.ValidIpv4Addresses), MemberType = typeof(IPAddressParsing))]
public void Parse_InvalidPort_IPv4_Throws(string address, string expectedAddress)
{
_ = expectedAddress;
Parse_InvalidPort_Throws(address, isIPv4: true);
}
[Theory]
[MemberData(nameof(IPAddressParsing.ValidIpv6Addresses), MemberType = typeof(IPAddressParsing))]
public void Parse_InvalidPort_IPv6_Throws(string address, string expectedAddress)
{
_ = expectedAddress;
Parse_InvalidPort_Throws(address, isIPv4: false);
}
private void Parse_InvalidPort_Throws(string address, bool isIPv4)
{
InvalidPortHelper(isIPv4 ? $"{address}:65536" : $"[{address}]:65536"); // port exceeds max
InvalidPortHelper(isIPv4 ? $"{address}:-300" : $"[{address}]:-300"); // port is negative
InvalidPortHelper(isIPv4 ? $"{address}:+300" : $"[{address}]:+300"); // plug sign
int portNumber = 1;
for (int i = 0; i < 5; i++)
{
InvalidPortHelper(isIPv4 ? $"{address}:a{portNumber}" : $"[{address}]:a{portNumber}"); // character at start of port
InvalidPortHelper(isIPv4 ? $"{address}:{portNumber}a" : $"[{address}]:{portNumber}a"); // character at end of port
InvalidPortHelper(isIPv4 ? $"{address}]:{portNumber}" : $"[{address}]]:{portNumber}"); // bracket where it should not be
InvalidPortHelper(isIPv4 ? $"{address}:]{portNumber}" : $"[{address}]:]{portNumber}"); // bracket after colon
InvalidPortHelper(isIPv4 ? $"{address}:{portNumber}]" : $"[{address}]:{portNumber}]"); // trailing bracket
InvalidPortHelper(isIPv4 ? $"{address}:{portNumber}:" : $"[{address}]:{portNumber}:"); // trailing colon
InvalidPortHelper(isIPv4 ? $"{address}:{portNumber}:{portNumber}" : $"[{address}]:{portNumber}]:{portNumber}"); // double port
InvalidPortHelper(isIPv4 ? $"{address}:{portNumber}a{portNumber}" : $"[{address}]:{portNumber}a{portNumber}"); // character in the middle of numbers
string addressAndPort = isIPv4 ? $"{address}::{portNumber}" : $"[{address}]::{portNumber}"; // double delimiter
// Appending two colons to an address may create a valid one (e.g. "0" becomes "0::x").
// If and only if the address parsers says it's not valid then we should as well
if (!IPAddress.TryParse(addressAndPort, out IPAddress ipAddress))
{
InvalidPortHelper(addressAndPort);
}
// i.e.: 1; 12; 123; 1234; 12345
portNumber *= 10;
portNumber += i + 2;
}
}
private void InvalidPortHelper(string addressAndPort)
{
// TryParse should return false and set result to null
Assert.False(IPEndPoint.TryParse(addressAndPort, out IPEndPoint result));
Assert.Null(result);
// Parse should throw
Assert.Throws<FormatException>(() => IPEndPoint.Parse(addressAndPort));
}
public static readonly object[][] ValidIpv6AddressesNoPort =
{
new object[] { "Fe08::1", "fe08::1" },
new object[] { "0000:0000:0000:0000:0000:0000:0000:0000", "::" },
new object[] { "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" },
new object[] { "0:0:0:0:0:0:0:0", "::" },
new object[] { "1:0:0:0:0:0:0:0", "1::" },
new object[] { "0:1:0:0:0:0:0:0", "0:1::" },
new object[] { "0:0:1:0:0:0:0:0", "0:0:1::" },
new object[] { "0:0:0:1:0:0:0:0", "0:0:0:1::" },
new object[] { "0:0:0:0:1:0:0:0", "::1:0:0:0" },
new object[] { "0:0:0:0:0:1:0:0", "::1:0:0" },
new object[] { "0:0:0:0:0:0:1:0", "::0.1.0.0" },
new object[] { "0:0:0:0:0:0:2:0", "::0.2.0.0" },
new object[] { "0:0:0:0:0:0:F:0", "::0.15.0.0" },
new object[] { "0:0:0:0:0:0:10:0", "::0.16.0.0" },
new object[] { "0:0:0:0:0:0:A0:0", "::0.160.0.0" },
new object[] { "0:0:0:0:0:0:F0:0", "::0.240.0.0" },
new object[] { "0:0:0:0:0:0:FF:0", "::0.255.0.0" },
new object[] { "0:0:0:0:0:0:0:1", "::1" },
new object[] { "0:0:0:0:0:0:0:2", "::2" },
new object[] { "0:0:0:0:0:0:0:F", "::F" },
new object[] { "0:0:0:0:0:0:0:10", "::10" },
new object[] { "0:0:0:0:0:0:0:1A", "::1A" },
new object[] { "0:0:0:0:0:0:0:A0", "::A0" },
new object[] { "0:0:0:0:0:0:0:F0", "::F0" },
new object[] { "0:0:0:0:0:0:0:FF", "::FF" },
new object[] { "0:0:0:0:0:0:0:1001", "::1001" },
new object[] { "0:0:0:0:0:0:0:1002", "::1002" },
new object[] { "0:0:0:0:0:0:0:100F", "::100F" },
new object[] { "0:0:0:0:0:0:0:1010", "::1010" },
new object[] { "0:0:0:0:0:0:0:10A0", "::10A0" },
new object[] { "0:0:0:0:0:0:0:10F0", "::10F0" },
new object[] { "0:0:0:0:0:0:0:10FF", "::10FF" },
new object[] { "0:0:0:0:0:0:1:1", "::0.1.0.1" },
new object[] { "0:0:0:0:0:0:2:2", "::0.2.0.2" },
new object[] { "0:0:0:0:0:0:F:F", "::0.15.0.15" },
new object[] { "0:0:0:0:0:0:10:10", "::0.16.0.16" },
new object[] { "0:0:0:0:0:0:A0:A0", "::0.160.0.160" },
new object[] { "0:0:0:0:0:0:F0:F0", "::0.240.0.240" },
new object[] { "0:0:0:0:0:0:FF:FF", "::0.255.0.255" },
new object[] { "0:0:0:0:0:FFFF:0:1", "::FFFF:0:1" },
new object[] { "0:0:0:0:0:FFFF:0:2", "::FFFF:0:2" },
new object[] { "0:0:0:0:0:FFFF:0:F", "::FFFF:0:F" },
new object[] { "0:0:0:0:0:FFFF:0:10", "::FFFF:0:10" },
new object[] { "0:0:0:0:0:FFFF:0:A0", "::FFFF:0:A0" },
new object[] { "0:0:0:0:0:FFFF:0:F0", "::FFFF:0:F0" },
new object[] { "0:0:0:0:0:FFFF:0:FF", "::FFFF:0:FF" },
new object[] { "0:0:0:0:0:FFFF:1:0", "::FFFF:0.1.0.0" },
new object[] { "0:0:0:0:0:FFFF:2:0", "::FFFF:0.2.0.0" },
new object[] { "0:0:0:0:0:FFFF:F:0", "::FFFF:0.15.0.0" },
new object[] { "0:0:0:0:0:FFFF:10:0", "::FFFF:0.16.0.0" },
new object[] { "0:0:0:0:0:FFFF:A0:0", "::FFFF:0.160.0.0" },
new object[] { "0:0:0:0:0:FFFF:F0:0", "::FFFF:0.240.0.0" },
new object[] { "0:0:0:0:0:FFFF:FF:0", "::FFFF:0.255.0.0" },
new object[] { "0:0:0:0:0:FFFF:0:1001", "::FFFF:0:1001" },
new object[] { "0:0:0:0:0:FFFF:0:1002", "::FFFF:0:1002" },
new object[] { "0:0:0:0:0:FFFF:0:100F", "::FFFF:0:100F" },
new object[] { "0:0:0:0:0:FFFF:0:1010", "::FFFF:0:1010" },
new object[] { "0:0:0:0:0:FFFF:0:10A0", "::FFFF:0:10A0" },
new object[] { "0:0:0:0:0:FFFF:0:10F0", "::FFFF:0:10F0" },
new object[] { "0:0:0:0:0:FFFF:0:10FF", "::FFFF:0:10FF" },
new object[] { "0:0:0:0:0:FFFF:1:1", "::FFFF:0.1.0.1" },
new object[] { "0:0:0:0:0:FFFF:2:2", "::FFFF:0.2.0.2" },
new object[] { "0:0:0:0:0:FFFF:F:F", "::FFFF:0.15.0.15" },
new object[] { "0:0:0:0:0:FFFF:10:10", "::FFFF:0.16.0.16" },
new object[] { "0:0:0:0:0:FFFF:A0:A0", "::FFFF:0.160.0.160" },
new object[] { "0:0:0:0:0:FFFF:F0:F0", "::FFFF:0.240.0.240" },
new object[] { "0:0:0:0:0:FFFF:FF:FF", "::FFFF:0.255.0.255" },
new object[] { "0:7:7:7:7:7:7:7", "0:7:7:7:7:7:7:7" },
new object[] { "1:0:0:0:0:0:0:1", "1::1" },
new object[] { "1:1:0:0:0:0:0:0", "1:1::" },
new object[] { "2:2:0:0:0:0:0:0", "2:2::" },
new object[] { "1:1:0:0:0:0:0:1", "1:1::1" },
new object[] { "1:0:1:0:0:0:0:1", "1:0:1::1" },
new object[] { "1:0:0:1:0:0:0:1", "1:0:0:1::1" },
new object[] { "1:0:0:0:1:0:0:1", "1::1:0:0:1" },
new object[] { "1:0:0:0:0:1:0:1", "1::1:0:1" },
new object[] { "1:0:0:0:0:0:1:1", "1::1:1" },
new object[] { "1:1:0:0:1:0:0:1", "1:1::1:0:0:1" },
new object[] { "1:0:1:0:0:1:0:1", "1:0:1::1:0:1" },
new object[] { "1:0:0:1:0:0:1:1", "1::1:0:0:1:1" },
new object[] { "1:1:0:0:0:1:0:1", "1:1::1:0:1" },
new object[] { "1:0:0:0:1:0:1:1", "1::1:0:1:1" },
new object[] { "1:1:1:1:1:1:1:0", "1:1:1:1:1:1:1:0" },
new object[] { "7:7:7:7:7:7:7:0", "7:7:7:7:7:7:7:0" },
new object[] { "E:0:0:0:0:0:0:1", "E::1" },
new object[] { "E:0:0:0:0:0:2:2", "E::2:2" },
new object[] { "E:0:6:6:6:6:6:6", "E:0:6:6:6:6:6:6" },
new object[] { "E:E:0:0:0:0:0:1", "E:E::1" },
new object[] { "E:E:0:0:0:0:2:2", "E:E::2:2" },
new object[] { "E:E:0:5:5:5:5:5", "E:E:0:5:5:5:5:5" },
new object[] { "E:E:E:0:0:0:0:1", "E:E:E::1" },
new object[] { "E:E:E:0:0:0:2:2", "E:E:E::2:2" },
new object[] { "E:E:E:0:4:4:4:4", "E:E:E:0:4:4:4:4" },
new object[] { "E:E:E:E:0:0:0:1", "E:E:E:E::1" },
new object[] { "E:E:E:E:0:0:2:2", "E:E:E:E::2:2" },
new object[] { "E:E:E:E:0:3:3:3", "E:E:E:E:0:3:3:3" },
new object[] { "E:E:E:E:E:0:0:1", "E:E:E:E:E::1" },
new object[] { "E:E:E:E:E:0:2:2", "E:E:E:E:E:0:2:2" },
new object[] { "E:E:E:E:E:E:0:1", "E:E:E:E:E:E:0:1" },
new object[] { "::FFFF:192.168.0.1", "::FFFF:192.168.0.1" },
new object[] { "::FFFF:0.168.0.1", "::FFFF:0.168.0.1" },
new object[] { "::0.0.255.255", "::FFFF" },
new object[] { "::EEEE:10.0.0.1", "::EEEE:A00:1" },
new object[] { "::10.0.0.1", "::10.0.0.1" },
new object[] { "1234:0:0:0:0:1234:0:0", "1234::1234:0:0" },
new object[] { "1:0:1:0:1:0:1:0", "1:0:1:0:1:0:1:0" },
new object[] { "1:1:1:0:0:1:1:0", "1:1:1::1:1:0" },
new object[] { "0:0:0:0:0:1234:0:0", "::1234:0:0" },
new object[] { "3ffe:38e1::0100:1:0001", "3ffe:38e1::100:1:1" },
new object[] { "0:0:1:2:00:00:000:0000", "0:0:1:2::" },
new object[] { "100:0:1:2:0:0:000:abcd", "100:0:1:2::abcd" },
new object[] { "ffff:0:0:0:0:0:00:abcd", "ffff::abcd" },
new object[] { "ffff:0:0:2:0:0:00:abcd", "ffff:0:0:2::abcd" },
new object[] { "0:0:1:2:0:00:0000:0000", "0:0:1:2::" },
new object[] { "0000:0000::1:0000:0000", "::1:0:0" },
new object[] { "0:0:111:234:5:6:789A:0", "::111:234:5:6:789a:0" },
new object[] { "11:22:33:44:55:66:77:8", "11:22:33:44:55:66:77:8" },
new object[] { "::7711:ab42:1230:0:0:0", "0:0:7711:ab42:1230::" },
new object[] { "::", "::" },
new object[] { "2001:0db8::0001", "2001:db8::1" }, // leading 0s suppressed
new object[] { "3731:54:65fe:2::a7", "3731:54:65fe:2::a7" }, // Unicast
new object[] { "3731:54:65fe:2::a8", "3731:54:65fe:2::a8" }, // Anycast
// ScopeID
new object[] { "Fe08::1%13542", "fe08::1%13542" },
new object[] { "1::%1", "1::%1" },
new object[] { "::1%12", "::1%12" },
new object[] { "::%123", "::%123" },
// v4 as v6
new object[] { "FE08::192.168.0.1", "fe08::c0a8:1" }, // Output is not IPv4 mapped
new object[] { "::192.168.0.1", "::192.168.0.1" },
new object[] { "::FFFF:192.168.0.1", "::ffff:192.168.0.1" }, // SIIT
new object[] { "::FFFF:0:192.168.0.1", "::ffff:0:192.168.0.1" }, // SIIT
new object[] { "::5EFE:192.168.0.1", "::5efe:192.168.0.1" }, // ISATAP
new object[] { "1::5EFE:192.168.0.1", "1::5efe:192.168.0.1" }, // ISATAP
new object[] { "::192.168.0.010", "::192.168.0.10" }, // Embedded IPv4 octal, read as decimal
};
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: ObjectReader
**
**
** Purpose: DeSerializes Binary Wire format
**
**
===========================================================*/
namespace System.Runtime.Serialization.Formatters.Binary {
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Security;
using System.Diagnostics;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
using StackCrawlMark = System.Threading.StackCrawlMark;
internal sealed class ObjectReader
{
// System.Serializer information
internal Stream m_stream;
internal ISurrogateSelector m_surrogates;
internal StreamingContext m_context;
internal ObjectManager m_objectManager;
internal InternalFE formatterEnums;
internal SerializationBinder m_binder;
// Top object and headers
internal long topId;
internal bool bSimpleAssembly = false;
internal Object handlerObject;
internal Object m_topObject;
internal Header[] headers;
internal HeaderHandler handler;
internal SerObjectInfoInit serObjectInfoInit;
internal IFormatterConverter m_formatterConverter;
// Stack of Object ParseRecords
internal SerStack stack;
// ValueType Fixup Stack
private SerStack valueFixupStack;
// Cross AppDomain
internal Object[] crossAppDomainArray; //Set by the BinaryFormatter
//MethodCall and MethodReturn are handled special for perf reasons
private bool bFullDeserialization;
#if FEATURE_REMOTING
private bool bMethodCall;
private bool bMethodReturn;
private BinaryMethodCall binaryMethodCall;
private BinaryMethodReturn binaryMethodReturn;
private bool bIsCrossAppDomain;
#endif
#if !DISABLE_CAS_USE
private static FileIOPermission sfileIOPermission = new FileIOPermission(PermissionState.Unrestricted);
#endif
private SerStack ValueFixupStack
{
get {
if (valueFixupStack == null)
valueFixupStack = new SerStack("ValueType Fixup Stack");
return valueFixupStack;
}
}
internal Object TopObject{
get {
return m_topObject;
}
set {
m_topObject = value;
if (m_objectManager != null)
m_objectManager.TopObject = value;
}
}
#if FEATURE_REMOTING
internal void SetMethodCall(BinaryMethodCall binaryMethodCall)
{
bMethodCall = true;
this.binaryMethodCall = binaryMethodCall;
}
internal void SetMethodReturn(BinaryMethodReturn binaryMethodReturn)
{
bMethodReturn = true;
this.binaryMethodReturn = binaryMethodReturn;
}
#endif
internal ObjectReader(Stream stream, ISurrogateSelector selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder binder)
{
if (stream == null)
{
throw new ArgumentNullException("stream", Environment.GetResourceString("ArgumentNull_Stream"));
}
Contract.EndContractBlock();
SerTrace.Log(this, "Constructor ISurrogateSelector ", ((selector == null) ? "null selector " : "selector present"));
m_stream=stream;
m_surrogates = selector;
m_context = context;
m_binder = binder;
#if !FEATURE_PAL && FEATURE_SERIALIZATION
// This is a hack to allow us to write a type-limiting deserializer
// when we know exactly what type to expect at the head of the
// object graph.
if (m_binder != null) {
ResourceReader.TypeLimitingDeserializationBinder tldBinder = m_binder as ResourceReader.TypeLimitingDeserializationBinder;
if (tldBinder != null)
tldBinder.ObjectReader = this;
}
#endif // !FEATURE_PAL && FEATURE_SERIALIZATION
this.formatterEnums = formatterEnums;
//SerTrace.Log( this, "Constructor formatterEnums.FEtopObject ",formatterEnums.FEtopObject);
}
#if FEATURE_REMOTING || MOBILE_LEGACY
[System.Security.SecurityCritical] // auto-generated
internal Object Deserialize(HeaderHandler handler, __BinaryParser serParser, bool fCheck, bool isCrossAppDomain, IMethodCallMessage methodCallMessage) {
if (serParser == null)
throw new ArgumentNullException("serParser", Environment.GetResourceString("ArgumentNull_WithParamName", serParser));
Contract.EndContractBlock();
#if _DEBUG
SerTrace.Log( this, "Deserialize Entry handler", handler);
#endif
bFullDeserialization = false;
TopObject = null;
topId = 0;
#if FEATURE_REMOTING
bMethodCall = false;
bMethodReturn = false;
bIsCrossAppDomain = isCrossAppDomain;
#endif
bSimpleAssembly = (formatterEnums.FEassemblyFormat == FormatterAssemblyStyle.Simple);
#if !MONO
if (fCheck)
{
CodeAccessPermission.Demand(PermissionType.SecuritySerialization);
}
#endif
this.handler = handler;
Contract.Assert(!bFullDeserialization, "we just set bFullDeserialization to false");
// Will call back to ParseObject, ParseHeader for each object found
serParser.Run();
#if _DEBUG
SerTrace.Log( this, "Deserialize Finished Parsing DoFixups");
#endif
if (bFullDeserialization)
m_objectManager.DoFixups();
#if FEATURE_REMOTING
if (!bMethodCall && !bMethodReturn)
#endif
{
if (TopObject == null)
throw new SerializationException(Environment.GetResourceString("Serialization_TopObject"));
//if TopObject has a surrogate then the actual object may be changed during special fixup
//So refresh it using topID.
if (HasSurrogate(TopObject.GetType()) && topId != 0)//Not yet resolved
TopObject = m_objectManager.GetObject(topId);
if (TopObject is IObjectReference)
{
TopObject = ((IObjectReference)TopObject).GetRealObject(m_context);
}
}
SerTrace.Log( this, "Deserialize Exit ",TopObject);
if (bFullDeserialization)
{
m_objectManager.RaiseDeserializationEvent(); // This will raise both IDeserialization and [OnDeserialized] events
}
// Return the headers if there is a handler
if (handler != null)
{
handlerObject = handler(headers);
}
#if FEATURE_REMOTING
if (bMethodCall)
{
Object[] methodCallArray = TopObject as Object[];
TopObject = binaryMethodCall.ReadArray(methodCallArray, handlerObject);
}
else if (bMethodReturn)
{
Object[] methodReturnArray = TopObject as Object[];
TopObject = binaryMethodReturn.ReadArray(methodReturnArray, methodCallMessage, handlerObject);
}
#endif
return TopObject;
}
#endif
#if !FEATURE_REMOTING
internal Object Deserialize(HeaderHandler handler, __BinaryParser serParser, bool fCheck)
{
if (serParser == null)
throw new ArgumentNullException("serParser", Environment.GetResourceString("ArgumentNull_WithParamName", serParser));
Contract.EndContractBlock();
#if _DEBUG
SerTrace.Log( this, "Deserialize Entry handler", handler);
#endif
bFullDeserialization = false;
TopObject = null;
topId = 0;
#if FEATURE_REMOTING
bMethodCall = false;
bMethodReturn = false;
bIsCrossAppDomain = isCrossAppDomain;
#endif
bSimpleAssembly = (formatterEnums.FEassemblyFormat == FormatterAssemblyStyle.Simple);
#if !MONO
if (fCheck)
{
CodeAccessPermission.Demand(PermissionType.SecuritySerialization);
}
#endif
this.handler = handler;
if (bFullDeserialization)
{
// Reinitialize
#if FEATURE_REMOTING
m_objectManager = new ObjectManager(m_surrogates, m_context, false, bIsCrossAppDomain);
#else
m_objectManager = new ObjectManager(m_surrogates, m_context, false, false);
#endif
serObjectInfoInit = new SerObjectInfoInit();
}
// Will call back to ParseObject, ParseHeader for each object found
serParser.Run();
#if _DEBUG
SerTrace.Log( this, "Deserialize Finished Parsing DoFixups");
#endif
if (bFullDeserialization)
m_objectManager.DoFixups();
#if FEATURE_REMOTING
if (!bMethodCall && !bMethodReturn)
#endif
{
if (TopObject == null)
throw new SerializationException(Environment.GetResourceString("Serialization_TopObject"));
//if TopObject has a surrogate then the actual object may be changed during special fixup
//So refresh it using topID.
if (HasSurrogate(TopObject.GetType()) && topId != 0)//Not yet resolved
TopObject = m_objectManager.GetObject(topId);
if (TopObject is IObjectReference)
{
TopObject = ((IObjectReference)TopObject).GetRealObject(m_context);
}
}
SerTrace.Log( this, "Deserialize Exit ",TopObject);
if (bFullDeserialization)
{
m_objectManager.RaiseDeserializationEvent(); // This will raise both IDeserialization and [OnDeserialized] events
}
// Return the headers if there is a handler
if (handler != null)
{
handlerObject = handler(headers);
}
#if FEATURE_REMOTING
if (bMethodCall)
{
Object[] methodCallArray = TopObject as Object[];
TopObject = binaryMethodCall.ReadArray(methodCallArray, handlerObject);
}
else if (bMethodReturn)
{
Object[] methodReturnArray = TopObject as Object[];
TopObject = binaryMethodReturn.ReadArray(methodReturnArray, methodCallMessage, handlerObject);
}
#endif
return TopObject;
}
#endif
[System.Security.SecurityCritical] // auto-generated
private bool HasSurrogate(Type t){
if (m_surrogates == null)
return false;
ISurrogateSelector notUsed;
return m_surrogates.GetSurrogate(t, m_context, out notUsed) != null;
}
[System.Security.SecurityCritical] // auto-generated
private void CheckSerializable(Type t)
{
if (!t.IsSerializable && !HasSurrogate(t))
throw new SerializationException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Serialization_NonSerType"),
t.FullName, t.Assembly.FullName));
}
[System.Security.SecurityCritical] // auto-generated
private void InitFullDeserialization()
{
bFullDeserialization = true;
stack = new SerStack("ObjectReader Object Stack");
#if FEATURE_REMOTING
m_objectManager = new ObjectManager(m_surrogates, m_context, false, bIsCrossAppDomain);
#else
m_objectManager = new ObjectManager(m_surrogates, m_context, false, false);
#endif
if (m_formatterConverter == null)
m_formatterConverter = new FormatterConverter();
}
internal Object CrossAppDomainArray(int index)
{
Contract.Assert((index < crossAppDomainArray.Length),
"[System.Runtime.Serialization.Formatters.BinaryObjectReader index out of range for CrossAppDomainArray]");
return crossAppDomainArray[index];
}
[System.Security.SecurityCritical] // auto-generated
internal ReadObjectInfo CreateReadObjectInfo(Type objectType)
{
return ReadObjectInfo.Create(objectType, m_surrogates, m_context, m_objectManager, serObjectInfoInit, m_formatterConverter, bSimpleAssembly);
}
[System.Security.SecurityCritical] // auto-generated
internal ReadObjectInfo CreateReadObjectInfo(Type objectType, String[] memberNames, Type[] memberTypes)
{
return ReadObjectInfo.Create(objectType, memberNames, memberTypes, m_surrogates, m_context, m_objectManager, serObjectInfoInit, m_formatterConverter, bSimpleAssembly);
}
// Main Parse routine, called by the XML Parse Handlers in XMLParser and also called internally to
[System.Security.SecurityCritical] // auto-generated
internal void Parse(ParseRecord pr)
{
#if _DEBUG
SerTrace.Log( this, "Parse");
stack.Dump();
pr.Dump();
#endif
switch (pr.PRparseTypeEnum)
{
case InternalParseTypeE.SerializedStreamHeader:
ParseSerializedStreamHeader(pr);
break;
case InternalParseTypeE.SerializedStreamHeaderEnd:
ParseSerializedStreamHeaderEnd(pr);
break;
case InternalParseTypeE.Object:
ParseObject(pr);
break;
case InternalParseTypeE.ObjectEnd:
ParseObjectEnd(pr);
break;
case InternalParseTypeE.Member:
ParseMember(pr);
break;
case InternalParseTypeE.MemberEnd:
ParseMemberEnd(pr);
break;
case InternalParseTypeE.Body:
case InternalParseTypeE.BodyEnd:
case InternalParseTypeE.Envelope:
case InternalParseTypeE.EnvelopeEnd:
break;
case InternalParseTypeE.Empty:
default:
throw new SerializationException(Environment.GetResourceString("Serialization_XMLElement", pr.PRname));
}
}
// Styled ParseError output
private void ParseError(ParseRecord processing, ParseRecord onStack)
{
#if _DEBUG
SerTrace.Log( this, " ParseError ",processing," ",onStack);
#endif
throw new SerializationException(Environment.GetResourceString("Serialization_ParseError",onStack.PRname+" "+((Enum)onStack.PRparseTypeEnum) + " "+processing.PRname+" "+((Enum)processing.PRparseTypeEnum)));
}
// Parse the SerializedStreamHeader element. This is the first element in the stream if present
private void ParseSerializedStreamHeader(ParseRecord pr)
{
#if _DEBUG
SerTrace.Log( this, "SerializedHeader ",pr);
#endif
stack.Push(pr);
}
// Parse the SerializedStreamHeader end element. This is the last element in the stream if present
private void ParseSerializedStreamHeaderEnd(ParseRecord pr)
{
#if _DEBUG
SerTrace.Log( this, "SerializedHeaderEnd ",pr);
#endif
stack.Pop();
}
#if FEATURE_REMOTING
private bool IsRemoting {
get {
//return (m_context.State & (StreamingContextStates.Persistence|StreamingContextStates.File|StreamingContextStates.Clone)) == 0;
return (bMethodCall || bMethodReturn);
}
}
[System.Security.SecurityCritical] // auto-generated
internal void CheckSecurity(ParseRecord pr)
{
InternalST.SoapAssert(pr!=null, "[BinaryObjectReader.CheckSecurity]pr!=null");
Type t = pr.PRdtType;
if ((object)t != null){
if( IsRemoting){
if (typeof(MarshalByRefObject).IsAssignableFrom(t))
throw new ArgumentException(Environment.GetResourceString("Serialization_MBRAsMBV", t.FullName));
FormatterServices.CheckTypeSecurity(t, formatterEnums.FEsecurityLevel);
}
}
}
#endif
// New object encountered in stream
[System.Security.SecurityCritical] // auto-generated
private void ParseObject(ParseRecord pr)
{
#if _DEBUG
SerTrace.Log( this, "ParseObject Entry ");
#endif
if (!bFullDeserialization)
InitFullDeserialization();
if (pr.PRobjectPositionEnum == InternalObjectPositionE.Top)
topId = pr.PRobjectId;
if (pr.PRparseTypeEnum == InternalParseTypeE.Object)
{
stack.Push(pr); // Nested objects member names are already on stack
}
if (pr.PRobjectTypeEnum == InternalObjectTypeE.Array)
{
ParseArray(pr);
#if _DEBUG
SerTrace.Log( this, "ParseObject Exit, ParseArray ");
#endif
return;
}
// If the Type is null, this means we have a typeload issue
// mark the object with TypeLoadExceptionHolder
if ((object)pr.PRdtType == null)
{
pr.PRnewObj = new TypeLoadExceptionHolder(pr.PRkeyDt);
return;
}
if (Object.ReferenceEquals(pr.PRdtType, Converter.typeofString))
{
// String as a top level object
if (pr.PRvalue != null)
{
pr.PRnewObj = pr.PRvalue;
if (pr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
#if _DEBUG
SerTrace.Log( this, "ParseObject String as top level, Top Object Resolved");
#endif
TopObject = pr.PRnewObj;
//stack.Pop();
return;
}
else
{
#if _DEBUG
SerTrace.Log( this, "ParseObject String as an object");
#endif
stack.Pop();
RegisterObject(pr.PRnewObj, pr, (ParseRecord)stack.Peek());
return;
}
}
else
{
// xml Doesn't have the value until later
return;
}
}
else {
CheckSerializable(pr.PRdtType);
#if FEATURE_REMOTING
if (IsRemoting && formatterEnums.FEsecurityLevel != TypeFilterLevel.Full)
pr.PRnewObj = FormatterServices.GetSafeUninitializedObject(pr.PRdtType);
else
#endif
pr.PRnewObj = FormatterServices.GetUninitializedObject(pr.PRdtType);
// Run the OnDeserializing methods
m_objectManager.RaiseOnDeserializingEvent(pr.PRnewObj);
}
if (pr.PRnewObj == null)
throw new SerializationException(Environment.GetResourceString("Serialization_TopObjectInstantiate",pr.PRdtType));
if (pr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
#if _DEBUG
SerTrace.Log( this, "ParseObject Top Object Resolved ",pr.PRnewObj.GetType());
#endif
TopObject = pr.PRnewObj;
}
if (pr.PRobjectInfo == null)
pr.PRobjectInfo = ReadObjectInfo.Create(pr.PRdtType, m_surrogates, m_context, m_objectManager, serObjectInfoInit, m_formatterConverter, bSimpleAssembly);
#if FEATURE_REMOTING
CheckSecurity(pr);
#endif
#if _DEBUG
SerTrace.Log( this, "ParseObject Exit ");
#endif
}
// End of object encountered in stream
[System.Security.SecurityCritical] // auto-generated
private void ParseObjectEnd(ParseRecord pr)
{
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd Entry ",pr.Trace());
#endif
ParseRecord objectPr = (ParseRecord)stack.Peek();
if (objectPr == null)
objectPr = pr;
//Contract.Assert(objectPr != null, "[System.Runtime.Serialization.Formatters.ParseObjectEnd]objectPr != null");
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd objectPr ",objectPr.Trace());
#endif
if (objectPr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd Top Object dtType ",objectPr.PRdtType);
#endif
if (Object.ReferenceEquals(objectPr.PRdtType, Converter.typeofString))
{
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd Top String");
#endif
objectPr.PRnewObj = objectPr.PRvalue;
TopObject = objectPr.PRnewObj;
return;
}
}
stack.Pop();
ParseRecord parentPr = (ParseRecord)stack.Peek();
if (objectPr.PRnewObj == null)
return;
if (objectPr.PRobjectTypeEnum == InternalObjectTypeE.Array)
{
if (objectPr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd Top Object (Array) Resolved");
#endif
TopObject = objectPr.PRnewObj;
}
#if _DEBUG
SerTrace.Log( this, "ParseArray RegisterObject ",objectPr.PRobjectId," ",objectPr.PRnewObj.GetType());
#endif
RegisterObject(objectPr.PRnewObj, objectPr, parentPr);
return;
}
objectPr.PRobjectInfo.PopulateObjectMembers(objectPr.PRnewObj, objectPr.PRmemberData);
// Registration is after object is populated
if ((!objectPr.PRisRegistered) && (objectPr.PRobjectId > 0))
{
#if _DEBUG
SerTrace.Log( this, "ParseObject Register Object ",objectPr.PRobjectId," ",objectPr.PRnewObj.GetType());
#endif
RegisterObject(objectPr.PRnewObj, objectPr, parentPr);
}
if (objectPr.PRisValueTypeFixup)
{
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd ValueTypeFixup ",objectPr.PRnewObj.GetType());
#endif
ValueFixup fixup = (ValueFixup)ValueFixupStack.Pop(); //Value fixup
fixup.Fixup(objectPr, parentPr); // Value fixup
}
if (objectPr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd Top Object Resolved ",objectPr.PRnewObj.GetType());
#endif
TopObject = objectPr.PRnewObj;
}
objectPr.PRobjectInfo.ObjectEnd();
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd Exit ",objectPr.PRnewObj.GetType()," id: ",objectPr.PRobjectId);
#endif
}
// Array object encountered in stream
[System.Security.SecurityCritical] // auto-generated
private void ParseArray(ParseRecord pr)
{
SerTrace.Log( this, "ParseArray Entry");
long genId = pr.PRobjectId;
if (pr.PRarrayTypeEnum == InternalArrayTypeE.Base64)
{
SerTrace.Log( this, "ParseArray bin.base64 ",pr.PRvalue.Length," ",pr.PRvalue);
// ByteArray
if (pr.PRvalue.Length > 0)
pr.PRnewObj = Convert.FromBase64String(pr.PRvalue);
else
pr.PRnewObj = new Byte[0];
if (stack.Peek() == pr)
{
SerTrace.Log( this, "ParseArray, bin.base64 has been stacked");
stack.Pop();
}
if (pr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
TopObject = pr.PRnewObj;
}
ParseRecord parentPr = (ParseRecord)stack.Peek();
// Base64 can be registered at this point because it is populated
SerTrace.Log( this, "ParseArray RegisterObject ",pr.PRobjectId," ",pr.PRnewObj.GetType());
RegisterObject(pr.PRnewObj, pr, parentPr);
}
else if ((pr.PRnewObj != null) && Converter.IsWriteAsByteArray(pr.PRarrayElementTypeCode))
{
// Primtive typed Array has already been read
if (pr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
TopObject = pr.PRnewObj;
}
ParseRecord parentPr = (ParseRecord)stack.Peek();
// Primitive typed array can be registered at this point because it is populated
SerTrace.Log( this, "ParseArray RegisterObject ",pr.PRobjectId," ",pr.PRnewObj.GetType());
RegisterObject(pr.PRnewObj, pr, parentPr);
}
else if ((pr.PRarrayTypeEnum == InternalArrayTypeE.Jagged) || (pr.PRarrayTypeEnum == InternalArrayTypeE.Single))
{
// Multidimensional jagged array or single array
SerTrace.Log( this, "ParseArray Before Jagged,Simple create ",pr.PRarrayElementType," ",pr.PRlengthA[0]);
bool bCouldBeValueType = true;
if ((pr.PRlowerBoundA == null) || (pr.PRlowerBoundA[0] == 0))
{
if (Object.ReferenceEquals(pr.PRarrayElementType, Converter.typeofString))
{
pr.PRobjectA = new String[pr.PRlengthA[0]];
pr.PRnewObj = pr.PRobjectA;
bCouldBeValueType = false;
}
else if (Object.ReferenceEquals(pr.PRarrayElementType, Converter.typeofObject))
{
pr.PRobjectA = new Object[pr.PRlengthA[0]];
pr.PRnewObj = pr.PRobjectA;
bCouldBeValueType = false;
}
else if ((object)pr.PRarrayElementType != null) {
pr.PRnewObj = Array.UnsafeCreateInstance(pr.PRarrayElementType, pr.PRlengthA[0]);
}
pr.PRisLowerBound = false;
}
else
{
if ((object)pr.PRarrayElementType != null) {
pr.PRnewObj = Array.UnsafeCreateInstance(pr.PRarrayElementType, pr.PRlengthA, pr.PRlowerBoundA);
}
pr.PRisLowerBound = true;
}
if (pr.PRarrayTypeEnum == InternalArrayTypeE.Single)
{
if (!pr.PRisLowerBound && (Converter.IsWriteAsByteArray(pr.PRarrayElementTypeCode)))
{
pr.PRprimitiveArray = new PrimitiveArray(pr.PRarrayElementTypeCode, (Array)pr.PRnewObj);
}
else if (bCouldBeValueType && (object)pr.PRarrayElementType != null)
{
if (!pr.PRarrayElementType.IsValueType && !pr.PRisLowerBound)
pr.PRobjectA = (Object[])pr.PRnewObj;
}
}
SerTrace.Log( this, "ParseArray Jagged,Simple Array ",pr.PRnewObj.GetType());
// For binary, headers comes in as an array of header objects
if (pr.PRobjectPositionEnum == InternalObjectPositionE.Headers)
{
SerTrace.Log( this, "ParseArray header array");
headers = (Header[])pr.PRnewObj;
}
pr.PRindexMap = new int[1];
}
else if (pr.PRarrayTypeEnum == InternalArrayTypeE.Rectangular)
{
// Rectangle array
pr.PRisLowerBound = false;
if (pr.PRlowerBoundA != null)
{
for (int i=0; i<pr.PRrank; i++)
{
if (pr.PRlowerBoundA[i] != 0)
pr.PRisLowerBound = true;
}
}
if ((object)pr.PRarrayElementType != null){
if (!pr.PRisLowerBound)
pr.PRnewObj = Array.UnsafeCreateInstance(pr.PRarrayElementType, pr.PRlengthA);
else
pr.PRnewObj = Array.UnsafeCreateInstance(pr.PRarrayElementType, pr.PRlengthA, pr.PRlowerBoundA);
}
SerTrace.Log( this, "ParseArray Rectangle Array ",pr.PRnewObj.GetType()," lower Bound ",pr.PRisLowerBound);
// Calculate number of items
int sum = 1;
for (int i=0; i<pr.PRrank; i++)
{
sum = sum*pr.PRlengthA[i];
}
pr.PRindexMap = new int[pr.PRrank];
pr.PRrectangularMap = new int[pr.PRrank];
pr.PRlinearlength = sum;
}
else
throw new SerializationException(Environment.GetResourceString("Serialization_ArrayType",((Enum)pr.PRarrayTypeEnum)));
#if FEATURE_REMOTING
CheckSecurity(pr);
#endif
SerTrace.Log( this, "ParseArray Exit");
}
// Builds a map for each item in an incoming rectangle array. The map specifies where the item is placed in the output Array Object
private void NextRectangleMap(ParseRecord pr)
{
// For each invocation, calculate the next rectangular array position
// example
// indexMap 0 [0,0,0]
// indexMap 1 [0,0,1]
// indexMap 2 [0,0,2]
// indexMap 3 [0,0,3]
// indexMap 4 [0,1,0]
for (int irank = pr.PRrank-1; irank>-1; irank--)
{
// Find the current or lower dimension which can be incremented.
if (pr.PRrectangularMap[irank] < pr.PRlengthA[irank]-1)
{
// The current dimension is at maximum. Increase the next lower dimension by 1
pr.PRrectangularMap[irank]++;
if (irank < pr.PRrank-1)
{
// The current dimension and higher dimensions are zeroed.
for (int i = irank+1; i<pr.PRrank; i++)
pr.PRrectangularMap[i] = 0;
}
Array.Copy(pr.PRrectangularMap, pr.PRindexMap, pr.PRrank);
break;
}
}
}
// Array object item encountered in stream
[System.Security.SecurityCritical] // auto-generated
private void ParseArrayMember(ParseRecord pr)
{
SerTrace.Log( this, "ParseArrayMember Entry");
ParseRecord objectPr = (ParseRecord)stack.Peek();
// Set up for inserting value into correct array position
if (objectPr.PRarrayTypeEnum == InternalArrayTypeE.Rectangular)
{
if (objectPr.PRmemberIndex > 0)
NextRectangleMap(objectPr); // Rectangle array, calculate position in array
if (objectPr.PRisLowerBound)
{
for (int i=0; i<objectPr.PRrank; i++)
{
objectPr.PRindexMap[i] = objectPr.PRrectangularMap[i] + objectPr.PRlowerBoundA[i];
}
}
}
else
{
if (!objectPr.PRisLowerBound)
{
objectPr.PRindexMap[0] = objectPr.PRmemberIndex; // Zero based array
}
else
objectPr.PRindexMap[0] = objectPr.PRlowerBoundA[0]+objectPr.PRmemberIndex; // Lower Bound based array
}
IndexTraceMessage("ParseArrayMember isLowerBound "+objectPr.PRisLowerBound+" indexMap ", objectPr.PRindexMap);
// Set Array element according to type of element
if (pr.PRmemberValueEnum == InternalMemberValueE.Reference)
{
// Object Reference
// See if object has already been instantiated
Object refObj = m_objectManager.GetObject(pr.PRidRef);
if (refObj == null)
{
// Object not instantiated
// Array fixup manager
IndexTraceMessage("ParseArrayMember Record Fixup "+objectPr.PRnewObj.GetType(), objectPr.PRindexMap);
int[] fixupIndex = new int[objectPr.PRrank];
Array.Copy(objectPr.PRindexMap, 0, fixupIndex, 0, objectPr.PRrank);
SerTrace.Log( this, "ParseArrayMember RecordArrayElementFixup objectId ",objectPr.PRobjectId," idRef ",pr.PRidRef);
m_objectManager.RecordArrayElementFixup(objectPr.PRobjectId, fixupIndex, pr.PRidRef);
}
else
{
IndexTraceMessage("ParseArrayMember SetValue ObjectReference "+objectPr.PRnewObj.GetType()+" "+refObj, objectPr.PRindexMap);
if (objectPr.PRobjectA != null)
objectPr.PRobjectA[objectPr.PRindexMap[0]] = refObj;
else
((Array)objectPr.PRnewObj).SetValue(refObj, objectPr.PRindexMap); // Object has been instantiated
}
}
else if (pr.PRmemberValueEnum == InternalMemberValueE.Nested)
{
//Set up dtType for ParseObject
SerTrace.Log( this, "ParseArrayMember Nested ");
if ((object)pr.PRdtType == null)
{
pr.PRdtType = objectPr.PRarrayElementType;
}
ParseObject(pr);
stack.Push(pr);
if ((object)objectPr.PRarrayElementType != null) {
if ((objectPr.PRarrayElementType.IsValueType) && (pr.PRarrayElementTypeCode == InternalPrimitiveTypeE.Invalid))
{
#if _DEBUG
SerTrace.Log( "ParseArrayMember ValueType ObjectPr ",objectPr.PRnewObj," index ",objectPr.PRmemberIndex);
#endif
pr.PRisValueTypeFixup = true; //Valuefixup
ValueFixupStack.Push(new ValueFixup((Array)objectPr.PRnewObj, objectPr.PRindexMap)); //valuefixup
}
else
{
#if _DEBUG
SerTrace.Log( "ParseArrayMember SetValue Nested, memberIndex ",objectPr.PRmemberIndex);
IndexTraceMessage("ParseArrayMember SetValue Nested ContainerObject "+objectPr.PRnewObj.GetType()+" "+objectPr.PRnewObj+" item Object "+pr.PRnewObj+" index ", objectPr.PRindexMap);
stack.Dump();
SerTrace.Log( "ParseArrayMember SetValue Nested ContainerObject objectPr ",objectPr.Trace());
SerTrace.Log( "ParseArrayMember SetValue Nested ContainerObject pr ",pr.Trace());
#endif
if (objectPr.PRobjectA != null)
objectPr.PRobjectA[objectPr.PRindexMap[0]] = pr.PRnewObj;
else
((Array)objectPr.PRnewObj).SetValue(pr.PRnewObj, objectPr.PRindexMap);
}
}
}
else if (pr.PRmemberValueEnum == InternalMemberValueE.InlineValue)
{
if ((Object.ReferenceEquals(objectPr.PRarrayElementType, Converter.typeofString)) || (Object.ReferenceEquals(pr.PRdtType, Converter.typeofString)))
{
// String in either a string array, or a string element of an object array
ParseString(pr, objectPr);
IndexTraceMessage("ParseArrayMember SetValue String "+objectPr.PRnewObj.GetType()+" "+pr.PRvalue, objectPr.PRindexMap);
if (objectPr.PRobjectA != null)
objectPr.PRobjectA[objectPr.PRindexMap[0]] = (Object)pr.PRvalue;
else
((Array)objectPr.PRnewObj).SetValue((Object)pr.PRvalue, objectPr.PRindexMap);
}
else if (objectPr.PRisArrayVariant)
{
// Array of type object
if (pr.PRkeyDt == null)
throw new SerializationException(Environment.GetResourceString("Serialization_ArrayTypeObject"));
Object var = null;
if (Object.ReferenceEquals(pr.PRdtType, Converter.typeofString))
{
ParseString(pr, objectPr);
var = pr.PRvalue;
}
else if (Object.ReferenceEquals(pr.PRdtTypeCode, InternalPrimitiveTypeE.Invalid))
{
CheckSerializable(pr.PRdtType);
// Not nested and invalid, so it is an empty object
#if FEATURE_REMOTING
if (IsRemoting && formatterEnums.FEsecurityLevel != TypeFilterLevel.Full)
var = FormatterServices.GetSafeUninitializedObject(pr.PRdtType);
else
#endif
var = FormatterServices.GetUninitializedObject(pr.PRdtType);
}
else
{
if (pr.PRvarValue != null)
var = pr.PRvarValue;
else
var = Converter.FromString(pr.PRvalue, pr.PRdtTypeCode);
}
IndexTraceMessage("ParseArrayMember SetValue variant or Object "+objectPr.PRnewObj.GetType()+" var "+var+" indexMap ", objectPr.PRindexMap);
if (objectPr.PRobjectA != null)
objectPr.PRobjectA[objectPr.PRindexMap[0]] = var;
else
((Array)objectPr.PRnewObj).SetValue(var, objectPr.PRindexMap); // Primitive type
}
else
{
// Primitive type
if (objectPr.PRprimitiveArray != null)
{
// Fast path for Soap primitive arrays. Binary was handled in the BinaryParser
objectPr.PRprimitiveArray.SetValue(pr.PRvalue, objectPr.PRindexMap[0]);
}
else
{
Object var = null;
if (pr.PRvarValue != null)
var = pr.PRvarValue;
else
var = Converter.FromString(pr.PRvalue, objectPr.PRarrayElementTypeCode);
SerTrace.Log( this, "ParseArrayMember SetValue Primitive pr.PRvalue "+var," elementTypeCode ",((Enum)objectPr.PRdtTypeCode));
IndexTraceMessage("ParseArrayMember SetValue Primitive "+objectPr.PRnewObj.GetType()+" var: "+var+" varType "+var.GetType(), objectPr.PRindexMap);
if (objectPr.PRobjectA != null)
{
SerTrace.Log( this, "ParseArrayMember SetValue Primitive predefined array "+objectPr.PRobjectA.GetType());
objectPr.PRobjectA[objectPr.PRindexMap[0]] = var;
}
else
((Array)objectPr.PRnewObj).SetValue(var, objectPr.PRindexMap); // Primitive type
SerTrace.Log( this, "ParseArrayMember SetValue Primitive after");
}
}
}
else if (pr.PRmemberValueEnum == InternalMemberValueE.Null)
{
SerTrace.Log( "ParseArrayMember Null item ",pr.PRmemberIndex," nullCount ",pr.PRnullCount);
objectPr.PRmemberIndex += pr.PRnullCount-1; //also incremented again below
}
else
ParseError(pr, objectPr);
#if _DEBUG
SerTrace.Log( "ParseArrayMember increment memberIndex ",objectPr.PRmemberIndex," ",objectPr.Trace());
#endif
objectPr.PRmemberIndex++;
SerTrace.Log( "ParseArrayMember Exit");
}
[System.Security.SecurityCritical] // auto-generated
private void ParseArrayMemberEnd(ParseRecord pr)
{
SerTrace.Log( this, "ParseArrayMemberEnd");
// If this is a nested array object, then pop the stack
if (pr.PRmemberValueEnum == InternalMemberValueE.Nested)
{
ParseObjectEnd(pr);
}
}
// Object member encountered in stream
[System.Security.SecurityCritical] // auto-generated
private void ParseMember(ParseRecord pr)
{
SerTrace.Log( this, "ParseMember Entry ");
ParseRecord objectPr = (ParseRecord)stack.Peek();
String objName = null;
if (objectPr != null)
objName = objectPr.PRname;
#if _DEBUG
SerTrace.Log( this, "ParseMember ",objectPr.PRobjectId," ",pr.PRname);
SerTrace.Log( this, "ParseMember objectPr ",objectPr.Trace());
SerTrace.Log( this, "ParseMember pr ",pr.Trace());
#endif
switch (pr.PRmemberTypeEnum)
{
case InternalMemberTypeE.Item:
ParseArrayMember(pr);
return;
case InternalMemberTypeE.Field:
break;
}
//if ((pr.PRdtType == null) && !objectPr.PRobjectInfo.isSi)
if (((object)pr.PRdtType == null) && objectPr.PRobjectInfo.isTyped)
{
SerTrace.Log( this, "ParseMember pr.PRdtType null and not isSi");
pr.PRdtType = objectPr.PRobjectInfo.GetType(pr.PRname);
if ((object)pr.PRdtType != null)
pr.PRdtTypeCode = Converter.ToCode(pr.PRdtType);
}
if (pr.PRmemberValueEnum == InternalMemberValueE.Null)
{
// Value is Null
SerTrace.Log( this, "ParseMember null member: ",pr.PRname);
SerTrace.Log( this, "AddValue 1");
objectPr.PRobjectInfo.AddValue(pr.PRname, null, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
else if (pr.PRmemberValueEnum == InternalMemberValueE.Nested)
{
SerTrace.Log( this, "ParseMember Nested Type member: ",pr.PRname," objectPr.PRnewObj ",objectPr.PRnewObj);
ParseObject(pr);
stack.Push(pr);
SerTrace.Log( this, "AddValue 2 ",pr.PRnewObj," is value type ",pr.PRnewObj.GetType().IsValueType);
if ((pr.PRobjectInfo != null) && ((object)pr.PRobjectInfo.objectType != null) && (pr.PRobjectInfo.objectType.IsValueType))
{
SerTrace.Log( "ParseMember ValueType ObjectPr ",objectPr.PRnewObj," memberName ",pr.PRname," nested object ",pr.PRnewObj);
pr.PRisValueTypeFixup = true; //Valuefixup
ValueFixupStack.Push(new ValueFixup(objectPr.PRnewObj, pr.PRname, objectPr.PRobjectInfo));//valuefixup
}
else
{
SerTrace.Log( this, "AddValue 2A ");
objectPr.PRobjectInfo.AddValue(pr.PRname, pr.PRnewObj, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
}
else if (pr.PRmemberValueEnum == InternalMemberValueE.Reference)
{
SerTrace.Log( this, "ParseMember Reference Type member: ",pr.PRname);
// See if object has already been instantiated
Object refObj = m_objectManager.GetObject(pr.PRidRef);
if (refObj == null)
{
SerTrace.Log( this, "ParseMember RecordFixup: ",pr.PRname);
SerTrace.Log( this, "AddValue 3");
objectPr.PRobjectInfo.AddValue(pr.PRname, null, ref objectPr.PRsi, ref objectPr.PRmemberData);
objectPr.PRobjectInfo.RecordFixup(objectPr.PRobjectId, pr.PRname, pr.PRidRef); // Object not instantiated
}
else
{
SerTrace.Log( this, "ParseMember Referenced Object Known ",pr.PRname," ",refObj);
SerTrace.Log( this, "AddValue 5");
objectPr.PRobjectInfo.AddValue(pr.PRname, refObj, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
}
else if (pr.PRmemberValueEnum == InternalMemberValueE.InlineValue)
{
// Primitive type or String
SerTrace.Log( this, "ParseMember primitive or String member: ",pr.PRname);
if (Object.ReferenceEquals(pr.PRdtType, Converter.typeofString))
{
ParseString(pr, objectPr);
SerTrace.Log( this, "AddValue 6");
objectPr.PRobjectInfo.AddValue(pr.PRname, pr.PRvalue, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
else if (pr.PRdtTypeCode == InternalPrimitiveTypeE.Invalid)
{
// The member field was an object put the value is Inline either bin.Base64 or invalid
if (pr.PRarrayTypeEnum == InternalArrayTypeE.Base64)
{
SerTrace.Log( this, "AddValue 7");
objectPr.PRobjectInfo.AddValue(pr.PRname, Convert.FromBase64String(pr.PRvalue), ref objectPr.PRsi, ref objectPr.PRmemberData);
}
else if (Object.ReferenceEquals(pr.PRdtType, Converter.typeofObject))
throw new SerializationException(Environment.GetResourceString("Serialization_TypeMissing", pr.PRname));
else
{
SerTrace.Log( this, "Object Class with no memberInfo data Member "+pr.PRname+" type "+pr.PRdtType);
ParseString(pr, objectPr); // Register the object if it has an objectId
// Object Class with no memberInfo data
// only special case where AddValue is needed?
if (Object.ReferenceEquals(pr.PRdtType, Converter.typeofSystemVoid))
{
SerTrace.Log( this, "AddValue 9");
objectPr.PRobjectInfo.AddValue(pr.PRname, pr.PRdtType, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
else if (objectPr.PRobjectInfo.isSi)
{
// ISerializable are added as strings, the conversion to type is done by the
// ISerializable object
SerTrace.Log( this, "AddValue 10");
objectPr.PRobjectInfo.AddValue(pr.PRname, pr.PRvalue, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
}
}
else
{
Object var = null;
if (pr.PRvarValue != null)
var = pr.PRvarValue;
else
var = Converter.FromString(pr.PRvalue, pr.PRdtTypeCode);
#if _DEBUG
// Not a string, convert the value
SerTrace.Log( this, "ParseMember Converting primitive and storing");
stack.Dump();
SerTrace.Log( this, "ParseMember pr "+pr.Trace());
SerTrace.Log( this, "ParseMember objectPr ",objectPr.Trace());
SerTrace.Log( this, "AddValue 11");
#endif
objectPr.PRobjectInfo.AddValue(pr.PRname, var, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
}
else
ParseError(pr, objectPr);
}
// Object member end encountered in stream
[System.Security.SecurityCritical] // auto-generated
private void ParseMemberEnd(ParseRecord pr)
{
SerTrace.Log( this, "ParseMemberEnd");
switch (pr.PRmemberTypeEnum)
{
case InternalMemberTypeE.Item:
ParseArrayMemberEnd(pr);
return;
case InternalMemberTypeE.Field:
if (pr.PRmemberValueEnum == InternalMemberValueE.Nested)
ParseObjectEnd(pr);
break;
default:
ParseError(pr, (ParseRecord)stack.Peek());
break;
}
}
// Processes a string object by getting an internal ID for it and registering it with the objectManager
[System.Security.SecurityCritical] // auto-generated
private void ParseString(ParseRecord pr, ParseRecord parentPr)
{
SerTrace.Log( this, "ParseString Entry ",pr.PRobjectId," ",pr.PRvalue," ",pr.PRisRegistered);
// Process String class
if ((!pr.PRisRegistered) && (pr.PRobjectId > 0))
{
SerTrace.Log( this, "ParseString RegisterObject ",pr.PRvalue," ",pr.PRobjectId);
// String is treated as an object if it has an id
//m_objectManager.RegisterObject(pr.PRvalue, pr.PRobjectId);
RegisterObject(pr.PRvalue, pr, parentPr, true);
}
}
[System.Security.SecurityCritical] // auto-generated
private void RegisterObject(Object obj, ParseRecord pr, ParseRecord objectPr)
{
RegisterObject(obj, pr, objectPr, false);
}
[System.Security.SecurityCritical] // auto-generated
private void RegisterObject(Object obj, ParseRecord pr, ParseRecord objectPr, bool bIsString)
{
if (!pr.PRisRegistered)
{
pr.PRisRegistered = true;
SerializationInfo si = null;
long parentId = 0;
MemberInfo memberInfo = null;
int[] indexMap = null;
if (objectPr != null)
{
indexMap = objectPr.PRindexMap;
parentId = objectPr.PRobjectId;
if (objectPr.PRobjectInfo != null)
{
if (!objectPr.PRobjectInfo.isSi)
{
// ParentId is only used if there is a memberInfo
memberInfo = objectPr.PRobjectInfo.GetMemberInfo(pr.PRname);
}
}
}
// SerializationInfo is always needed for ISerialization
si = pr.PRsi;
SerTrace.Log( this, "RegisterObject 0bj ",obj," objectId ",pr.PRobjectId," si ", si," parentId ",parentId," memberInfo ",memberInfo, " indexMap "+indexMap);
if (bIsString)
m_objectManager.RegisterString((String)obj, pr.PRobjectId, si, parentId, memberInfo);
else
m_objectManager.RegisterObject(obj, pr.PRobjectId, si, parentId, memberInfo, indexMap);
}
}
// Assigns an internal ID associated with the binary id number
// Older formatters generate ids for valuetypes using a different counter than ref types. Newer ones use
// a single counter, only value types have a negative value. Need a way to handle older formats.
private const int THRESHOLD_FOR_VALUETYPE_IDS = Int32.MaxValue;
private bool bOldFormatDetected = false;
private IntSizedArray valTypeObjectIdTable;
[System.Security.SecurityCritical] // auto-generated
internal long GetId(long objectId)
{
if (!bFullDeserialization)
InitFullDeserialization();
if (objectId > 0)
return objectId;
if (bOldFormatDetected || objectId == -1)
{
// Alarm bells. This is an old format. Deal with it.
bOldFormatDetected = true;
if (valTypeObjectIdTable == null)
valTypeObjectIdTable = new IntSizedArray();
long tempObjId = 0;
if ((tempObjId = valTypeObjectIdTable[(int)objectId]) == 0)
{
tempObjId = THRESHOLD_FOR_VALUETYPE_IDS + objectId;
valTypeObjectIdTable[(int)objectId] = (int)tempObjId;
}
return tempObjId;
}
return -1 * objectId;
}
// Trace which includes a single dimensional int array
[Conditional("SER_LOGGING")]
private void IndexTraceMessage(String message, int[] index)
{
StringBuilder sb = StringBuilderCache.Acquire(10);
sb.Append("[");
for (int i=0; i<index.Length; i++)
{
sb.Append(index[i]);
if (i != index.Length -1)
sb.Append(",");
}
sb.Append("]");
SerTrace.Log( this, message," ", StringBuilderCache.GetStringAndRelease(sb));
}
[System.Security.SecurityCritical] // auto-generated
internal Type Bind(String assemblyString, String typeString)
{
Type type = null;
if (m_binder != null)
type = m_binder.BindToType(assemblyString, typeString);
if ((object)type == null)
type= FastBindToType(assemblyString, typeString);
return type;
}
internal class TypeNAssembly
{
public Type type;
public String assemblyName;
}
NameCache typeCache = new NameCache();
[System.Security.SecurityCritical] // auto-generated
internal Type FastBindToType(String assemblyName, String typeName)
{
Type type = null;
TypeNAssembly entry = (TypeNAssembly)typeCache.GetCachedValue(typeName);
if (entry == null || entry.assemblyName != assemblyName)
{
Assembly assm = null;
if (bSimpleAssembly)
{
try {
#if !DISABLE_CAS_USE
sfileIOPermission.Assert();
#endif
try {
#if FEATURE_FUSION
assm = ObjectReader.ResolveSimpleAssemblyName(new AssemblyName(assemblyName));
#else // FEATURE_FUSION
Assembly.Load(assemblyName);
#endif // FEATURE_FUSION
}
finally {
#if !DISABLE_CAS_USE
CodeAccessPermission.RevertAssert();
#endif
}
}
catch(Exception e){
SerTrace.Log( this, "FastBindTypeType ",e.ToString());
}
if (assm == null)
return null;
ObjectReader.GetSimplyNamedTypeFromAssembly(assm, typeName, ref type);
}
else {
try
{
#if !DISABLE_CAS_USE
sfileIOPermission.Assert();
#endif
try {
assm = Assembly.Load(assemblyName);
}
finally {
#if !DISABLE_CAS_USE
CodeAccessPermission.RevertAssert();
#endif
}
}
catch (Exception e)
{
SerTrace.Log( this, "FastBindTypeType ",e.ToString());
}
if (assm == null)
return null;
type = FormatterServices.GetTypeFromAssembly(assm, typeName);
}
if ((object)type == null)
return null;
// before adding it to cache, let us do the security check
CheckTypeForwardedTo(assm, type.Assembly, type);
entry = new TypeNAssembly();
entry.type = type;
entry.assemblyName = assemblyName;
typeCache.SetCachedValue(entry);
}
return entry.type;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
private static Assembly ResolveSimpleAssemblyName(AssemblyName assemblyName)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMe;
Assembly assm = RuntimeAssembly.LoadWithPartialNameInternal(assemblyName, null, ref stackMark);
if (assm == null && assemblyName != null)
assm = RuntimeAssembly.LoadWithPartialNameInternal(assemblyName.Name, null, ref stackMark);
return assm;
}
[System.Security.SecurityCritical] // auto-generated
private static void GetSimplyNamedTypeFromAssembly(Assembly assm, string typeName, ref Type type)
{
// Catching any exceptions that could be thrown from a failure on assembly load
// This is necessary, for example, if there are generic parameters that are qualified with a version of the assembly that predates the one available
try
{
type = FormatterServices.GetTypeFromAssembly(assm, typeName);
}
catch (TypeLoadException) { }
catch (FileNotFoundException) { }
catch (FileLoadException) { }
catch (BadImageFormatException) { }
if ((object)type == null)
{
type = Type.GetType(typeName, ObjectReader.ResolveSimpleAssemblyName, new TopLevelAssemblyTypeResolver(assm).ResolveType, false /* throwOnError */);
}
}
private String previousAssemblyString;
private String previousName;
private Type previousType;
//private int hit;
[System.Security.SecurityCritical] // auto-generated
internal Type GetType(BinaryAssemblyInfo assemblyInfo, String name)
{
Type objectType = null;
if (((previousName != null) && (previousName.Length == name.Length) && (previousName.Equals(name))) &&
((previousAssemblyString != null) && (previousAssemblyString.Length == assemblyInfo.assemblyString.Length) &&(previousAssemblyString.Equals(assemblyInfo.assemblyString))))
{
objectType = previousType;
//Console.WriteLine("Hit "+(++hit)+" "+objectType);
}
else
{
objectType = Bind(assemblyInfo.assemblyString, name);
if ((object)objectType == null)
{
Assembly sourceAssembly = assemblyInfo.GetAssembly();
if (bSimpleAssembly)
{
ObjectReader.GetSimplyNamedTypeFromAssembly(sourceAssembly, name, ref objectType);
}
else
{
objectType = FormatterServices.GetTypeFromAssembly(sourceAssembly, name);
}
// here let us do the security check
if (objectType != null)
{
CheckTypeForwardedTo(sourceAssembly, objectType.Assembly, objectType);
}
}
previousAssemblyString = assemblyInfo.assemblyString;
previousName = name;
previousType = objectType;
}
//Console.WriteLine("name "+name+" assembly "+assemblyInfo.assemblyString+" objectType "+objectType);
return objectType;
}
[SecuritySafeCritical]
private static void CheckTypeForwardedTo(Assembly sourceAssembly, Assembly destAssembly, Type resolvedType)
{
if ( !FormatterServices.UnsafeTypeForwardersIsEnabled() && sourceAssembly != destAssembly )
{
// we have a type forward to attribute !
#if !DISABLE_CAS_USE
// we can try to see if the dest assembly has less permissionSet
if (!destAssembly.PermissionSet.IsSubsetOf(sourceAssembly.PermissionSet))
#endif
{
// let us try to see if typeforwardedfrom is there
// let us hit the cache first
TypeInformation typeInfo = BinaryFormatter.GetTypeInformation(resolvedType);
if (typeInfo.HasTypeForwardedFrom)
{
Assembly typeFowardedFromAssembly = null;
try
{
// if this Assembly.Load failed, we still want to throw security exception
typeFowardedFromAssembly = Assembly.Load(typeInfo.AssemblyString);
}
catch { }
#if !DISABLE_CAS_USE
if (typeFowardedFromAssembly != sourceAssembly)
{
// throw security exception
throw new SecurityException() { Demanded = sourceAssembly.PermissionSet };
}
#endif
}
else
{
#if !DISABLE_CAS_USE
// throw security exception
throw new SecurityException() { Demanded = sourceAssembly.PermissionSet };
#endif
}
}
}
}
internal sealed class TopLevelAssemblyTypeResolver
{
private Assembly m_topLevelAssembly;
public TopLevelAssemblyTypeResolver(Assembly topLevelAssembly)
{
m_topLevelAssembly = topLevelAssembly;
}
public Type ResolveType(Assembly assembly, string simpleTypeName, bool ignoreCase)
{
if (assembly == null)
assembly = m_topLevelAssembly;
return assembly.GetType(simpleTypeName, false, ignoreCase);
}
}
}
}
| |
// 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 System;
using System.Collections;
using System.Threading;
using Alachisoft.NCache.Common.DataStructures;
using Alachisoft.NCache.Common.Monitoring;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Common.Threading;
using Alachisoft.NCache.Common.DataStructures.Clustered;
using Alachisoft.NCache.Caching.Maintenance;
using Alachisoft.NCache.Common.Pooling;
using Alachisoft.NCache.Common.Caching;
using Alachisoft.NCache.Util;
using System.Collections.Generic;
namespace Alachisoft.NCache.Caching.Topologies.Clustered
{
#region Queue replicator
public class AsyncItemReplicator : IDisposable, IGRShutDown
{
CacheRuntimeContext _context = null;
TimeSpan _interval = new TimeSpan(0, 0, 2);
Thread runner = null;
OptimizedQueue _queue;
private Hashtable _updateIndexKeys = Hashtable.Synchronized(new Hashtable());
private long _uniqueKeyNumber;
private int _updateIndexMoveThreshhold = 200;
private int _moveCount;
private bool stopped = true;
private int _bulkKeysToReplicate = 300;
private Latch _shutdownStatusLatch = new Latch(ShutDownStatus.NONE);
internal AsyncItemReplicator(CacheRuntimeContext context, TimeSpan interval)
{
_bulkKeysToReplicate = ServiceConfiguration.BulkItemsToReplicate;
this._context = context;
this._interval = interval;
_queue = new OptimizedQueue(context);
}
public void WindUpTask()
{
if (!stopped)
{
_context.NCacheLog.CriticalInfo("AsyncItemReplicator", "WindUp Task Started.");
if (_queue != null)
_context.NCacheLog.CriticalInfo("AsyncItemReplicator", "Async Replicator Queue Count: " + _queue.Count);
_interval = new TimeSpan(0, 0, 0);
_shutdownStatusLatch.SetStatusBit(ShutDownStatus.SHUTDOWN_INPROGRESS, ShutDownStatus.NONE);
_context.NCacheLog.CriticalInfo("AsyncItemReplicator", "WindUp Task Ended.");
}
}
public void WaitForShutDown(long interval)
{
if (!stopped)
{
_context.NCacheLog.CriticalInfo("AsyncItemReplicator", "Waiting for shutdown task completion.");
if(_queue.Count > 0)
_shutdownStatusLatch.WaitForAny(ShutDownStatus.SHUTDOWN_COMPLETED, interval * 1000);
if (_queue != null && _queue.Count > 0)
_context.NCacheLog.CriticalInfo("AsyncItemReplicator", "Remaining Async Replicator operations: " + _queue.Count);
_context.NCacheLog.CriticalInfo("AsyncItemReplicator", "Shutdown task completed.");
}
}
/// <summary>
/// Creates a new Thread and Starts it.
/// </summary>
public void Start()
{
if (stopped)
{
stopped = false;
runner = new Thread(new ThreadStart(Run));
runner.IsBackground = true;
runner.Name = "AsyncItemReplicationThread";
runner.Start();
}
}
/// <summary>
/// An operation to update an index on the replica node is queued to be
/// replicate. These operations are send in bulk to the replica node.
/// </summary>
/// <param name="key"></param>
public void AddUpdateIndexKey(object key)
{
lock (_updateIndexKeys.SyncRoot)
{
_updateIndexKeys[key] = null;
_context.PerfStatsColl.IncrementSlidingIndexQueueSizeStats(_updateIndexKeys.Count);
}
}
public void RemoveUpdateIndexKey(object key)
{
lock (_updateIndexKeys.SyncRoot)
{
_updateIndexKeys.Remove(key);
_context.PerfStatsColl.IncrementSlidingIndexQueueSizeStats(_updateIndexKeys.Count);
}
}
/// <summary>
/// Add the key and entry in teh Hashtable for Invalidation by preodic thread.
/// </summary>
/// <param name="key">The key of the item to invalidate.</param>
/// <param name="entry">CacheEntry to Invalidate.</param>
internal void EnqueueOperation(object key, ReplicationOperation operation)
{
try
{
if (key == null)
key = System.Guid.NewGuid().ToString() + Interlocked.Increment(ref _uniqueKeyNumber);
_queue.Enqueue(key, operation);
if (ServerMonitor.MonitorActivity)
ServerMonitor.LogClientActivity("AsyncReplicator.Enque", "queue_size :" + _queue.Count);
_context.PerfStatsColl.IncrementMirrorQueueSizeStats(_queue.Count);
}
catch (Exception e)
{
if (_context.NCacheLog.IsErrorEnabled) _context.NCacheLog.Error("AsyncItemReplicator", string.Format("Exception: {0}", e.ToString()));
}
}
/// <summary>
/// Clears the Queue of any keys for replication.
/// </summary>
public void Clear()
{
_queue.Clear();
_context.PerfStatsColl.IncrementMirrorQueueSizeStats(_queue.Count);
}
/// <summary>
/// Clears the Queue of any keys for replication.
/// </summary>
internal void EnqueueClear(ReplicationOperation operation)
{
_queue.Clear();
this.EnqueueOperation("NcAcHe$Cl@Ea%R", operation);
}
private object[] GetIndexOperations()
{
object[] keys = null;
lock (_updateIndexKeys.SyncRoot)
{
_moveCount++;
if (_updateIndexKeys.Count >= _updateIndexMoveThreshhold || _moveCount > 2)
{
if (_updateIndexKeys.Count > 0)
{
keys = new object[_updateIndexKeys.Count];
IDictionaryEnumerator ide = _updateIndexKeys.GetEnumerator();
int index = 0;
while (ide.MoveNext())
{
keys[index] = ide.Key;
index++;
}
}
_moveCount = 0;
_updateIndexKeys.Clear();
}
}
return keys;
}
/// <summary>
/// replication thread function.
/// note: While replicating operations, a dummy '0' sequence id is passed.
/// this sequence id is totally ignored by asynchronous POR, but we are keeping it
/// to maintain the symmetry in API.
/// </summary>
public void Run()
{
//reload threashold value from service config, consider the probability that values would have been changed by user
_bulkKeysToReplicate = ServiceConfiguration.BulkItemsToReplicate;
IList opCodesToBeReplicated = new ClusteredArrayList(_bulkKeysToReplicate);
IList infoToBeReplicated = new ClusteredArrayList(_bulkKeysToReplicate);
IList compilationInfo = new ClusteredArrayList(_bulkKeysToReplicate);
IList userPayLoad = new ClusteredArrayList();
IOptimizedQueueOperation operation = null;
try
{
while (!stopped || _queue.Count > 0)
{
DateTime startedAt = DateTime.Now;
DateTime finishedAt = DateTime.Now;
try
{
for (int i = 0; _queue.Count > 0 && i < _bulkKeysToReplicate; i++)
{
operation = _queue.Dequeue();
DictionaryEntry entry = (DictionaryEntry)operation.Data;
opCodesToBeReplicated.Add(entry.Key);
infoToBeReplicated.Add(entry.Value);
if (operation.UserPayLoad != null)
{
if (userPayLoad == null)
userPayLoad = new ArrayList();
for (int j = 0; j < operation.UserPayLoad.Length; j++)
{
userPayLoad.Add(operation.UserPayLoad.GetValue(j));
}
}
compilationInfo.Add(operation.PayLoadSize);
}
object[] updateIndexKeys = GetIndexOperations();
if (!stopped)
{
if (opCodesToBeReplicated.Count > 0 || updateIndexKeys != null)
{
if (updateIndexKeys != null)
{
opCodesToBeReplicated.Add((int)ClusterCacheBase.OpCodes.UpdateIndice);
infoToBeReplicated.Add(updateIndexKeys);
}
_context.CacheImpl.ReplicateOperations(opCodesToBeReplicated, infoToBeReplicated, userPayLoad, compilationInfo, _context.CacheImpl.OperationSequenceId, _context.CacheImpl.CurrentViewId);
}
}
if (!stopped && _context.PerfStatsColl != null) _context.PerfStatsColl.IncrementMirrorQueueSizeStats(_queue.Count);
}
catch (Exception e)
{
if (e.Message.IndexOf("operation timeout", StringComparison.OrdinalIgnoreCase) >= 0 && !_shutdownStatusLatch.IsAnyBitsSet(ShutDownStatus.SHUTDOWN_INPROGRESS))
{
_context.NCacheLog.CriticalInfo("AsyncReplicator.Run", "Bulk operation timedout. Retrying the operation.");
try
{
if (!stopped)
{
_context.CacheImpl.ReplicateOperations(opCodesToBeReplicated, infoToBeReplicated, userPayLoad, compilationInfo, 0, 0);
_context.NCacheLog.CriticalInfo("AsyncReplicator.Run", "RETRY is successfull.");
}
}
catch (Exception ex)
{
if (_context.NCacheLog.IsErrorEnabled) _context.NCacheLog.Error( "AsyncReplicator.RUN", "Error occurred while retrying operation. " + ex.ToString());
}
}
else
if (_context.NCacheLog.IsErrorEnabled) _context.NCacheLog.Error( "AsyncReplicator.RUN", e.ToString());
}
finally
{
if (infoToBeReplicated != null)
{
foreach (var data in infoToBeReplicated)
{
CacheEntry entry = data as CacheEntry;
if (entry != null)
{
entry.MarkFree(NCModulesConstants.Global);
entry.MarkFree(NCModulesConstants.Replication);
}
ReturnReplicatedPooledItemsToPool(data as object[], _context.TransactionalPoolManager);
}
}
if(userPayLoad != null)
{
foreach (var val in userPayLoad)
{
OperationContext context = val as OperationContext;
context?.MarkFree(NCModulesConstants.Replication);
}
}
opCodesToBeReplicated.Clear();
infoToBeReplicated.Clear();
compilationInfo.Clear();
if (userPayLoad != null)
userPayLoad.Clear();
finishedAt = DateTime.Now;
}
if (_queue.Count > 0)
continue;
else if (_queue.Count == 0 && _shutdownStatusLatch.IsAnyBitsSet(ShutDownStatus.SHUTDOWN_INPROGRESS))
{
_shutdownStatusLatch.SetStatusBit(ShutDownStatus.SHUTDOWN_COMPLETED, ShutDownStatus.SHUTDOWN_INPROGRESS);
return;
}
if ((finishedAt.Ticks - startedAt.Ticks) < _interval.Ticks)
Thread.Sleep(_interval.Subtract(finishedAt.Subtract(startedAt)));
else
Thread.Sleep(_interval);
}
}
catch (ThreadAbortException ta)
{
}
catch (ThreadInterruptedException ti)
{
}
catch (NullReferenceException)
{
}
catch (Exception e)
{
if (!stopped)
_context.NCacheLog.Error("AsyncReplicator.RUN", "Async replicator stopped. " + e.ToString());
}
}
/// <summary>
/// Stops and disposes the Repliaction thread. The thread can be started using Start method.
/// <param name="gracefulStop">If true then operations pending in the queue are performed
/// on the passive node, otherwise stopped instantly </param>
/// </summary>
public void Stop(bool gracefulStop)
{
stopped = true;
if (runner != null && runner.IsAlive)
{
if (gracefulStop)
runner.Join();
else
{
try
{
if (runner.IsAlive)
{
_context.NCacheLog.Flush();
#if !NETCORE
runner.Abort();
#elif NETCORE
runner.Interrupt();
#endif
}
}
catch (Exception) { }
}
try
{
Clear();
}
catch { }
}
}
/// <summary>
/// Returns the number of operations in the queue.
/// </summary>
public long QueueCount
{
get { return _queue.Count; }
}
#region IDisposable Members
/// <summary>
/// Terminates the replciation thread and Disposes the instance.
/// </summary>
public void Dispose()
{
Stop(false);
runner = null;
}
#endregion
private void ReturnReplicatedPooledItemsToPool(object[] info, PoolManager poolManager)
{
if (poolManager == null)
return;
if (info?.Length > 0)
{
foreach (var infoElem in info)
{
switch (infoElem)
{
case CacheEntry cacheEntryReplicated:
MiscUtil.ReturnEntryToPool(cacheEntryReplicated, poolManager);
break;
case OperationContext operationContextReplicated:
MiscUtil.ReturnOperationContextToPool(operationContextReplicated, poolManager);
break;
default:
// Ignore non-pooled items
break;
}
}
}
}
private void ReturnPooledPayloadToPool(IList<Array> payloads, PoolManager poolManager)
{
if (poolManager == null)
return;
if (payloads?.Count > 0)
{
foreach (var payload in payloads)
{
if (payload?.Length > 0)
{
foreach (var innerPayload in payload)
{
switch (innerPayload)
{
case byte[] bytes:
MiscUtil.ReturnByteArrayToPool(bytes, poolManager);
break;
default:
// Ignore non-pooled items
break;
}
}
}
}
}
}
}
#endregion
}
| |
//
// 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;
namespace IBM.Data.DB2
{
/// <summary>
/// Summary description for DB2Constants.
/// </summary>
public sealed class DB2Constants
{
public const short SQL_HANDLE_ENV = 1;
public const short SQL_HANDLE_DBC = 2;
public const short SQL_HANDLE_STMT = 3;
public const short SQL_HANDLE_DESC = 4;
[Flags]
public enum RetCode : short
{
SQL_SUCCESS = 0,
SQL_SUCCESS_WITH_INFO = 1,
SQL_NEED_DATA = 99,
SQL_NO_DATA = 100,
SQL_STILL_EXECUTING = 2,
SQL_ERROR = -1,
SQL_INVALID_HANDLE = -2,
SQL_SUCCESS_BOTH = SQL_SUCCESS | SQL_SUCCESS_WITH_INFO
}
//public static class RetCode
//{
// /* RETCODE values */
// public const short SQL_SUCCESS = 0;
// public const short SQL_SUCCESS_WITH_INFO = 1;
// public const short SQL_NEED_DATA = 99;
// public const short SQL_NO_DATA = 100;
// public const short SQL_STILL_EXECUTING = 2;
// public const short SQL_ERROR = -1;
// public const short SQL_INVALID_HANDLE = -2;
//}
/* RETCODE values */
//public const short SQL_SUCCESS = 0;
//public const short SQL_SUCCESS_WITH_INFO = 1;
//public const short SQL_NEED_DATA = 99;
//public const short SQL_NO_DATA = 100;
//public const short SQL_STILL_EXECUTING = 2;
//public const short SQL_ERROR = -1;
//public const short SQL_INVALID_HANDLE = -2;
public const int SQL_NTS = -3;
public const long SQL_NULL_HANDLE = 0L;
public const short SQL_COMMIT = 0;
public const short SQL_ROLLBACK = 1;
public const short SQL_NO_DATA_FOUND = 100;
/* SQLFreeStmt option values */
public const short SQL_CLOSE = 0;
public const short SQL_DROP = 1;
public const short SQL_UNBIND = 2;
public const short SQL_RESET_PARAMS = 3;
/* Isolation levels */
public const long SQL_TXN_READ_UNCOMMITTED = 0x00000001L;
public const long SQL_TXN_READ_COMMITTED = 0x00000002L;
public const long SQL_TXN_REPEATABLE_READ = 0x00000004L;
public const long SQL_TXN_SERIALIZABLE_READ = 0x00000008L;
public const long SQL_TXN_NOCOMMIT = 0x00000020L;
/* Connect options */
public const int SQL_ATTR_TXN_ISOLATION = 108;
public const int SQL_ATTR_AUTOCOMMIT = 102;
public const int SQL_ATTR_LOGIN_TIMEOUT = 103; //CLI not supported
public const int SQL_ATTR_CONNECTION_TIMEOUT = 113; //CLI not supported
/* attribute */
public const int SQL_ATTR_ANSI_APP = 115;
public const int SQL_AA_TRUE = 1; /* the application is an ANSI app */
public const int SQL_AA_FALSE = 0; /* the application is a Unicode app */
public const int SQL_ATTR_CONNECTION_DEAD = 1209; /* GetConnectAttr only */
public const int SQL_CD_TRUE = 1; /* the connection is dead */
public const int SQL_CD_FALSE = 0; /* the connection is not dead */
public const int SQL_ATTR_QUERY_TIMEOUT = 0;
public const int SQL_ATTR_MAX_ROWS = 1;
public const int SQL_ATTR_DEFERRED_PREPARE = 1277;
/*Used for batch operations*/
public const int SQL_ATTR_PARAMSET_SIZE = 22;
public const int SQL_ATTR_PARAM_STATUS_PTR = 20;
public const int SQL_ATTR_PARAMS_PROCESSED_PTR = 21;
public const int SQL_ATTR_PARAM_BIND_TYPE = 18;
/*XML option*/
public const int SQL_ATTR_XML_DECLARATION = 2552;
/*XML option values*/
public const int SQL_XML_DECLARATION_NONE = 0x00000000;
public const int SQL_XML_DECLARATION_BOM = 0x00000001;
public const int SQL_XML_DECLARATION_BASE = 0x00000002;
public const int SQL_XML_DECLARATION_ENCATTR = 0x00000004;
public const int SQL_IS_POINTER = -4;
public const int SQL_IS_UINTEGER = -5;
public const int SQL_IS_INTEGER = -6;
public const int SQL_IS_USMALLINT = -7;
public const int SQL_IS_SMALLINT = -8;
public const long SQL_AUTOCOMMIT_OFF = 0L;
public const long SQL_AUTOCOMMIT_ON = 1L;
/* Data Types */
public const int SQL_UNKNOWN_TYPE = 0;
public const int SQL_CHAR = 1;
public const int SQL_NUMERIC = 2;
public const int SQL_DECIMAL = 3;
public const int SQL_INTEGER = 4;
public const int SQL_SMALLINT = 5;
public const int SQL_FLOAT = 6;
public const int SQL_REAL = 7;
public const int SQL_DOUBLE = 8;
public const int SQL_DATETIME = 9;
public const int SQL_VARCHAR = 12;
public const int SQL_VARBINARY = (-3);
public const int SQL_LONGVARBINARY = (-4);
public const int SQL_BIGINT = (-5);
public const int SQL_BIT = (-7);
public const int SQL_WCHAR = (-8);
public const int SQL_WVARCHAR = (-9);
public const int SQL_WLONGVARCHAR = (-10);
public const int SQL_GUID = (-11);
public const int SQL_UTINYINT = (-28);
public const int SQL_TYPE_DATE = 91;
public const int SQL_TYPE_TIME = 92;
public const int SQL_TYPE_TIMESTAMP = 93;
public const int SQL_TYPE_BINARY = -2;
public const int SQL_GRAPHIC = -95;
public const int SQL_VARGRAPHIC = -96;
public const int SQL_LONGVARGRAPHIC = -97;
public const int SQL_TYPE_BLOB = -98;
public const int SQL_TYPE_CLOB = -99;
public const int SQL_DBCLOB = 350;
public const int SQL_XML = -370;
public const int SQL_C_CHAR = SQL_CHAR;
public const int SQL_C_WCHAR = SQL_WCHAR;
public const int SQL_C_SBIGINT = -25;
public const int SQL_C_SLONG = -16;
public const int SQL_C_SSHORT = -15;
public const int SQL_C_TYPE_BINARY = -2;
public const int SQL_C_DOUBLE = 8;
public const int SQL_C_DECIMAL_IBM = 3;
public const int SQL_C_DECIMAL_OLEDB = 2514;
public const int SQL_C_DEFAULT = 99;
public const int SQL_C_TYPE_DATE = 91;
public const int SQL_C_TYPE_TIME = 92;
public const int SQL_C_TYPE_TIMESTAMP = 93;
public const int SQL_C_TYPE_NUMERIC = 2;
public const int SQL_C_TYPE_REAL = 7;
public const int SQL_BLOB_LOCATOR = 31;
public const int SQL_CLOB_LOCATOR = 41;
public const int SQL_DBCLOB_LOCATOR = -351;
public const int SQL_C_BLOB_LOCATOR = SQL_BLOB_LOCATOR;
public const int SQL_C_CLOB_LOCATOR = SQL_CLOB_LOCATOR;
public const int SQL_C_DBCLOB_LOCATOR = SQL_DBCLOB_LOCATOR;
public const int SQL_USER_DEFINED_TYPE = (-450);
/* Special length values */
public const int SQL_NULL_DATA = -1;
/* SQLDriverConnect Options */
public const int SQL_DRIVER_NOPROMPT = 0;
public const int SQL_DRIVER_COMPLETE = 1;
public const int SQL_DRIVER_PROMPT = 2;
public const int SQL_DRIVER_COMPLETE_REQUIRED = 3;
/* Null settings */
public const int SQL_NO_NULLS = 0;
public const int SQL_NULLABLE = 1;
public const int SQL_NULLABLE_UNKNOWN = 2;
public const int SQL_PARAM_BIND_BY_COLUMN = 0;
/* Defines for SQLBindParameter and SQLProcedureColumns */
public const int SQL_PARAM_TYPE_UNKNOWN = 0;
public const int SQL_PARAM_INPUT = 1;
public const int SQL_PARAM_INPUT_OUTPUT = 2;
public const int SQL_RESULT_COL = 3;
public const int SQL_PARAM_OUTPUT = 4;
public const int SQL_RETURN_VALUE = 5;
/*Defines for SQLColAttributeW*/
public const int SQL_DESC_ALLOC_TYPE = 1099;
public const int SQL_DESC_AUTO_UNIQUE_VALUE = 11;
public const int SQL_DESC_BASE_COLUMN_NAME = 22;
public const int SQL_DESC_BASE_TABLE_NAME = 23;
public const int SQL_DESC_COLUMN_CATALOG_NAME = 17;
public const int SQL_DESC_COLUMN_NAME = 1;
public const int SQL_DESC_SCHEMA_NAME = 16;
public const int SQL_DESC_COLUMN_TABLE_NAME = 15;
public const int SQL_DESC_CONCISE_TYPE = 2;
public const int SQL_DESC_COUNT = 1001;
public const int SQL_DESC_DATA_PTR = 1010;
public const int SQL_DESC_DATETIME_INTERVAL_CODE = 1007;
public const int SQL_DESC_INDICATOR_PTR = 1009;
public const int SQL_DESC_LENGTH = 1003;
public const int SQL_DESC_NAME = 1011;
public const int SQL_DESC_NULLABLE = 1008;
public const int SQL_DESC_OCTET_LENGTH = 1013;
public const int SQL_DESC_OCTET_LENGTH_PTR = 1004;
public const int SQL_DESC_PRECISION = 1005;
public const int SQL_DESC_SCALE = 1006;
public const int SQL_DESC_TYPE = 1002;
public const int SQL_DESC_TYPE_NAME = 14;
public const int SQL_DESC_UNNAMED = 1012;
public const int SQL_DESC_UNSIGNED = 8;
public const int SQL_DESC_UPDATABLE = 10;
/* generally useful constants */
public const int SQL_MAX_DSN_LENGTH = 32; /* maximum data source name size */
public const int SQL_MAX_OPTION_STRING_LENGTH = 256;
public const int SQL_DBMS_NAME = 17;
public const int SQL_DBMS_VER = 18;
public const int SQL_ATTR_TRACE = 104;
public const int SQL_ATTR_OPTIMIZE_FOR_NROWS = 2450;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ReportsOperations.
/// </summary>
public static partial class ReportsOperationsExtensions
{
/// <summary>
/// Lists report records.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
public static IPage<ReportRecordContract> ListByApi(this IReportsOperations operations, ODataQuery<ReportRecordContract> odataQuery, string resourceGroupName, string serviceName)
{
return ((IReportsOperations)operations).ListByApiAsync(odataQuery, resourceGroupName, serviceName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListByApiAsync(this IReportsOperations operations, ODataQuery<ReportRecordContract> odataQuery, string resourceGroupName, string serviceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByApiWithHttpMessagesAsync(odataQuery, resourceGroupName, serviceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by User.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
public static IPage<ReportRecordContract> ListByUser(this IReportsOperations operations, ODataQuery<ReportRecordContract> odataQuery, string resourceGroupName, string serviceName)
{
return operations.ListByUserAsync(odataQuery, resourceGroupName, serviceName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by User.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListByUserAsync(this IReportsOperations operations, ODataQuery<ReportRecordContract> odataQuery, string resourceGroupName, string serviceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByUserWithHttpMessagesAsync(odataQuery, resourceGroupName, serviceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by API Operations.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
public static IPage<ReportRecordContract> ListByOperation(this IReportsOperations operations, ODataQuery<ReportRecordContract> odataQuery, string resourceGroupName, string serviceName)
{
return operations.ListByOperationAsync(odataQuery, resourceGroupName, serviceName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by API Operations.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListByOperationAsync(this IReportsOperations operations, ODataQuery<ReportRecordContract> odataQuery, string resourceGroupName, string serviceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByOperationWithHttpMessagesAsync(odataQuery, resourceGroupName, serviceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by Product.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
public static IPage<ReportRecordContract> ListByProduct(this IReportsOperations operations, ODataQuery<ReportRecordContract> odataQuery, string resourceGroupName, string serviceName)
{
return ((IReportsOperations)operations).ListByProductAsync(odataQuery, resourceGroupName, serviceName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by Product.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListByProductAsync(this IReportsOperations operations, ODataQuery<ReportRecordContract> odataQuery, string resourceGroupName, string serviceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByProductWithHttpMessagesAsync(odataQuery, resourceGroupName, serviceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by GeoGraphy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<ReportRecordContract> ListByGeo(this IReportsOperations operations, string resourceGroupName, string serviceName, ODataQuery<ReportRecordContract> odataQuery = default(ODataQuery<ReportRecordContract>))
{
return operations.ListByGeoAsync(resourceGroupName, serviceName, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by GeoGraphy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListByGeoAsync(this IReportsOperations operations, string resourceGroupName, string serviceName, ODataQuery<ReportRecordContract> odataQuery = default(ODataQuery<ReportRecordContract>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByGeoWithHttpMessagesAsync(resourceGroupName, serviceName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<ReportRecordContract> ListBySubscription(this IReportsOperations operations, string resourceGroupName, string serviceName, ODataQuery<ReportRecordContract> odataQuery = default(ODataQuery<ReportRecordContract>))
{
return operations.ListBySubscriptionAsync(resourceGroupName, serviceName, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListBySubscriptionAsync(this IReportsOperations operations, string resourceGroupName, string serviceName, ODataQuery<ReportRecordContract> odataQuery = default(ODataQuery<ReportRecordContract>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBySubscriptionWithHttpMessagesAsync(resourceGroupName, serviceName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by Time.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='interval'>
/// By time interval. Interval must be multiple of 15 minutes and may not be
/// zero. The value should be in ISO 8601 format
/// (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to
/// convert TimeSpan to a valid interval string: XmlConvert.ToString(new
/// TimeSpan(hours, minutes, secconds))
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<ReportRecordContract> ListByTime(this IReportsOperations operations, string resourceGroupName, string serviceName, System.TimeSpan interval, ODataQuery<ReportRecordContract> odataQuery = default(ODataQuery<ReportRecordContract>))
{
return operations.ListByTimeAsync(resourceGroupName, serviceName, interval, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by Time.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='interval'>
/// By time interval. Interval must be multiple of 15 minutes and may not be
/// zero. The value should be in ISO 8601 format
/// (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to
/// convert TimeSpan to a valid interval string: XmlConvert.ToString(new
/// TimeSpan(hours, minutes, secconds))
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListByTimeAsync(this IReportsOperations operations, string resourceGroupName, string serviceName, System.TimeSpan interval, ODataQuery<ReportRecordContract> odataQuery = default(ODataQuery<ReportRecordContract>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByTimeWithHttpMessagesAsync(resourceGroupName, serviceName, interval, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by Request.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
public static IEnumerable<RequestReportRecordContract> ListByRequest(this IReportsOperations operations, ODataQuery<RequestReportRecordContract> odataQuery, string resourceGroupName, string serviceName)
{
return operations.ListByRequestAsync(odataQuery, resourceGroupName, serviceName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by Request.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<RequestReportRecordContract>> ListByRequestAsync(this IReportsOperations operations, ODataQuery<RequestReportRecordContract> odataQuery, string resourceGroupName, string serviceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByRequestWithHttpMessagesAsync(odataQuery, resourceGroupName, serviceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ReportRecordContract> ListByApiNext(this IReportsOperations operations, string nextPageLink)
{
return operations.ListByApiNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListByApiNextAsync(this IReportsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByApiNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by User.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ReportRecordContract> ListByUserNext(this IReportsOperations operations, string nextPageLink)
{
return operations.ListByUserNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by User.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListByUserNextAsync(this IReportsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByUserNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by API Operations.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ReportRecordContract> ListByOperationNext(this IReportsOperations operations, string nextPageLink)
{
return operations.ListByOperationNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by API Operations.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListByOperationNextAsync(this IReportsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByOperationNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by Product.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ReportRecordContract> ListByProductNext(this IReportsOperations operations, string nextPageLink)
{
return operations.ListByProductNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by Product.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListByProductNextAsync(this IReportsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByProductNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by GeoGraphy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ReportRecordContract> ListByGeoNext(this IReportsOperations operations, string nextPageLink)
{
return operations.ListByGeoNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by GeoGraphy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListByGeoNextAsync(this IReportsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByGeoNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ReportRecordContract> ListBySubscriptionNext(this IReportsOperations operations, string nextPageLink)
{
return operations.ListBySubscriptionNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListBySubscriptionNextAsync(this IReportsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBySubscriptionNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists report records by Time.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ReportRecordContract> ListByTimeNext(this IReportsOperations operations, string nextPageLink)
{
return operations.ListByTimeNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists report records by Time.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ReportRecordContract>> ListByTimeNextAsync(this IReportsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByTimeNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Linq;
namespace HTLib2
{
public static partial class LinAlg
{
static bool Eye_SelfTest = HDebug.IsDebuggerAttached;
public static MatrixByArr Eye(int size, double diagval=1)
{
if(Eye_SelfTest)
{
Eye_SelfTest = false;
MatrixByArr tT0 = new double[3, 3] { { 2, 0, 0 }, { 0, 2, 0 }, { 0, 0, 2 }, };
MatrixByArr tT1 = Eye(3, 2);
HDebug.AssertTolerance(double.Epsilon, tT0 - tT1);
}
MatrixByArr mat = new MatrixByArr(size,size);
for(int i=0; i<size; i++)
mat[i, i] = diagval;
return mat;
}
static bool Tr_SelfTest = HDebug.IsDebuggerAttached;
public static Matrix Tr(this Matrix M)
{
if(Tr_SelfTest)
{
Tr_SelfTest = false;
Matrix tM0 = new double[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
Matrix tT0 = new double[3, 2] { { 1, 4 }, { 2, 5 }, { 3, 6 } };
Matrix tT1 = Tr(tM0);
HDebug.AssertToleranceMatrix(double.Epsilon, tT0 - tT1);
}
Matrix tr = Matrix.Zeros(M.RowSize, M.ColSize);
for(int c=0; c<tr.ColSize; c++)
for(int r=0; r<tr.RowSize; r++)
tr[c, r] = M[r, c];
return tr;
}
static bool Diagd_SelfTest = HDebug.IsDebuggerAttached;
public static MatrixByArr Diag(this Vector d)
{
if(Diagd_SelfTest)
{
Diagd_SelfTest = false;
MatrixByArr tD1 = new double[3, 3] { { 1, 0, 0 }, { 0, 2, 0 }, { 0, 0, 3 } };
Vector td1 = new double[3] { 1, 2, 3 };
MatrixByArr tD = Diag(td1);
HDebug.AssertTolerance(double.Epsilon, tD - tD1);
}
int size = d.Size;
MatrixByArr D = new MatrixByArr(size, size);
for(int i=0; i < size; i++)
D[i, i] = d[i];
return D;
}
static bool DiagD_SelfTest = HDebug.IsDebuggerAttached;
public static Vector Diag(this Matrix D)
{
if(DiagD_SelfTest)
{
DiagD_SelfTest = false;
MatrixByArr tD1 = new double[3, 3] { { 1, 0, 0 }, { 0, 2, 0 }, { 0, 0, 3 } };
Vector td1 = new double[3] { 1, 2, 3 };
Vector td = Diag(tD1);
HDebug.AssertTolerance(double.Epsilon, td - td1);
}
HDebug.Assert(D.ColSize == D.RowSize);
int size = D.ColSize;
Vector d = new double[size];
for(int i=0; i<size; i++)
d[i] = D[i,i];
return d;
}
static bool DV_SelfTest1 = HDebug.IsDebuggerAttached;
public static Vector DV(Matrix D, Vector V, bool assertDiag = true)
{
if(DV_SelfTest1)
{
DV_SelfTest1 = false;
MatrixByArr tD = new double[3, 3] { { 1, 0, 0 }, { 0, 2, 0 }, { 0, 0, 3 } };
Vector tV = new double[3] { 1, 2, 3 };
Vector tDV = new double[3] { 1, 4, 9 };
// [1 0 0] [1] [1]
// [0 2 0] * [2] = [4]
// [0 0 3] [3] [9]
HDebug.AssertTolerance(double.Epsilon, DV(tD, tV) - tDV);
}
// D is the diagonal matrix
HDebug.Assert(D.ColSize == D.RowSize);
if(assertDiag) // check diagonal matrix
HDebug.AssertToleranceMatrix(double.Epsilon, D - Diag(Diag(D)));
HDebug.Assert(D.ColSize == V.Size);
Vector diagD = Diag(D);
Vector diagDV = DV(diagD, V);
return diagDV;
}
static bool DV_SelfTest2 = HDebug.IsDebuggerAttached;
public static Vector DV(Vector D, Vector V, bool assertDiag = true)
{
if(DV_SelfTest2)
{
DV_SelfTest2 = false;
Vector tD = new double[3] { 1, 2, 3 };
Vector tV = new double[3] { 1, 2, 3 };
Vector tDV = new double[3] { 1, 4, 9 };
// [1 0 0] [1] [1]
// [0 2 0] * [2] = [4]
// [0 0 3] [3] [9]
HDebug.AssertTolerance(double.Epsilon, DV(tD, tV) - tDV);
}
// D is the diagonal matrix
HDebug.Assert(D.Size == V.Size);
int size = V.Size;
Vector dv = new double[size];
for(int i=0; i < size; i++)
dv[i] = D[i] * V[i];
return dv;
}
static bool MD_SelfTest = HDebug.IsDebuggerAttached;
public static MatrixByArr MD(MatrixByArr M, Vector D)
{ // M * Diag(D)
if(MD_SelfTest)
{
MD_SelfTest = false;
MatrixByArr tM = new double[3, 3] { { 1, 2, 3 }
, { 4, 5, 6 }
, { 7, 8, 9 } };
Vector tD = new double[3] { 1, 2, 3 };
MatrixByArr tMD0 = new double[3, 3] { { 1, 4, 9 }
, { 4, 10, 18 }
, { 7, 16, 27 } };
MatrixByArr tMD1 = MD(tM, tD);
MatrixByArr dtMD = tMD0 - tMD1;
double maxAbsDtMD = dtMD.ToArray().HAbs().HMax();
Debug.Assert(maxAbsDtMD == 0);
}
HDebug.Assert(M.RowSize == D.Size);
MatrixByArr lMD = new double[M.ColSize, M.RowSize];
for(int c=0; c<lMD.ColSize; c++)
for(int r=0; r<lMD.RowSize; r++)
lMD[c, r] = M[c, r] * D[r];
return lMD;
}
static bool MV_SelfTest = HDebug.IsDebuggerAttached;
static bool MV_SelfTest_lmat_rvec = HDebug.IsDebuggerAttached;
public static Vector MV<MATRIX>(MATRIX lmat, Vector rvec, string options="")
where MATRIX : IMatrix<double>
{
Vector result = new Vector(lmat.ColSize);
MV(lmat, rvec, result, options);
if(MV_SelfTest_lmat_rvec)
{
MV_SelfTest_lmat_rvec = false;
HDebug.Assert(lmat.RowSize == rvec.Size);
Vector lresult = new Vector(lmat.ColSize);
for(int c=0; c<lmat.ColSize; c++)
for(int r=0; r<lmat.RowSize; r++)
lresult[c] += lmat[c, r] * rvec[r];
HDebug.AssertTolerance(double.Epsilon, lresult-result);
}
return result;
}
public static void MV<MATRIX>(MATRIX lmat, Vector rvec, Vector result, string options="")
where MATRIX : IMatrix<double>
{
if(MV_SelfTest)
{
MV_SelfTest = false;
MatrixByArr tM = new double[4, 3] { { 1, 2, 3 }
, { 4, 5, 6 }
, { 7, 8, 9 }
, { 10, 11, 12 } };
Vector tV = new double[3] { 1, 2, 3 };
Vector tMV0 = new double[4] { 14, 32, 50, 68 };
Vector tMV1 = MV(tM, tV);
double err = (tMV0 - tMV1).ToArray().HAbs().Max();
HDebug.Assert(err == 0);
}
HDebug.Assert(lmat.RowSize == rvec.Size);
HDebug.Assert(lmat.ColSize == result.Size);
if(options.Split(';').Contains("parallel") == false)
{
for(int c=0; c<lmat.ColSize; c++)
for(int r=0; r<lmat.RowSize; r++)
result[c] += lmat[c, r] * rvec[r];
}
else
{
System.Threading.Tasks.Parallel.For(0, lmat.ColSize, delegate(int c)
{
for(int r=0; r<lmat.RowSize; r++)
result[c] += lmat[c, r] * rvec[r];
});
}
}
//static bool MtM_SelfTest = HDebug.IsDebuggerAttached;
public static Matrix MtM(Matrix lmat, Matrix rmat)
{
bool MtM_SelfTest = false;//HDebug.IsDebuggerAttached;
if(MtM_SelfTest)
{
MtM_SelfTest = false;
/// >> A=[ 1,5 ; 2,6 ; 3,7 ; 4,8 ];
/// >> B=[ 1,2,3 ; 3,4,5 ; 5,6,7 ; 7,8,9 ];
/// >> A'*B
/// ans =
/// 50 60 70
/// 114 140 166
Matrix _A = new double[4, 2] {{ 1,5 },{ 2,6 },{ 3,7 },{ 4,8 }};
Matrix _B = new double[4, 3] {{ 1,2,3 },{ 3,4,5 },{ 5,6,7 },{ 7,8,9 }};
Matrix _AtB = MtM(_A, _B);
Matrix _AtB_sol = new double[2,3]
{ { 50, 60, 70 }
, { 114, 140, 166 } };
double err = (_AtB - _AtB_sol).HAbsMax();
HDebug.Assert(err == 0);
}
HDebug.Assert(lmat.ColSize == rmat.ColSize);
int size1 = lmat.RowSize;
int size2 = rmat.ColSize;
int size3 = rmat.RowSize;
Matrix result = Matrix.Zeros(size1, size3);
for(int c=0; c<size1; c++)
for(int r=0; r<size3; r++)
{
double sum = 0;
for(int i=0; i<size2; i++)
// tr(lmat[c,i]) * rmat[i,r] => lmat[i,c] * rmat[i,r]
sum += lmat[i,c] * rmat[i,r];
result[c, r] = sum;
}
return result;
}
//static bool MMt_SelfTest = HDebug.IsDebuggerAttached;
public static Matrix MMt(Matrix lmat, Matrix rmat)
{
bool MMt_SelfTest = false;//HDebug.IsDebuggerAttached;
if(MMt_SelfTest)
{
MMt_SelfTest = false;
/// >> A=[ 1,2,3,4 ; 5,6,7,8 ];
/// >> B=[ 1,3,5,7 ; 2,4,6,8 ; 3,5,7,9 ];
/// >> A*B'
/// ans =
/// 50 60 70
/// 114 140 166
Matrix _A = new double[2, 4]
{ { 1, 2, 3, 4 }
, { 5, 6, 7, 8 } };
Matrix _B = new double[3, 4]
{ { 1, 3, 5, 7 }
, { 2, 4, 6, 8 }
, { 3, 5, 7, 9 } };
Matrix _AtB = MMt(_A, _B);
Matrix _AtB_sol = new double[2,3]
{ { 50, 60, 70 }
, { 114, 140, 166 } };
double err = (_AtB - _AtB_sol).HAbsMax();
HDebug.Assert(err == 0);
}
HDebug.Assert(lmat.RowSize == rmat.RowSize);
int size1 = lmat.ColSize;
int size2 = lmat.RowSize;
int size3 = rmat.ColSize;
Matrix result = Matrix.Zeros(size1, size3);
for(int c=0; c<size1; c++)
for(int r=0; r<size3; r++)
{
double sum = 0;
for(int i=0; i<size2; i++)
// lmat[c,i] * tr(rmat[i,r]) => lmat[c,i] * rmat[r,i]
sum += lmat[c,i] * rmat[r,i];
result[c, r] = sum;
}
return result;
}
static bool MtV_SelfTest = HDebug.IsDebuggerAttached;
public static Vector MtV(Matrix lmat, Vector rvec)
{
if(MtV_SelfTest)
{
MtV_SelfTest = false;
/// >> A = [ 1,2,3 ; 4,5,6 ; 7,8,9 ; 10,11,12 ];
/// >> B = [ 1; 2; 3; 4 ];
/// >> A'*B
/// ans =
/// 70
/// 80
/// 90
MatrixByArr tM = new double[4, 3] { { 1, 2, 3 }
, { 4, 5, 6 }
, { 7, 8, 9 }
, { 10, 11, 12 } };
Vector tV = new double[4] { 1, 2, 3, 4 };
Vector tMtV0 = new double[3] { 70, 80, 90 };
Vector tMtV1 = MtV(tM, tV);
double err = (tMtV0 - tMtV1).ToArray().HAbs().Max();
HDebug.Assert(err == 0);
}
HDebug.Assert(lmat.ColSize == rvec.Size);
Vector result = new Vector(lmat.RowSize);
for(int c=0; c<lmat.ColSize; c++)
for(int r=0; r<lmat.RowSize; r++)
result[r] += lmat[c, r] * rvec[c];
return result;
}
public static bool V1tD2V3_SelfTest = HDebug.IsDebuggerAttached;
public static double V1tD2V3(Vector V1, Matrix D2, Vector V3, bool assertDiag=true)
{
if(V1tD2V3_SelfTest)
{
V1tD2V3_SelfTest = false;
Vector tV1 = new double[3] { 1, 2, 3 };
MatrixByArr tD2 = new double[3, 3] { { 2, 0, 0 }, { 0, 3, 0 }, { 0, 0, 4 } };
Vector tV3 = new double[3] { 3, 4, 5 };
// [2 ] [3] [ 6]
// [1 2 3] * [ 3 ] * [4] = [1 2 3] * [12] = 6+24+60 = 90
// [ 4] [5] [20]
double tV1tD2V3 = 90;
HDebug.AssertTolerance(double.Epsilon, tV1tD2V3 - V1tD2V3(tV1, tD2, tV3));
}
if(assertDiag) // check diagonal matrix
HDebug.AssertToleranceMatrix(double.Epsilon, D2 - Diag(Diag(D2)));
HDebug.Assert(V1.Size == D2.ColSize);
HDebug.Assert(D2.RowSize == V3.Size );
Vector lD2V3 = DV(D2, V3, assertDiag);
double lV1tD2V3 = VtV(V1, lD2V3);
return lV1tD2V3;
}
public static MatrixByArr VVt(Vector lvec, Vector rvec)
{
MatrixByArr outmat = new MatrixByArr(lvec.Size, rvec.Size);
VVt(lvec, rvec, outmat);
return outmat;
}
public static void VVt(Vector lvec, Vector rvec, MatrixByArr outmat)
{
HDebug.Exception(outmat.ColSize == lvec.Size);
HDebug.Exception(outmat.RowSize == rvec.Size);
//MatrixByArr mat = new MatrixByArr(lvec.Size, rvec.Size);
for(int c = 0; c < lvec.Size; c++)
for(int r = 0; r < rvec.Size; r++)
outmat[c, r] = lvec[c] * rvec[r];
}
public static void VVt_AddTo(Vector lvec, Vector rvec, MatrixByArr mat)
{
HDebug.Exception(mat.ColSize == lvec.Size);
HDebug.Exception(mat.RowSize == rvec.Size);
for(int c = 0; c < lvec.Size; c++)
for(int r = 0; r < rvec.Size; r++)
mat[c, r] += lvec[c] * rvec[r];
}
public static void sVVt_AddTo(double scale, Vector lvec, Vector rvec, MatrixByArr mat)
{
HDebug.Exception(mat.ColSize == lvec.Size);
HDebug.Exception(mat.RowSize == rvec.Size);
for(int c = 0; c < lvec.Size; c++)
for(int r = 0; r < rvec.Size; r++)
mat[c, r] += lvec[c] * rvec[r] * scale;
}
public static bool DMD_selftest = HDebug.IsDebuggerAttached;
public static MATRIX DMD<MATRIX>(Vector diagmat1, MATRIX mat,Vector diagmat2, Func<int,int,MATRIX> Zeros)
where MATRIX : IMatrix<double>
{
if(DMD_selftest)
#region selftest
{
HDebug.ToDo("check");
DMD_selftest = false;
Vector td1 = new double[] { 1, 2, 3 };
Vector td2 = new double[] { 4, 5, 6 };
Matrix tm = new double[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Matrix dmd0 = LinAlg.Diag(td1) * tm * LinAlg.Diag(td2);
Matrix dmd1 = LinAlg.DMD(td1, tm, td2, Matrix.Zeros);
double err = (dmd0 - dmd1).HAbsMax();
HDebug.Assert(err == 0);
}
#endregion
MATRIX DMD = Zeros(mat.ColSize, mat.RowSize);
for(int c=0; c<mat.ColSize; c++)
for(int r=0; r<mat.RowSize; r++)
{
double v0 = mat[c, r];
double v1 = diagmat1[c] * v0 * diagmat2[r];
if(v0 == v1) continue;
DMD[c, r] = v1;
}
return DMD;
}
//public static bool VtMV_selftest = HDebug.IsDebuggerAttached;
public static double VtMV(Vector lvec, IMatrix<double> mat, Vector rvec) //, string options="")
{
if(HDebug.Selftest())
{
Vector _lvec = new double[3] { 1, 2, 3 };
Matrix _mat = new double[3,4] { { 4, 5, 6, 7 }
, { 8, 9, 10, 11 }
, { 12, 13, 14, 15 }
};
Vector _rvec = new double[4] { 16, 17, 18, 19 };
double _v0 = VtMV(_lvec,_mat,_rvec);
double _v1 = 4580;
HDebug.Assert(_v0 == _v1);
}
HDebug.Assert(lvec.Size == mat.ColSize);
HDebug.Assert(mat.RowSize == rvec.Size);
double ret = 0;
for(int c=0; c<lvec.Size; c++)
for(int r=0; r<rvec.Size; r++)
ret += lvec[c] * mat[c,r] * rvec[r];
return ret;
// Vector MV = LinAlg.MV(mat, rvec, options);
// double VMV = LinAlg.VtV(lvec, MV);
// //Debug.AssertToleranceIf(lvec.Size<100, 0.00000001, Vector.VtV(lvec, Vector.MV(mat, rvec)) - VMV);
// return VMV;
}
public static MatrixByArr M_Mt(MatrixByArr lmat, MatrixByArr rmat)
{
// M + Mt
HDebug.Assert(lmat.ColSize == rmat.RowSize);
HDebug.Assert(lmat.RowSize == rmat.ColSize);
MatrixByArr MMt = lmat.CloneT();
for(int c = 0; c < MMt.ColSize; c++)
for(int r = 0; r < MMt.RowSize; r++)
MMt[c, r] += rmat[r, c];
return MMt;
}
public static double VtV(Vector l, Vector r)
{
HDebug.Assert(l.Size == r.Size);
int size = l.Size;
double result = 0;
for(int i=0; i < size; i++)
result += l[i] * r[i];
return result;
}
public static double[] ListVtV(Vector l, IList<Vector> rs)
{
double[] listvtv = new double[rs.Count];
for(int i=0; i<rs.Count; i++)
listvtv[i] = VtV(l, rs[i]);
return listvtv;
}
public static double VtV(Vector l, Vector r, IList<int> idxsele)
{
HDebug.Assert(l.Size == r.Size);
Vector ls = l.ToArray().HSelectByIndex(idxsele);
Vector rs = r.ToArray().HSelectByIndex(idxsele);
return VtV(ls, rs);
}
public static Vector VtMM(Vector v1, Matrix m2, Matrix m3)
{
Vector v12 = VtM(v1, m2);
return VtM(v12, m3);
}
public static class AddToM
{
public static void VVt(Matrix M, Vector V)
{
HDebug.Assert(M.ColSize == V.Size);
HDebug.Assert(M.RowSize == V.Size);
int size = V.Size;
for(int c=0; c<size; c++)
for(int r=0; r<size; r++)
M[c, r] += V[c] * V[r];
}
}
public static Vector VtM<MATRIX>(Vector lvec, MATRIX rmat)
where MATRIX : IMatrix<double>
{
HDebug.Assert(lvec.Size == rmat.ColSize);
Vector result = new Vector(rmat.RowSize);
for(int c=0; c<rmat.ColSize; c++)
for(int r=0; r<rmat.RowSize; r++)
result[r] += lvec[c] * rmat[c, r];
return result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Diagnostics;
using System.Data.SqlClient;
using System.Reflection;
namespace System.Data.Common
{
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 Convert.ToBoolean(value);
}
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 Convert.ToBoolean(value);
}
catch (InvalidCastException e)
{
throw ADP.ConvertFailed(value.GetType(), typeof(Boolean), e);
}
}
internal static int ConvertToInt32(object value)
{
try
{
return Convert.ToInt32(value);
}
catch (InvalidCastException e)
{
throw ADP.ConvertFailed(value.GetType(), typeof(Int32), e);
}
}
internal static string ConvertToString(object value)
{
try
{
return Convert.ToString(value);
}
catch (InvalidCastException e)
{
throw ADP.ConvertFailed(value.GetType(), typeof(String), e);
}
}
private const string ApplicationIntentReadWriteString = "ReadWrite";
private 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().GetTypeInfo().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 = "";
// SqlClient
internal const ApplicationIntent ApplicationIntent = System.Data.SqlClient.ApplicationIntent.ReadWrite;
internal const string ApplicationName = "Core .Net SqlClient Data Provider";
internal const string AttachDBFilename = "";
internal const int ConnectTimeout = 15;
internal const string CurrentLanguage = "";
internal const string DataSource = "";
internal const bool Encrypt = false;
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 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 DbConnectionStringKeywords
{
// all
// internal const string NamedConnection = "Named Connection";
// 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 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";
}
}
| |
//
// 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.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing API Policy.
/// </summary>
internal partial class ApiPolicyOperations : IServiceOperations<ApiManagementClient>, IApiPolicyOperations
{
/// <summary>
/// Initializes a new instance of the ApiPolicyOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ApiPolicyOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Deletes specific API policy of the Api Management service instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string aid, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (aid == null)
{
throw new ArgumentNullException("aid");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("aid", aid);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/apis/";
url = url + Uri.EscapeDataString(aid);
url = url + "/policy";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-10-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets specific API policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='format'>
/// Required. Format of the policy. Supported formats:
/// application/vnd.ms-azure-apim.policy+xml,
/// application/vnd.ms-azure-apim.policy.raw+xml
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get policy output operation.
/// </returns>
public async Task<PolicyGetResponse> GetAsync(string resourceGroupName, string serviceName, string aid, string format, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (aid == null)
{
throw new ArgumentNullException("aid");
}
if (format == null)
{
throw new ArgumentNullException("format");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("aid", aid);
tracingParameters.Add("format", format);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/apis/";
url = url + Uri.EscapeDataString(aid);
url = url + "/policy";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-10-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", format);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
PolicyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new PolicyGetResponse();
result.PolicyBytes = Encoding.UTF8.GetBytes(responseContent);
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Sets policy for API.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='format'>
/// Required. Format of the policy. Supported formats:
/// application/vnd.ms-azure-apim.policy+xml,
/// application/vnd.ms-azure-apim.policy.raw+xml
/// </param>
/// <param name='policyStream'>
/// Required. Policy stream.
/// </param>
/// <param name='etag'>
/// Optional. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> SetAsync(string resourceGroupName, string serviceName, string aid, string format, Stream policyStream, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (aid == null)
{
throw new ArgumentNullException("aid");
}
if (format == null)
{
throw new ArgumentNullException("format");
}
if (policyStream == null)
{
throw new ArgumentNullException("policyStream");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("aid", aid);
tracingParameters.Add("format", format);
tracingParameters.Add("policyStream", policyStream);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "SetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/apis/";
url = url + Uri.EscapeDataString(aid);
url = url + "/policy";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-10-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
Stream requestContent = policyStream;
httpRequest.Content = new StreamContent(requestContent);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(format);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.MembershipService;
using Orleans.Providers;
using System.Collections.Generic;
namespace Orleans.Hosting
{
public static class LegacyClusterConfigurationExtensions
{
/// <summary>
/// Specifies the configuration to use for this silo.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <param name="configuration">The configuration.</param>
/// <remarks>This method may only be called once per builder instance.</remarks>
/// <returns>The silo builder.</returns>
public static ISiloHostBuilder UseConfiguration(this ISiloHostBuilder builder, ClusterConfiguration configuration)
{
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
return builder.AddLegacyClusterConfigurationSupport(configuration);
}
/// <summary>
/// Loads <see cref="ClusterConfiguration"/> using <see cref="ClusterConfiguration.StandardLoad"/>.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <returns>The silo builder.</returns>
public static ISiloHostBuilder LoadClusterConfiguration(this ISiloHostBuilder builder)
{
var configuration = new ClusterConfiguration();
configuration.StandardLoad();
return builder.UseConfiguration(configuration);
}
/// <summary>
/// Configures a localhost silo.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <param name="siloPort">The silo-to-silo communication port.</param>
/// <param name="gatewayPort">The client-to-silo communication port.</param>
/// <returns>The silo builder.</returns>
public static ISiloHostBuilder ConfigureLocalHostPrimarySilo(this ISiloHostBuilder builder, int siloPort = 22222, int gatewayPort = 40000)
{
builder.ConfigureSiloName(Silo.PrimarySiloName);
return builder.UseConfiguration(ClusterConfiguration.LocalhostPrimarySilo(siloPort, gatewayPort));
}
public static ISiloHostBuilder AddLegacyClusterConfigurationSupport(this ISiloHostBuilder builder, ClusterConfiguration configuration)
{
LegacyMembershipConfigurator.ConfigureServices(configuration.Globals, builder);
LegacyRemindersConfigurator.Configure(configuration.Globals, builder);
return builder.ConfigureServices(services => AddLegacyClusterConfigurationSupport(services, configuration));
}
private static void AddLegacyClusterConfigurationSupport(IServiceCollection services, ClusterConfiguration configuration)
{
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
if (services.TryGetClusterConfiguration() != null)
{
throw new InvalidOperationException("Cannot configure legacy ClusterConfiguration support twice");
}
// these will eventually be removed once our code doesn't depend on the old ClientConfiguration
services.AddSingleton(configuration);
services.TryAddSingleton<LegacyConfigurationWrapper>();
services.TryAddSingleton(sp => sp.GetRequiredService<LegacyConfigurationWrapper>().ClusterConfig.Globals);
services.TryAddTransient(sp => sp.GetRequiredService<LegacyConfigurationWrapper>().NodeConfig);
services.TryAddSingleton<Factory<NodeConfiguration>>(
sp =>
{
var initializationParams = sp.GetRequiredService<LegacyConfigurationWrapper>();
return () => initializationParams.NodeConfig;
});
services.Configure<ClusterOptions>(options =>
{
if (string.IsNullOrWhiteSpace(options.ClusterId) && !string.IsNullOrWhiteSpace(configuration.Globals.ClusterId))
{
options.ClusterId = configuration.Globals.ClusterId;
}
if (options.ServiceId == Guid.Empty)
{
options.ServiceId = configuration.Globals.ServiceId;
}
});
services.Configure<MultiClusterOptions>(options =>
{
var globals = configuration.Globals;
if (globals.HasMultiClusterNetwork)
{
options.HasMultiClusterNetwork = true;
options.BackgroundGossipInterval = globals.BackgroundGossipInterval;
options.DefaultMultiCluster = globals.DefaultMultiCluster?.ToList();
options.GlobalSingleInstanceNumberRetries = globals.GlobalSingleInstanceNumberRetries;
options.GlobalSingleInstanceRetryInterval = globals.GlobalSingleInstanceRetryInterval;
options.MaxMultiClusterGateways = globals.MaxMultiClusterGateways;
options.UseGlobalSingleInstanceByDefault = globals.UseGlobalSingleInstanceByDefault;
foreach(GlobalConfiguration.GossipChannelConfiguration channelConfig in globals.GossipChannels)
{
options.GossipChannels.Add(GlobalConfiguration.Remap(channelConfig.ChannelType), channelConfig.ConnectionString);
}
}
});
services.TryAddFromExisting<IMessagingConfiguration, GlobalConfiguration>();
services.AddOptions<SiloStatisticsOptions>()
.Configure<NodeConfiguration>((options, nodeConfig) => LegacyConfigurationExtensions.CopyStatisticsOptions(nodeConfig, options))
.Configure<GlobalConfiguration>((options, config) =>
{
options.DeploymentLoadPublisherRefreshTime = config.DeploymentLoadPublisherRefreshTime;
});
services.AddOptions<LoadSheddingOptions>()
.Configure<NodeConfiguration>((options, nodeConfig) =>
{
options.LoadSheddingEnabled = nodeConfig.LoadSheddingEnabled;
options.LoadSheddingLimit = nodeConfig.LoadSheddingLimit;
});
// Translate legacy configuration to new Options
services.AddOptions<SiloMessagingOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
LegacyConfigurationExtensions.CopyCommonMessagingOptions(config, options);
options.SiloSenderQueues = config.SiloSenderQueues;
options.GatewaySenderQueues = config.GatewaySenderQueues;
options.MaxForwardCount = config.MaxForwardCount;
options.ClientDropTimeout = config.ClientDropTimeout;
options.ClientRegistrationRefresh = config.ClientRegistrationRefresh;
options.MaxRequestProcessingTime = config.MaxRequestProcessingTime;
options.AssumeHomogenousSilosForTesting = config.AssumeHomogenousSilosForTesting;
})
.Configure<NodeConfiguration>((options, config) =>
{
options.PropagateActivityId = config.PropagateActivityId;
LimitValue requestLimit = config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS);
options.MaxEnqueuedRequestsSoftLimit = requestLimit.SoftLimitThreshold;
options.MaxEnqueuedRequestsHardLimit = requestLimit.HardLimitThreshold;
LimitValue statelessWorkerRequestLimit = config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER);
options.MaxEnqueuedRequestsSoftLimit_StatelessWorker = statelessWorkerRequestLimit.SoftLimitThreshold;
options.MaxEnqueuedRequestsHardLimit_StatelessWorker = statelessWorkerRequestLimit.HardLimitThreshold;
});
services.Configure<NetworkingOptions>(options => LegacyConfigurationExtensions.CopyNetworkingOptions(configuration.Globals, options));
services.AddOptions<EndpointOptions>()
.Configure<IOptions<SiloOptions>>((options, siloOptions) =>
{
var nodeConfig = configuration.GetOrCreateNodeConfigurationForSilo(siloOptions.Value.SiloName);
if (!string.IsNullOrEmpty(nodeConfig.HostNameOrIPAddress) || nodeConfig.Port != 0)
{
options.AdvertisedIPAddress = nodeConfig.Endpoint.Address;
options.SiloPort = nodeConfig.Endpoint.Port;
}
});
services.Configure<SerializationProviderOptions>(options =>
{
options.SerializationProviders = configuration.Globals.SerializationProviders;
options.FallbackSerializationProvider = configuration.Globals.FallbackSerializationProvider;
});
services.Configure<TelemetryOptions>(options =>
{
LegacyConfigurationExtensions.CopyTelemetryOptions(configuration.Defaults.TelemetryConfiguration, services, options);
});
services.AddOptions<GrainClassOptions>().Configure<IOptions<SiloOptions>>((options, siloOptions) =>
{
var nodeConfig = configuration.GetOrCreateNodeConfigurationForSilo(siloOptions.Value.SiloName);
options.ExcludedGrainTypes.AddRange(nodeConfig.ExcludedGrainTypes);
});
services.AddOptions<SchedulingOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.AllowCallChainReentrancy = config.AllowCallChainReentrancy;
options.PerformDeadlockDetection = config.PerformDeadlockDetection;
})
.Configure<NodeConfiguration>((options, nodeConfig) =>
{
options.MaxActiveThreads = nodeConfig.MaxActiveThreads;
options.DelayWarningThreshold = nodeConfig.DelayWarningThreshold;
options.ActivationSchedulingQuantum = nodeConfig.ActivationSchedulingQuantum;
options.TurnWarningLengthThreshold = nodeConfig.TurnWarningLengthThreshold;
options.EnableWorkerThreadInjection = nodeConfig.EnableWorkerThreadInjection;
LimitValue itemLimit = nodeConfig.LimitManager.GetLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS);
options.MaxPendingWorkItemsSoftLimit = itemLimit.SoftLimitThreshold;
options.MaxPendingWorkItemsHardLimit = itemLimit.HardLimitThreshold;
});
services.AddOptions<GrainCollectionOptions>().Configure<GlobalConfiguration>((options, config) =>
{
options.CollectionQuantum = config.CollectionQuantum;
options.CollectionAge = config.Application.DefaultCollectionAgeLimit;
foreach (GrainTypeConfiguration grainConfig in config.Application.ClassSpecific)
{
if(grainConfig.CollectionAgeLimit.HasValue)
{
options.ClassSpecificCollectionAge.Add(grainConfig.FullTypeName, grainConfig.CollectionAgeLimit.Value);
}
};
});
LegacyProviderConfigurator<ISiloLifecycle>.ConfigureServices(configuration.Globals.ProviderConfigurations, services);
if (!string.IsNullOrWhiteSpace(configuration.Globals.DefaultPlacementStrategy))
{
services.AddSingleton(typeof(PlacementStrategy), MapDefaultPlacementStrategy(configuration.Globals.DefaultPlacementStrategy));
}
services.AddOptions<ActivationCountBasedPlacementOptions>().Configure<GlobalConfiguration>((options, config) =>
{
options.ChooseOutOf = config.ActivationCountBasedPlacementChooseOutOf;
});
services.AddOptions<StaticClusterDeploymentOptions>().Configure<ClusterConfiguration>((options, config) =>
{
options.SiloNames = config.Overrides.Keys.ToList();
});
// add grain service configs as keyed services
short id = 0;
foreach (IGrainServiceConfiguration grainServiceConfiguration in configuration.Globals.GrainServiceConfigurations.GrainServices.Values)
{
services.AddSingletonKeyedService<long, IGrainServiceConfiguration>(id++, (sp, k) => grainServiceConfiguration);
}
// populate grain service options
id = 0;
services.AddOptions<GrainServiceOptions>().Configure<GlobalConfiguration>((options, config) =>
{
foreach(IGrainServiceConfiguration grainServiceConfiguration in config.GrainServiceConfigurations.GrainServices.Values)
{
options.GrainServices.Add(new KeyValuePair<string, short>(grainServiceConfiguration.ServiceType, id++));
}
});
services.AddOptions<ConsistentRingOptions>().Configure<GlobalConfiguration>((options, config) =>
{
options.UseVirtualBucketsConsistentRing = config.UseVirtualBucketsConsistentRing;
options.NumVirtualBucketsConsistentRing = config.NumVirtualBucketsConsistentRing;
});
services.AddOptions<ClusterMembershipOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.NumMissedTableIAmAliveLimit = config.NumMissedTableIAmAliveLimit;
options.LivenessEnabled = config.LivenessEnabled;
options.ProbeTimeout = config.ProbeTimeout;
options.TableRefreshTimeout = config.TableRefreshTimeout;
options.DeathVoteExpirationTimeout = config.DeathVoteExpirationTimeout;
options.IAmAliveTablePublishTimeout = config.IAmAliveTablePublishTimeout;
options.MaxJoinAttemptTime = config.MaxJoinAttemptTime;
options.ExpectedClusterSize = config.ExpectedClusterSize;
options.ValidateInitialConnectivity = config.ValidateInitialConnectivity;
options.NumMissedProbesLimit = config.NumMissedProbesLimit;
options.UseLivenessGossip = config.UseLivenessGossip;
options.NumProbedSilos = config.NumProbedSilos;
options.NumVotesForDeathDeclaration = config.NumVotesForDeathDeclaration;
})
.Configure<ClusterConfiguration>((options, config) =>
{
options.IsRunningAsUnitTest = config.IsRunningAsUnitTest;
});
services.AddOptions<GrainVersioningOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.DefaultCompatibilityStrategy = config.DefaultCompatibilityStrategy?.GetType().Name ?? GrainVersioningOptions.DEFAULT_COMPATABILITY_STRATEGY;
options.DefaultVersionSelectorStrategy = config.DefaultVersionSelectorStrategy?.GetType().Name ?? GrainVersioningOptions.DEFAULT_VERSION_SELECTOR_STRATEGY;
});
services.AddOptions<PerformanceTuningOptions>()
.Configure<NodeConfiguration>((options, config) =>
{
options.DefaultConnectionLimit = config.DefaultConnectionLimit;
options.Expect100Continue = config.Expect100Continue;
options.UseNagleAlgorithm = config.UseNagleAlgorithm;
options.MinDotNetThreadPoolSize = config.MinDotNetThreadPoolSize;
});
services.AddOptions<TypeManagementOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.TypeMapRefreshInterval = config.TypeMapRefreshInterval;
});
services.AddOptions<GrainDirectoryOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.CachingStrategy = Remap(config.DirectoryCachingStrategy);
options.CacheSize = config.CacheSize;
options.InitialCacheTTL = config.InitialCacheTTL;
options.MaximumCacheTTL = config.MaximumCacheTTL;
options.CacheTTLExtensionFactor = config.CacheTTLExtensionFactor;
options.LazyDeregistrationDelay = config.DirectoryLazyDeregistrationDelay;
});
}
private static Type MapDefaultPlacementStrategy(string strategy)
{
switch (strategy)
{
case nameof(RandomPlacement):
return typeof(RandomPlacement);
case nameof(PreferLocalPlacement):
return typeof(PreferLocalPlacement);
case nameof(SystemPlacement):
return typeof(SystemPlacement);
case nameof(ActivationCountBasedPlacement):
return typeof(ActivationCountBasedPlacement);
case nameof(HashBasedPlacement):
return typeof(HashBasedPlacement);
default:
return null;
}
}
public static ClusterConfiguration TryGetClusterConfiguration(this IServiceCollection services)
{
return services
.FirstOrDefault(s => s.ServiceType == typeof(ClusterConfiguration))
?.ImplementationInstance as ClusterConfiguration;
}
private static GrainDirectoryOptions.CachingStrategyType Remap(GlobalConfiguration.DirectoryCachingStrategyType type)
{
switch (type)
{
case GlobalConfiguration.DirectoryCachingStrategyType.None:
return GrainDirectoryOptions.CachingStrategyType.None;
case GlobalConfiguration.DirectoryCachingStrategyType.LRU:
return GrainDirectoryOptions.CachingStrategyType.LRU;
case GlobalConfiguration.DirectoryCachingStrategyType.Adaptive:
return GrainDirectoryOptions.CachingStrategyType.Adaptive;
default:
throw new NotSupportedException($"DirectoryCachingStrategyType {type} is not supported");
}
}
}
}
| |
using System.Collections;
using ChainUtils.BouncyCastle.Math;
using ChainUtils.BouncyCastle.Math.EC;
using ChainUtils.BouncyCastle.Utilities;
using ChainUtils.BouncyCastle.Utilities.Collections;
using ChainUtils.BouncyCastle.Utilities.Encoders;
namespace ChainUtils.BouncyCastle.Asn1.X9
{
/**
* table of the current named curves defined in X.962 EC-DSA.
*/
public sealed class X962NamedCurves
{
private X962NamedCurves()
{
}
internal class Prime192v1Holder
: X9ECParametersHolder
{
private Prime192v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime192v1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("ffffffffffffffffffffffff99def836146bc9b1b4d22831", 16);
var h = BigInteger.One;
ECCurve cFp192v1 = new FpCurve(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"),
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16),
new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16),
n, h);
return new X9ECParameters(
cFp192v1,
cFp192v1.DecodePoint(
Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")),
n, h,
Hex.Decode("3045AE6FC8422f64ED579528D38120EAE12196D5"));
}
}
internal class Prime192v2Holder
: X9ECParametersHolder
{
private Prime192v2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime192v2Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("fffffffffffffffffffffffe5fb1a724dc80418648d8dd31", 16);
var h = BigInteger.One;
ECCurve cFp192v2 = new FpCurve(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"),
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16),
new BigInteger("cc22d6dfb95c6b25e49c0d6364a4e5980c393aa21668d953", 16),
n, h);
return new X9ECParameters(
cFp192v2,
cFp192v2.DecodePoint(
Hex.Decode("03eea2bae7e1497842f2de7769cfe9c989c072ad696f48034a")),
n, h,
Hex.Decode("31a92ee2029fd10d901b113e990710f0d21ac6b6"));
}
}
internal class Prime192v3Holder
: X9ECParametersHolder
{
private Prime192v3Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime192v3Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("ffffffffffffffffffffffff7a62d031c83f4294f640ec13", 16);
var h = BigInteger.One;
ECCurve cFp192v3 = new FpCurve(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"),
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16),
new BigInteger("22123dc2395a05caa7423daeccc94760a7d462256bd56916", 16),
n, h);
return new X9ECParameters(
cFp192v3,
cFp192v3.DecodePoint(
Hex.Decode("027d29778100c65a1da1783716588dce2b8b4aee8e228f1896")),
n, h,
Hex.Decode("c469684435deb378c4b65ca9591e2a5763059a2e"));
}
}
internal class Prime239v1Holder
: X9ECParametersHolder
{
private Prime239v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime239v1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("7fffffffffffffffffffffff7fffff9e5e9a9f5d9071fbd1522688909d0b", 16);
var h = BigInteger.One;
ECCurve cFp239v1 = new FpCurve(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),
new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16),
n, h);
return new X9ECParameters(
cFp239v1,
cFp239v1.DecodePoint(
Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")),
n, h,
Hex.Decode("e43bb460f0b80cc0c0b075798e948060f8321b7d"));
}
}
internal class Prime239v2Holder
: X9ECParametersHolder
{
private Prime239v2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime239v2Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("7fffffffffffffffffffffff800000cfa7e8594377d414c03821bc582063", 16);
var h = BigInteger.One;
ECCurve cFp239v2 = new FpCurve(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),
new BigInteger("617fab6832576cbbfed50d99f0249c3fee58b94ba0038c7ae84c8c832f2c", 16),
n, h);
return new X9ECParameters(
cFp239v2,
cFp239v2.DecodePoint(
Hex.Decode("0238af09d98727705120c921bb5e9e26296a3cdcf2f35757a0eafd87b830e7")),
n, h,
Hex.Decode("e8b4011604095303ca3b8099982be09fcb9ae616"));
}
}
internal class Prime239v3Holder
: X9ECParametersHolder
{
private Prime239v3Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime239v3Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("7fffffffffffffffffffffff7fffff975deb41b3a6057c3c432146526551", 16);
var h = BigInteger.One;
ECCurve cFp239v3 = new FpCurve(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),
new BigInteger("255705fa2a306654b1f4cb03d6a750a30c250102d4988717d9ba15ab6d3e", 16),
n, h);
return new X9ECParameters(
cFp239v3,
cFp239v3.DecodePoint(
Hex.Decode("036768ae8e18bb92cfcf005c949aa2c6d94853d0e660bbf854b1c9505fe95a")),
n, h,
Hex.Decode("7d7374168ffe3471b60a857686a19475d3bfa2ff"));
}
}
internal class Prime256v1Holder
: X9ECParametersHolder
{
private Prime256v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime256v1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", 16);
var h = BigInteger.One;
ECCurve cFp256v1 = new FpCurve(
new BigInteger("115792089210356248762697446949407573530086143415290314195533631308867097853951"),
new BigInteger("ffffffff00000001000000000000000000000000fffffffffffffffffffffffc", 16),
new BigInteger("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", 16),
n, h);
return new X9ECParameters(
cFp256v1,
cFp256v1.DecodePoint(
Hex.Decode("036b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296")),
n, h,
Hex.Decode("c49d360886e704936a6678e1139d26b7819f7e90"));
}
}
/*
* F2m Curves
*/
internal class C2pnb163v1Holder
: X9ECParametersHolder
{
private C2pnb163v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb163v1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("0400000000000000000001E60FC8821CC74DAEAFC1", 16);
var h = BigInteger.Two;
ECCurve c2m163v1 = new F2mCurve(
163,
1, 2, 8,
new BigInteger("072546B5435234A422E0789675F432C89435DE5242", 16),
new BigInteger("00C9517D06D5240D3CFF38C74B20B6CD4D6F9DD4D9", 16),
n, h);
return new X9ECParameters(
c2m163v1,
c2m163v1.DecodePoint(
Hex.Decode("0307AF69989546103D79329FCC3D74880F33BBE803CB")),
n, h,
Hex.Decode("D2C0FB15760860DEF1EEF4D696E6768756151754"));
}
}
internal class C2pnb163v2Holder
: X9ECParametersHolder
{
private C2pnb163v2Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb163v2Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("03FFFFFFFFFFFFFFFFFFFDF64DE1151ADBB78F10A7", 16);
var h = BigInteger.Two;
ECCurve c2m163v2 = new F2mCurve(
163,
1, 2, 8,
new BigInteger("0108B39E77C4B108BED981ED0E890E117C511CF072", 16),
new BigInteger("0667ACEB38AF4E488C407433FFAE4F1C811638DF20", 16),
n, h);
return new X9ECParameters(
c2m163v2,
c2m163v2.DecodePoint(
Hex.Decode("030024266E4EB5106D0A964D92C4860E2671DB9B6CC5")),
n, h,
null);
}
}
internal class C2pnb163v3Holder
: X9ECParametersHolder
{
private C2pnb163v3Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb163v3Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("03FFFFFFFFFFFFFFFFFFFE1AEE140F110AFF961309", 16);
var h = BigInteger.Two;
ECCurve c2m163v3 = new F2mCurve(
163,
1, 2, 8,
new BigInteger("07A526C63D3E25A256A007699F5447E32AE456B50E", 16),
new BigInteger("03F7061798EB99E238FD6F1BF95B48FEEB4854252B", 16),
n, h);
return new X9ECParameters(
c2m163v3,
c2m163v3.DecodePoint(Hex.Decode("0202F9F87B7C574D0BDECF8A22E6524775F98CDEBDCB")),
n, h,
null);
}
}
internal class C2pnb176w1Holder
: X9ECParametersHolder
{
private C2pnb176w1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb176w1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("010092537397ECA4F6145799D62B0A19CE06FE26AD", 16);
var h = BigInteger.ValueOf(0xFF6E);
ECCurve c2m176w1 = new F2mCurve(
176,
1, 2, 43,
new BigInteger("00E4E6DB2995065C407D9D39B8D0967B96704BA8E9C90B", 16),
new BigInteger("005DDA470ABE6414DE8EC133AE28E9BBD7FCEC0AE0FFF2", 16),
n, h);
return new X9ECParameters(
c2m176w1,
c2m176w1.DecodePoint(
Hex.Decode("038D16C2866798B600F9F08BB4A8E860F3298CE04A5798")),
n, h,
null);
}
}
internal class C2tnb191v1Holder
: X9ECParametersHolder
{
private C2tnb191v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb191v1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("40000000000000000000000004A20E90C39067C893BBB9A5", 16);
var h = BigInteger.Two;
ECCurve c2m191v1 = new F2mCurve(
191,
9,
new BigInteger("2866537B676752636A68F56554E12640276B649EF7526267", 16),
new BigInteger("2E45EF571F00786F67B0081B9495A3D95462F5DE0AA185EC", 16),
n, h);
return new X9ECParameters(
c2m191v1,
c2m191v1.DecodePoint(
Hex.Decode("0236B3DAF8A23206F9C4F299D7B21A9C369137F2C84AE1AA0D")),
n, h,
Hex.Decode("4E13CA542744D696E67687561517552F279A8C84"));
}
}
internal class C2tnb191v2Holder
: X9ECParametersHolder
{
private C2tnb191v2Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb191v2Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("20000000000000000000000050508CB89F652824E06B8173", 16);
var h = BigInteger.ValueOf(4);
ECCurve c2m191v2 = new F2mCurve(
191,
9,
new BigInteger("401028774D7777C7B7666D1366EA432071274F89FF01E718", 16),
new BigInteger("0620048D28BCBD03B6249C99182B7C8CD19700C362C46A01", 16),
n, h);
return new X9ECParameters(
c2m191v2,
c2m191v2.DecodePoint(
Hex.Decode("023809B2B7CC1B28CC5A87926AAD83FD28789E81E2C9E3BF10")),
n, h,
null);
}
}
internal class C2tnb191v3Holder
: X9ECParametersHolder
{
private C2tnb191v3Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb191v3Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("155555555555555555555555610C0B196812BFB6288A3EA3", 16);
var h = BigInteger.ValueOf(6);
ECCurve c2m191v3 = new F2mCurve(
191,
9,
new BigInteger("6C01074756099122221056911C77D77E77A777E7E7E77FCB", 16),
new BigInteger("71FE1AF926CF847989EFEF8DB459F66394D90F32AD3F15E8", 16),
n, h);
return new X9ECParameters(
c2m191v3,
c2m191v3.DecodePoint(
Hex.Decode("03375D4CE24FDE434489DE8746E71786015009E66E38A926DD")),
n, h,
null);
}
}
internal class C2pnb208w1Holder
: X9ECParametersHolder
{
private C2pnb208w1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb208w1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("0101BAF95C9723C57B6C21DA2EFF2D5ED588BDD5717E212F9D", 16);
var h = BigInteger.ValueOf(0xFE48);
ECCurve c2m208w1 = new F2mCurve(
208,
1, 2, 83,
new BigInteger("0", 16),
new BigInteger("00C8619ED45A62E6212E1160349E2BFA844439FAFC2A3FD1638F9E", 16),
n, h);
return new X9ECParameters(
c2m208w1,
c2m208w1.DecodePoint(
Hex.Decode("0289FDFBE4ABE193DF9559ECF07AC0CE78554E2784EB8C1ED1A57A")),
n, h,
null);
}
}
internal class C2tnb239v1Holder
: X9ECParametersHolder
{
private C2tnb239v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb239v1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("2000000000000000000000000000000F4D42FFE1492A4993F1CAD666E447", 16);
var h = BigInteger.ValueOf(4);
ECCurve c2m239v1 = new F2mCurve(
239,
36,
new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16),
new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16),
n, h);
return new X9ECParameters(
c2m239v1,
c2m239v1.DecodePoint(
Hex.Decode("0257927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D")),
n, h,
null);
}
}
internal class C2tnb239v2Holder
: X9ECParametersHolder
{
private C2tnb239v2Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb239v2Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("1555555555555555555555555555553C6F2885259C31E3FCDF154624522D", 16);
var h = BigInteger.ValueOf(6);
ECCurve c2m239v2 = new F2mCurve(
239,
36,
new BigInteger("4230017757A767FAE42398569B746325D45313AF0766266479B75654E65F", 16),
new BigInteger("5037EA654196CFF0CD82B2C14A2FCF2E3FF8775285B545722F03EACDB74B", 16),
n, h);
return new X9ECParameters(
c2m239v2,
c2m239v2.DecodePoint(
Hex.Decode("0228F9D04E900069C8DC47A08534FE76D2B900B7D7EF31F5709F200C4CA205")),
n, h,
null);
}
}
internal class C2tnb239v3Holder
: X9ECParametersHolder
{
private C2tnb239v3Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb239v3Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("0CCCCCCCCCCCCCCCCCCCCCCCCCCCCCAC4912D2D9DF903EF9888B8A0E4CFF", 16);
var h = BigInteger.ValueOf(10);
ECCurve c2m239v3 = new F2mCurve(
239,
36,
new BigInteger("01238774666A67766D6676F778E676B66999176666E687666D8766C66A9F", 16),
new BigInteger("6A941977BA9F6A435199ACFC51067ED587F519C5ECB541B8E44111DE1D40", 16),
n, h);
return new X9ECParameters(
c2m239v3,
c2m239v3.DecodePoint(
Hex.Decode("0370F6E9D04D289C4E89913CE3530BFDE903977D42B146D539BF1BDE4E9C92")),
n, h,
null);
}
}
internal class C2pnb272w1Holder
: X9ECParametersHolder
{
private C2pnb272w1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb272w1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("0100FAF51354E0E39E4892DF6E319C72C8161603FA45AA7B998A167B8F1E629521", 16);
var h = BigInteger.ValueOf(0xFF06);
ECCurve c2m272w1 = new F2mCurve(
272,
1, 3, 56,
new BigInteger("0091A091F03B5FBA4AB2CCF49C4EDD220FB028712D42BE752B2C40094DBACDB586FB20", 16),
new BigInteger("7167EFC92BB2E3CE7C8AAAFF34E12A9C557003D7C73A6FAF003F99F6CC8482E540F7", 16),
n, h);
return new X9ECParameters(
c2m272w1,
c2m272w1.DecodePoint(
Hex.Decode("026108BABB2CEEBCF787058A056CBE0CFE622D7723A289E08A07AE13EF0D10D171DD8D")),
n, h,
null);
}
}
internal class C2pnb304w1Holder
: X9ECParametersHolder
{
private C2pnb304w1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb304w1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("0101D556572AABAC800101D556572AABAC8001022D5C91DD173F8FB561DA6899164443051D", 16);
var h = BigInteger.ValueOf(0xFE2E);
ECCurve c2m304w1 = new F2mCurve(
304,
1, 2, 11,
new BigInteger("00FD0D693149A118F651E6DCE6802085377E5F882D1B510B44160074C1288078365A0396C8E681", 16),
new BigInteger("00BDDB97E555A50A908E43B01C798EA5DAA6788F1EA2794EFCF57166B8C14039601E55827340BE", 16),
n, h);
return new X9ECParameters(
c2m304w1,
c2m304w1.DecodePoint(
Hex.Decode("02197B07845E9BE2D96ADB0F5F3C7F2CFFBD7A3EB8B6FEC35C7FD67F26DDF6285A644F740A2614")),
n, h,
null);
}
}
internal class C2tnb359v1Holder
: X9ECParametersHolder
{
private C2tnb359v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb359v1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("01AF286BCA1AF286BCA1AF286BCA1AF286BCA1AF286BC9FB8F6B85C556892C20A7EB964FE7719E74F490758D3B", 16);
var h = BigInteger.ValueOf(0x4C);
ECCurve c2m359v1 = new F2mCurve(
359,
68,
new BigInteger("5667676A654B20754F356EA92017D946567C46675556F19556A04616B567D223A5E05656FB549016A96656A557", 16),
new BigInteger("2472E2D0197C49363F1FE7F5B6DB075D52B6947D135D8CA445805D39BC345626089687742B6329E70680231988", 16),
n, h);
return new X9ECParameters(
c2m359v1,
c2m359v1.DecodePoint(
Hex.Decode("033C258EF3047767E7EDE0F1FDAA79DAEE3841366A132E163ACED4ED2401DF9C6BDCDE98E8E707C07A2239B1B097")),
n, h,
null);
}
}
internal class C2pnb368w1Holder
: X9ECParametersHolder
{
private C2pnb368w1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb368w1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("010090512DA9AF72B08349D98A5DD4C7B0532ECA51CE03E2D10F3B7AC579BD87E909AE40A6F131E9CFCE5BD967", 16);
var h = BigInteger.ValueOf(0xFF70);
ECCurve c2m368w1 = new F2mCurve(
368,
1, 2, 85,
new BigInteger("00E0D2EE25095206F5E2A4F9ED229F1F256E79A0E2B455970D8D0D865BD94778C576D62F0AB7519CCD2A1A906AE30D", 16),
new BigInteger("00FC1217D4320A90452C760A58EDCD30C8DD069B3C34453837A34ED50CB54917E1C2112D84D164F444F8F74786046A", 16),
n, h);
return new X9ECParameters(
c2m368w1,
c2m368w1.DecodePoint(
Hex.Decode("021085E2755381DCCCE3C1557AFA10C2F0C0C2825646C5B34A394CBCFA8BC16B22E7E789E927BE216F02E1FB136A5F")),
n, h,
null);
}
}
internal class C2tnb431r1Holder
: X9ECParametersHolder
{
private C2tnb431r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb431r1Holder();
protected override X9ECParameters CreateParameters()
{
var n = new BigInteger("0340340340340340340340340340340340340340340340340340340323C313FAB50589703B5EC68D3587FEC60D161CC149C1AD4A91", 16);
var h = BigInteger.ValueOf(0x2760);
ECCurve c2m431r1 = new F2mCurve(
431,
120,
new BigInteger("1A827EF00DD6FC0E234CAF046C6A5D8A85395B236CC4AD2CF32A0CADBDC9DDF620B0EB9906D0957F6C6FEACD615468DF104DE296CD8F", 16),
new BigInteger("10D9B4A3D9047D8B154359ABFB1B7F5485B04CEB868237DDC9DEDA982A679A5A919B626D4E50A8DD731B107A9962381FB5D807BF2618", 16),
n, h);
return new X9ECParameters(
c2m431r1,
c2m431r1.DecodePoint(
Hex.Decode("02120FC05D3C67A99DE161D2F4092622FECA701BE4F50F4758714E8A87BBF2A658EF8C21E7C5EFE965361F6C2999C0C247B0DBD70CE6B7")),
n, h,
null);
}
}
private static readonly IDictionary objIds = Platform.CreateHashtable();
private static readonly IDictionary curves = Platform.CreateHashtable();
private static readonly IDictionary names = Platform.CreateHashtable();
private static void DefineCurve(
string name,
DerObjectIdentifier oid,
X9ECParametersHolder holder)
{
objIds.Add(name, oid);
names.Add(oid, name);
curves.Add(oid, holder);
}
static X962NamedCurves()
{
DefineCurve("prime192v1", X9ObjectIdentifiers.Prime192v1, Prime192v1Holder.Instance);
DefineCurve("prime192v2", X9ObjectIdentifiers.Prime192v2, Prime192v2Holder.Instance);
DefineCurve("prime192v3", X9ObjectIdentifiers.Prime192v3, Prime192v3Holder.Instance);
DefineCurve("prime239v1", X9ObjectIdentifiers.Prime239v1, Prime239v1Holder.Instance);
DefineCurve("prime239v2", X9ObjectIdentifiers.Prime239v2, Prime239v2Holder.Instance);
DefineCurve("prime239v3", X9ObjectIdentifiers.Prime239v3, Prime239v3Holder.Instance);
DefineCurve("prime256v1", X9ObjectIdentifiers.Prime256v1, Prime256v1Holder.Instance);
DefineCurve("c2pnb163v1", X9ObjectIdentifiers.C2Pnb163v1, C2pnb163v1Holder.Instance);
DefineCurve("c2pnb163v2", X9ObjectIdentifiers.C2Pnb163v2, C2pnb163v2Holder.Instance);
DefineCurve("c2pnb163v3", X9ObjectIdentifiers.C2Pnb163v3, C2pnb163v3Holder.Instance);
DefineCurve("c2pnb176w1", X9ObjectIdentifiers.C2Pnb176w1, C2pnb176w1Holder.Instance);
DefineCurve("c2tnb191v1", X9ObjectIdentifiers.C2Tnb191v1, C2tnb191v1Holder.Instance);
DefineCurve("c2tnb191v2", X9ObjectIdentifiers.C2Tnb191v2, C2tnb191v2Holder.Instance);
DefineCurve("c2tnb191v3", X9ObjectIdentifiers.C2Tnb191v3, C2tnb191v3Holder.Instance);
DefineCurve("c2pnb208w1", X9ObjectIdentifiers.C2Pnb208w1, C2pnb208w1Holder.Instance);
DefineCurve("c2tnb239v1", X9ObjectIdentifiers.C2Tnb239v1, C2tnb239v1Holder.Instance);
DefineCurve("c2tnb239v2", X9ObjectIdentifiers.C2Tnb239v2, C2tnb239v2Holder.Instance);
DefineCurve("c2tnb239v3", X9ObjectIdentifiers.C2Tnb239v3, C2tnb239v3Holder.Instance);
DefineCurve("c2pnb272w1", X9ObjectIdentifiers.C2Pnb272w1, C2pnb272w1Holder.Instance);
DefineCurve("c2pnb304w1", X9ObjectIdentifiers.C2Pnb304w1, C2pnb304w1Holder.Instance);
DefineCurve("c2tnb359v1", X9ObjectIdentifiers.C2Tnb359v1, C2tnb359v1Holder.Instance);
DefineCurve("c2pnb368w1", X9ObjectIdentifiers.C2Pnb368w1, C2pnb368w1Holder.Instance);
DefineCurve("c2tnb431r1", X9ObjectIdentifiers.C2Tnb431r1, C2tnb431r1Holder.Instance);
}
public static X9ECParameters GetByName(
string name)
{
var oid = (DerObjectIdentifier)objIds[Platform.ToLowerInvariant(name)];
return oid == null ? null : GetByOid(oid);
}
/**
* return the X9ECParameters object for the named curve represented by
* the passed in object identifier. Null if the curve isn't present.
*
* @param oid an object identifier representing a named curve, if present.
*/
public static X9ECParameters GetByOid(
DerObjectIdentifier oid)
{
var holder = (X9ECParametersHolder) curves[oid];
return holder == null ? null : holder.Parameters;
}
/**
* return the object identifier signified by the passed in name. Null
* if there is no object identifier associated with name.
*
* @return the object identifier associated with name, if present.
*/
public static DerObjectIdentifier GetOid(
string name)
{
return (DerObjectIdentifier)objIds[Platform.ToLowerInvariant(name)];
}
/**
* return the named curve name represented by the given object identifier.
*/
public static string GetName(
DerObjectIdentifier oid)
{
return (string) names[oid];
}
/**
* returns an enumeration containing the name strings for curves
* contained in this structure.
*/
public static IEnumerable Names
{
get { return new EnumerableProxy(objIds.Keys); }
}
}
}
| |
// 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 System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for NetworkSecurityGroupsOperations.
/// </summary>
public static partial class NetworkSecurityGroupsOperationsExtensions
{
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
public static void Delete(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName)
{
operations.DeleteAsync(resourceGroupName, networkSecurityGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
public static NetworkSecurityGroup Get(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, networkSecurityGroupName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkSecurityGroup> GetAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
public static NetworkSecurityGroup CreateOrUpdate(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkSecurityGroup> CreateOrUpdateAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<NetworkSecurityGroup> ListAll(this INetworkSecurityGroupsOperations operations)
{
return operations.ListAllAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkSecurityGroup>> ListAllAsync(this INetworkSecurityGroupsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<NetworkSecurityGroup> List(this INetworkSecurityGroupsOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkSecurityGroup>> ListAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
public static void BeginDelete(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName)
{
operations.BeginDeleteAsync(resourceGroupName, networkSecurityGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
public static NetworkSecurityGroup BeginCreateOrUpdate(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkSecurityGroup> BeginCreateOrUpdateAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<NetworkSecurityGroup> ListAllNext(this INetworkSecurityGroupsOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkSecurityGroup>> ListAllNextAsync(this INetworkSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<NetworkSecurityGroup> ListNext(this INetworkSecurityGroupsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkSecurityGroup>> ListNextAsync(this INetworkSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using HETSAPI.Models;
using HETSAPI.ViewModels;
namespace HETSAPI.Services.Impl
{
/// <summary>
///
/// </summary>
public class DistrictService : IDistrictService
{
private readonly DbAppContext _context;
/// <summary>
/// Create a service and set the database context
/// </summary>
public DistrictService(DbAppContext context)
{
_context = context;
}
public void AdjustRecord (District item)
{
if (item != null)
{
if (item.Region != null)
{
item.Region = _context.Regions.FirstOrDefault(x => x.Id == item.Region.Id);
}
}
}
/// <summary>
///
/// </summary>
/// <remarks>Adds a number of districts.</remarks>
/// <param name="items"></param>
/// <response code="200">OK</response>
public virtual IActionResult DistrictsBulkPostAsync(District[] items)
{
if (items == null)
{
return new BadRequestResult();
}
foreach (District item in items)
{
AdjustRecord(item);
bool exists = _context.Districts.Any(a => a.Id == item.Id);
if (exists)
{
_context.Districts.Update(item);
}
else
{
_context.Districts.Add(item);
}
}
// Save the changes
_context.SaveChanges();
return new NoContentResult();
}
/// <summary>
///
/// </summary>
/// <remarks>Returns a list of available districts</remarks>
/// <response code="200">OK</response>
public virtual IActionResult DistrictsGetAsync()
{
// eager loading of regions
var result = _context.Districts
.Include(x => x.Region)
.ToList();
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Deletes a district</remarks>
/// <param name="id">id of District to delete</param>
/// <response code="200">OK</response>
/// <response code="404">District not found</response>
public virtual IActionResult DistrictsIdDeletePostAsync(int id)
{
var exists = _context.Districts.Any(a => a.Id == id);
if (exists)
{
var item = _context.Districts.First(a => a.Id == id);
if (item != null)
{
_context.Districts.Remove(item);
// Save the changes
_context.SaveChanges();
}
return new ObjectResult(item);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Returns a specific district</remarks>
/// <param name="id">id of Districts to fetch</param>
/// <response code="200">OK</response>
public virtual IActionResult DistrictsIdGetAsync(int id)
{
var exists = _context.Districts.Any(a => a.Id == id);
if (exists)
{
var result = _context.Districts
.Where(a => a.Id == id)
.Include(a => a.Region)
.FirstOrDefault();
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Updates a district</remarks>
/// <param name="id">id of District to update</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">District not found</response>
public virtual IActionResult DistrictsIdPutAsync(int id, District body)
{
var exists = _context.Districts.Any(a => a.Id == id);
if (exists && id == body.Id)
{
AdjustRecord(body);
_context.Districts.Update(body);
// Save the changes
_context.SaveChanges();
return new ObjectResult(body);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Returns the Service Areas for a specific region</remarks>
/// <param name="id">id of District for which to fetch the ServiceAreas</param>
/// <response code="200">OK</response>
public virtual IActionResult DistrictsIdServiceareasGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Adds a district</remarks>
/// <param name="body"></param>
/// <response code="200">OK</response>
public virtual IActionResult DistrictsPostAsync(District body)
{
AdjustRecord(body);
var exists = _context.Districts.Any(a => a.Id == body.Id);
if (exists )
{
_context.Districts.Update(body);
// Save the changes
}
else
{
// record not found
_context.Districts.Add(body);
}
_context.SaveChanges();
return new ObjectResult(body);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Umbraco.Core.Cache;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.FaultHandling;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Persistence.Repositories
{
//TODO: We need to get a readonly ISO code for the domain assigned
internal class DomainRepository : PetaPocoRepositoryBase<int, IDomain>, IDomainRepository
{
public DomainRepository(IDatabaseUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax)
: base(work, cache, logger, sqlSyntax)
{
}
private FullDataSetRepositoryCachePolicyFactory<IDomain, int> _cachePolicyFactory;
protected override IRepositoryCachePolicyFactory<IDomain, int> CachePolicyFactory
{
get
{
//Use a FullDataSet cache policy - this will cache the entire GetAll result in a single collection
return _cachePolicyFactory ?? (_cachePolicyFactory = new FullDataSetRepositoryCachePolicyFactory<IDomain, int>(
RuntimeCache, GetEntityId, () => PerformGetAll(), false));
}
}
protected override IDomain PerformGet(int id)
{
//use the underlying GetAll which will force cache all domains
return GetAll().FirstOrDefault(x => x.Id == id);
}
protected override IEnumerable<IDomain> PerformGetAll(params int[] ids)
{
var sql = GetBaseQuery(false).Where("umbracoDomains.id > 0");
if (ids.Any())
{
sql.Where("umbracoDomains.id in (@ids)", new { ids = ids });
}
return Database.Fetch<DomainDto>(sql).Select(ConvertFromDto);
}
protected override IEnumerable<IDomain> PerformGetByQuery(IQuery<IDomain> query)
{
throw new NotSupportedException("This repository does not support this method");
}
protected override Sql GetBaseQuery(bool isCount)
{
var sql = new Sql();
if (isCount)
{
sql.Select("COUNT(*)").From<DomainDto>(SqlSyntax);
}
else
{
sql.Select("umbracoDomains.*, umbracoLanguage.languageISOCode")
.From<DomainDto>(SqlSyntax)
.LeftJoin<LanguageDto>(SqlSyntax)
.On<DomainDto, LanguageDto>(SqlSyntax, dto => dto.DefaultLanguage, dto => dto.Id);
}
return sql;
}
protected override string GetBaseWhereClause()
{
return "umbracoDomains.id = @Id";
}
protected override IEnumerable<string> GetDeleteClauses()
{
var list = new List<string>
{
"DELETE FROM umbracoDomains WHERE id = @Id"
};
return list;
}
protected override Guid NodeObjectTypeId
{
get { throw new NotImplementedException(); }
}
protected override void PersistNewItem(IDomain entity)
{
var exists = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoDomains WHERE domainName = @domainName", new { domainName = entity.DomainName });
if (exists > 0) throw new DuplicateNameException(string.Format("The domain name {0} is already assigned", entity.DomainName));
if (entity.RootContentId.HasValue)
{
var contentExists = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM cmsContent WHERE nodeId = @id", new { id = entity.RootContentId.Value });
if (contentExists == 0) throw new NullReferenceException("No content exists with id " + entity.RootContentId.Value);
}
if (entity.LanguageId.HasValue)
{
var languageExists = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoLanguage WHERE id = @id", new { id = entity.LanguageId.Value });
if (languageExists == 0) throw new NullReferenceException("No language exists with id " + entity.LanguageId.Value);
}
((UmbracoDomain)entity).AddingEntity();
var factory = new DomainModelFactory();
var dto = factory.BuildDto(entity);
var id = Convert.ToInt32(Database.Insert(dto));
entity.Id = id;
//if the language changed, we need to resolve the ISO code!
if (entity.LanguageId.HasValue)
{
((UmbracoDomain)entity).LanguageIsoCode = Database.ExecuteScalar<string>("SELECT languageISOCode FROM umbracoLanguage WHERE id=@langId", new { langId = entity.LanguageId });
}
entity.ResetDirtyProperties();
}
protected override void PersistUpdatedItem(IDomain entity)
{
((UmbracoDomain)entity).UpdatingEntity();
var exists = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoDomains WHERE domainName = @domainName AND umbracoDomains.id <> @id",
new { domainName = entity.DomainName, id = entity.Id });
//ensure there is no other domain with the same name on another entity
if (exists > 0) throw new DuplicateNameException(string.Format("The domain name {0} is already assigned", entity.DomainName));
if (entity.RootContentId.HasValue)
{
var contentExists = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM cmsContent WHERE nodeId = @id", new { id = entity.RootContentId.Value });
if (contentExists == 0) throw new NullReferenceException("No content exists with id " + entity.RootContentId.Value);
}
if (entity.LanguageId.HasValue)
{
var languageExists = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoLanguage WHERE id = @id", new { id = entity.LanguageId.Value });
if (languageExists == 0) throw new NullReferenceException("No language exists with id " + entity.LanguageId.Value);
}
var factory = new DomainModelFactory();
var dto = factory.BuildDto(entity);
Database.Update(dto);
//if the language changed, we need to resolve the ISO code!
if (entity.WasPropertyDirty("LanguageId"))
{
((UmbracoDomain)entity).LanguageIsoCode = Database.ExecuteScalar<string>("SELECT languageISOCode FROM umbracoLanguage WHERE id=@langId", new {langId = entity.LanguageId});
}
entity.ResetDirtyProperties();
}
public IDomain GetByName(string domainName)
{
return GetAll().FirstOrDefault(x => x.DomainName.InvariantEquals(domainName));
}
public bool Exists(string domainName)
{
return GetAll().Any(x => x.DomainName.InvariantEquals(domainName));
}
public IEnumerable<IDomain> GetAll(bool includeWildcards)
{
return GetAll().Where(x => includeWildcards || x.IsWildcard == false);
}
public IEnumerable<IDomain> GetAssignedDomains(int contentId, bool includeWildcards)
{
return GetAll()
.Where(x => x.RootContentId == contentId)
.Where(x => includeWildcards || x.IsWildcard == false);
}
private IDomain ConvertFromDto(DomainDto dto)
{
var factory = new DomainModelFactory();
var entity = factory.BuildEntity(dto);
return entity;
}
internal class DomainModelFactory
{
public IDomain BuildEntity(DomainDto dto)
{
var domain = new UmbracoDomain(dto.DomainName, dto.IsoCode)
{
Id = dto.Id,
LanguageId = dto.DefaultLanguage,
RootContentId = dto.RootStructureId
};
//on initial construction we don't want to have dirty properties tracked
// http://issues.umbraco.org/issue/U4-1946
domain.ResetDirtyProperties(false);
return domain;
}
public DomainDto BuildDto(IDomain entity)
{
var dto = new DomainDto { DefaultLanguage = entity.LanguageId, DomainName = entity.DomainName, Id = entity.Id, RootStructureId = entity.RootContentId };
return dto;
}
}
}
}
| |
// 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.DirectoryServices.ActiveDirectory
{
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.DirectoryServices;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.ComponentModel;
using System.Security.Permissions;
[Flags]
public enum ActiveDirectorySiteOptions
{
None = 0,
AutoTopologyDisabled = 1,
TopologyCleanupDisabled = 2,
AutoMinimumHopDisabled = 4,
StaleServerDetectDisabled = 8,
AutoInterSiteTopologyDisabled = 16,
GroupMembershipCachingEnabled = 32,
ForceKccWindows2003Behavior = 64,
UseWindows2000IstgElection = 128,
RandomBridgeHeaderServerSelectionDisabled = 256,
UseHashingForReplicationSchedule = 512,
RedundantServerTopologyEnabled = 1024
}
public class ActiveDirectorySite : IDisposable
{
internal DirectoryContext context = null;
private string _name = null;
internal DirectoryEntry cachedEntry = null;
private DirectoryEntry _ntdsEntry = null;
private ActiveDirectorySubnetCollection _subnets = null;
private DirectoryServer _topologyGenerator = null;
private ReadOnlySiteCollection _adjacentSites = new ReadOnlySiteCollection();
private bool _disposed = false;
private DomainCollection _domains = new DomainCollection(null);
private ReadOnlyDirectoryServerCollection _servers = new ReadOnlyDirectoryServerCollection();
private ReadOnlySiteLinkCollection _links = new ReadOnlySiteLinkCollection();
private ActiveDirectorySiteOptions _siteOptions = ActiveDirectorySiteOptions.None;
private ReadOnlyDirectoryServerCollection _bridgeheadServers = new ReadOnlyDirectoryServerCollection();
private DirectoryServerCollection _SMTPBridgeheadServers = null;
private DirectoryServerCollection _RPCBridgeheadServers = null;
private byte[] _replicationSchedule = null;
internal bool existing = false;
private bool _subnetRetrieved = false;
private bool _isADAMServer = false;
private bool _checkADAM = false;
private bool _topologyTouched = false;
private bool _adjacentSitesRetrieved = false;
private string _siteDN = null;
private bool _domainsRetrieved = false;
private bool _serversRetrieved = false;
private bool _belongLinksRetrieved = false;
private bool _bridgeheadServerRetrieved = false;
private bool _SMTPBridgeRetrieved = false;
private bool _RPCBridgeRetrieved = false;
private static int s_ERROR_NO_SITENAME = 1919;
public static ActiveDirectorySite FindByName(DirectoryContext context, string siteName)
{
// find an existing site
ValidateArgument(context, siteName);
// work with copy of the context
context = new DirectoryContext(context);
// bind to the rootdse to get the configurationnamingcontext
DirectoryEntry de;
string sitedn;
try
{
de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
sitedn = "CN=Sites," + (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext);
de = DirectoryEntryManager.GetDirectoryEntry(context, sitedn);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
try
{
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=site)(objectCategory=site)(name=" + Utils.GetEscapedFilterValue(siteName) + "))",
new string[] { "distinguishedName" },
SearchScope.OneLevel,
false, /* don't need paged search */
false /* don't need to cache result */);
SearchResult srchResult = adSearcher.FindOne();
if (srchResult == null)
{
// no such site object
throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySite), siteName);
}
// it is an existing site object
ActiveDirectorySite site = new ActiveDirectorySite(context, siteName, true);
return site;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
// object is not found since we cannot even find the container in which to search
throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySite), siteName);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
de.Dispose();
}
}
public ActiveDirectorySite(DirectoryContext context, string siteName)
{
ValidateArgument(context, siteName);
// work with copy of the context
context = new DirectoryContext(context);
this.context = context;
_name = siteName;
// bind to the rootdse to get the configurationnamingcontext
DirectoryEntry de = null;
try
{
de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext);
_siteDN = "CN=Sites," + config;
// bind to the site container
de = DirectoryEntryManager.GetDirectoryEntry(context, _siteDN);
string rdn = "cn=" + _name;
rdn = Utils.GetEscapedPath(rdn);
cachedEntry = de.Children.Add(rdn, "site");
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
finally
{
if (de != null)
de.Dispose();
}
_subnets = new ActiveDirectorySubnetCollection(context, "CN=" + siteName + "," + _siteDN);
string transportDN = "CN=IP,CN=Inter-Site Transports," + _siteDN;
_RPCBridgeheadServers = new DirectoryServerCollection(context, "CN=" + siteName + "," + _siteDN, transportDN);
transportDN = "CN=SMTP,CN=Inter-Site Transports," + _siteDN;
_SMTPBridgeheadServers = new DirectoryServerCollection(context, "CN=" + siteName + "," + _siteDN, transportDN);
}
internal ActiveDirectorySite(DirectoryContext context, string siteName, bool existing)
{
Debug.Assert(existing == true);
this.context = context;
_name = siteName;
this.existing = existing;
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
_siteDN = "CN=Sites," + (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext);
cachedEntry = DirectoryEntryManager.GetDirectoryEntry(context, "CN=" + siteName + "," + _siteDN);
_subnets = new ActiveDirectorySubnetCollection(context, "CN=" + siteName + "," + _siteDN);
string transportDN = "CN=IP,CN=Inter-Site Transports," + _siteDN;
_RPCBridgeheadServers = new DirectoryServerCollection(context, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName), transportDN);
transportDN = "CN=SMTP,CN=Inter-Site Transports," + _siteDN;
_SMTPBridgeheadServers = new DirectoryServerCollection(context, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName), transportDN);
}
public static ActiveDirectorySite GetComputerSite()
{
// make sure that this is the platform that we support
new DirectoryContext(DirectoryContextType.Forest);
IntPtr ptr = (IntPtr)0;
int result = UnsafeNativeMethods.DsGetSiteName(null, ref ptr);
if (result != 0)
{
// computer is not in a site
if (result == s_ERROR_NO_SITENAME)
throw new ActiveDirectoryObjectNotFoundException(SR.NoCurrentSite, typeof(ActiveDirectorySite), null);
else
throw ExceptionHelper.GetExceptionFromErrorCode(result);
}
else
{
try
{
string siteName = Marshal.PtrToStringUni(ptr);
Debug.Assert(siteName != null);
// find the forest this machine belongs to
string forestName = Locator.GetDomainControllerInfo(null, null, null, (long)PrivateLocatorFlags.DirectoryServicesRequired).DnsForestName;
DirectoryContext currentContext = Utils.GetNewDirectoryContext(forestName, DirectoryContextType.Forest, null);
// existing site
ActiveDirectorySite site = ActiveDirectorySite.FindByName(currentContext, siteName);
return site;
}
finally
{
if (ptr != (IntPtr)0)
Marshal.FreeHGlobal(ptr);
}
}
}
public string Name
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return _name;
}
}
public DomainCollection Domains
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (existing)
{
if (!_domainsRetrieved)
{
// clear it first to be safe in case GetDomains fail in the middle and leave partial results there
_domains.Clear();
GetDomains();
_domainsRetrieved = true;
}
}
return _domains;
}
}
public ActiveDirectorySubnetCollection Subnets
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (existing)
{
// if asked the first time, we need to properly construct the subnets collection
if (!_subnetRetrieved)
{
_subnets.initialized = false;
_subnets.Clear();
GetSubnets();
_subnetRetrieved = true;
}
}
_subnets.initialized = true;
return _subnets;
}
}
public ReadOnlyDirectoryServerCollection Servers
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (existing)
{
if (!_serversRetrieved)
{
_servers.Clear();
GetServers();
_serversRetrieved = true;
}
}
return _servers;
}
}
public ReadOnlySiteCollection AdjacentSites
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (existing)
{
if (!_adjacentSitesRetrieved)
{
_adjacentSites.Clear();
GetAdjacentSites();
_adjacentSitesRetrieved = true;
}
}
return _adjacentSites;
}
}
public ReadOnlySiteLinkCollection SiteLinks
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (existing)
{
if (!_belongLinksRetrieved)
{
_links.Clear();
GetLinks();
_belongLinksRetrieved = true;
}
}
return _links;
}
}
public DirectoryServer InterSiteTopologyGenerator
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (existing)
{
// have not load topology generator information from the directory and user has not set it yet
if (_topologyGenerator == null && !_topologyTouched)
{
bool ISTGExist;
try
{
ISTGExist = NTDSSiteEntry.Properties.Contains("interSiteTopologyGenerator");
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (ISTGExist)
{
string serverDN = (string)PropertyManager.GetPropertyValue(context, NTDSSiteEntry, PropertyManager.InterSiteTopologyGenerator);
string hostname = null;
DirectoryEntry tmp = DirectoryEntryManager.GetDirectoryEntry(context, serverDN);
try
{
hostname = (string)PropertyManager.GetPropertyValue(context, tmp.Parent, PropertyManager.DnsHostName);
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
// indicates a demoted server
return null;
}
}
if (IsADAM)
{
int port = (int)PropertyManager.GetPropertyValue(context, tmp, PropertyManager.MsDSPortLDAP);
string fullHostName = hostname;
if (port != 389)
{
fullHostName = hostname + ":" + port;
}
_topologyGenerator = new AdamInstance(Utils.GetNewDirectoryContext(fullHostName, DirectoryContextType.DirectoryServer, context), fullHostName);
}
else
{
_topologyGenerator = new DomainController(Utils.GetNewDirectoryContext(hostname, DirectoryContextType.DirectoryServer, context), hostname);
}
}
}
}
return _topologyGenerator;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (value == null)
throw new ArgumentNullException("value");
if (existing)
{
// for existing site, nTDSSiteSettings needs to exist
DirectoryEntry tmp = NTDSSiteEntry;
}
_topologyTouched = true;
_topologyGenerator = value;
}
}
public ActiveDirectorySiteOptions Options
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (existing)
{
try
{
if (NTDSSiteEntry.Properties.Contains("options"))
{
return (ActiveDirectorySiteOptions)NTDSSiteEntry.Properties["options"][0];
}
else
return ActiveDirectorySiteOptions.None;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
else
return _siteOptions;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (existing)
{
try
{
NTDSSiteEntry.Properties["options"].Value = value;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
else
_siteOptions = value;
}
}
public string Location
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
if (cachedEntry.Properties.Contains("location"))
{
return (string)cachedEntry.Properties["location"][0];
}
else
return null;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
if (value == null)
{
if (cachedEntry.Properties.Contains("location"))
cachedEntry.Properties["location"].Clear();
}
else
{
cachedEntry.Properties["location"].Value = value;
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public ReadOnlyDirectoryServerCollection BridgeheadServers
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!_bridgeheadServerRetrieved)
{
_bridgeheadServers = GetBridgeheadServers();
_bridgeheadServerRetrieved = true;
}
return _bridgeheadServers;
}
}
public DirectoryServerCollection PreferredSmtpBridgeheadServers
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (existing)
{
if (!_SMTPBridgeRetrieved)
{
_SMTPBridgeheadServers.initialized = false;
_SMTPBridgeheadServers.Clear();
GetPreferredBridgeheadServers(ActiveDirectoryTransportType.Smtp);
_SMTPBridgeRetrieved = true;
}
}
_SMTPBridgeheadServers.initialized = true;
return _SMTPBridgeheadServers;
}
}
public DirectoryServerCollection PreferredRpcBridgeheadServers
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (existing)
{
if (!_RPCBridgeRetrieved)
{
_RPCBridgeheadServers.initialized = false;
_RPCBridgeheadServers.Clear();
GetPreferredBridgeheadServers(ActiveDirectoryTransportType.Rpc);
_RPCBridgeRetrieved = true;
}
}
_RPCBridgeheadServers.initialized = true;
return _RPCBridgeheadServers;
}
}
public ActiveDirectorySchedule IntraSiteReplicationSchedule
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
ActiveDirectorySchedule schedule = null;
if (existing)
{
// if exists in the cache, return it, otherwise null is returned
try
{
if (NTDSSiteEntry.Properties.Contains("schedule"))
{
byte[] tmpSchedule = (byte[])NTDSSiteEntry.Properties["schedule"][0];
Debug.Assert(tmpSchedule != null && tmpSchedule.Length == 188);
schedule = new ActiveDirectorySchedule();
schedule.SetUnmanagedSchedule(tmpSchedule);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
else
{
if (_replicationSchedule != null)
{
// newly created site, get the schedule if already has been set by the user
schedule = new ActiveDirectorySchedule();
schedule.SetUnmanagedSchedule(_replicationSchedule);
}
}
return schedule;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (existing)
{
try
{
if (value == null)
{
// clear it out if existing before
if (NTDSSiteEntry.Properties.Contains("schedule"))
NTDSSiteEntry.Properties["schedule"].Clear();
}
else
// replace with the new value
NTDSSiteEntry.Properties["schedule"].Value = value.GetUnmanagedSchedule();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
else
{
// clear out the schedule
if (value == null)
_replicationSchedule = null;
else
{
// replace with the new value
_replicationSchedule = value.GetUnmanagedSchedule();
}
}
}
}
private bool IsADAM
{
get
{
if (!_checkADAM)
{
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
PropertyValueCollection values = null;
try
{
values = de.Properties["supportedCapabilities"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (values.Contains(SupportedCapability.ADAMOid))
_isADAMServer = true;
}
return _isADAMServer;
}
}
private DirectoryEntry NTDSSiteEntry
{
get
{
if (_ntdsEntry == null)
{
DirectoryEntry tmp = DirectoryEntryManager.GetDirectoryEntry(context, "CN=NTDS Site Settings," + (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName));
try
{
tmp.RefreshCache();
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
string message = String.Format(CultureInfo.CurrentCulture, SR.NTDSSiteSetting , _name);
throw new ActiveDirectoryOperationException(message, e, 0x2030);
}
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
_ntdsEntry = tmp;
}
return _ntdsEntry;
}
}
public void Save()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
// commit changes
cachedEntry.CommitChanges();
foreach (DictionaryEntry e in _subnets.changeList)
{
try
{
((DirectoryEntry)e.Value).CommitChanges();
}
catch (COMException exception)
{
// there is a bug in ADSI that when targeting ADAM, permissive modify control is not used.
if (exception.ErrorCode != unchecked((int)0x8007200A))
throw ExceptionHelper.GetExceptionFromCOMException(exception);
}
}
// reset status variables
_subnets.changeList.Clear();
_subnetRetrieved = false;
// need to throw better exception for ADAM since its SMTP transport is not available
foreach (DictionaryEntry e in _SMTPBridgeheadServers.changeList)
{
try
{
((DirectoryEntry)e.Value).CommitChanges();
}
catch (COMException exception)
{
// SMTP transport is not supported on ADAM
if (IsADAM && (exception.ErrorCode == unchecked((int)0x8007202F)))
throw new NotSupportedException(SR.NotSupportTransportSMTP);
// there is a bug in ADSI that when targeting ADAM, permissive modify control is not used.
if (exception.ErrorCode != unchecked((int)0x8007200A))
throw ExceptionHelper.GetExceptionFromCOMException(exception);
}
}
_SMTPBridgeheadServers.changeList.Clear();
_SMTPBridgeRetrieved = false;
foreach (DictionaryEntry e in _RPCBridgeheadServers.changeList)
{
try
{
((DirectoryEntry)e.Value).CommitChanges();
}
catch (COMException exception)
{
// there is a bug in ADSI that when targeting ADAM, permissive modify control is not used.
if (exception.ErrorCode != unchecked((int)0x8007200A))
throw ExceptionHelper.GetExceptionFromCOMException(exception);
}
}
_RPCBridgeheadServers.changeList.Clear();
_RPCBridgeRetrieved = false;
if (existing)
{
// topology generator is changed
if (_topologyTouched)
{
try
{
DirectoryServer server = InterSiteTopologyGenerator;
string ntdsaName = (server is DomainController) ? ((DomainController)server).NtdsaObjectName : ((AdamInstance)server).NtdsaObjectName;
NTDSSiteEntry.Properties["interSiteTopologyGenerator"].Value = ntdsaName;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
NTDSSiteEntry.CommitChanges();
_topologyTouched = false;
}
else
{
try
{
// create nTDSSiteSettings object
DirectoryEntry tmpEntry = cachedEntry.Children.Add("CN=NTDS Site Settings", "nTDSSiteSettings");
//set properties on the Site NTDS settings object
DirectoryServer replica = InterSiteTopologyGenerator;
if (replica != null)
{
string ntdsaName = (replica is DomainController) ? ((DomainController)replica).NtdsaObjectName : ((AdamInstance)replica).NtdsaObjectName;
tmpEntry.Properties["interSiteTopologyGenerator"].Value = ntdsaName;
}
tmpEntry.Properties["options"].Value = _siteOptions;
if (_replicationSchedule != null)
{
tmpEntry.Properties["schedule"].Value = _replicationSchedule;
}
tmpEntry.CommitChanges();
// cached the entry
_ntdsEntry = tmpEntry;
// create servers contain object
tmpEntry = cachedEntry.Children.Add("CN=Servers", "serversContainer");
tmpEntry.CommitChanges();
if (!IsADAM)
{
// create the licensingSiteSettings object
tmpEntry = cachedEntry.Children.Add("CN=Licensing Site Settings", "licensingSiteSettings");
tmpEntry.CommitChanges();
}
}
finally
{
// entry is created on the backend store successfully
existing = true;
}
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
public void Delete()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!existing)
{
throw new InvalidOperationException(SR.CannotDelete);
}
else
{
try
{
cachedEntry.DeleteTree();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public override string ToString()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return _name;
}
private ReadOnlyDirectoryServerCollection GetBridgeheadServers()
{
NativeComInterfaces.IAdsPathname pathCracker = (NativeComInterfaces.IAdsPathname)new NativeComInterfaces.Pathname();
// need to turn off the escaping for name
pathCracker.EscapedMode = NativeComInterfaces.ADS_ESCAPEDMODE_OFF_EX;
ReadOnlyDirectoryServerCollection collection = new ReadOnlyDirectoryServerCollection();
if (existing)
{
Hashtable bridgeHeadTable = new Hashtable();
Hashtable nonBridgHeadTable = new Hashtable();
Hashtable hostNameTable = new Hashtable();
const string ocValue = "CN=Server";
// get destination bridgehead servers
// first go to the servers container under the current site and then do a search to get the all server objects.
string serverContainer = "CN=Servers," + (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName);
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, serverContainer);
try
{
// go through connection objects and find out its fromServer property.
ADSearcher adSearcher = new ADSearcher(de,
"(|(objectCategory=server)(objectCategory=NTDSConnection))",
new string[] { "fromServer", "distinguishedName", "dNSHostName", "objectCategory" },
SearchScope.Subtree,
true, /* need paged search */
true /* need cached result as we need to go back to the first record */);
SearchResultCollection conResults = null;
try
{
conResults = adSearcher.FindAll();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
try
{
// find out whether fromServer indicates replicating from a server in another site.
foreach (SearchResult r in conResults)
{
string objectCategoryValue = (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.ObjectCategory);
if (Utils.Compare(objectCategoryValue, 0, ocValue.Length, ocValue, 0, ocValue.Length) == 0)
{
hostNameTable.Add((string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DistinguishedName), (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DnsHostName));
}
}
foreach (SearchResult r in conResults)
{
string objectCategoryValue = (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.ObjectCategory);
if (Utils.Compare(objectCategoryValue, 0, ocValue.Length, ocValue, 0, ocValue.Length) != 0)
{
string fromServer = (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.FromServer);
// escaping manipulation
string fromSite = Utils.GetPartialDN(fromServer, 3);
pathCracker.Set(fromSite, NativeComInterfaces.ADS_SETTYPE_DN);
fromSite = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF);
Debug.Assert(fromSite != null && Utils.Compare(fromSite, 0, 3, "CN=", 0, 3) == 0);
fromSite = fromSite.Substring(3);
string serverObjectName = Utils.GetPartialDN((string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DistinguishedName), 2);
// don't know whether it is a bridgehead server yet.
if (!bridgeHeadTable.Contains(serverObjectName))
{
string hostName = (string)hostNameTable[serverObjectName];
// add if not yet done
if (!nonBridgHeadTable.Contains(serverObjectName))
nonBridgHeadTable.Add(serverObjectName, hostName);
// check whether from different site
if (Utils.Compare((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.Cn), fromSite) != 0)
{
// the server is a bridgehead server
bridgeHeadTable.Add(serverObjectName, hostName);
nonBridgHeadTable.Remove(serverObjectName);
}
}
}
}
}
finally
{
conResults.Dispose();
}
}
finally
{
de.Dispose();
}
// get source bridgehead server
if (nonBridgHeadTable.Count != 0)
{
// go to sites container to get all the connecdtion object that replicates from servers in the current sites that have
// not been determined whether it is a bridgehead server or not.
DirectoryEntry serverEntry = DirectoryEntryManager.GetDirectoryEntry(context, _siteDN);
// constructing the filter
StringBuilder str = new StringBuilder(100);
if (nonBridgHeadTable.Count > 1)
str.Append("(|");
foreach (DictionaryEntry val in nonBridgHeadTable)
{
str.Append("(fromServer=");
str.Append("CN=NTDS Settings,");
str.Append(Utils.GetEscapedFilterValue((string)val.Key));
str.Append(")");
}
if (nonBridgHeadTable.Count > 1)
str.Append(")");
ADSearcher adSearcher = new ADSearcher(serverEntry,
"(&(objectClass=nTDSConnection)(objectCategory=NTDSConnection)" + str.ToString() + ")",
new string[] { "fromServer", "distinguishedName" },
SearchScope.Subtree);
SearchResultCollection conResults = null;
try
{
conResults = adSearcher.FindAll();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
try
{
foreach (SearchResult r in conResults)
{
string fromServer = (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.FromServer);
string serverObject = fromServer.Substring(17);
if (nonBridgHeadTable.Contains(serverObject))
{
string otherSite = Utils.GetPartialDN((string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DistinguishedName), 4);
// escaping manipulation
pathCracker.Set(otherSite, NativeComInterfaces.ADS_SETTYPE_DN);
otherSite = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF);
Debug.Assert(otherSite != null && Utils.Compare(otherSite, 0, 3, "CN=", 0, 3) == 0);
otherSite = otherSite.Substring(3);
// check whether from different sites
if (Utils.Compare(otherSite, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.Cn)) != 0)
{
string val = (string)nonBridgHeadTable[serverObject];
nonBridgHeadTable.Remove(serverObject);
bridgeHeadTable.Add(serverObject, val);
}
}
}
}
finally
{
conResults.Dispose();
serverEntry.Dispose();
}
}
DirectoryEntry ADAMEntry = null;
foreach (DictionaryEntry e in bridgeHeadTable)
{
DirectoryServer replica = null;
string host = (string)e.Value;
// construct directoryreplica
if (IsADAM)
{
ADAMEntry = DirectoryEntryManager.GetDirectoryEntry(context, "CN=NTDS Settings," + e.Key);
int port = (int)PropertyManager.GetPropertyValue(context, ADAMEntry, PropertyManager.MsDSPortLDAP);
string fullhost = host;
if (port != 389)
{
fullhost = host + ":" + port;
}
replica = new AdamInstance(Utils.GetNewDirectoryContext(fullhost, DirectoryContextType.DirectoryServer, context), fullhost);
}
else
{
replica = new DomainController(Utils.GetNewDirectoryContext(host, DirectoryContextType.DirectoryServer, context), host);
}
collection.Add(replica);
}
}
return collection;
}
public DirectoryEntry GetDirectoryEntry()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!existing)
{
throw new InvalidOperationException(SR.CannotGetObject);
}
else
{
return DirectoryEntryManager.GetDirectoryEntryInternal(context, cachedEntry.Path);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free other state (managed objects)
if (cachedEntry != null)
cachedEntry.Dispose();
if (_ntdsEntry != null)
_ntdsEntry.Dispose();
}
// free your own state (unmanaged objects)
_disposed = true;
}
private static void ValidateArgument(DirectoryContext context, string siteName)
{
// basic validation first
if (context == null)
throw new ArgumentNullException("context");
// if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail
if ((context.Name == null) && (!context.isRootDomain()))
{
throw new ArgumentException(SR.ContextNotAssociatedWithDomain, "context");
}
// more validation for the context, if the target is not null, then it should be either forest name or server name
if (context.Name != null)
{
if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet()))
throw new ArgumentException(SR.NotADOrADAM, "context");
}
if (siteName == null)
throw new ArgumentNullException("siteName");
if (siteName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, "siteName");
}
private void GetSubnets()
{
// performs a search to find out the subnets that belong to this site
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext);
string subnetContainer = "CN=Subnets,CN=Sites," + config;
de = DirectoryEntryManager.GetDirectoryEntry(context, subnetContainer);
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=subnet)(objectCategory=subnet)(siteObject=" + Utils.GetEscapedFilterValue((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)) + "))",
new string[] { "cn", "location" },
SearchScope.OneLevel
);
SearchResultCollection results = null;
try
{
results = adSearcher.FindAll();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
try
{
string subnetName = null;
foreach (SearchResult result in results)
{
subnetName = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.Cn);
ActiveDirectorySubnet subnet = new ActiveDirectorySubnet(context, subnetName, null, true);
// set the cached entry
subnet.cachedEntry = result.GetDirectoryEntry();
// set the site info
subnet.Site = this;
_subnets.Add(subnet);
}
}
finally
{
results.Dispose();
de.Dispose();
}
}
private void GetAdjacentSites()
{
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
string config = (string)de.Properties["configurationNamingContext"][0];
string transportContainer = "CN=Inter-Site Transports,CN=Sites," + config;
de = DirectoryEntryManager.GetDirectoryEntry(context, transportContainer);
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=siteLink)(objectCategory=SiteLink)(siteList=" + Utils.GetEscapedFilterValue((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)) + "))",
new string[] { "cn", "distinguishedName" },
SearchScope.Subtree);
SearchResultCollection results = null;
try
{
results = adSearcher.FindAll();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
try
{
ActiveDirectorySiteLink link = null;
foreach (SearchResult result in results)
{
string dn = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.DistinguishedName);
string linkName = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.Cn);
string transportName = (string)Utils.GetDNComponents(dn)[1].Value;
ActiveDirectoryTransportType transportType;
if (String.Compare(transportName, "IP", StringComparison.OrdinalIgnoreCase) == 0)
transportType = ActiveDirectoryTransportType.Rpc;
else if (String.Compare(transportName, "SMTP", StringComparison.OrdinalIgnoreCase) == 0)
transportType = ActiveDirectoryTransportType.Smtp;
else
{
// should not happen
string message = String.Format(CultureInfo.CurrentCulture, SR.UnknownTransport , transportName);
throw new ActiveDirectoryOperationException(message);
}
try
{
link = new ActiveDirectorySiteLink(context, linkName, transportType, true, result.GetDirectoryEntry());
foreach (ActiveDirectorySite tmpSite in link.Sites)
{
// don't add itself
if (Utils.Compare(tmpSite.Name, Name) == 0)
continue;
if (!_adjacentSites.Contains(tmpSite))
_adjacentSites.Add(tmpSite);
}
}
finally
{
link.Dispose();
}
}
}
finally
{
results.Dispose();
de.Dispose();
}
}
private void GetLinks()
{
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext);
string transportContainer = "CN=Inter-Site Transports,CN=Sites," + config;
de = DirectoryEntryManager.GetDirectoryEntry(context, transportContainer);
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=siteLink)(objectCategory=SiteLink)(siteList=" + Utils.GetEscapedFilterValue((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)) + "))",
new string[] { "cn", "distinguishedName" },
SearchScope.Subtree);
SearchResultCollection results = null;
try
{
results = adSearcher.FindAll();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
try
{
foreach (SearchResult result in results)
{
// construct the sitelinks at the same time
DirectoryEntry connectionEntry = result.GetDirectoryEntry();
string cn = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.Cn);
string transport = Utils.GetDNComponents((string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.DistinguishedName))[1].Value;
ActiveDirectorySiteLink link = null;
if (String.Compare(transport, "IP", StringComparison.OrdinalIgnoreCase) == 0)
link = new ActiveDirectorySiteLink(context, cn, ActiveDirectoryTransportType.Rpc, true, connectionEntry);
else if (String.Compare(transport, "SMTP", StringComparison.OrdinalIgnoreCase) == 0)
link = new ActiveDirectorySiteLink(context, cn, ActiveDirectoryTransportType.Smtp, true, connectionEntry);
else
{
// should not happen
string message = String.Format(CultureInfo.CurrentCulture, SR.UnknownTransport , transport);
throw new ActiveDirectoryOperationException(message);
}
_links.Add(link);
}
}
finally
{
results.Dispose();
de.Dispose();
}
}
private void GetDomains()
{
// for ADAM, there is no concept of domain, we just return empty collection which is good enough
if (!IsADAM)
{
string serverName = cachedEntry.Options.GetCurrentServerName();
DomainController dc = DomainController.GetDomainController(Utils.GetNewDirectoryContext(serverName, DirectoryContextType.DirectoryServer, context));
IntPtr handle = dc.Handle;
Debug.Assert(handle != (IntPtr)0);
IntPtr info = (IntPtr)0;
// call DsReplicaSyncAllW
IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
UnsafeNativeMethods.DsListDomainsInSiteW dsListDomainsInSiteW = (UnsafeNativeMethods.DsListDomainsInSiteW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsListDomainsInSiteW));
int result = dsListDomainsInSiteW(handle, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName), ref info);
if (result != 0)
throw ExceptionHelper.GetExceptionFromErrorCode(result, serverName);
try
{
DS_NAME_RESULT names = new DS_NAME_RESULT();
Marshal.PtrToStructure(info, names);
int count = names.cItems;
IntPtr val = names.rItems;
if (count > 0)
{
Debug.Assert(val != (IntPtr)0);
int status = Marshal.ReadInt32(val);
IntPtr tmpPtr = (IntPtr)0;
for (int i = 0; i < count; i++)
{
tmpPtr = IntPtr.Add(val, Marshal.SizeOf(typeof(DS_NAME_RESULT_ITEM)) * i);
DS_NAME_RESULT_ITEM nameResult = new DS_NAME_RESULT_ITEM();
Marshal.PtrToStructure(tmpPtr, nameResult);
if (nameResult.status == DS_NAME_ERROR.DS_NAME_NO_ERROR || nameResult.status == DS_NAME_ERROR.DS_NAME_ERROR_DOMAIN_ONLY)
{
string domainName = Marshal.PtrToStringUni(nameResult.pName);
if (domainName != null && domainName.Length > 0)
{
string d = Utils.GetDnsNameFromDN(domainName);
Domain domain = new Domain(Utils.GetNewDirectoryContext(d, DirectoryContextType.Domain, context), d);
_domains.Add(domain);
}
}
}
}
}
finally
{
// call DsFreeNameResultW
functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
UnsafeNativeMethods.DsFreeNameResultW dsFreeNameResultW = (UnsafeNativeMethods.DsFreeNameResultW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsFreeNameResultW));
dsFreeNameResultW(info);
}
}
}
private void GetServers()
{
ADSearcher adSearcher = new ADSearcher(cachedEntry,
"(&(objectClass=server)(objectCategory=server))",
new string[] { "dNSHostName" },
SearchScope.Subtree);
SearchResultCollection results = null;
try
{
results = adSearcher.FindAll();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
try
{
foreach (SearchResult result in results)
{
string hostName = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.DnsHostName);
DirectoryEntry de = result.GetDirectoryEntry();
DirectoryEntry child = null;
DirectoryServer replica = null;
// make sure that the server is not demoted
try
{
child = de.Children.Find("CN=NTDS Settings", "nTDSDSA");
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
continue;
}
else
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (IsADAM)
{
int port = (int)PropertyManager.GetPropertyValue(context, child, PropertyManager.MsDSPortLDAP);
string fullHostName = hostName;
if (port != 389)
{
fullHostName = hostName + ":" + port;
}
replica = new AdamInstance(Utils.GetNewDirectoryContext(fullHostName, DirectoryContextType.DirectoryServer, context), fullHostName);
}
else
replica = new DomainController(Utils.GetNewDirectoryContext(hostName, DirectoryContextType.DirectoryServer, context), hostName);
_servers.Add(replica);
}
}
finally
{
results.Dispose();
}
}
private void GetPreferredBridgeheadServers(ActiveDirectoryTransportType transport)
{
string serverContainerDN = "CN=Servers," + PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName);
string transportDN = null;
if (transport == ActiveDirectoryTransportType.Smtp)
transportDN = "CN=SMTP,CN=Inter-Site Transports," + _siteDN;
else
transportDN = "CN=IP,CN=Inter-Site Transports," + _siteDN;
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, serverContainerDN);
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=server)(objectCategory=Server)(bridgeheadTransportList=" + Utils.GetEscapedFilterValue(transportDN) + "))",
new string[] { "dNSHostName", "distinguishedName" },
SearchScope.OneLevel);
SearchResultCollection results = null;
try
{
results = adSearcher.FindAll();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
try
{
DirectoryEntry ADAMEntry = null;
foreach (SearchResult result in results)
{
string hostName = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.DnsHostName);
DirectoryEntry resultEntry = result.GetDirectoryEntry();
DirectoryServer replica = null;
try
{
ADAMEntry = resultEntry.Children.Find("CN=NTDS Settings", "nTDSDSA");
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (IsADAM)
{
int port = (int)PropertyManager.GetPropertyValue(context, ADAMEntry, PropertyManager.MsDSPortLDAP);
string fullHostName = hostName;
if (port != 389)
{
fullHostName = hostName + ":" + port;
}
replica = new AdamInstance(Utils.GetNewDirectoryContext(fullHostName, DirectoryContextType.DirectoryServer, context), fullHostName);
}
else
replica = new DomainController(Utils.GetNewDirectoryContext(hostName, DirectoryContextType.DirectoryServer, context), hostName);
if (transport == ActiveDirectoryTransportType.Smtp)
_SMTPBridgeheadServers.Add(replica);
else
_RPCBridgeheadServers.Add(replica);
}
}
finally
{
de.Dispose();
results.Dispose();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.SpanTests
{
public static partial class SpanTests
{
[Fact]
public static void LastIndexOfSequenceMatchAtStart()
{
Span<int> span = new Span<int>(new int[] { 5, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
Span<int> value = new Span<int>(new int[] { 5, 1, 77 });
int index = span.LastIndexOf(value);
Assert.Equal(0, index);
}
[Fact]
public static void LastIndexOfSequenceMultipleMatch()
{
Span<int> span = new Span<int>(new int[] { 1, 2, 3, 1, 2, 3, 1, 2, 3, 1 });
Span<int> value = new Span<int>(new int[] { 2, 3 });
int index = span.LastIndexOf(value);
Assert.Equal(7, index);
}
[Fact]
public static void LastIndexOfSequenceRestart()
{
Span<int> span = new Span<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 8, 9, 77, 0, 1 });
Span<int> value = new Span<int>(new int[] { 77, 77, 88 });
int index = span.LastIndexOf(value);
Assert.Equal(10, index);
}
[Fact]
public static void LastIndexOfSequenceNoMatch()
{
Span<int> span = new Span<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
Span<int> value = new Span<int>(new int[] { 77, 77, 88, 99 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceNotEvenAHeadMatch()
{
Span<int> span = new Span<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
Span<int> value = new Span<int>(new int[] { 100, 77, 88, 99 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceMatchAtVeryEnd()
{
Span<int> span = new Span<int>(new int[] { 0, 1, 2, 3, 4, 5 });
Span<int> value = new Span<int>(new int[] { 3, 4, 5 });
int index = span.LastIndexOf(value);
Assert.Equal(3, index);
}
[Fact]
public static void LastIndexOfSequenceJustPastVeryEnd()
{
Span<int> span = new Span<int>(new int[] { 0, 1, 2, 3, 4, 5 }, 0, 5);
Span<int> value = new Span<int>(new int[] { 3, 4, 5 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceZeroLengthValue()
{
// A zero-length value is always "found" at the start of the span.
Span<int> span = new Span<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
Span<int> value = new Span<int>(Array.Empty<int>());
int index = span.LastIndexOf(value);
Assert.Equal(0, index);
}
[Fact]
public static void LastIndexOfSequenceZeroLengthSpan()
{
Span<int> span = new Span<int>(Array.Empty<int>());
Span<int> value = new Span<int>(new int[] { 1, 2, 3 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValue()
{
// A zero-length value is always "found" at the start of the span.
Span<int> span = new Span<int>(new int[] { 0, 1, 2, 3, 4, 5 });
Span<int> value = new Span<int>(new int[] { 2 });
int index = span.LastIndexOf(value);
Assert.Equal(2, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValueAtVeryEnd()
{
// A zero-length value is always "found" at the start of the span.
Span<int> span = new Span<int>(new int[] { 0, 1, 2, 3, 4, 5 });
Span<int> value = new Span<int>(new int[] { 5 });
int index = span.LastIndexOf(value);
Assert.Equal(5, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValueMultipleTimes()
{
// A zero-length value is always "found" at the start of the span.
Span<int> span = new Span<int>(new int[] { 0, 1, 5, 3, 4, 5 });
Span<int> value = new Span<int>(new int[] { 5 });
int index = span.LastIndexOf(value);
Assert.Equal(5, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValueJustPasttVeryEnd()
{
// A zero-length value is always "found" at the start of the span.
Span<int> span = new Span<int>(new int[] { 0, 1, 2, 3, 4, 5 }, 0, 5);
Span<int> value = new Span<int>(new int[] { 5 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceMatchAtStart_String()
{
Span<string> span = new Span<string>(new string[] { "5", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" });
Span<string> value = new Span<string>(new string[] { "5", "1", "77" });
int index = span.LastIndexOf(value);
Assert.Equal(0, index);
}
[Fact]
public static void LastIndexOfSequenceMultipleMatch_String()
{
Span<string> span = new Span<string>(new string[] { "1", "2", "3", "1", "2", "3", "1", "2", "3" });
Span<string> value = new Span<string>(new string[] { "2", "3" });
int index = span.LastIndexOf(value);
Assert.Equal(7, index);
}
[Fact]
public static void LastIndexOfSequenceRestart_String()
{
Span<string> span = new Span<string>(new string[] { "0", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "8", "9", "77", "0", "1" });
Span<string> value = new Span<string>(new string[] { "77", "77", "88" });
int index = span.LastIndexOf(value);
Assert.Equal(10, index);
}
[Fact]
public static void LastIndexOfSequenceNoMatch_String()
{
Span<string> span = new Span<string>(new string[] { "0", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" });
Span<string> value = new Span<string>(new string[] { "77", "77", "88", "99" });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceNotEvenAHeadMatch_String()
{
Span<string> span = new Span<string>(new string[] { "0", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" });
Span<string> value = new Span<string>(new string[] { "100", "77", "88", "99" });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceMatchAtVeryEnd_String()
{
Span<string> span = new Span<string>(new string[] { "0", "1", "2", "3", "4", "5" });
Span<string> value = new Span<string>(new string[] { "3", "4", "5" });
int index = span.LastIndexOf(value);
Assert.Equal(3, index);
}
[Fact]
public static void LastIndexOfSequenceJustPastVeryEnd_String()
{
Span<string> span = new Span<string>(new string[] { "0", "1", "2", "3", "4", "5" }, 0, 5);
Span<string> value = new Span<string>(new string[] { "3", "4", "5" });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceZeroLengthValue_String()
{
// A zero-length value is always "found" at the start of the span.
Span<string> span = new Span<string>(new string[] { "0", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" });
Span<string> value = new Span<string>(Array.Empty<string>());
int index = span.LastIndexOf(value);
Assert.Equal(0, index);
}
[Fact]
public static void LastIndexOfSequenceZeroLengthSpan_String()
{
Span<string> span = new Span<string>(Array.Empty<string>());
Span<string> value = new Span<string>(new string[] { "1", "2", "3" });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValue_String()
{
// A zero-length value is always "found" at the start of the span.
Span<string> span = new Span<string>(new string[] { "0", "1", "2", "3", "4", "5" });
Span<string> value = new Span<string>(new string[] { "2" });
int index = span.LastIndexOf(value);
Assert.Equal(2, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValueAtVeryEnd_String()
{
// A zero-length value is always "found" at the start of the span.
Span<string> span = new Span<string>(new string[] { "0", "1", "2", "3", "4", "5" });
Span<string> value = new Span<string>(new string[] { "5" });
int index = span.LastIndexOf(value);
Assert.Equal(5, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValueJustPasttVeryEnd_String()
{
// A zero-length value is always "found" at the start of the span.
Span<string> span = new Span<string>(new string[] { "0", "1", "2", "3", "4", "5" }, 0, 5);
Span<string> value = new Span<string>(new string[] { "5" });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Theory]
[MemberData(nameof(TestHelpers.LastIndexOfNullSequenceData), MemberType = typeof(TestHelpers))]
public static void LastIndexOfNullSequence_String(string[] spanInput, string[] searchInput, int expected)
{
Span<string> theStrings = spanInput;
Assert.Equal(expected, theStrings.LastIndexOf(searchInput));
Assert.Equal(expected, theStrings.LastIndexOf((ReadOnlySpan<string>)searchInput));
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Lucene.Net.Util;
using NUnit.Framework;
using Document = Lucene.Net.Documents.Document;
using FieldSelector = Lucene.Net.Documents.FieldSelector;
using CorruptIndexException = Lucene.Net.Index.CorruptIndexException;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using TermPositions = Lucene.Net.Index.TermPositions;
namespace Lucene.Net.Search
{
/// <summary> Holds all implementations of classes in the o.a.l.search package as a
/// back-compatibility test. It does not run any tests per-se, however if
/// someone adds a method to an interface or abstract method to an abstract
/// class, one of the implementations here will fail to compile and so we know
/// back-compat policy was violated.
/// </summary>
sealed class JustCompileSearch
{
private const System.String UNSUPPORTED_MSG = "unsupported: used for back-compat testing only !";
internal sealed class JustCompileSearcher:Searcher
{
public /*protected internal*/ override Weight CreateWeight(Query query)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
protected override void Dispose(bool disposing)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override Document Doc(int i)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override int[] DocFreqs(Term[] terms)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override Explanation Explain(Query query, int doc)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override Similarity Similarity
{
get { throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG); }
set { throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG); }
}
public override void Search(Query query, Collector results)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override void Search(Query query, Filter filter, Collector results)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override TopDocs Search(Query query, Filter filter, int n)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override TopFieldDocs Search(Query query, Filter filter, int n, Sort sort)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override TopDocs Search(Query query, int n)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override int DocFreq(Term term)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override Explanation Explain(Weight weight, int doc)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override int MaxDoc
{
get
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
public override Query Rewrite(Query query)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override void Search(Weight weight, Filter filter, Collector results)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override TopDocs Search(Weight weight, Filter filter, int n)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override TopFieldDocs Search(Weight weight, Filter filter, int n, Sort sort)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override Document Doc(int n, FieldSelector fieldSelector)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
internal sealed class JustCompileCollector:Collector
{
public override void Collect(int doc)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override void SetNextReader(IndexReader reader, int docBase)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override void SetScorer(Scorer scorer)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override bool AcceptsDocsOutOfOrder
{
get { throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG); }
}
}
internal sealed class JustCompileDocIdSet:DocIdSet
{
public override DocIdSetIterator Iterator()
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
internal sealed class JustCompileDocIdSetIterator:DocIdSetIterator
{
public override int DocID()
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override int NextDoc()
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override int Advance(int target)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
[Serializable]
internal sealed class JustCompileExtendedFieldCacheLongParser : Lucene.Net.Search.LongParser
{
public long ParseLong(System.String string_Renamed)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
[Serializable]
internal sealed class JustCompileExtendedFieldCacheDoubleParser : Lucene.Net.Search.DoubleParser
{
public double ParseDouble(System.String string_Renamed)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
internal sealed class JustCompileFieldComparator:FieldComparator
{
public override int Compare(int slot1, int slot2)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override int CompareBottom(int doc)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override void Copy(int slot, int doc)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override void SetBottom(int slot)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override void SetNextReader(IndexReader reader, int docBase)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override IComparable this[int slot]
{
get { throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG); }
}
}
[Serializable]
internal sealed class JustCompileFieldComparatorSource:FieldComparatorSource
{
public override FieldComparator NewComparator(System.String fieldname, int numHits, int sortPos, bool reversed)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
[Serializable]
internal sealed class JustCompileFilter:Filter
{
// Filter is just an abstract class with no abstract methods. However it is
// still added here in case someone will add abstract methods in the future.
public override DocIdSet GetDocIdSet(IndexReader reader)
{
return null;
}
}
internal sealed class JustCompileFilteredDocIdSet:FilteredDocIdSet
{
public JustCompileFilteredDocIdSet(DocIdSet innerSet):base(innerSet)
{
}
public /*protected internal*/ override bool Match(int docid)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
internal sealed class JustCompileFilteredDocIdSetIterator:FilteredDocIdSetIterator
{
public JustCompileFilteredDocIdSetIterator(DocIdSetIterator innerIter):base(innerIter)
{
}
public /*protected internal*/ override bool Match(int doc)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
internal sealed class JustCompileFilteredTermEnum:FilteredTermEnum
{
public override float Difference()
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override bool EndEnum()
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
/*protected internal*/ protected internal override bool TermCompare(Term term)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
/*internal sealed class JustCompilePhraseScorer : Lucene.Net.Search.PhraseScorer // {{Not needed for Lucene.Net}}
{
internal JustCompilePhraseScorer(Weight weight, TermPositions[] tps, int[] offsets, Similarity similarity, byte[] norms)
: base(weight, tps, offsets, similarity, norms)
{
}
protected internal override float PhraseFreq()
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}*/
[Serializable]
internal sealed class JustCompileQuery:Query
{
public override System.String ToString(System.String field)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
internal sealed class JustCompileScorer:Scorer
{
internal JustCompileScorer(Similarity similarity):base(similarity)
{
}
public /*protected internal*/ override bool Score(Collector collector, int max, int firstDocID)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override float Score()
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override int DocID()
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override int NextDoc()
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override int Advance(int target)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
[Serializable]
internal sealed class JustCompileSimilarity:Similarity
{
public override float Coord(int overlap, int maxOverlap)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override float Idf(int docFreq, int numDocs)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override float LengthNorm(System.String fieldName, int numTokens)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override float QueryNorm(float sumOfSquaredWeights)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override float SloppyFreq(int distance)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override float Tf(float freq)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
[Serializable]
internal sealed class JustCompileSpanFilter:SpanFilter
{
public override SpanFilterResult BitSpans(IndexReader reader)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override DocIdSet GetDocIdSet(IndexReader reader)
{
return null;
}
}
internal sealed class JustCompileTopDocsCollector : TopDocsCollector<ScoreDoc>
{
internal JustCompileTopDocsCollector(PriorityQueue<ScoreDoc> pq)
: base(pq)
{
}
public override void Collect(int doc)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override void SetNextReader(IndexReader reader, int docBase)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override void SetScorer(Scorer scorer)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override bool AcceptsDocsOutOfOrder
{
get { throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG); }
}
}
[Serializable]
internal sealed class JustCompileWeight:Weight
{
public override Explanation Explain(IndexReader reader, int doc)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override Query Query
{
get { throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG); }
}
public override float Value
{
get { throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG); }
}
public override void Normalize(float norm)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override float GetSumOfSquaredWeights()
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
public override Scorer Scorer(IndexReader reader, bool scoreDocsInOrder, bool topScorer)
{
throw new System.NotSupportedException(Lucene.Net.Search.JustCompileSearch.UNSUPPORTED_MSG);
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Steamworks.Data;
namespace Steamworks
{
internal unsafe class ISteamInput : SteamInterface
{
internal ISteamInput( bool IsGameServer )
{
SetupInterface( IsGameServer );
}
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_SteamInput_v006", CallingConvention = Platform.CC)]
internal static extern IntPtr SteamAPI_SteamInput_v006();
public override IntPtr GetUserInterfacePointer() => SteamAPI_SteamInput_v006();
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_Init", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _Init( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bExplicitlyCallRunFrame );
#endregion
internal bool Init( [MarshalAs( UnmanagedType.U1 )] bool bExplicitlyCallRunFrame )
{
var returnValue = _Init( Self, bExplicitlyCallRunFrame );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_Shutdown", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _Shutdown( IntPtr self );
#endregion
internal bool Shutdown()
{
var returnValue = _Shutdown( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_SetInputActionManifestFilePath", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetInputActionManifestFilePath( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchInputActionManifestAbsolutePath );
#endregion
internal bool SetInputActionManifestFilePath( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchInputActionManifestAbsolutePath )
{
var returnValue = _SetInputActionManifestFilePath( Self, pchInputActionManifestAbsolutePath );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_RunFrame", CallingConvention = Platform.CC)]
private static extern void _RunFrame( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bReservedValue );
#endregion
internal void RunFrame( [MarshalAs( UnmanagedType.U1 )] bool bReservedValue )
{
_RunFrame( Self, bReservedValue );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_BWaitForData", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _BWaitForData( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bWaitForever, uint unTimeout );
#endregion
internal bool BWaitForData( [MarshalAs( UnmanagedType.U1 )] bool bWaitForever, uint unTimeout )
{
var returnValue = _BWaitForData( Self, bWaitForever, unTimeout );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_BNewDataAvailable", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _BNewDataAvailable( IntPtr self );
#endregion
internal bool BNewDataAvailable()
{
var returnValue = _BNewDataAvailable( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetConnectedControllers", CallingConvention = Platform.CC)]
private static extern int _GetConnectedControllers( IntPtr self, [In,Out] InputHandle_t[] handlesOut );
#endregion
internal int GetConnectedControllers( [In,Out] InputHandle_t[] handlesOut )
{
var returnValue = _GetConnectedControllers( Self, handlesOut );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_EnableDeviceCallbacks", CallingConvention = Platform.CC)]
private static extern void _EnableDeviceCallbacks( IntPtr self );
#endregion
internal void EnableDeviceCallbacks()
{
_EnableDeviceCallbacks( Self );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetActionSetHandle", CallingConvention = Platform.CC)]
private static extern InputActionSetHandle_t _GetActionSetHandle( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszActionSetName );
#endregion
internal InputActionSetHandle_t GetActionSetHandle( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszActionSetName )
{
var returnValue = _GetActionSetHandle( Self, pszActionSetName );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_ActivateActionSet", CallingConvention = Platform.CC)]
private static extern void _ActivateActionSet( IntPtr self, InputHandle_t inputHandle, InputActionSetHandle_t actionSetHandle );
#endregion
internal void ActivateActionSet( InputHandle_t inputHandle, InputActionSetHandle_t actionSetHandle )
{
_ActivateActionSet( Self, inputHandle, actionSetHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetCurrentActionSet", CallingConvention = Platform.CC)]
private static extern InputActionSetHandle_t _GetCurrentActionSet( IntPtr self, InputHandle_t inputHandle );
#endregion
internal InputActionSetHandle_t GetCurrentActionSet( InputHandle_t inputHandle )
{
var returnValue = _GetCurrentActionSet( Self, inputHandle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_ActivateActionSetLayer", CallingConvention = Platform.CC)]
private static extern void _ActivateActionSetLayer( IntPtr self, InputHandle_t inputHandle, InputActionSetHandle_t actionSetLayerHandle );
#endregion
internal void ActivateActionSetLayer( InputHandle_t inputHandle, InputActionSetHandle_t actionSetLayerHandle )
{
_ActivateActionSetLayer( Self, inputHandle, actionSetLayerHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_DeactivateActionSetLayer", CallingConvention = Platform.CC)]
private static extern void _DeactivateActionSetLayer( IntPtr self, InputHandle_t inputHandle, InputActionSetHandle_t actionSetLayerHandle );
#endregion
internal void DeactivateActionSetLayer( InputHandle_t inputHandle, InputActionSetHandle_t actionSetLayerHandle )
{
_DeactivateActionSetLayer( Self, inputHandle, actionSetLayerHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_DeactivateAllActionSetLayers", CallingConvention = Platform.CC)]
private static extern void _DeactivateAllActionSetLayers( IntPtr self, InputHandle_t inputHandle );
#endregion
internal void DeactivateAllActionSetLayers( InputHandle_t inputHandle )
{
_DeactivateAllActionSetLayers( Self, inputHandle );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetActiveActionSetLayers", CallingConvention = Platform.CC)]
private static extern int _GetActiveActionSetLayers( IntPtr self, InputHandle_t inputHandle, [In,Out] InputActionSetHandle_t[] handlesOut );
#endregion
internal int GetActiveActionSetLayers( InputHandle_t inputHandle, [In,Out] InputActionSetHandle_t[] handlesOut )
{
var returnValue = _GetActiveActionSetLayers( Self, inputHandle, handlesOut );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetDigitalActionHandle", CallingConvention = Platform.CC)]
private static extern InputDigitalActionHandle_t _GetDigitalActionHandle( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszActionName );
#endregion
internal InputDigitalActionHandle_t GetDigitalActionHandle( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszActionName )
{
var returnValue = _GetDigitalActionHandle( Self, pszActionName );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetDigitalActionData", CallingConvention = Platform.CC)]
private static extern DigitalState _GetDigitalActionData( IntPtr self, InputHandle_t inputHandle, InputDigitalActionHandle_t digitalActionHandle );
#endregion
internal DigitalState GetDigitalActionData( InputHandle_t inputHandle, InputDigitalActionHandle_t digitalActionHandle )
{
var returnValue = _GetDigitalActionData( Self, inputHandle, digitalActionHandle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetDigitalActionOrigins", CallingConvention = Platform.CC)]
private static extern int _GetDigitalActionOrigins( IntPtr self, InputHandle_t inputHandle, InputActionSetHandle_t actionSetHandle, InputDigitalActionHandle_t digitalActionHandle, ref InputActionOrigin originsOut );
#endregion
internal int GetDigitalActionOrigins( InputHandle_t inputHandle, InputActionSetHandle_t actionSetHandle, InputDigitalActionHandle_t digitalActionHandle, ref InputActionOrigin originsOut )
{
var returnValue = _GetDigitalActionOrigins( Self, inputHandle, actionSetHandle, digitalActionHandle, ref originsOut );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetStringForDigitalActionName", CallingConvention = Platform.CC)]
private static extern Utf8StringPointer _GetStringForDigitalActionName( IntPtr self, InputDigitalActionHandle_t eActionHandle );
#endregion
internal string GetStringForDigitalActionName( InputDigitalActionHandle_t eActionHandle )
{
var returnValue = _GetStringForDigitalActionName( Self, eActionHandle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetAnalogActionHandle", CallingConvention = Platform.CC)]
private static extern InputAnalogActionHandle_t _GetAnalogActionHandle( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszActionName );
#endregion
internal InputAnalogActionHandle_t GetAnalogActionHandle( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pszActionName )
{
var returnValue = _GetAnalogActionHandle( Self, pszActionName );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetAnalogActionData", CallingConvention = Platform.CC)]
private static extern AnalogState _GetAnalogActionData( IntPtr self, InputHandle_t inputHandle, InputAnalogActionHandle_t analogActionHandle );
#endregion
internal AnalogState GetAnalogActionData( InputHandle_t inputHandle, InputAnalogActionHandle_t analogActionHandle )
{
var returnValue = _GetAnalogActionData( Self, inputHandle, analogActionHandle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetAnalogActionOrigins", CallingConvention = Platform.CC)]
private static extern int _GetAnalogActionOrigins( IntPtr self, InputHandle_t inputHandle, InputActionSetHandle_t actionSetHandle, InputAnalogActionHandle_t analogActionHandle, ref InputActionOrigin originsOut );
#endregion
internal int GetAnalogActionOrigins( InputHandle_t inputHandle, InputActionSetHandle_t actionSetHandle, InputAnalogActionHandle_t analogActionHandle, ref InputActionOrigin originsOut )
{
var returnValue = _GetAnalogActionOrigins( Self, inputHandle, actionSetHandle, analogActionHandle, ref originsOut );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetGlyphPNGForActionOrigin", CallingConvention = Platform.CC)]
private static extern Utf8StringPointer _GetGlyphPNGForActionOrigin( IntPtr self, InputActionOrigin eOrigin, GlyphSize eSize, uint unFlags );
#endregion
internal string GetGlyphPNGForActionOrigin( InputActionOrigin eOrigin, GlyphSize eSize, uint unFlags )
{
var returnValue = _GetGlyphPNGForActionOrigin( Self, eOrigin, eSize, unFlags );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetGlyphSVGForActionOrigin", CallingConvention = Platform.CC)]
private static extern Utf8StringPointer _GetGlyphSVGForActionOrigin( IntPtr self, InputActionOrigin eOrigin, uint unFlags );
#endregion
internal string GetGlyphSVGForActionOrigin( InputActionOrigin eOrigin, uint unFlags )
{
var returnValue = _GetGlyphSVGForActionOrigin( Self, eOrigin, unFlags );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetGlyphForActionOrigin_Legacy", CallingConvention = Platform.CC)]
private static extern Utf8StringPointer _GetGlyphForActionOrigin_Legacy( IntPtr self, InputActionOrigin eOrigin );
#endregion
internal string GetGlyphForActionOrigin_Legacy( InputActionOrigin eOrigin )
{
var returnValue = _GetGlyphForActionOrigin_Legacy( Self, eOrigin );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetStringForActionOrigin", CallingConvention = Platform.CC)]
private static extern Utf8StringPointer _GetStringForActionOrigin( IntPtr self, InputActionOrigin eOrigin );
#endregion
internal string GetStringForActionOrigin( InputActionOrigin eOrigin )
{
var returnValue = _GetStringForActionOrigin( Self, eOrigin );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetStringForAnalogActionName", CallingConvention = Platform.CC)]
private static extern Utf8StringPointer _GetStringForAnalogActionName( IntPtr self, InputAnalogActionHandle_t eActionHandle );
#endregion
internal string GetStringForAnalogActionName( InputAnalogActionHandle_t eActionHandle )
{
var returnValue = _GetStringForAnalogActionName( Self, eActionHandle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_StopAnalogActionMomentum", CallingConvention = Platform.CC)]
private static extern void _StopAnalogActionMomentum( IntPtr self, InputHandle_t inputHandle, InputAnalogActionHandle_t eAction );
#endregion
internal void StopAnalogActionMomentum( InputHandle_t inputHandle, InputAnalogActionHandle_t eAction )
{
_StopAnalogActionMomentum( Self, inputHandle, eAction );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetMotionData", CallingConvention = Platform.CC)]
private static extern MotionState _GetMotionData( IntPtr self, InputHandle_t inputHandle );
#endregion
internal MotionState GetMotionData( InputHandle_t inputHandle )
{
var returnValue = _GetMotionData( Self, inputHandle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_TriggerVibration", CallingConvention = Platform.CC)]
private static extern void _TriggerVibration( IntPtr self, InputHandle_t inputHandle, ushort usLeftSpeed, ushort usRightSpeed );
#endregion
internal void TriggerVibration( InputHandle_t inputHandle, ushort usLeftSpeed, ushort usRightSpeed )
{
_TriggerVibration( Self, inputHandle, usLeftSpeed, usRightSpeed );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_TriggerVibrationExtended", CallingConvention = Platform.CC)]
private static extern void _TriggerVibrationExtended( IntPtr self, InputHandle_t inputHandle, ushort usLeftSpeed, ushort usRightSpeed, ushort usLeftTriggerSpeed, ushort usRightTriggerSpeed );
#endregion
internal void TriggerVibrationExtended( InputHandle_t inputHandle, ushort usLeftSpeed, ushort usRightSpeed, ushort usLeftTriggerSpeed, ushort usRightTriggerSpeed )
{
_TriggerVibrationExtended( Self, inputHandle, usLeftSpeed, usRightSpeed, usLeftTriggerSpeed, usRightTriggerSpeed );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_TriggerSimpleHapticEvent", CallingConvention = Platform.CC)]
private static extern void _TriggerSimpleHapticEvent( IntPtr self, InputHandle_t inputHandle, ControllerHapticLocation eHapticLocation, byte nIntensity, char nGainDB, byte nOtherIntensity, char nOtherGainDB );
#endregion
internal void TriggerSimpleHapticEvent( InputHandle_t inputHandle, ControllerHapticLocation eHapticLocation, byte nIntensity, char nGainDB, byte nOtherIntensity, char nOtherGainDB )
{
_TriggerSimpleHapticEvent( Self, inputHandle, eHapticLocation, nIntensity, nGainDB, nOtherIntensity, nOtherGainDB );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_SetLEDColor", CallingConvention = Platform.CC)]
private static extern void _SetLEDColor( IntPtr self, InputHandle_t inputHandle, byte nColorR, byte nColorG, byte nColorB, uint nFlags );
#endregion
internal void SetLEDColor( InputHandle_t inputHandle, byte nColorR, byte nColorG, byte nColorB, uint nFlags )
{
_SetLEDColor( Self, inputHandle, nColorR, nColorG, nColorB, nFlags );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_Legacy_TriggerHapticPulse", CallingConvention = Platform.CC)]
private static extern void _Legacy_TriggerHapticPulse( IntPtr self, InputHandle_t inputHandle, SteamControllerPad eTargetPad, ushort usDurationMicroSec );
#endregion
internal void Legacy_TriggerHapticPulse( InputHandle_t inputHandle, SteamControllerPad eTargetPad, ushort usDurationMicroSec )
{
_Legacy_TriggerHapticPulse( Self, inputHandle, eTargetPad, usDurationMicroSec );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_Legacy_TriggerRepeatedHapticPulse", CallingConvention = Platform.CC)]
private static extern void _Legacy_TriggerRepeatedHapticPulse( IntPtr self, InputHandle_t inputHandle, SteamControllerPad eTargetPad, ushort usDurationMicroSec, ushort usOffMicroSec, ushort unRepeat, uint nFlags );
#endregion
internal void Legacy_TriggerRepeatedHapticPulse( InputHandle_t inputHandle, SteamControllerPad eTargetPad, ushort usDurationMicroSec, ushort usOffMicroSec, ushort unRepeat, uint nFlags )
{
_Legacy_TriggerRepeatedHapticPulse( Self, inputHandle, eTargetPad, usDurationMicroSec, usOffMicroSec, unRepeat, nFlags );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_ShowBindingPanel", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _ShowBindingPanel( IntPtr self, InputHandle_t inputHandle );
#endregion
internal bool ShowBindingPanel( InputHandle_t inputHandle )
{
var returnValue = _ShowBindingPanel( Self, inputHandle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetInputTypeForHandle", CallingConvention = Platform.CC)]
private static extern InputType _GetInputTypeForHandle( IntPtr self, InputHandle_t inputHandle );
#endregion
internal InputType GetInputTypeForHandle( InputHandle_t inputHandle )
{
var returnValue = _GetInputTypeForHandle( Self, inputHandle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetControllerForGamepadIndex", CallingConvention = Platform.CC)]
private static extern InputHandle_t _GetControllerForGamepadIndex( IntPtr self, int nIndex );
#endregion
internal InputHandle_t GetControllerForGamepadIndex( int nIndex )
{
var returnValue = _GetControllerForGamepadIndex( Self, nIndex );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetGamepadIndexForController", CallingConvention = Platform.CC)]
private static extern int _GetGamepadIndexForController( IntPtr self, InputHandle_t ulinputHandle );
#endregion
internal int GetGamepadIndexForController( InputHandle_t ulinputHandle )
{
var returnValue = _GetGamepadIndexForController( Self, ulinputHandle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetStringForXboxOrigin", CallingConvention = Platform.CC)]
private static extern Utf8StringPointer _GetStringForXboxOrigin( IntPtr self, XboxOrigin eOrigin );
#endregion
internal string GetStringForXboxOrigin( XboxOrigin eOrigin )
{
var returnValue = _GetStringForXboxOrigin( Self, eOrigin );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetGlyphForXboxOrigin", CallingConvention = Platform.CC)]
private static extern Utf8StringPointer _GetGlyphForXboxOrigin( IntPtr self, XboxOrigin eOrigin );
#endregion
internal string GetGlyphForXboxOrigin( XboxOrigin eOrigin )
{
var returnValue = _GetGlyphForXboxOrigin( Self, eOrigin );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetActionOriginFromXboxOrigin", CallingConvention = Platform.CC)]
private static extern InputActionOrigin _GetActionOriginFromXboxOrigin( IntPtr self, InputHandle_t inputHandle, XboxOrigin eOrigin );
#endregion
internal InputActionOrigin GetActionOriginFromXboxOrigin( InputHandle_t inputHandle, XboxOrigin eOrigin )
{
var returnValue = _GetActionOriginFromXboxOrigin( Self, inputHandle, eOrigin );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_TranslateActionOrigin", CallingConvention = Platform.CC)]
private static extern InputActionOrigin _TranslateActionOrigin( IntPtr self, InputType eDestinationInputType, InputActionOrigin eSourceOrigin );
#endregion
internal InputActionOrigin TranslateActionOrigin( InputType eDestinationInputType, InputActionOrigin eSourceOrigin )
{
var returnValue = _TranslateActionOrigin( Self, eDestinationInputType, eSourceOrigin );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetDeviceBindingRevision", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetDeviceBindingRevision( IntPtr self, InputHandle_t inputHandle, ref int pMajor, ref int pMinor );
#endregion
internal bool GetDeviceBindingRevision( InputHandle_t inputHandle, ref int pMajor, ref int pMinor )
{
var returnValue = _GetDeviceBindingRevision( Self, inputHandle, ref pMajor, ref pMinor );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetRemotePlaySessionID", CallingConvention = Platform.CC)]
private static extern uint _GetRemotePlaySessionID( IntPtr self, InputHandle_t inputHandle );
#endregion
internal uint GetRemotePlaySessionID( InputHandle_t inputHandle )
{
var returnValue = _GetRemotePlaySessionID( Self, inputHandle );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamInput_GetSessionInputConfigurationSettings", CallingConvention = Platform.CC)]
private static extern ushort _GetSessionInputConfigurationSettings( IntPtr self );
#endregion
internal ushort GetSessionInputConfigurationSettings()
{
var returnValue = _GetSessionInputConfigurationSettings( Self );
return returnValue;
}
}
}
| |
namespace AutoUSBBackup.GUI.Shared
{
partial class WelcomeListView
{
/// <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 ) )
{
if ( mIcon != null )
mIcon.Dispose();
if ( mFolderIcon != null )
mFolderIcon.Dispose();
components.Dispose();
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.mVolumeContextMenu = new System.Windows.Forms.ContextMenuStrip( this.components );
this.restoreVolumeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.addNewVolumeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.removeVolumeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mSpecificOperationsGroupBox = new System.Windows.Forms.GroupBox();
this.mRemoveVolumeButton = new System.Windows.Forms.Button();
this.mRestoreVolumeButton = new System.Windows.Forms.Button();
this.mCommonOperationsGroupBox = new System.Windows.Forms.GroupBox();
this.mBackupAllNowButton = new System.Windows.Forms.Button();
this.mButtonOptions = new System.Windows.Forms.Button();
this.mAddVolumeButton = new System.Windows.Forms.Button();
this.mSplitContainer = new System.Windows.Forms.SplitContainer();
this.mVolumeListView = new BrightIdeasSoftware.ObjectListView();
this.mColumn = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.mLogTextBox = new AutoUSBBackup.GUI.Shared.LogTextBox();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.openLocationInExplorer = new System.Windows.Forms.ToolStripMenuItem();
this.openBackupLocationInExplorer = new System.Windows.Forms.ToolStripMenuItem();
this.mVolumeContextMenu.SuspendLayout();
this.mSpecificOperationsGroupBox.SuspendLayout();
this.mCommonOperationsGroupBox.SuspendLayout();
this.mSplitContainer.Panel1.SuspendLayout();
this.mSplitContainer.Panel2.SuspendLayout();
this.mSplitContainer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.mVolumeListView)).BeginInit();
this.SuspendLayout();
//
// mVolumeContextMenu
//
this.mVolumeContextMenu.Items.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.restoreVolumeToolStripMenuItem,
this.toolStripSeparator1,
this.addNewVolumeToolStripMenuItem,
this.removeVolumeToolStripMenuItem,
this.toolStripSeparator2,
this.openLocationInExplorer,
this.openBackupLocationInExplorer} );
this.mVolumeContextMenu.Name = "mVolumeContextMenu";
this.mVolumeContextMenu.Size = new System.Drawing.Size( 250, 148 );
this.mVolumeContextMenu.Opening += new System.ComponentModel.CancelEventHandler( this.mVolumeContextMenu_Opening );
//
// restoreVolumeToolStripMenuItem
//
this.restoreVolumeToolStripMenuItem.Name = "restoreVolumeToolStripMenuItem";
this.restoreVolumeToolStripMenuItem.Size = new System.Drawing.Size( 249, 22 );
this.restoreVolumeToolStripMenuItem.Text = "R&estore volume...";
this.restoreVolumeToolStripMenuItem.Click += new System.EventHandler( this.restoreVolumeToolStripMenuItem_Click );
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size( 246, 6 );
//
// addNewVolumeToolStripMenuItem
//
this.addNewVolumeToolStripMenuItem.Name = "addNewVolumeToolStripMenuItem";
this.addNewVolumeToolStripMenuItem.Size = new System.Drawing.Size( 249, 22 );
this.addNewVolumeToolStripMenuItem.Text = "&Add new volume...";
this.addNewVolumeToolStripMenuItem.Click += new System.EventHandler( this.addNewVolumeToolStripMenuItem_Click );
//
// removeVolumeToolStripMenuItem
//
this.removeVolumeToolStripMenuItem.Name = "removeVolumeToolStripMenuItem";
this.removeVolumeToolStripMenuItem.Size = new System.Drawing.Size( 249, 22 );
this.removeVolumeToolStripMenuItem.Text = "&Remove volume...";
this.removeVolumeToolStripMenuItem.Click += new System.EventHandler( this.removeVolumeToolStripMenuItem_Click );
//
// mSpecificOperationsGroupBox
//
this.mSpecificOperationsGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.mSpecificOperationsGroupBox.Controls.Add( this.mRemoveVolumeButton );
this.mSpecificOperationsGroupBox.Controls.Add( this.mRestoreVolumeButton );
this.mSpecificOperationsGroupBox.Location = new System.Drawing.Point( 382, 119 );
this.mSpecificOperationsGroupBox.MinimumSize = new System.Drawing.Size( 102, 105 );
this.mSpecificOperationsGroupBox.Name = "mSpecificOperationsGroupBox";
this.mSpecificOperationsGroupBox.Size = new System.Drawing.Size( 116, 219 );
this.mSpecificOperationsGroupBox.TabIndex = 3;
this.mSpecificOperationsGroupBox.TabStop = false;
//
// mRemoveVolumeButton
//
this.mRemoveVolumeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.mRemoveVolumeButton.Enabled = false;
this.mRemoveVolumeButton.Location = new System.Drawing.Point( 6, 190 );
this.mRemoveVolumeButton.Name = "mRemoveVolumeButton";
this.mRemoveVolumeButton.Size = new System.Drawing.Size( 104, 23 );
this.mRemoveVolumeButton.TabIndex = 2;
this.mRemoveVolumeButton.Text = "Remove";
this.mRemoveVolumeButton.UseVisualStyleBackColor = true;
this.mRemoveVolumeButton.Click += new System.EventHandler( this.mRemoveVolumeButton_Click );
//
// mRestoreVolumeButton
//
this.mRestoreVolumeButton.Enabled = false;
this.mRestoreVolumeButton.Location = new System.Drawing.Point( 6, 19 );
this.mRestoreVolumeButton.Name = "mRestoreVolumeButton";
this.mRestoreVolumeButton.Size = new System.Drawing.Size( 104, 23 );
this.mRestoreVolumeButton.TabIndex = 1;
this.mRestoreVolumeButton.Text = "Restore...";
this.mRestoreVolumeButton.UseVisualStyleBackColor = true;
this.mRestoreVolumeButton.Click += new System.EventHandler( this.mRestoreVolumeButton_Click );
//
// mCommonOperationsGroupBox
//
this.mCommonOperationsGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.mCommonOperationsGroupBox.Controls.Add( this.mBackupAllNowButton );
this.mCommonOperationsGroupBox.Controls.Add( this.mButtonOptions );
this.mCommonOperationsGroupBox.Controls.Add( this.mAddVolumeButton );
this.mCommonOperationsGroupBox.Location = new System.Drawing.Point( 382, 3 );
this.mCommonOperationsGroupBox.MinimumSize = new System.Drawing.Size( 102, 79 );
this.mCommonOperationsGroupBox.Name = "mCommonOperationsGroupBox";
this.mCommonOperationsGroupBox.Size = new System.Drawing.Size( 116, 118 );
this.mCommonOperationsGroupBox.TabIndex = 4;
this.mCommonOperationsGroupBox.TabStop = false;
//
// mBackupAllNowButton
//
this.mBackupAllNowButton.Location = new System.Drawing.Point( 6, 77 );
this.mBackupAllNowButton.Name = "mBackupAllNowButton";
this.mBackupAllNowButton.Size = new System.Drawing.Size( 104, 23 );
this.mBackupAllNowButton.TabIndex = 5;
this.mBackupAllNowButton.Text = "Backup All Now";
this.mBackupAllNowButton.UseVisualStyleBackColor = true;
this.mBackupAllNowButton.Click += new System.EventHandler( this.mBackupAllNowButton_Click );
//
// mButtonOptions
//
this.mButtonOptions.Enabled = false;
this.mButtonOptions.Location = new System.Drawing.Point( 7, 48 );
this.mButtonOptions.Name = "mButtonOptions";
this.mButtonOptions.Size = new System.Drawing.Size( 104, 23 );
this.mButtonOptions.TabIndex = 4;
this.mButtonOptions.Text = "Options";
this.mButtonOptions.UseVisualStyleBackColor = true;
this.mButtonOptions.Click += new System.EventHandler( this.mButtonOptions_Click );
//
// mAddVolumeButton
//
this.mAddVolumeButton.Location = new System.Drawing.Point( 6, 19 );
this.mAddVolumeButton.Name = "mAddVolumeButton";
this.mAddVolumeButton.Size = new System.Drawing.Size( 104, 23 );
this.mAddVolumeButton.TabIndex = 0;
this.mAddVolumeButton.Text = "Add...";
this.mAddVolumeButton.UseVisualStyleBackColor = true;
this.mAddVolumeButton.Click += new System.EventHandler( this.mAddVolumeButton_Click );
//
// mSplitContainer
//
this.mSplitContainer.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.mSplitContainer.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
this.mSplitContainer.Location = new System.Drawing.Point( 0, 3 );
this.mSplitContainer.Name = "mSplitContainer";
this.mSplitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// mSplitContainer.Panel1
//
this.mSplitContainer.Panel1.Controls.Add( this.mVolumeListView );
//
// mSplitContainer.Panel2
//
this.mSplitContainer.Panel2.Controls.Add( this.mLogTextBox );
this.mSplitContainer.Size = new System.Drawing.Size( 376, 335 );
this.mSplitContainer.SplitterDistance = 167;
this.mSplitContainer.TabIndex = 12;
//
// mVolumeListView
//
this.mVolumeListView.AllColumns.Add( this.mColumn );
this.mVolumeListView.CheckBoxes = true;
this.mVolumeListView.Columns.AddRange( new System.Windows.Forms.ColumnHeader[] {
this.mColumn} );
this.mVolumeListView.ContextMenuStrip = this.mVolumeContextMenu;
this.mVolumeListView.Dock = System.Windows.Forms.DockStyle.Fill;
this.mVolumeListView.FullRowSelect = true;
this.mVolumeListView.Location = new System.Drawing.Point( 0, 0 );
this.mVolumeListView.MultiSelect = false;
this.mVolumeListView.Name = "mVolumeListView";
this.mVolumeListView.OwnerDraw = true;
this.mVolumeListView.ShowGroups = false;
this.mVolumeListView.ShowImagesOnSubItems = true;
this.mVolumeListView.Size = new System.Drawing.Size( 376, 167 );
this.mVolumeListView.TabIndex = 13;
this.mVolumeListView.UseCompatibleStateImageBehavior = false;
this.mVolumeListView.View = System.Windows.Forms.View.Details;
//
// mColumn
//
this.mColumn.FillsFreeSpace = true;
this.mColumn.MinimumWidth = 150;
this.mColumn.Text = "Volume";
this.mColumn.Width = 190;
//
// mLogTextBox
//
this.mLogTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.mLogTextBox.Location = new System.Drawing.Point( 0, 0 );
this.mLogTextBox.Name = "mLogTextBox";
this.mLogTextBox.Size = new System.Drawing.Size( 376, 164 );
this.mLogTextBox.TabIndex = 14;
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size( 246, 6 );
//
// openLocationInExplorer
//
this.openLocationInExplorer.Name = "openLocationInExplorer";
this.openLocationInExplorer.Size = new System.Drawing.Size( 249, 22 );
this.openLocationInExplorer.Text = "Open location in explorer";
this.openLocationInExplorer.Click += new System.EventHandler( this.openLocationInExplorer_Click );
//
// openBackupLocationInExplorer
//
this.openBackupLocationInExplorer.Name = "openBackupLocationInExplorer";
this.openBackupLocationInExplorer.Size = new System.Drawing.Size( 249, 22 );
this.openBackupLocationInExplorer.Text = "Open backup location in explorer";
this.openBackupLocationInExplorer.Click += new System.EventHandler( this.openBackupLocationInExplorer_Click );
//
// WelcomeListView
//
this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F );
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add( this.mSplitContainer );
this.Controls.Add( this.mCommonOperationsGroupBox );
this.Controls.Add( this.mSpecificOperationsGroupBox );
this.MinimumSize = new System.Drawing.Size( 325, 196 );
this.Name = "WelcomeListView";
this.Size = new System.Drawing.Size( 501, 341 );
this.mVolumeContextMenu.ResumeLayout( false );
this.mSpecificOperationsGroupBox.ResumeLayout( false );
this.mCommonOperationsGroupBox.ResumeLayout( false );
this.mSplitContainer.Panel1.ResumeLayout( false );
this.mSplitContainer.Panel2.ResumeLayout( false );
this.mSplitContainer.ResumeLayout( false );
((System.ComponentModel.ISupportInitialize)(this.mVolumeListView)).EndInit();
this.ResumeLayout( false );
}
#endregion
private System.Windows.Forms.ContextMenuStrip mVolumeContextMenu;
private System.Windows.Forms.ToolStripMenuItem restoreVolumeToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem addNewVolumeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem removeVolumeToolStripMenuItem;
private System.Windows.Forms.GroupBox mSpecificOperationsGroupBox;
private System.Windows.Forms.GroupBox mCommonOperationsGroupBox;
private System.Windows.Forms.Button mRemoveVolumeButton;
private System.Windows.Forms.Button mRestoreVolumeButton;
private System.Windows.Forms.Button mAddVolumeButton;
private System.Windows.Forms.Button mButtonOptions;
private System.Windows.Forms.SplitContainer mSplitContainer;
private BrightIdeasSoftware.ObjectListView mVolumeListView;
private BrightIdeasSoftware.OLVColumn mColumn;
private LogTextBox mLogTextBox;
private System.Windows.Forms.Button mBackupAllNowButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem openLocationInExplorer;
private System.Windows.Forms.ToolStripMenuItem openBackupLocationInExplorer;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using static System.TestHelpers;
namespace System.SpanTests
{
public static partial class SpanTests
{
[Fact]
public static void ReverseEmpty()
{
var span = Span<byte>.Empty;
span.Reverse();
byte[] actual = { 1, 2, 3, 4 };
byte[] expected = { 1, 2, 3, 4 };
span = actual;
span.Slice(2, 0).Reverse();
Assert.Equal<byte>(expected, span.ToArray());
}
[Fact]
public static void ReverseEmptyWithReference()
{
var span = Span<string>.Empty;
span.Reverse();
string[] actual = { "a", "b", "c", "d" };
string[] expected = { "a", "b", "c", "d" };
span = actual;
span.Slice(2, 0).Reverse();
Assert.Equal<string>(expected, span.ToArray());
}
[Fact]
public static void ReverseByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
var actual = new byte[length];
for (int i = 0; i < length; i++)
{
actual[i] = (byte)i;
}
byte[] expected = new byte[length];
Array.Copy(actual, expected, length);
Array.Reverse(expected);
var span = new Span<byte>(actual);
span.Reverse();
Assert.Equal<byte>(expected, actual);
}
}
[Fact]
public static void ReverseByteTwiceReturnsOriginal()
{
byte[] actual = { 1, 2, 3, 4, 5 };
byte[] expected = { 1, 2, 3, 4, 5 };
Span<byte> span = actual;
span.Reverse();
span.Reverse();
Assert.Equal<byte>(expected, actual);
}
[Fact]
public static void ReverseByteUnaligned()
{
const int length = 32;
const int offset = 1;
var actualFull = new byte[length];
for (int i = 0; i < length; i++)
{
actualFull[i] = (byte)i;
}
byte[] expectedFull = new byte[length];
Array.Copy(actualFull, expectedFull, length);
Array.Reverse(expectedFull, offset, length - offset - 1);
var expectedSpan = new Span<byte>(expectedFull, offset, length - offset - 1);
var actualSpan = new Span<byte>(actualFull, offset, length - offset - 1);
actualSpan.Reverse();
byte[] actual = actualSpan.ToArray();
byte[] expected = expectedSpan.ToArray();
Assert.Equal<byte>(expected, actual);
Assert.Equal(expectedFull[0], actualFull[0]);
Assert.Equal(expectedFull[length - 1], actualFull[length - 1]);
}
[Fact]
public static void ReverseIntPtrOffset()
{
const int length = 32;
const int offset = 2;
var actualFull = new IntPtr[length];
for (int i = 0; i < length; i++)
{
actualFull[i] = IntPtr.Zero + i;
}
IntPtr[] expectedFull = new IntPtr[length];
Array.Copy(actualFull, expectedFull, length);
Array.Reverse(expectedFull, offset, length - offset);
var expectedSpan = new Span<IntPtr>(expectedFull, offset, length - offset);
var actualSpan = new Span<IntPtr>(actualFull, offset, length - offset);
actualSpan.Reverse();
IntPtr[] actual = actualSpan.ToArray();
IntPtr[] expected = expectedSpan.ToArray();
Assert.Equal<IntPtr>(expected, actual);
Assert.Equal(expectedFull[0], actualFull[0]);
Assert.Equal(expectedFull[1], actualFull[1]);
}
[Fact]
public static void ReverseValueTypeWithoutReferences()
{
const int length = 2048;
int[] actual = new int[length];
for (int i = 0; i < length; i++)
{
actual[i] = i;
}
int[] expected = new int[length];
Array.Copy(actual, expected, length);
Array.Reverse(expected);
var span = new Span<int>(actual);
span.Reverse();
Assert.Equal<int>(expected, actual);
}
[Fact]
public static void ReverseValueTypeWithoutReferencesPointerSize()
{
const int length = 15;
long[] actual = new long[length];
for (int i = 0; i < length; i++)
{
actual[i] = i;
}
long[] expected = new long[length];
Array.Copy(actual, expected, length);
Array.Reverse(expected);
var span = new Span<long>(actual);
span.Reverse();
Assert.Equal<long>(expected, actual);
}
[Fact]
public static void ReverseReferenceType()
{
const int length = 2048;
string[] actual = new string[length];
for (int i = 0; i < length; i++)
{
actual[i] = i.ToString();
}
string[] expected = new string[length];
Array.Copy(actual, expected, length);
Array.Reverse(expected);
var span = new Span<string>(actual);
span.Reverse();
Assert.Equal<string>(expected, actual);
}
[Fact]
public static void ReverseReferenceTwiceReturnsOriginal()
{
string[] actual = { "a1", "b2", "c3" };
string[] expected = { "a1", "b2", "c3" };
var span = new Span<string>(actual);
span.Reverse();
span.Reverse();
Assert.Equal<string>(expected, actual);
}
[Fact]
public static void ReverseEnumType()
{
TestEnum[] actual = { TestEnum.e0, TestEnum.e1, TestEnum.e2 };
TestEnum[] expected = { TestEnum.e2, TestEnum.e1, TestEnum.e0 };
var span = new Span<TestEnum>(actual);
span.Reverse();
Assert.Equal<TestEnum>(expected, actual);
}
[Fact]
public static void ReverseValueTypeWithReferences()
{
TestValueTypeWithReference[] actual = {
new TestValueTypeWithReference() { I = 1, S = "a" },
new TestValueTypeWithReference() { I = 2, S = "b" },
new TestValueTypeWithReference() { I = 3, S = "c" } };
TestValueTypeWithReference[] expected = {
new TestValueTypeWithReference() { I = 3, S = "c" },
new TestValueTypeWithReference() { I = 2, S = "b" },
new TestValueTypeWithReference() { I = 1, S = "a" } };
var span = new Span<TestValueTypeWithReference>(actual);
span.Reverse();
Assert.Equal<TestValueTypeWithReference>(expected, actual);
}
}
}
| |
namespace Signum.Test.LinqProvider;
public class SelectImplementationsTest1
{
public SelectImplementationsTest1()
{
MusicStarter.StartAndLoad();
Connector.CurrentLogger = new DebugTextWriter();
}
[Fact]
public void SelectType()
{
var list = Database.Query<AlbumEntity>()
.Select(a => a.GetType()).ToList();
}
[Fact]
public void SelectTypeNull()
{
var list = Database.Query<LabelEntity>()
.Select(a => new { Label = a.ToLite(), a.Owner, OwnerType = a.Owner!.Entity.GetType() }).ToList();
}
[Fact]
public void SelectLiteIB()
{
var list = Database.Query<AlbumEntity>()
.Select(a => a.Author.ToLite()).ToList();
}
[Fact]
public void SelectLiteIBDouble()
{
var query = Database.Query<AlbumEntity>()
.Select(a => new
{
ToStr1 = a.Author.ToLite(),
ToStr2 = a.Author.ToLite()
});
Assert.Equal(2, query.QueryText().CountRepetitions("LEFT OUTER JOIN"));
query.ToList();
}
[Fact]
public void SelectLiteIBDoubleWhereUnion()
{
var query = Database.Query<AlbumEntity>()
.Where(a => a.Author.CombineUnion().ToLite().ToString()!.Length > 0)
.Select(a => a.Author.CombineUnion().ToLite());
Assert.Equal(3, query.QueryText().CountRepetitions("LEFT OUTER JOIN"));
query.ToList();
}
[Fact]
public void SelectLiteIBDoubleWhereSwitch()
{
var query = Database.Query<AlbumEntity>()
.Where(a => a.Author.CombineCase().ToLite().ToString()!.Length > 0)
.Select(a => a.Author.CombineCase().ToLite());
Assert.Equal(2, query.QueryText().CountRepetitions("LEFT OUTER JOIN"));
query.ToList();
}
[Fact]
public void SelectTypeIBA()
{
var list = Database.Query<NoteWithDateEntity>()
.Select(a => new { Type = a.Target.GetType(), Target = a.Target.ToLite() }).ToList();
}
[Fact]
public void SelectTypeLiteIB()
{
var list = Database.Query<AwardNominationEntity>()
.Select(a => a.Award.EntityType).ToList();
}
[Fact]
public void SelectEntityWithLiteIb()
{
var list = Database.Query<AwardNominationEntity>().Where(a => a.Award.Entity is GrammyAwardEntity).ToList();
}
[Fact]
public void SelectEntityWithLiteIbType()
{
var list = Database.Query<AwardNominationEntity>().Where(a => a.Award.Entity.GetType() == typeof(GrammyAwardEntity)).ToList();
}
[Fact]
public void SelectEntityWithLiteIbTypeContains()
{
Type[] types = new Type[] { typeof(GrammyAwardEntity) };
var list = Database.Query<AwardNominationEntity>().Where(a => types.Contains(a.Award.Entity.GetType())).ToList();
}
[Fact]
public void SelectEntityWithLiteIbRuntimeType()
{
var list = Database.Query<AwardNominationEntity>().Where(a => a.Award.EntityType == typeof(GrammyAwardEntity)).ToList();
}
[Fact]
public void SelectLiteUpcast()
{
var list = Database.Query<ArtistEntity>()
.Select(a => a.ToLite()).ToList();
}
[Fact]
public void SelectLiteCastUpcast()
{
var list = Database.Query<ArtistEntity>()
.SelectMany(a => a.Friends).Select(a=>(Lite<IAuthorEntity>)a).ToList();
}
[Fact]
public void SelectLiteCastNocast()
{
var list = Database.Query<ArtistEntity>()
.SelectMany(a => a.Friends).Select(a =>(Lite<ArtistEntity>)a).ToList();
}
[Fact]
public void SelectLiteCastDowncast()
{
var list = Database.Query<AlbumEntity>()
.Select(a => (Lite<ArtistEntity>)a.Author.ToLite()).ToList();
}
[Fact]
public void SelectLiteGenericUpcast()
{
var list = SelectAuthorsLite<ArtistEntity, IAuthorEntity>();
}
public List<Lite<LT>> SelectAuthorsLite<T, LT>()
where T : Entity, LT
where LT : class, IEntity
{
return Database.Query<T>().Select(a => a.ToLite<LT>()).ToList(); //an explicit convert is injected in this scenario
}
[Fact]
public void SelectLiteIBRedundantUnion()
{
var list = (from a in Database.Query<AlbumEntity>()
let band = (BandEntity)a.Author
select new { Artist = band.ToString(), Author = a.Author.CombineUnion().ToString() }).ToList();
Assert.Equal(Database.Query<AlbumEntity>().Count(), list.Count);
}
[Fact]
public void SelectLiteIBRedundantSwitch()
{
var list = (from a in Database.Query<AlbumEntity>()
let band = (BandEntity)a.Author
select new { Artist = band.ToString(), Author = a.Author.CombineCase().ToString() }).ToList();
Assert.Equal(Database.Query<AlbumEntity>().Count(), list.Count);
}
[Fact]
public void SelectLiteIBWhereUnion()
{
var list = Database.Query<AlbumEntity>()
.Select(a => a.Author.CombineUnion().ToLite())
.Where(a => a.ToString()!.StartsWith("Michael")).ToList();
}
[Fact]
public void SelectLiteIBWhereSwitch()
{
var list = Database.Query<AlbumEntity>()
.Select(a => a.Author.CombineCase().ToLite())
.Where(a => a.ToString()!.StartsWith("Michael")).ToList();
}
[Fact]
public void SelectLiteIBA()
{
var list = Database.Query<NoteWithDateEntity>().Select(a => a.Target.ToLite()).ToList();
}
[Fact]
public void SelectSimpleEntity()
{
var list3 = Database.Query<ArtistEntity>().ToList();
}
[Fact]
public void SelectEntity()
{
var list3 = Database.Query<AlbumEntity>().ToList();
}
[Fact]
public void SelectEntitySelect()
{
var list = Database.Query<AlbumEntity>().Select(a => a).ToList();
}
[Fact]
public void SelectEntityIB()
{
var list = Database.Query<AlbumEntity>().Select(a => a.Author).ToList();
}
[Fact]
public void SelectEntityIBRedundan()
{
var list = (from a in Database.Query<AlbumEntity>()
let aut = a.Author
select new { aut, a.Author }).ToList();
}
[Fact]
public void SelectEntityIBA()
{
var list = Database.Query<NoteWithDateEntity>().Select(a => a.Target).ToList();
}
[Fact]
public void SelectCastIB()
{
var list = (from a in Database.Query<AlbumEntity>()
select ((ArtistEntity)a.Author).Name ??
((BandEntity)a.Author).Name).ToList();
}
[Fact]
public void SelectCastIBPolymorphicUnion()
{
var list = (from a in Database.Query<AlbumEntity>()
select a.Author.CombineUnion().Name).ToList();
}
[Fact]
public void SelectCastIBPolymorphicSwitch()
{
var list = (from a in Database.Query<AlbumEntity>()
select a.Author.CombineCase().Name).ToList();
}
[Fact]
public void SelectCastIBPolymorphicForceNullify()
{
var list = (from a in Database.Query<AwardNominationEntity>()
select (int?)a.Award!.Entity.Year).ToList();
}
[Fact]
public void SelectCastIBPolymorphicIBUnion()
{
var list = (from a in Database.Query<AlbumEntity>()
select a.Author.CombineUnion().LastAward.Try(la => la.ToLite())).ToList();
}
[Fact]
public void SelectCastIBPolymorphicIBSwitch()
{
var list = (from a in Database.Query<AlbumEntity>()
select a.Author.CombineCase().LastAward.Try(la => la.ToLite())).ToList();
}
[Fact]
public void SelectCastIBA()
{
var list = (from n in Database.Query<NoteWithDateEntity>()
select
((ArtistEntity)n.Target).Name ??
((AlbumEntity)n.Target).Name ??
((BandEntity)n.Target).Name).ToList();
}
[Fact]
public void SelectCastIBACastOperator()
{
var list = (from n in Database.Query<NoteWithDateEntity>()
select n.Target).Cast<BandEntity>().ToList();
}
[Fact]
public void SelectCastIBAOfTypeOperator()
{
var list = (from n in Database.Query<NoteWithDateEntity>()
select n.Target).OfType<BandEntity>().ToList();
}
[Fact]
public void SelectCastIsIB()
{
var list = (from a in Database.Query<AlbumEntity>()
select (a.Author is ArtistEntity ? ((ArtistEntity)a.Author).Name :
((BandEntity)a.Author).Name)).ToList();
}
[Fact]
public void SelectCastIsIBA()
{
var list = (from n in Database.Query<NoteWithDateEntity>()
select n.Target is ArtistEntity ? ((ArtistEntity)n.Target).Name : ((BandEntity)n.Target).Name).ToList();
}
[Fact]
public void SelectCastIsIBADouble()
{
var query = (from n in Database.Query<NoteWithDateEntity>()
select new
{
Name = n.Target is ArtistEntity ? ((ArtistEntity)n.Target).Name : ((BandEntity)n.Target).Name,
FullName = n.Target is ArtistEntity ? ((ArtistEntity)n.Target).FullName : ((BandEntity)n.Target).FullName
});
Assert.Equal(1, query.QueryText().CountRepetitions("Artist"));
query.ToList();
}
[Fact]
public void SelectCastIsIBADoubleWhere()
{
var query = (from n in Database.Query<NoteWithDateEntity>()
where (n.Target is ArtistEntity ? ((ArtistEntity)n.Target).Name : ((BandEntity)n.Target).Name).Length > 0
select n.Target is ArtistEntity ? ((ArtistEntity)n.Target).FullName : ((BandEntity)n.Target).FullName);
Assert.Equal(1, query.QueryText().CountRepetitions("Artist"));
query.ToList();
}
[Fact]
public void SelectIsIBLite()
{
var query = (from n in Database.Query<NoteWithDateEntity>()
where n.Target.ToLite() is Lite<AlbumEntity>
select n.Target.ToLite()).ToList();
}
[Fact]
public void SelectIsIBALite()
{
var query = (from a in Database.Query<AwardNominationEntity>()
where a.Author is Lite<BandEntity>
select a.Author).ToList();
}
[Fact]
public void SelectCastIBALite()
{
var query = (from n in Database.Query<NoteWithDateEntity>()
select (Lite<AlbumEntity>)n.Target.ToLite()).ToList();
}
[Fact]
public void SelectCastIBLite()
{
var query = (from a in Database.Query<AwardNominationEntity>()
select (Lite<BandEntity>)a.Author).ToList();
}
//AwardNominationEntity
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Security
{
//
// This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context.
// This file contains the private implementation.
//
public partial class NegotiateStream : AuthenticatedStream
{
private static AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback);
private static AsyncProtocolCallback s_readCallback = new AsyncProtocolCallback(ReadCallback);
private int _NestedWrite;
private int _NestedRead;
private byte[] _ReadHeader;
// Never updated directly, special properties are used.
private byte[] _InternalBuffer;
private int _InternalOffset;
private int _InternalBufferCount;
private void InitializeStreamPart()
{
_ReadHeader = new byte[4];
}
private byte[] InternalBuffer
{
get
{
return _InternalBuffer;
}
}
private int InternalOffset
{
get
{
return _InternalOffset;
}
}
private int InternalBufferCount
{
get
{
return _InternalBufferCount;
}
}
private void DecrementInternalBufferCount(int decrCount)
{
_InternalOffset += decrCount;
_InternalBufferCount -= decrCount;
}
private void EnsureInternalBufferSize(int bytes)
{
_InternalBufferCount = bytes;
_InternalOffset = 0;
if (InternalBuffer == null || InternalBuffer.Length < bytes)
{
_InternalBuffer = new byte[bytes];
}
}
private void AdjustInternalBufferOffsetSize(int bytes, int offset)
{
_InternalBufferCount = bytes;
_InternalOffset = offset;
}
//
// Validates user parameters for all Read/Write methods.
//
private void ValidateParameters(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (count > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.net_offset_plus_count);
}
}
//
// Combined sync/async write method. For sync request asyncRequest==null.
//
private void ProcessWrite(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
ValidateParameters(buffer, offset, count);
if (Interlocked.Exchange(ref _NestedWrite, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncRequest != null ? "BeginWrite" : "Write"), "write"));
}
bool failed = false;
try
{
StartWriting(buffer, offset, count, asyncRequest);
}
catch (Exception e)
{
failed = true;
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_write, e);
}
finally
{
if (asyncRequest == null || failed)
{
_NestedWrite = 0;
}
}
}
private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
// We loop to this method from the callback.
// If the last chunk was just completed from async callback (count < 0), we complete user request.
if (count >= 0)
{
byte[] outBuffer = null;
do
{
int chunkBytes = Math.Min(count, NegoState.MaxWriteDataSize);
int encryptedBytes;
try
{
encryptedBytes = _negoState.EncryptData(buffer, offset, chunkBytes, ref outBuffer);
}
catch (Exception e)
{
throw new IOException(SR.net_io_encrypt, e);
}
if (asyncRequest != null)
{
// prepare for the next request
asyncRequest.SetNextRequest(buffer, offset + chunkBytes, count - chunkBytes, null);
Task t = InnerStream.WriteAsync(outBuffer, 0, encryptedBytes);
if (t.IsCompleted)
{
t.GetAwaiter().GetResult();
}
else
{
IAsyncResult ar = TaskToApm.Begin(t, s_writeCallback, asyncRequest);
if (!ar.CompletedSynchronously)
{
return;
}
TaskToApm.End(ar);
}
}
else
{
InnerStream.Write(outBuffer, 0, encryptedBytes);
}
offset += chunkBytes;
count -= chunkBytes;
} while (count != 0);
}
if (asyncRequest != null)
{
asyncRequest.CompleteUser();
}
}
//
// Combined sync/async read method. For sync request asyncRequest==null.
// There is a little overhead because we need to pass buffer/offset/count used only in sync.
// Still the benefit is that we have a common sync/async code path.
//
private int ProcessRead(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
ValidateParameters(buffer, offset, count);
if (Interlocked.Exchange(ref _NestedRead, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncRequest != null ? "BeginRead" : "Read"), "read"));
}
bool failed = false;
try
{
if (InternalBufferCount != 0)
{
int copyBytes = InternalBufferCount > count ? count : InternalBufferCount;
if (copyBytes != 0)
{
Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, copyBytes);
DecrementInternalBufferCount(copyBytes);
}
asyncRequest?.CompleteUser(copyBytes);
return copyBytes;
}
// Performing actual I/O.
return StartReading(buffer, offset, count, asyncRequest);
}
catch (Exception e)
{
failed = true;
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_read, e);
}
finally
{
if (asyncRequest == null || failed)
{
_NestedRead = 0;
}
}
}
//
// To avoid recursion when 0 bytes have been decrypted, loop until decryption results in at least 1 byte.
//
private int StartReading(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
int result;
// When we read -1 bytes means we have decrypted 0 bytes, need looping.
while ((result = StartFrameHeader(buffer, offset, count, asyncRequest)) == -1);
return result;
}
private int StartFrameHeader(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
int readBytes = 0;
if (asyncRequest != null)
{
asyncRequest.SetNextRequest(_ReadHeader, 0, _ReadHeader.Length, s_readCallback);
_ = FixedSizeReader.ReadPacketAsync(InnerStream, asyncRequest);
if (!asyncRequest.MustCompleteSynchronously)
{
return 0;
}
readBytes = asyncRequest.Result;
}
else
{
readBytes = FixedSizeReader.ReadPacket(InnerStream, _ReadHeader, 0, _ReadHeader.Length);
}
return StartFrameBody(readBytes, buffer, offset, count, asyncRequest);
}
private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
if (readBytes == 0)
{
//EOF
asyncRequest?.CompleteUser(0);
return 0;
}
if (!(readBytes == _ReadHeader.Length))
{
NetEventSource.Fail(this, $"Frame size must be 4 but received {readBytes} bytes.");
}
// Replace readBytes with the body size recovered from the header content.
readBytes = _ReadHeader[3];
readBytes = (readBytes << 8) | _ReadHeader[2];
readBytes = (readBytes << 8) | _ReadHeader[1];
readBytes = (readBytes << 8) | _ReadHeader[0];
//
// The body carries 4 bytes for trailer size slot plus trailer, hence <=4 frame size is always an error.
// Additionally we'd like to restrict the read frame size to 64k.
//
if (readBytes <= 4 || readBytes > NegoState.MaxReadFrameSize)
{
throw new IOException(SR.net_frame_read_size);
}
//
// Always pass InternalBuffer for SSPI "in place" decryption.
// A user buffer can be shared by many threads in that case decryption/integrity check may fail cause of data corruption.
//
EnsureInternalBufferSize(readBytes);
if (asyncRequest != null)
{
asyncRequest.SetNextRequest(InternalBuffer, 0, readBytes, s_readCallback);
_ = FixedSizeReader.ReadPacketAsync(InnerStream, asyncRequest);
if (!asyncRequest.MustCompleteSynchronously)
{
return 0;
}
readBytes = asyncRequest.Result;
}
else //Sync
{
readBytes = FixedSizeReader.ReadPacket(InnerStream, InternalBuffer, 0, readBytes);
}
return ProcessFrameBody(readBytes, buffer, offset, count, asyncRequest);
}
private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
if (readBytes == 0)
{
// We already checked that the frame body is bigger than 0 bytes
// Hence, this is an EOF ... fire.
throw new IOException(SR.net_io_eof);
}
// Decrypt into internal buffer, change "readBytes" to count now _Decrypted Bytes_
int internalOffset;
readBytes = _negoState.DecryptData(InternalBuffer, 0, readBytes, out internalOffset);
// Decrypted data start from zero offset, the size can be shrunk after decryption.
AdjustInternalBufferOffsetSize(readBytes, internalOffset);
if (readBytes == 0 && count != 0)
{
// Read again.
return -1;
}
if (readBytes > count)
{
readBytes = count;
}
Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, readBytes);
// This will adjust both the remaining internal buffer count and the offset.
DecrementInternalBufferCount(readBytes);
asyncRequest?.CompleteUser(readBytes);
return readBytes;
}
private static void WriteCallback(IAsyncResult transportResult)
{
if (transportResult.CompletedSynchronously)
{
return;
}
if (!(transportResult.AsyncState is AsyncProtocolRequest))
{
NetEventSource.Fail(transportResult, "State type is wrong, expected AsyncProtocolRequest.");
}
AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState;
try
{
NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject;
TaskToApm.End(transportResult);
if (asyncRequest.Count == 0)
{
// This was the last chunk.
asyncRequest.Count = -1;
}
negoStream.StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest);
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
asyncRequest.CompleteUserWithError(e);
}
}
private static void ReadCallback(AsyncProtocolRequest asyncRequest)
{
// Async ONLY completion.
try
{
NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject;
BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult;
// This is an optimization to avoid an additional callback.
if ((object)asyncRequest.Buffer == (object)negoStream._ReadHeader)
{
negoStream.StartFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest);
}
else
{
if (-1 == negoStream.ProcessFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest))
{
// In case we decrypted 0 bytes, start another reading.
negoStream.StartReading(bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest);
}
}
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
asyncRequest.CompleteUserWithError(e);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias Scripting;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.FileSystem;
using Microsoft.CodeAnalysis.Editor.Implementation.Interactive;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Interactive;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
using RelativePathResolver = Scripting::Microsoft.CodeAnalysis.RelativePathResolver;
public abstract class InteractiveEvaluator : IInteractiveEvaluator, ICurrentWorkingDirectoryDiscoveryService
{
// full path or null
private readonly string _responseFilePath;
private readonly InteractiveHost _interactiveHost;
private string _initialWorkingDirectory;
private ImmutableArray<CommandLineSourceFile> _rspSourceFiles;
private readonly IContentType _contentType;
private readonly InteractiveWorkspace _workspace;
private IInteractiveWindow _currentWindow;
private ImmutableHashSet<MetadataReference> _references;
private MetadataReferenceResolver _metadataReferenceResolver;
private SourceReferenceResolver _sourceReferenceResolver;
private ProjectId _previousSubmissionProjectId;
private ProjectId _currentSubmissionProjectId;
private readonly IViewClassifierAggregatorService _classifierAggregator;
private readonly IInteractiveWindowCommandsFactory _commandsFactory;
private readonly ImmutableArray<IInteractiveWindowCommand> _commands;
private IInteractiveWindowCommands _interactiveCommands;
private ITextView _currentTextView;
private ITextBuffer _currentSubmissionBuffer;
private readonly ISet<ValueTuple<ITextView, ITextBuffer>> _submissionBuffers = new HashSet<ValueTuple<ITextView, ITextBuffer>>();
private int _submissionCount = 0;
private readonly EventHandler<ContentTypeChangedEventArgs> _contentTypeChangedHandler;
public ImmutableArray<string> ReferenceSearchPaths { get; private set; }
public ImmutableArray<string> SourceSearchPaths { get; private set; }
public string WorkingDirectory { get; private set; }
internal InteractiveEvaluator(
IContentType contentType,
HostServices hostServices,
IViewClassifierAggregatorService classifierAggregator,
IInteractiveWindowCommandsFactory commandsFactory,
ImmutableArray<IInteractiveWindowCommand> commands,
string responseFilePath,
string initialWorkingDirectory,
string interactiveHostPath,
Type replType)
{
Debug.Assert(responseFilePath == null || PathUtilities.IsAbsolute(responseFilePath));
_contentType = contentType;
_responseFilePath = responseFilePath;
_workspace = new InteractiveWorkspace(this, hostServices);
_contentTypeChangedHandler = new EventHandler<ContentTypeChangedEventArgs>(LanguageBufferContentTypeChanged);
_classifierAggregator = classifierAggregator;
_initialWorkingDirectory = initialWorkingDirectory;
_commandsFactory = commandsFactory;
_commands = commands;
var hostPath = interactiveHostPath;
_interactiveHost = new InteractiveHost(replType, hostPath, initialWorkingDirectory);
_interactiveHost.ProcessStarting += ProcessStarting;
WorkingDirectory = initialWorkingDirectory;
}
public IContentType ContentType
{
get
{
return _contentType;
}
}
public IInteractiveWindow CurrentWindow
{
get
{
return _currentWindow;
}
set
{
if (_currentWindow != value)
{
_interactiveHost.Output = value.OutputWriter;
_interactiveHost.ErrorOutput = value.ErrorOutputWriter;
if (_currentWindow != null)
{
_currentWindow.SubmissionBufferAdded -= SubmissionBufferAdded;
}
_currentWindow = value;
}
_currentWindow.SubmissionBufferAdded += SubmissionBufferAdded;
_interactiveCommands = _commandsFactory.CreateInteractiveCommands(_currentWindow, "#", _commands);
}
}
protected IInteractiveWindowCommands InteractiveCommands
{
get
{
return _interactiveCommands;
}
}
protected abstract string LanguageName { get; }
protected abstract CompilationOptions GetSubmissionCompilationOptions(string name, MetadataReferenceResolver metadataReferenceResolver, SourceReferenceResolver sourceReferenceResolver);
protected abstract ParseOptions ParseOptions { get; }
protected abstract CommandLineParser CommandLineParser { get; }
#region Initialization
public string GetConfiguration()
{
return null;
}
private IInteractiveWindow GetInteractiveWindow()
{
var window = CurrentWindow;
if (window == null)
{
throw new InvalidOperationException(EditorFeaturesResources.EngineMustBeAttachedToAnInteractiveWindow);
}
return window;
}
public Task<ExecutionResult> InitializeAsync()
{
var window = GetInteractiveWindow();
_interactiveHost.Output = window.OutputWriter;
_interactiveHost.ErrorOutput = window.ErrorOutputWriter;
return ResetAsyncWorker();
}
public void Dispose()
{
_workspace.Dispose();
_interactiveHost.Dispose();
}
/// <summary>
/// Invoked by <see cref="InteractiveHost"/> when a new process is being started.
/// </summary>
private void ProcessStarting(bool initialize)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.BeginInvoke(new Action(() => ProcessStarting(initialize)));
return;
}
// Freeze all existing classifications and then clear the list of
// submission buffers we have.
FreezeClassifications();
_submissionBuffers.Clear();
// We always start out empty
_workspace.ClearSolution();
_currentSubmissionProjectId = null;
_previousSubmissionProjectId = null;
var metadataService = _workspace.CurrentSolution.Services.MetadataService;
ReferenceSearchPaths = ImmutableArray.Create(FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()));
SourceSearchPaths = ImmutableArray.Create(FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)));
if (initialize && File.Exists(_responseFilePath))
{
// The base directory for relative paths is the directory that contains the .rsp file.
// Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
var rspArguments = this.CommandLineParser.Parse(new[] { "@" + _responseFilePath }, Path.GetDirectoryName(_responseFilePath), RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/);
ReferenceSearchPaths = ReferenceSearchPaths.AddRange(rspArguments.ReferencePaths);
// the base directory for references specified in the .rsp file is the .rsp file directory:
var rspMetadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, rspArguments.BaseDirectory);
// ignore unresolved references, they will be reported in the interactive window:
var rspReferences = rspArguments.ResolveMetadataReferences(rspMetadataReferenceResolver)
.Where(r => !(r is UnresolvedMetadataReference));
var interactiveHelpersRef = metadataService.GetReference(typeof(Script).Assembly.Location, MetadataReferenceProperties.Assembly);
var interactiveHostObjectRef = metadataService.GetReference(typeof(InteractiveScriptGlobals).Assembly.Location, MetadataReferenceProperties.Assembly);
_references = ImmutableHashSet.Create<MetadataReference>(
interactiveHelpersRef,
interactiveHostObjectRef)
.Union(rspReferences);
// we need to create projects for these:
_rspSourceFiles = rspArguments.SourceFiles;
}
else
{
var mscorlibRef = metadataService.GetReference(typeof(object).Assembly.Location, MetadataReferenceProperties.Assembly);
_references = ImmutableHashSet.Create<MetadataReference>(mscorlibRef);
_rspSourceFiles = ImmutableArray.Create<CommandLineSourceFile>();
}
_metadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, _initialWorkingDirectory);
_sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, _initialWorkingDirectory);
// create the first submission project in the workspace after reset:
if (_currentSubmissionBuffer != null)
{
AddSubmission(_currentTextView, _currentSubmissionBuffer, this.LanguageName);
}
}
private Dispatcher Dispatcher
{
get { return ((FrameworkElement)GetInteractiveWindow().TextView).Dispatcher; }
}
private static MetadataReferenceResolver CreateMetadataReferenceResolver(IMetadataService metadataService, ImmutableArray<string> searchPaths, string baseDirectory)
{
return new RuntimeMetadataReferenceResolver(
new RelativePathResolver(searchPaths, baseDirectory),
null,
GacFileResolver.IsAvailable ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null,
(path, properties) => metadataService.GetReference(path, properties));
}
private static SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory)
{
return new SourceFileResolver(searchPaths, baseDirectory);
}
#endregion
#region Workspace
private void SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs args)
{
AddSubmission(_currentWindow.TextView, args.NewBuffer, this.LanguageName);
}
// The REPL window might change content type to host command content type (when a host command is typed at the beginning of the buffer).
private void LanguageBufferContentTypeChanged(object sender, ContentTypeChangedEventArgs e)
{
// It's not clear whether this situation will ever happen, but just in case.
if (e.BeforeContentType == e.AfterContentType)
{
return;
}
var buffer = e.Before.TextBuffer;
var contentTypeName = this.ContentType.TypeName;
var afterIsLanguage = e.AfterContentType.IsOfType(contentTypeName);
var afterIsInteractiveCommand = e.AfterContentType.IsOfType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName);
var beforeIsLanguage = e.BeforeContentType.IsOfType(contentTypeName);
var beforeIsInteractiveCommand = e.BeforeContentType.IsOfType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName);
Debug.Assert((afterIsLanguage && beforeIsInteractiveCommand)
|| (beforeIsLanguage && afterIsInteractiveCommand));
// We're switching between the target language and the Interactive Command "language".
// First, remove the current submission from the solution.
var oldSolution = _workspace.CurrentSolution;
var newSolution = oldSolution;
foreach (var documentId in _workspace.GetRelatedDocumentIds(buffer.AsTextContainer()))
{
Debug.Assert(documentId != null);
newSolution = newSolution.RemoveDocument(documentId);
// TODO (tomat): Is there a better way to remove mapping between buffer and document in REPL?
// Perhaps TrackingWorkspace should implement RemoveDocumentAsync?
_workspace.ClearOpenDocument(documentId);
}
// Next, remove the previous submission project and update the workspace.
newSolution = newSolution.RemoveProject(_currentSubmissionProjectId);
_workspace.SetCurrentSolution(newSolution);
// Add a new submission with the correct language for the current buffer.
var languageName = afterIsLanguage
? this.LanguageName
: InteractiveLanguageNames.InteractiveCommand;
AddSubmission(_currentTextView, buffer, languageName);
}
private void AddSubmission(ITextView textView, ITextBuffer subjectBuffer, string languageName)
{
var solution = _workspace.CurrentSolution;
Project project;
if (_previousSubmissionProjectId == null)
{
// insert projects for initialization files listed in .rsp:
// If we have separate files, then those are implicitly #loaded. For this, we'll
// create a submission chain
foreach (var file in _rspSourceFiles)
{
project = CreateSubmissionProject(solution, languageName);
var documentId = DocumentId.CreateNewId(project.Id, debugName: file.Path);
solution = project.Solution.AddDocument(documentId, Path.GetFileName(file.Path), new FileTextLoader(file.Path, defaultEncoding: null));
_previousSubmissionProjectId = project.Id;
}
}
// project for the new submission:
project = CreateSubmissionProject(solution, languageName);
// Keep track of this buffer so we can freeze the classifications for it in the future.
var viewAndBuffer = ValueTuple.Create(textView, subjectBuffer);
if (!_submissionBuffers.Contains(viewAndBuffer))
{
_submissionBuffers.Add(ValueTuple.Create(textView, subjectBuffer));
}
SetSubmissionDocument(subjectBuffer, project);
_currentSubmissionProjectId = project.Id;
if (_currentSubmissionBuffer != null)
{
_currentSubmissionBuffer.ContentTypeChanged -= _contentTypeChangedHandler;
}
subjectBuffer.ContentTypeChanged += _contentTypeChangedHandler;
subjectBuffer.Properties[typeof(ICurrentWorkingDirectoryDiscoveryService)] = this;
_currentSubmissionBuffer = subjectBuffer;
_currentTextView = textView;
}
private Project CreateSubmissionProject(Solution solution, string languageName)
{
var name = "Submission#" + (_submissionCount++);
// Grab a local copy so we aren't closing over the field that might change. The
// collection itself is an immutable collection.
var localReferences = _references;
// TODO (tomat): needs implementation in InteractiveHostService as well
// var localCompilationOptions = (rspArguments != null) ? rspArguments.CompilationOptions : CompilationOptions.Default;
var localCompilationOptions = GetSubmissionCompilationOptions(name, _metadataReferenceResolver, _sourceReferenceResolver);
var localParseOptions = ParseOptions;
var projectId = ProjectId.CreateNewId(debugName: name);
solution = solution.AddProject(
ProjectInfo.Create(
projectId,
VersionStamp.Create(),
name: name,
assemblyName: name,
language: languageName,
compilationOptions: localCompilationOptions,
parseOptions: localParseOptions,
documents: null,
projectReferences: null,
metadataReferences: localReferences,
hostObjectType: typeof(InteractiveScriptGlobals),
isSubmission: true));
if (_previousSubmissionProjectId != null)
{
solution = solution.AddProjectReference(projectId, new ProjectReference(_previousSubmissionProjectId));
}
return solution.GetProject(projectId);
}
private void SetSubmissionDocument(ITextBuffer buffer, Project project)
{
var documentId = DocumentId.CreateNewId(project.Id, debugName: project.Name);
var solution = project.Solution
.AddDocument(documentId, project.Name, buffer.CurrentSnapshot.AsText());
_workspace.SetCurrentSolution(solution);
// opening document will start workspace listening to changes in this text container
_workspace.OpenDocument(documentId, buffer.AsTextContainer());
}
private void FreezeClassifications()
{
foreach (var textViewAndBuffer in _submissionBuffers)
{
var textView = textViewAndBuffer.Item1;
var textBuffer = textViewAndBuffer.Item2;
if (textBuffer != _currentSubmissionBuffer)
{
InertClassifierProvider.CaptureExistingClassificationSpans(_classifierAggregator, textView, textBuffer);
}
}
}
#endregion
#region IInteractiveEngine
public virtual bool CanExecuteCode(string text)
{
if (_interactiveCommands != null && _interactiveCommands.InCommand)
{
return true;
}
return false;
}
public Task<ExecutionResult> ResetAsync(bool initialize = true)
{
GetInteractiveWindow().AddInput(_interactiveCommands.CommandPrefix + "reset");
GetInteractiveWindow().WriteLine("Resetting execution engine.");
GetInteractiveWindow().FlushOutput();
return ResetAsyncWorker(initialize);
}
private async Task<ExecutionResult> ResetAsyncWorker(bool initialize = true)
{
try
{
var options = new InteractiveHostOptions(
initializationFile: initialize ? _responseFilePath : null,
culture: CultureInfo.CurrentUICulture);
var result = await _interactiveHost.ResetAsync(options).ConfigureAwait(false);
if (result.Success)
{
UpdateResolvers(result);
}
return new ExecutionResult(result.Success);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public async Task<ExecutionResult> ExecuteCodeAsync(string text)
{
try
{
if (InteractiveCommands.InCommand)
{
var cmdResult = InteractiveCommands.TryExecuteCommand();
if (cmdResult != null)
{
return await cmdResult.ConfigureAwait(false);
}
}
var result = await _interactiveHost.ExecuteAsync(text).ConfigureAwait(false);
if (result.Success)
{
// We are not executing a command (the current content type is not "Interactive Command"),
// so the source document should not have been removed.
Debug.Assert(_workspace.CurrentSolution.GetProject(_currentSubmissionProjectId).HasDocuments);
// only remember the submission if we compiled successfully, otherwise we
// ignore it's id so we don't reference it in the next submission.
_previousSubmissionProjectId = _currentSubmissionProjectId;
// Grab any directive references from it
var compilation = await _workspace.CurrentSolution.GetProject(_previousSubmissionProjectId).GetCompilationAsync().ConfigureAwait(false);
_references = _references.Union(compilation.DirectiveReferences);
// update local search paths - remote paths has already been updated
UpdateResolvers(result);
}
return new ExecutionResult(result.Success);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public void AbortExecution()
{
// TODO: abort execution
}
public string FormatClipboard()
{
// keep the clipboard content as is
return null;
}
#endregion
#region Paths, Resolvers
private void UpdateResolvers(RemoteExecutionResult result)
{
UpdateResolvers(result.ChangedReferencePaths.AsImmutableOrNull(), result.ChangedSourcePaths.AsImmutableOrNull(), result.ChangedWorkingDirectory);
}
private void UpdateResolvers(ImmutableArray<string> changedReferenceSearchPaths, ImmutableArray<string> changedSourceSearchPaths, string changedWorkingDirectory)
{
if (changedReferenceSearchPaths.IsDefault && changedSourceSearchPaths.IsDefault && changedWorkingDirectory == null)
{
return;
}
var solution = _workspace.CurrentSolution;
// Maybe called after reset, when no submissions are available.
var optionsOpt = (_currentSubmissionProjectId != null) ? solution.GetProjectState(_currentSubmissionProjectId).CompilationOptions : null;
if (changedWorkingDirectory != null)
{
WorkingDirectory = changedWorkingDirectory;
}
if (!changedReferenceSearchPaths.IsDefault || changedWorkingDirectory != null)
{
ReferenceSearchPaths = changedReferenceSearchPaths;
_metadataReferenceResolver = CreateMetadataReferenceResolver(_workspace.CurrentSolution.Services.MetadataService, ReferenceSearchPaths, WorkingDirectory);
if (optionsOpt != null)
{
optionsOpt = optionsOpt.WithMetadataReferenceResolver(_metadataReferenceResolver);
}
}
if (!changedSourceSearchPaths.IsDefault || changedWorkingDirectory != null)
{
SourceSearchPaths = changedSourceSearchPaths;
_sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, WorkingDirectory);
if (optionsOpt != null)
{
optionsOpt = optionsOpt.WithSourceReferenceResolver(_sourceReferenceResolver);
}
}
if (optionsOpt != null)
{
_workspace.SetCurrentSolution(solution.WithProjectCompilationOptions(_currentSubmissionProjectId, optionsOpt));
}
}
public async Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory)
{
try
{
var result = await _interactiveHost.SetPathsAsync(referenceSearchPaths.ToArray(), sourceSearchPaths.ToArray(), workingDirectory).ConfigureAwait(false);
UpdateResolvers(result);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public string GetPrompt()
{
if (CurrentWindow.CurrentLanguageBuffer != null &&
CurrentWindow.CurrentLanguageBuffer.CurrentSnapshot.LineCount > 1)
{
return ". ";
}
return "> ";
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using MaterialDesignThemes.Wpf.Transitions;
using System.Collections.Generic;
namespace MaterialDesignThemes.Wpf
{
[TemplateVisualState(GroupName = TemplateAllDrawersGroupName, Name = TemplateAllDrawersAllClosedStateName)]
[TemplateVisualState(GroupName = TemplateAllDrawersGroupName, Name = TemplateAllDrawersAnyOpenStateName)]
[TemplateVisualState(GroupName = TemplateLeftDrawerGroupName, Name = TemplateLeftClosedStateName)]
[TemplateVisualState(GroupName = TemplateLeftDrawerGroupName, Name = TemplateLeftOpenStateName)]
[TemplateVisualState(GroupName = TemplateTopDrawerGroupName, Name = TemplateTopClosedStateName)]
[TemplateVisualState(GroupName = TemplateTopDrawerGroupName, Name = TemplateTopOpenStateName)]
[TemplateVisualState(GroupName = TemplateRightDrawerGroupName, Name = TemplateRightClosedStateName)]
[TemplateVisualState(GroupName = TemplateRightDrawerGroupName, Name = TemplateRightOpenStateName)]
[TemplateVisualState(GroupName = TemplateBottomDrawerGroupName, Name = TemplateBottomClosedStateName)]
[TemplateVisualState(GroupName = TemplateBottomDrawerGroupName, Name = TemplateBottomOpenStateName)]
[TemplatePart(Name = TemplateContentCoverPartName, Type = typeof(FrameworkElement))]
[TemplatePart(Name = TemplateLeftDrawerPartName, Type = typeof(FrameworkElement))]
[TemplatePart(Name = TemplateTopDrawerPartName, Type = typeof(FrameworkElement))]
[TemplatePart(Name = TemplateRightDrawerPartName, Type = typeof(FrameworkElement))]
[TemplatePart(Name = TemplateBottomDrawerPartName, Type = typeof(FrameworkElement))]
public class DrawerHost : ContentControl
{
public const string TemplateAllDrawersGroupName = "AllDrawers";
public const string TemplateAllDrawersAllClosedStateName = "AllClosed";
public const string TemplateAllDrawersAnyOpenStateName = "AnyOpen";
public const string TemplateLeftDrawerGroupName = "LeftDrawer";
public const string TemplateLeftClosedStateName = "LeftDrawerClosed";
public const string TemplateLeftOpenStateName = "LeftDrawerOpen";
public const string TemplateTopDrawerGroupName = "TopDrawer";
public const string TemplateTopClosedStateName = "TopDrawerClosed";
public const string TemplateTopOpenStateName = "TopDrawerOpen";
public const string TemplateRightDrawerGroupName = "RightDrawer";
public const string TemplateRightClosedStateName = "RightDrawerClosed";
public const string TemplateRightOpenStateName = "RightDrawerOpen";
public const string TemplateBottomDrawerGroupName = "BottomDrawer";
public const string TemplateBottomClosedStateName = "BottomDrawerClosed";
public const string TemplateBottomOpenStateName = "BottomDrawerOpen";
public const string TemplateContentCoverPartName = "PART_ContentCover";
public const string TemplateLeftDrawerPartName = "PART_LeftDrawer";
public const string TemplateTopDrawerPartName = "PART_TopDrawer";
public const string TemplateRightDrawerPartName = "PART_RightDrawer";
public const string TemplateBottomDrawerPartName = "PART_BottomDrawer";
public static RoutedCommand OpenDrawerCommand = new RoutedCommand();
public static RoutedCommand CloseDrawerCommand = new RoutedCommand();
private FrameworkElement _templateContentCoverElement;
private FrameworkElement _leftDrawerElement;
private FrameworkElement _topDrawerElement;
private FrameworkElement _rightDrawerElement;
private FrameworkElement _bottomDrawerElement;
private bool _lockZIndexes;
private readonly IDictionary<DependencyProperty, DependencyPropertyKey> _zIndexPropertyLookup = new Dictionary<DependencyProperty, DependencyPropertyKey>
{
{ IsLeftDrawerOpenProperty, LeftDrawerZIndexPropertyKey },
{ IsTopDrawerOpenProperty, TopDrawerZIndexPropertyKey },
{ IsRightDrawerOpenProperty, RightDrawerZIndexPropertyKey },
{ IsBottomDrawerOpenProperty, BottomDrawerZIndexPropertyKey }
};
static DrawerHost()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DrawerHost), new FrameworkPropertyMetadata(typeof(DrawerHost)));
}
public DrawerHost()
{
CommandBindings.Add(new CommandBinding(OpenDrawerCommand, OpenDrawerHandler));
CommandBindings.Add(new CommandBinding(CloseDrawerCommand, CloseDrawerHandler));
}
#region top drawer
public static readonly DependencyProperty TopDrawerContentProperty = DependencyProperty.Register(
nameof(TopDrawerContent), typeof(object), typeof(DrawerHost), new PropertyMetadata(default(object)));
public object TopDrawerContent
{
get { return (object)GetValue(TopDrawerContentProperty); }
set { SetValue(TopDrawerContentProperty, value); }
}
public static readonly DependencyProperty TopDrawerContentTemplateProperty = DependencyProperty.Register(
nameof(TopDrawerContentTemplate), typeof(DataTemplate), typeof(DrawerHost), new PropertyMetadata(default(DataTemplate)));
public DataTemplate TopDrawerContentTemplate
{
get { return (DataTemplate)GetValue(TopDrawerContentTemplateProperty); }
set { SetValue(TopDrawerContentTemplateProperty, value); }
}
public static readonly DependencyProperty TopDrawerContentTemplateSelectorProperty = DependencyProperty.Register(
nameof(TopDrawerContentTemplateSelector), typeof(DataTemplateSelector), typeof(DrawerHost), new PropertyMetadata(default(DataTemplateSelector)));
public DataTemplateSelector TopDrawerContentTemplateSelector
{
get { return (DataTemplateSelector)GetValue(TopDrawerContentTemplateSelectorProperty); }
set { SetValue(TopDrawerContentTemplateSelectorProperty, value); }
}
public static readonly DependencyProperty TopDrawerContentStringFormatProperty = DependencyProperty.Register(
nameof(TopDrawerContentStringFormat), typeof(string), typeof(DrawerHost), new PropertyMetadata(default(string)));
public string TopDrawerContentStringFormat
{
get { return (string)GetValue(TopDrawerContentStringFormatProperty); }
set { SetValue(TopDrawerContentStringFormatProperty, value); }
}
public static readonly DependencyProperty TopDrawerBackgroundProperty = DependencyProperty.Register(
nameof(TopDrawerBackground), typeof(Brush), typeof(DrawerHost), new PropertyMetadata(default(Brush)));
public Brush TopDrawerBackground
{
get { return (Brush)GetValue(TopDrawerBackgroundProperty); }
set { SetValue(TopDrawerBackgroundProperty, value); }
}
public static readonly DependencyProperty IsTopDrawerOpenProperty = DependencyProperty.Register(
nameof(IsTopDrawerOpen), typeof(bool), typeof(DrawerHost), new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsDrawerOpenPropertyChangedCallback));
public bool IsTopDrawerOpen
{
get { return (bool)GetValue(IsTopDrawerOpenProperty); }
set { SetValue(IsTopDrawerOpenProperty, value); }
}
private static readonly DependencyPropertyKey TopDrawerZIndexPropertyKey =
DependencyProperty.RegisterReadOnly(
"TopDrawerZIndex", typeof(int), typeof(DrawerHost),
new PropertyMetadata(4));
public static readonly DependencyProperty TopDrawerZIndexProperty = TopDrawerZIndexPropertyKey.DependencyProperty;
public int TopDrawerZIndex
{
get { return (int)GetValue(TopDrawerZIndexProperty); }
private set { SetValue(TopDrawerZIndexPropertyKey, value); }
}
#endregion
#region left drawer
public static readonly DependencyProperty LeftDrawerContentProperty = DependencyProperty.Register(
nameof(LeftDrawerContent), typeof (object), typeof (DrawerHost), new PropertyMetadata(default(object)));
public object LeftDrawerContent
{
get { return (object) GetValue(LeftDrawerContentProperty); }
set { SetValue(LeftDrawerContentProperty, value); }
}
public static readonly DependencyProperty LeftDrawerContentTemplateProperty = DependencyProperty.Register(
nameof(LeftDrawerContentTemplate), typeof (DataTemplate), typeof (DrawerHost), new PropertyMetadata(default(DataTemplate)));
public DataTemplate LeftDrawerContentTemplate
{
get { return (DataTemplate) GetValue(LeftDrawerContentTemplateProperty); }
set { SetValue(LeftDrawerContentTemplateProperty, value); }
}
public static readonly DependencyProperty LeftDrawerContentTemplateSelectorProperty = DependencyProperty.Register(
nameof(LeftDrawerContentTemplateSelector), typeof (DataTemplateSelector), typeof (DrawerHost), new PropertyMetadata(default(DataTemplateSelector)));
public DataTemplateSelector LeftDrawerContentTemplateSelector
{
get { return (DataTemplateSelector) GetValue(LeftDrawerContentTemplateSelectorProperty); }
set { SetValue(LeftDrawerContentTemplateSelectorProperty, value); }
}
public static readonly DependencyProperty LeftDrawerContentStringFormatProperty = DependencyProperty.Register(
nameof(LeftDrawerContentStringFormat), typeof (string), typeof (DrawerHost), new PropertyMetadata(default(string)));
public string LeftDrawerContentStringFormat
{
get { return (string) GetValue(LeftDrawerContentStringFormatProperty); }
set { SetValue(LeftDrawerContentStringFormatProperty, value); }
}
public static readonly DependencyProperty LeftDrawerBackgroundProperty = DependencyProperty.Register(
nameof(LeftDrawerBackground), typeof (Brush), typeof (DrawerHost), new PropertyMetadata(default(Brush)));
public Brush LeftDrawerBackground
{
get { return (Brush) GetValue(LeftDrawerBackgroundProperty); }
set { SetValue(LeftDrawerBackgroundProperty, value); }
}
public static readonly DependencyProperty IsLeftDrawerOpenProperty = DependencyProperty.Register(
nameof(IsLeftDrawerOpen), typeof (bool), typeof (DrawerHost), new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsDrawerOpenPropertyChangedCallback));
public bool IsLeftDrawerOpen
{
get { return (bool) GetValue(IsLeftDrawerOpenProperty); }
set { SetValue(IsLeftDrawerOpenProperty, value); }
}
private static readonly DependencyPropertyKey LeftDrawerZIndexPropertyKey =
DependencyProperty.RegisterReadOnly(
"LeftDrawerZIndex", typeof(int), typeof(DrawerHost),
new PropertyMetadata(2));
public static readonly DependencyProperty LeftDrawerZIndexProperty = LeftDrawerZIndexPropertyKey.DependencyProperty;
public int LeftDrawerZIndex
{
get { return (int)GetValue(LeftDrawerZIndexProperty); }
private set { SetValue(LeftDrawerZIndexPropertyKey, value); }
}
#endregion
#region right drawer
public static readonly DependencyProperty RightDrawerContentProperty = DependencyProperty.Register(
nameof(RightDrawerContent), typeof(object), typeof(DrawerHost), new PropertyMetadata(default(object)));
public object RightDrawerContent
{
get { return (object)GetValue(RightDrawerContentProperty); }
set { SetValue(RightDrawerContentProperty, value); }
}
public static readonly DependencyProperty RightDrawerContentTemplateProperty = DependencyProperty.Register(
nameof(RightDrawerContentTemplate), typeof(DataTemplate), typeof(DrawerHost), new PropertyMetadata(default(DataTemplate)));
public DataTemplate RightDrawerContentTemplate
{
get { return (DataTemplate)GetValue(RightDrawerContentTemplateProperty); }
set { SetValue(RightDrawerContentTemplateProperty, value); }
}
public static readonly DependencyProperty RightDrawerContentTemplateSelectorProperty = DependencyProperty.Register(
nameof(RightDrawerContentTemplateSelector), typeof(DataTemplateSelector), typeof(DrawerHost), new PropertyMetadata(default(DataTemplateSelector)));
public DataTemplateSelector RightDrawerContentTemplateSelector
{
get { return (DataTemplateSelector)GetValue(RightDrawerContentTemplateSelectorProperty); }
set { SetValue(RightDrawerContentTemplateSelectorProperty, value); }
}
public static readonly DependencyProperty RightDrawerContentStringFormatProperty = DependencyProperty.Register(
nameof(RightDrawerContentStringFormat), typeof(string), typeof(DrawerHost), new PropertyMetadata(default(string)));
public string RightDrawerContentStringFormat
{
get { return (string)GetValue(RightDrawerContentStringFormatProperty); }
set { SetValue(RightDrawerContentStringFormatProperty, value); }
}
public static readonly DependencyProperty RightDrawerBackgroundProperty = DependencyProperty.Register(
nameof(RightDrawerBackground), typeof(Brush), typeof(DrawerHost), new PropertyMetadata(default(Brush)));
public Brush RightDrawerBackground
{
get { return (Brush)GetValue(RightDrawerBackgroundProperty); }
set { SetValue(RightDrawerBackgroundProperty, value); }
}
public static readonly DependencyProperty IsRightDrawerOpenProperty = DependencyProperty.Register(
nameof(IsRightDrawerOpen), typeof(bool), typeof(DrawerHost), new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsDrawerOpenPropertyChangedCallback));
public bool IsRightDrawerOpen
{
get { return (bool)GetValue(IsRightDrawerOpenProperty); }
set { SetValue(IsRightDrawerOpenProperty, value); }
}
private static readonly DependencyPropertyKey RightDrawerZIndexPropertyKey =
DependencyProperty.RegisterReadOnly(
"RightDrawerZIndex", typeof(int), typeof(DrawerHost),
new PropertyMetadata(1));
public static readonly DependencyProperty RightDrawerZIndexProperty = RightDrawerZIndexPropertyKey.DependencyProperty;
public int RightDrawerZIndex
{
get { return (int)GetValue(RightDrawerZIndexProperty); }
private set { SetValue(RightDrawerZIndexPropertyKey, value); }
}
#endregion
#region bottom drawer
public static readonly DependencyProperty BottomDrawerContentProperty = DependencyProperty.Register(
nameof(BottomDrawerContent), typeof(object), typeof(DrawerHost), new PropertyMetadata(default(object)));
public object BottomDrawerContent
{
get { return (object)GetValue(BottomDrawerContentProperty); }
set { SetValue(BottomDrawerContentProperty, value); }
}
public static readonly DependencyProperty BottomDrawerContentTemplateProperty = DependencyProperty.Register(
nameof(BottomDrawerContentTemplate), typeof(DataTemplate), typeof(DrawerHost), new PropertyMetadata(default(DataTemplate)));
public DataTemplate BottomDrawerContentTemplate
{
get { return (DataTemplate)GetValue(BottomDrawerContentTemplateProperty); }
set { SetValue(BottomDrawerContentTemplateProperty, value); }
}
public static readonly DependencyProperty BottomDrawerContentTemplateSelectorProperty = DependencyProperty.Register(
nameof(BottomDrawerContentTemplateSelector), typeof(DataTemplateSelector), typeof(DrawerHost), new PropertyMetadata(default(DataTemplateSelector)));
public DataTemplateSelector BottomDrawerContentTemplateSelector
{
get { return (DataTemplateSelector)GetValue(BottomDrawerContentTemplateSelectorProperty); }
set { SetValue(BottomDrawerContentTemplateSelectorProperty, value); }
}
public static readonly DependencyProperty BottomDrawerContentStringFormatProperty = DependencyProperty.Register(
nameof(BottomDrawerContentStringFormat), typeof(string), typeof(DrawerHost), new PropertyMetadata(default(string)));
public string BottomDrawerContentStringFormat
{
get { return (string)GetValue(BottomDrawerContentStringFormatProperty); }
set { SetValue(BottomDrawerContentStringFormatProperty, value); }
}
public static readonly DependencyProperty BottomDrawerBackgroundProperty = DependencyProperty.Register(
nameof(BottomDrawerBackground), typeof(Brush), typeof(DrawerHost), new PropertyMetadata(default(Brush)));
public Brush BottomDrawerBackground
{
get { return (Brush)GetValue(BottomDrawerBackgroundProperty); }
set { SetValue(BottomDrawerBackgroundProperty, value); }
}
public static readonly DependencyProperty IsBottomDrawerOpenProperty = DependencyProperty.Register(
nameof(IsBottomDrawerOpen), typeof(bool), typeof(DrawerHost), new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsDrawerOpenPropertyChangedCallback));
public bool IsBottomDrawerOpen
{
get { return (bool)GetValue(IsBottomDrawerOpenProperty); }
set { SetValue(IsBottomDrawerOpenProperty, value); }
}
private static readonly DependencyPropertyKey BottomDrawerZIndexPropertyKey =
DependencyProperty.RegisterReadOnly(
"BottomDrawerZIndex", typeof(int), typeof(DrawerHost),
new PropertyMetadata(3));
public static readonly DependencyProperty BottomDrawerZIndexProperty = BottomDrawerZIndexPropertyKey.DependencyProperty;
public int BottomDrawerZIndex
{
get { return (int)GetValue(BottomDrawerZIndexProperty); }
private set { SetValue(BottomDrawerZIndexPropertyKey, value); }
}
#endregion
public override void OnApplyTemplate()
{
if (_templateContentCoverElement != null)
_templateContentCoverElement.PreviewMouseLeftButtonUp += TemplateContentCoverElementOnPreviewMouseLeftButtonUp;
WireDrawer(_leftDrawerElement, true);
WireDrawer(_topDrawerElement, true);
WireDrawer(_rightDrawerElement, true);
WireDrawer(_bottomDrawerElement, true);
base.OnApplyTemplate();
_templateContentCoverElement = GetTemplateChild(TemplateContentCoverPartName) as FrameworkElement;
if (_templateContentCoverElement != null)
_templateContentCoverElement.PreviewMouseLeftButtonUp += TemplateContentCoverElementOnPreviewMouseLeftButtonUp;
_leftDrawerElement = WireDrawer(GetTemplateChild(TemplateLeftDrawerPartName) as FrameworkElement, false);
_topDrawerElement = WireDrawer(GetTemplateChild(TemplateTopDrawerPartName) as FrameworkElement, false);
_rightDrawerElement = WireDrawer(GetTemplateChild(TemplateRightDrawerPartName) as FrameworkElement, false);
_bottomDrawerElement = WireDrawer(GetTemplateChild(TemplateBottomDrawerPartName) as FrameworkElement, false);
UpdateVisualStates(false);
}
private FrameworkElement WireDrawer(FrameworkElement drawerElement, bool unwire)
{
if (drawerElement == null) return null;
if (unwire)
{
drawerElement.GotFocus -= DrawerElement_GotFocus;
drawerElement.MouseDown -= DrawerElement_MouseDown;
return drawerElement;
}
drawerElement.GotFocus += DrawerElement_GotFocus;
drawerElement.MouseDown += DrawerElement_MouseDown;
return drawerElement;
}
private void DrawerElement_MouseDown(object sender, MouseButtonEventArgs e)
{
ReactToFocus(sender);
}
private void DrawerElement_GotFocus(object sender, RoutedEventArgs e)
{
ReactToFocus(sender);
}
private void ReactToFocus(object sender)
{
if (sender == _leftDrawerElement)
PrepareZIndexes(LeftDrawerZIndexPropertyKey);
else if (sender == _topDrawerElement)
PrepareZIndexes(TopDrawerZIndexPropertyKey);
else if (sender == _rightDrawerElement)
PrepareZIndexes(RightDrawerZIndexPropertyKey);
else if (sender == _bottomDrawerElement)
PrepareZIndexes(BottomDrawerZIndexPropertyKey);
}
private void TemplateContentCoverElementOnPreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
SetCurrentValue(IsLeftDrawerOpenProperty, false);
SetCurrentValue(IsRightDrawerOpenProperty, false);
SetCurrentValue(IsTopDrawerOpenProperty, false);
SetCurrentValue(IsBottomDrawerOpenProperty, false);
}
private void UpdateVisualStates(bool? useTransitions = null)
{
var anyOpen = IsTopDrawerOpen || IsLeftDrawerOpen || IsBottomDrawerOpen || IsRightDrawerOpen;
VisualStateManager.GoToState(this,
!anyOpen ? TemplateAllDrawersAllClosedStateName : TemplateAllDrawersAnyOpenStateName, useTransitions.HasValue ? useTransitions.Value : !TransitionAssist.GetDisableTransitions(this));
VisualStateManager.GoToState(this,
IsLeftDrawerOpen ? TemplateLeftOpenStateName : TemplateLeftClosedStateName, useTransitions.HasValue ? useTransitions.Value : !TransitionAssist.GetDisableTransitions(this));
VisualStateManager.GoToState(this,
IsTopDrawerOpen ? TemplateTopOpenStateName : TemplateTopClosedStateName, useTransitions.HasValue ? useTransitions.Value : !TransitionAssist.GetDisableTransitions(this));
VisualStateManager.GoToState(this,
IsRightDrawerOpen ? TemplateRightOpenStateName : TemplateRightClosedStateName, useTransitions.HasValue ? useTransitions.Value : !TransitionAssist.GetDisableTransitions(this));
VisualStateManager.GoToState(this,
IsBottomDrawerOpen ? TemplateBottomOpenStateName : TemplateBottomClosedStateName, useTransitions.HasValue ? useTransitions.Value : !TransitionAssist.GetDisableTransitions(this));
}
private static void IsDrawerOpenPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var drawerHost = (DrawerHost)dependencyObject;
if (!drawerHost._lockZIndexes && (bool)dependencyPropertyChangedEventArgs.NewValue)
drawerHost.PrepareZIndexes(drawerHost._zIndexPropertyLookup[dependencyPropertyChangedEventArgs.Property]);
drawerHost.UpdateVisualStates();
}
private void PrepareZIndexes(DependencyPropertyKey zIndexDependencyPropertyKey)
{
var newOrder = new[] { zIndexDependencyPropertyKey }
.Concat(_zIndexPropertyLookup.Values.Except(new[] { zIndexDependencyPropertyKey })
.OrderByDescending(dpk => (int)GetValue(dpk.DependencyProperty)))
.Reverse()
.Select((dpk, idx) => new { dpk, idx });
foreach (var a in newOrder)
SetValue(a.dpk, a.idx);
}
private void CloseDrawerHandler(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
{
if (executedRoutedEventArgs.Handled) return;
SetOpenFlag(executedRoutedEventArgs, false);
executedRoutedEventArgs.Handled = true;
}
private void OpenDrawerHandler(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
{
if (executedRoutedEventArgs.Handled) return;
SetOpenFlag(executedRoutedEventArgs, true);
executedRoutedEventArgs.Handled = true;
}
private void SetOpenFlag(ExecutedRoutedEventArgs executedRoutedEventArgs, bool value)
{
if (executedRoutedEventArgs.Parameter is Dock)
{
switch ((Dock)executedRoutedEventArgs.Parameter)
{
case Dock.Left:
SetCurrentValue(IsLeftDrawerOpenProperty, value);
break;
case Dock.Top:
SetCurrentValue(IsTopDrawerOpenProperty, value);
break;
case Dock.Right:
SetCurrentValue(IsRightDrawerOpenProperty, value);
break;
case Dock.Bottom:
SetCurrentValue(IsBottomDrawerOpenProperty, value);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
else
{
try
{
_lockZIndexes = true;
SetCurrentValue(IsLeftDrawerOpenProperty, value);
SetCurrentValue(IsTopDrawerOpenProperty, value);
SetCurrentValue(IsRightDrawerOpenProperty, value);
SetCurrentValue(IsBottomDrawerOpenProperty, value);
}
finally
{
_lockZIndexes = false;
}
}
}
}
}
| |
/* New BSD License
-------------------------------------------------------------------------------
Copyright (c) 2006-2012, EntitySpaces, LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the EntitySpaces, LLC 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 EntitySpaces, LLC BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlServerCe;
using Tiraggo.DynamicQuery;
using Tiraggo.Interfaces;
namespace Tiraggo.SqlServerCeProvider
{
class Shared
{
static public SqlCeCommand BuildDynamicInsertCommand(tgDataRequest request, tgEntitySavePacket packet)
{
string sql = String.Empty;
string defaults = String.Empty;
string into = String.Empty;
string values = String.Empty;
string comma = String.Empty;
string defaultComma = String.Empty;
string where = String.Empty;
string whereComma = String.Empty;
PropertyCollection props = new PropertyCollection();
SqlCeParameter p = null;
Dictionary<string, SqlCeParameter> types = Cache.GetParameters(request);
SqlCeCommand cmd = new SqlCeCommand();
if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
tgColumnMetadataCollection cols = request.Columns;
foreach (tgColumnMetadata col in cols)
{
bool isModified = packet.ModifiedColumns == null ? false : packet.ModifiedColumns.Contains(col.Name);
if (isModified && (!col.IsAutoIncrement && !col.IsConcurrency && !col.IsTiraggoConcurrency))
{
p = cmd.Parameters.Add(CloneParameter(types[col.Name]));
into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
values += comma + p.ParameterName;
comma = ", ";
}
else if (col.IsAutoIncrement)
{
props["AutoInc"] = col.Name;
props["Source"] = request.ProviderMetadata.Source;
}
else if (col.IsConcurrency)
{
props["Timestamp"] = col.Name;
props["Source"] = request.ProviderMetadata.Source;
}
else if (col.IsTiraggoConcurrency)
{
props["EntitySpacesConcurrency"] = col.Name;
into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
values += comma + "1";
comma = ", ";
p = CloneParameter(types[col.Name]);
p.Value = 1;
cmd.Parameters.Add(p);
}
else if (col.IsComputed)
{
// Do nothing but leave this here
}
else if (cols.IsSpecialColumn(col))
{
// Do nothing but leave this here
}
else if (col.HasDefault)
{
defaults += defaultComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
defaultComma = ",";
}
if (col.IsInPrimaryKey)
{
where += whereComma + col.Name;
whereComma = ",";
}
}
#region Special Columns
if (cols.DateAdded != null && cols.DateAdded.IsServerSide)
{
into += comma + Delimiters.ColumnOpen + cols.DateAdded.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["DateAdded.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.DateAdded.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
if (cols.DateModified != null && cols.DateModified.IsServerSide)
{
into += comma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["DateModified.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
if (cols.AddedBy != null && cols.AddedBy.IsServerSide)
{
into += comma + Delimiters.ColumnOpen + cols.AddedBy.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["AddedBy.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.AddedBy.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
if (cols.ModifiedBy != null && cols.ModifiedBy.IsServerSide)
{
into += comma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["ModifiedBy.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
#endregion
if (defaults.Length > 0)
{
comma = String.Empty;
props["Defaults"] = defaults;
props["Where"] = where;
}
sql += " INSERT INTO " + CreateFullName(request);
if (into.Length == 0)
{
foreach (tgColumnMetadata col in request.Columns)
{
if (!col.IsAutoIncrement && !col.IsComputed && !col.IsConcurrency)
{
into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
values += comma + "DEFAULT";
comma = ",";
}
}
}
if (into.Length != 0)
{
sql += "(" + into + ") VALUES (" + values + ")";
}
request.Properties = props;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return cmd;
}
static public SqlCeCommand BuildDynamicUpdateCommand(tgDataRequest request, tgEntitySavePacket packet)
{
string where = String.Empty;
string scomma = String.Empty;
string wcomma = String.Empty;
string defaults = String.Empty;
string defaultsWhere = String.Empty;
string defaultsComma = String.Empty;
string defaultsWhereComma = String.Empty;
string sql = "UPDATE " + CreateFullName(request) + " SET ";
PropertyCollection props = new PropertyCollection();
SqlCeParameter p = null;
Dictionary<string, SqlCeParameter> types = Cache.GetParameters(request);
SqlCeCommand cmd = new SqlCeCommand();
if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
tgColumnMetadataCollection cols = request.Columns;
foreach (tgColumnMetadata col in cols)
{
bool isModified = packet.ModifiedColumns == null ? false : packet.ModifiedColumns.Contains(col.Name);
if (isModified && (!col.IsAutoIncrement && !col.IsConcurrency && !col.IsTiraggoConcurrency))
{
p = cmd.Parameters.Add(CloneParameter(types[col.Name]));
sql += scomma;
sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
scomma = ", ";
}
else if (col.IsAutoIncrement)
{
// Nothing to do but leave this here
}
else if (col.IsConcurrency)
{
p = CloneParameter(types[col.Name]);
p.SourceVersion = DataRowVersion.Original;
cmd.Parameters.Add(p);
where += wcomma;
where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
wcomma = " AND ";
}
else if (col.IsTiraggoConcurrency)
{
props["EntitySpacesConcurrency"] = col.Name;
p = CloneParameter(types[col.Name]);
p.SourceVersion = DataRowVersion.Original;
cmd.Parameters.Add(p);
sql += scomma;
sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " + 1";
scomma = ", ";
where += wcomma;
where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
wcomma = " AND ";
}
else if (col.IsComputed)
{
// Do nothing but leave this here
}
else if (cols.IsSpecialColumn(col))
{
// Do nothing but leave this here
}
else if (col.HasDefault)
{
// defaults += defaultsComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
// defaultsComma = ",";
}
if (col.IsInPrimaryKey)
{
p = CloneParameter(types[col.Name]);
p.SourceVersion = DataRowVersion.Original;
cmd.Parameters.Add(p);
where += wcomma;
where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
wcomma = " AND ";
defaultsWhere += defaultsWhereComma + col.Name;
defaultsWhereComma = ",";
}
}
#region Special Columns
if (cols.DateModified != null && cols.DateModified.IsServerSide)
{
sql += scomma;
sql += Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose + " = " + request.ProviderMetadata["DateModified.ServerSideText"];
scomma = ", ";
defaults += defaultsComma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose;
defaultsComma = ",";
}
if (cols.ModifiedBy != null && cols.ModifiedBy.IsServerSide)
{
sql += scomma;
sql += Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose + " = " + request.ProviderMetadata["ModifiedBy.ServerSideText"];
scomma = ", ";
defaults += defaultsComma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose;
defaultsComma = ",";
}
#endregion
if (defaults.Length > 0)
{
props["Defaults"] = defaults;
props["Where"] = defaultsWhere;
}
sql += " WHERE (" + where + ")";
request.Properties = props;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return cmd;
}
static public SqlCeCommand BuildDynamicDeleteCommand(tgDataRequest request, List<string> modifiedColumns)
{
Dictionary<string, SqlCeParameter> types = Cache.GetParameters(request);
SqlCeCommand cmd = new SqlCeCommand();
if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
string sql = "DELETE FROM " + CreateFullName(request) + " ";
string comma = String.Empty;
comma = String.Empty;
sql += " WHERE ";
foreach (tgColumnMetadata col in request.Columns)
{
if (col.IsInPrimaryKey || col.IsTiraggoConcurrency)
{
SqlCeParameter p = types[col.Name];
cmd.Parameters.Add(CloneParameter(p));
sql += comma;
sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
comma = " AND ";
}
}
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return cmd;
}
static private SqlCeParameter CloneParameter(SqlCeParameter p)
{
ICloneable param = p as ICloneable;
return param.Clone() as SqlCeParameter;
}
static public string CreateFullName(tgDynamicQuerySerializable query)
{
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
tgProviderSpecificMetadata providerMetadata = iQuery.ProviderMetadata as tgProviderSpecificMetadata;
string name = String.Empty;
name += Delimiters.TableOpen;
if (query.tg.QuerySource != null)
name += query.tg.QuerySource;
else
name += providerMetadata.Destination;
name += Delimiters.TableClose;
return name;
}
static public string CreateFullName(tgDataRequest request)
{
string name = String.Empty;
name += Delimiters.TableOpen;
if (request.DynamicQuery != null && request.DynamicQuery.tg.QuerySource != null)
name += request.DynamicQuery.tg.QuerySource;
else
name += request.QueryText != null ? request.QueryText : request.ProviderMetadata.Destination;
name += Delimiters.TableClose;
return name;
}
static public string CreateFullName(tgProviderSpecificMetadata providerMetadata)
{
string name = String.Empty;
name += Delimiters.TableOpen;
name += providerMetadata.Destination;
name += Delimiters.TableClose;
return name;
}
static public tgConcurrencyException CheckForConcurrencyException(SqlCeException ex)
{
tgConcurrencyException ce = null;
if (ex.Errors != null)
{
foreach (SqlCeError err in ex.Errors)
{
if (err.NativeError == 532)
{
ce = new tgConcurrencyException(err.Message, ex);
break;
}
}
}
return ce;
}
static public void AddParameters(SqlCeCommand cmd, tgDataRequest request)
{
if (request.QueryType == tgQueryType.Text && request.QueryText != null && -1 != request.QueryText.IndexOf("{0}"))
{
int i = 0;
string token = String.Empty;
string sIndex = String.Empty;
string param = String.Empty;
foreach (tgParameter esParam in request.Parameters)
{
sIndex = i.ToString();
token = '{' + sIndex + '}';
param = Delimiters.Param + "p" + sIndex;
request.QueryText = request.QueryText.Replace(token, param);
i++;
cmd.Parameters.AddWithValue(Delimiters.Param + esParam.Name, esParam.Value);
}
}
else
{
SqlCeParameter param;
foreach (tgParameter esParam in request.Parameters)
{
param = cmd.Parameters.AddWithValue(Delimiters.Param + esParam.Name, esParam.Value);
switch (esParam.Direction)
{
case tgParameterDirection.InputOutput:
param.Direction = ParameterDirection.InputOutput;
break;
case tgParameterDirection.Output:
param.Direction = ParameterDirection.Output;
param.DbType = esParam.DbType;
param.Size = esParam.Size;
param.Scale = esParam.Scale;
param.Precision = esParam.Precision;
break;
case tgParameterDirection.ReturnValue:
param.Direction = ParameterDirection.ReturnValue;
break;
// The default is ParameterDirection.Input;
}
}
}
}
static public void GatherReturnParameters(SqlCeCommand cmd, tgDataRequest request, tgDataResponse response)
{
if (cmd.Parameters.Count > 0)
{
if (request.Parameters != null && request.Parameters.Count > 0)
{
response.Parameters = new tgParameters();
foreach (tgParameter esParam in request.Parameters)
{
if (esParam.Direction != tgParameterDirection.Input)
{
response.Parameters.Add(esParam);
SqlCeParameter p = cmd.Parameters[Delimiters.Param + esParam.Name];
esParam.Value = p.Value;
}
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using hw.DebugFormatter;
using hw.Helper;
using Reni;
using Reni.Parser;
using Reni.TokenClasses;
namespace ReniUI.Formatting
{
abstract class HierarchicalStructure : DumpableObject
{
internal class Frame : HierarchicalStructure
{
[Obsolete("",true)]
[DisableDump]
protected override IEnumerable<IEnumerable<ISourcePartEdit>> EditGroups
{
get
{
Tracer.Assert(Target.Left != null);
Tracer.Assert(Target.Left.Left == null);
Tracer.Assert(Target.Left.TokenClass is BeginOfText);
Tracer.Assert(Target.Left.Right != null);
Tracer.Assert(Target.TokenClass is EndOfText);
Tracer.Assert(Target.Right == null);
return T
(
CreateChild(Target.Left.Right).Edits,
GetWhiteSpacesEdits(Target)
);
}
}
}
[Obsolete("",true)]
class ListFrame : HierarchicalStructure
{
public ListFrame() => AdditionalLineBreaksForMultilineItems = true;
[DisableDump]
protected override IEnumerable<IEnumerable<ISourcePartEdit>> EditGroups
=> GetEditGroupsForChains<List>();
}
class ExpressionFrame : HierarchicalStructure
{
readonly ITokenClass TokenClass;
public ExpressionFrame(ITokenClass tokenClass) => TokenClass = tokenClass;
[Obsolete("",true)]
protected override IEnumerable<IEnumerable<ISourcePartEdit>> EditGroups
{
get
{
Tracer.Assert(Target.TokenClass == TokenClass, Target.Dump);
if(Target.Left != null)
{
yield return CreateChild(Target.Left).Edits;
if(IsLineSplit)
yield return T(SourcePartEditExtension.MinimalLineBreak);
}
yield return GetWhiteSpacesEdits(Target);
if(Target.Right != null)
yield return CreateChild(Target.Right).Edits;
}
}
}
[Obsolete("",true)]
class ColonFrame : HierarchicalStructure
{
[DisableDump]
protected override IEnumerable<IEnumerable<ISourcePartEdit>> EditGroups
=> GetEditGroupsForChains<Colon>();
protected override HierarchicalStructure Create(ITokenClass tokenClass, bool isLast)
{
var result = base.Create(tokenClass, isLast);
if(isLast && result is ExpressionFrame)
result.IsIndentRequired = true;
return result;
}
}
class ParenthesisFrame : HierarchicalStructure
{
[Obsolete("",true)]
[DisableDump]
protected override IEnumerable<IEnumerable<ISourcePartEdit>> EditGroups
{
get
{
Tracer.Assert(Target.Left != null);
Tracer.Assert(Target.Left.Left == null);
Tracer.Assert(Target.Left.TokenClass is LeftParenthesis);
Tracer.Assert(Target.Left.TokenClass.IsBelongingTo(Target.TokenClass));
Tracer.Assert(Target.TokenClass is RightParenthesis);
Tracer.Assert(Target.Right == null);
var isLineSplit = IsLineSplit;
yield return GetWhiteSpacesEdits(Target.Left);
if(isLineSplit)
yield return T(SourcePartEditExtension.MinimalLineBreak);
if(Target.Left.Right != null)
{
var child = CreateChild(Target.Left.Right);
child.ForceLineSplit = isLineSplit;
yield return child.Edits.Indent(IndentDirection.ToRight);
if(isLineSplit)
yield return T(SourcePartEditExtension.MinimalLineBreak);
}
yield return GetWhiteSpacesEdits(Target);
}
}
}
static bool GetIsSeparatorRequired(BinaryTree target)
=> !target.Token.PrecededWith.HasComment() &&
SeparatorExtension.Get(target.LeftNeighbor?.TokenClass, target.TokenClass);
static bool True => true;
static bool False => false;
bool AdditionalLineBreaksForMultilineItems;
internal Configuration Configuration;
bool ForceLineSplit;
bool IsIndentRequired;
internal BinaryTree Target;
[DisableDump]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[Obsolete("",true)]
internal IEnumerable<ISourcePartEdit> Edits
{
get
{
var trace = ObjectId == -240;
StartMethodDump(trace);
try
{
var result = EditGroups
.SelectMany(i => i)
.ToArray()
.Indent(IndentDirection);
Dump(nameof(result), result);
//Tracer.Assert(CheckMultilineExpectations(result), Binary.Dump);
Tracer.ConditionalBreak(trace);
return ReturnMethodDump(result, trace);
}
finally
{
EndMethodDump();
}
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[Obsolete("",true)]
IndentDirection IndentDirection => IsIndentRequired ? IndentDirection.ToRight : IndentDirection.NoIndent;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
protected virtual IEnumerable<IEnumerable<ISourcePartEdit>> EditGroups
{
get
{
NotImplementedMethod();
return default;
}
}
bool IsLineSplit => ForceLineSplit || GetHasAlreadyLineBreakOrIsTooLong(Target);
bool CheckMultilineExpectations(IEnumerable<ISourcePartEdit> result)
=> Target.Left == null && Target.Right == null && IsLineSplit ||
result.Skip(1).Any(edit => edit.HasLines) == IsLineSplit;
IEnumerable<ISourcePartEdit> GetWhiteSpacesEdits(BinaryTree target)
{
if(target.Token.PrecededWith.Any())
return T(new WhiteSpaceView(target.Token.PrecededWith, Configuration, GetIsSeparatorRequired(target)));
return T(new EmptyWhiteSpaceView(target.Token.Characters, GetIsSeparatorRequired(target)));
}
[Obsolete("",true)]
HierarchicalStructure CreateChild(BinaryTree target, bool isLast = false)
{
var child = Create(target.TokenClass, isLast);
child.Configuration = Configuration;
child.Target = target;
return child;
}
[Obsolete("",true)]
protected virtual HierarchicalStructure Create(ITokenClass tokenClass, bool isLast)
{
switch(tokenClass)
{
case List _: return new ListFrame();
case Colon _: return new ColonFrame();
case RightParenthesis _: return new ParenthesisFrame();
default: return new ExpressionFrame(tokenClass);
}
}
bool GetHasAlreadyLineBreakOrIsTooLong(BinaryTree target)
{
var basicLineLength = target.GetFlatLength(Configuration.EmptyLineLimit != 0);
return basicLineLength == null || basicLineLength > Configuration.MaxLineLength;
}
[Obsolete("",true)]
IEnumerable<IEnumerable<ISourcePartEdit>> GetEditGroupsForChains<TSeparator>()
where TSeparator : ITokenClass
=> Target
.Chain(target => target.Right)
.TakeWhile(target => target.TokenClass is TSeparator)
.Select(GetEdits<TSeparator>)
.SelectMany(i => i);
[Obsolete("",true)]
IEnumerable<IEnumerable<ISourcePartEdit>> GetEdits<TSeparator>(BinaryTree target)
where TSeparator : ITokenClass
{
yield return CreateChild(target.Left).Edits;
yield return GetWhiteSpacesEdits(target);
if(target.Right == null)
yield break;
if(IsLineSplit)
yield return T(GetLineSplitter(target, target.Right?.TokenClass is TSeparator));
if(!(target.Right.TokenClass is TSeparator))
yield return CreateChild(target.Right, true).Edits;
}
[Obsolete("",true)]
ISourcePartEdit GetLineSplitter(BinaryTree target, bool isInsideChain)
{
var second = target.Right;
if(isInsideChain)
second = second.Left;
if(!AdditionalLineBreaksForMultilineItems || second == null)
return SourcePartEditExtension.MinimalLineBreak;
if(GetHasAlreadyLineBreakOrIsTooLong(target.Left) || GetHasAlreadyLineBreakOrIsTooLong(second))
return SourcePartEditExtension.MinimalLineBreaks;
return SourcePartEditExtension.MinimalLineBreak;
}
protected override string GetNodeDump() => base.GetNodeDump() + " " + Target.Token.Characters.Id;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CmdrCompanion.Core
{
/// <summary>
/// A specialized dictionnary that is used to store lists of distance between a star and a set of other stars.
/// </summary>
/// <seealso cref="Star.KnownStarProximities"/>
public sealed class StarProximityCollection :
IDictionary<AstronomicalObject, float>,
ICollection<KeyValuePair<AstronomicalObject, float>>,
IDictionary,
ICollection,
IReadOnlyDictionary<AstronomicalObject, float>,
IReadOnlyCollection<KeyValuePair<AstronomicalObject, float>>,
IEnumerable<KeyValuePair<AstronomicalObject, float>>,
IEnumerable,
INotifyCollectionChanged
{
private Dictionary<AstronomicalObject, float> _data;
private SortedDictionary<float, List<AstronomicalObject>> _sortedIndex;
internal StarProximityCollection()
{
_data = new Dictionary<AstronomicalObject, float>();
_sortedIndex = new SortedDictionary<float, List<AstronomicalObject>>();
}
#region Structures
private class DictionaryEnumeratorWrapper<TKey, TValue> : IDictionaryEnumerator
{
private IEnumerator<KeyValuePair<TKey, TValue>> _innerEnumerator;
public DictionaryEnumeratorWrapper(IEnumerator<KeyValuePair<TKey, TValue>> enumerator)
{
_innerEnumerator = enumerator;
}
public DictionaryEntry Entry
{
get { return new DictionaryEntry(Key, Value); }
}
public object Key
{
get { return _innerEnumerator.Current.Key; }
}
public object Value
{
get { return _innerEnumerator.Current.Value; }
}
public object Current
{
get { return _innerEnumerator.Current; }
}
public bool MoveNext()
{
return _innerEnumerator.MoveNext();
}
public void Reset()
{
_innerEnumerator.Reset();
}
}
#endregion
#region Writing
internal void Set(AstronomicalObject star, float distance)
{
bool isNew = false;
float previousDistance = 0;
if(_data.ContainsKey(star))
{
if (_data[star] == distance)
return;
_sortedIndex[_data[star]].Remove(star);
previousDistance = _data[star];
_data[star] = distance;
}
else
{
_data.Add(star, distance);
isNew = true;
}
if (!_sortedIndex.ContainsKey(distance))
_sortedIndex.Add(distance, new List<AstronomicalObject>() { star });
else
_sortedIndex[distance].Add(star);
if (isNew)
OnCollectionChangedAdd(star);
else
OnCollectionChangedReplace(star, previousDistance);
}
#endregion
#region Collection interfaces
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2" />.</param>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the key; otherwise, false.
/// </returns>
public bool ContainsKey(AstronomicalObject key)
{
return _data.ContainsKey(key);
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
public IEnumerable<AstronomicalObject> Keys
{
get
{
return _sortedIndex.Values.SelectMany(v => v);
}
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key whose value to get.</param>
/// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value" /> parameter. This parameter is passed uninitialized.</param>
/// <returns>
/// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the specified key; otherwise, false.
/// </returns>
public bool TryGetValue(AstronomicalObject key, out float value)
{
return _data.TryGetValue(key, out value);
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
public IEnumerable<float> Values
{
get
{
return _sortedIndex.Keys;
}
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public float this[AstronomicalObject key]
{
get { return _data[key]; }
}
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
public int Count
{
get { return _data.Count; }
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<KeyValuePair<AstronomicalObject, float>> GetEnumerator()
{
foreach (KeyValuePair<float, List<AstronomicalObject>> pair in _sortedIndex)
foreach (AstronomicalObject s in pair.Value)
yield return new KeyValuePair<AstronomicalObject, float>(s, pair.Key);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
void IDictionary<AstronomicalObject, float>.Add(AstronomicalObject key, float value)
{
throw new NotSupportedException();
}
bool IDictionary<AstronomicalObject, float>.Remove(AstronomicalObject key)
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<AstronomicalObject, float>>.Add(KeyValuePair<AstronomicalObject, float> item)
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<AstronomicalObject, float>>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<KeyValuePair<AstronomicalObject, float>>.Contains(KeyValuePair<AstronomicalObject, float> item)
{
return ((ICollection<KeyValuePair<AstronomicalObject, float>>)_data).Contains(item);
}
void ICollection<KeyValuePair<AstronomicalObject, float>>.CopyTo(KeyValuePair<AstronomicalObject, float>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<AstronomicalObject, float>>)_data).CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<AstronomicalObject, float>>.IsReadOnly
{
get { return true; }
}
bool ICollection<KeyValuePair<AstronomicalObject, float>>.Remove(KeyValuePair<AstronomicalObject, float> item)
{
throw new NotSupportedException();
}
bool IDictionary<AstronomicalObject, float>.ContainsKey(AstronomicalObject key)
{
return _data.ContainsKey(key);
}
ICollection<AstronomicalObject> IDictionary<AstronomicalObject, float>.Keys
{
get { return _sortedIndex.Values.SelectMany(v => v).ToList(); }
}
bool IDictionary<AstronomicalObject, float>.TryGetValue(AstronomicalObject key, out float value)
{
return _data.TryGetValue(key, out value);
}
ICollection<float> IDictionary<AstronomicalObject, float>.Values
{
get { return _sortedIndex.Keys; }
}
float IDictionary<AstronomicalObject, float>.this[AstronomicalObject key]
{
get
{
return _data[key];
}
set
{
throw new NotSupportedException();
}
}
int ICollection<KeyValuePair<AstronomicalObject, float>>.Count
{
get { return _data.Count; }
}
IEnumerator<KeyValuePair<AstronomicalObject, float>> IEnumerable<KeyValuePair<AstronomicalObject, float>>.GetEnumerator()
{
return GetEnumerator();
}
void IDictionary.Add(object key, object value)
{
throw new NotSupportedException();
}
void IDictionary.Clear()
{
throw new NotSupportedException();
}
bool IDictionary.Contains(object key)
{
if (key is KeyValuePair<AstronomicalObject, float>)
return _data.Contains((KeyValuePair<AstronomicalObject, float>)key);
else
return false;
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new DictionaryEnumeratorWrapper<AstronomicalObject, float>(GetEnumerator());
}
bool IDictionary.IsFixedSize
{
get { return false; }
}
bool IDictionary.IsReadOnly
{
get { return true; }
}
ICollection IDictionary.Keys
{
get { return _sortedIndex.Values; }
}
void IDictionary.Remove(object key)
{
throw new NotSupportedException();
}
ICollection IDictionary.Values
{
get { return _sortedIndex.Keys; }
}
object IDictionary.this[object key]
{
get
{
if (key is AstronomicalObject)
return _data[(AstronomicalObject)key];
else
return null;
}
set
{
throw new NotSupportedException();
}
}
void ICollection.CopyTo(Array array, int index)
{
((ICollection)_data).CopyTo(array, index);
}
int ICollection.Count
{
get { return _data.Count; }
}
bool ICollection.IsSynchronized
{
get { return ((ICollection)_data).IsSynchronized; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_data).SyncRoot; }
}
#endregion
#region INotifyCollectionChanged
private void OnCollectionChangedAdd(AstronomicalObject newStar)
{
if (CollectionChanged != null)
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, _data[newStar]));
}
private void OnCollectionChangedReplace(AstronomicalObject changedStar, float previousDistance)
{
if (CollectionChanged != null)
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, (object)_data[changedStar], (object)new KeyValuePair<AstronomicalObject, float>(changedStar, previousDistance)));
}
/// <summary>
/// Occurs when the collection changes.
/// </summary>
public event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion
}
}
| |
namespace android.content
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.content.ContentProvider_))]
public abstract partial class ContentProvider : java.lang.Object, ComponentCallbacks
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ContentProvider()
{
InitJNI();
}
protected ContentProvider(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getContext1128;
public virtual global::android.content.Context getContext()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentProvider._getContext1128)) as android.content.Context;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._getContext1128)) as android.content.Context;
}
internal static global::MonoJavaBridge.MethodId _getType1129;
public abstract global::java.lang.String getType(android.net.Uri arg0);
internal static global::MonoJavaBridge.MethodId _delete1130;
public abstract int delete(android.net.Uri arg0, java.lang.String arg1, java.lang.String[] arg2);
internal static global::MonoJavaBridge.MethodId _insert1131;
public abstract global::android.net.Uri insert(android.net.Uri arg0, android.content.ContentValues arg1);
internal static global::MonoJavaBridge.MethodId _query1132;
public abstract global::android.database.Cursor query(android.net.Uri arg0, java.lang.String[] arg1, java.lang.String arg2, java.lang.String[] arg3, java.lang.String arg4);
internal static global::MonoJavaBridge.MethodId _update1133;
public abstract int update(android.net.Uri arg0, android.content.ContentValues arg1, java.lang.String arg2, java.lang.String[] arg3);
internal static global::MonoJavaBridge.MethodId _onCreate1134;
public abstract bool onCreate();
internal static global::MonoJavaBridge.MethodId _onConfigurationChanged1135;
public virtual void onConfigurationChanged(android.content.res.Configuration arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentProvider._onConfigurationChanged1135, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._onConfigurationChanged1135, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onLowMemory1136;
public virtual void onLowMemory()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentProvider._onLowMemory1136);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._onLowMemory1136);
}
internal static global::MonoJavaBridge.MethodId _applyBatch1137;
public virtual global::android.content.ContentProviderResult[] applyBatch(java.util.ArrayList arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.content.ContentProviderResult>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentProvider._applyBatch1137, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.ContentProviderResult[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.content.ContentProviderResult>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._applyBatch1137, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.ContentProviderResult[];
}
internal static global::MonoJavaBridge.MethodId _bulkInsert1138;
public virtual int bulkInsert(android.net.Uri arg0, android.content.ContentValues[] arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContentProvider._bulkInsert1138, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._bulkInsert1138, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _openFile1139;
public virtual global::android.os.ParcelFileDescriptor openFile(android.net.Uri arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentProvider._openFile1139, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.os.ParcelFileDescriptor;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._openFile1139, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.os.ParcelFileDescriptor;
}
internal static global::MonoJavaBridge.MethodId _openAssetFile1140;
public virtual global::android.content.res.AssetFileDescriptor openAssetFile(android.net.Uri arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentProvider._openAssetFile1140, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.res.AssetFileDescriptor;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._openAssetFile1140, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.res.AssetFileDescriptor;
}
internal static global::MonoJavaBridge.MethodId _setReadPermission1141;
protected virtual void setReadPermission(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentProvider._setReadPermission1141, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._setReadPermission1141, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getReadPermission1142;
public virtual global::java.lang.String getReadPermission()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentProvider._getReadPermission1142)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._getReadPermission1142)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setWritePermission1143;
protected virtual void setWritePermission(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentProvider._setWritePermission1143, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._setWritePermission1143, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getWritePermission1144;
public virtual global::java.lang.String getWritePermission()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentProvider._getWritePermission1144)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._getWritePermission1144)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setPathPermissions1145;
protected virtual void setPathPermissions(android.content.pm.PathPermission[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentProvider._setPathPermissions1145, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._setPathPermissions1145, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getPathPermissions1146;
public virtual global::android.content.pm.PathPermission[] getPathPermissions()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.content.pm.PathPermission>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentProvider._getPathPermissions1146)) as android.content.pm.PathPermission[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.content.pm.PathPermission>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._getPathPermissions1146)) as android.content.pm.PathPermission[];
}
internal static global::MonoJavaBridge.MethodId _openFileHelper1147;
protected virtual global::android.os.ParcelFileDescriptor openFileHelper(android.net.Uri arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentProvider._openFileHelper1147, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.os.ParcelFileDescriptor;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._openFileHelper1147, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.os.ParcelFileDescriptor;
}
internal static global::MonoJavaBridge.MethodId _isTemporary1148;
protected virtual bool isTemporary()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.ContentProvider._isTemporary1148);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._isTemporary1148);
}
internal static global::MonoJavaBridge.MethodId _attachInfo1149;
public virtual void attachInfo(android.content.Context arg0, android.content.pm.ProviderInfo arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentProvider._attachInfo1149, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentProvider.staticClass, global::android.content.ContentProvider._attachInfo1149, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _ContentProvider1150;
public ContentProvider() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.ContentProvider.staticClass, global::android.content.ContentProvider._ContentProvider1150);
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.content.ContentProvider.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/ContentProvider"));
global::android.content.ContentProvider._getContext1128 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "getContext", "()Landroid/content/Context;");
global::android.content.ContentProvider._getType1129 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "getType", "(Landroid/net/Uri;)Ljava/lang/String;");
global::android.content.ContentProvider._delete1130 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "delete", "(Landroid/net/Uri;Ljava/lang/String;[Ljava/lang/String;)I");
global::android.content.ContentProvider._insert1131 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "insert", "(Landroid/net/Uri;Landroid/content/ContentValues;)Landroid/net/Uri;");
global::android.content.ContentProvider._query1132 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "query", "(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;");
global::android.content.ContentProvider._update1133 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "update", "(Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I");
global::android.content.ContentProvider._onCreate1134 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "onCreate", "()Z");
global::android.content.ContentProvider._onConfigurationChanged1135 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "onConfigurationChanged", "(Landroid/content/res/Configuration;)V");
global::android.content.ContentProvider._onLowMemory1136 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "onLowMemory", "()V");
global::android.content.ContentProvider._applyBatch1137 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "applyBatch", "(Ljava/util/ArrayList;)[Landroid/content/ContentProviderResult;");
global::android.content.ContentProvider._bulkInsert1138 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "bulkInsert", "(Landroid/net/Uri;[Landroid/content/ContentValues;)I");
global::android.content.ContentProvider._openFile1139 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "openFile", "(Landroid/net/Uri;Ljava/lang/String;)Landroid/os/ParcelFileDescriptor;");
global::android.content.ContentProvider._openAssetFile1140 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "openAssetFile", "(Landroid/net/Uri;Ljava/lang/String;)Landroid/content/res/AssetFileDescriptor;");
global::android.content.ContentProvider._setReadPermission1141 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "setReadPermission", "(Ljava/lang/String;)V");
global::android.content.ContentProvider._getReadPermission1142 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "getReadPermission", "()Ljava/lang/String;");
global::android.content.ContentProvider._setWritePermission1143 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "setWritePermission", "(Ljava/lang/String;)V");
global::android.content.ContentProvider._getWritePermission1144 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "getWritePermission", "()Ljava/lang/String;");
global::android.content.ContentProvider._setPathPermissions1145 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "setPathPermissions", "([Landroid/content/pm/PathPermission;)V");
global::android.content.ContentProvider._getPathPermissions1146 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "getPathPermissions", "()[Landroid/content/pm/PathPermission;");
global::android.content.ContentProvider._openFileHelper1147 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "openFileHelper", "(Landroid/net/Uri;Ljava/lang/String;)Landroid/os/ParcelFileDescriptor;");
global::android.content.ContentProvider._isTemporary1148 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "isTemporary", "()Z");
global::android.content.ContentProvider._attachInfo1149 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "attachInfo", "(Landroid/content/Context;Landroid/content/pm/ProviderInfo;)V");
global::android.content.ContentProvider._ContentProvider1150 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider.staticClass, "<init>", "()V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.content.ContentProvider))]
public sealed partial class ContentProvider_ : android.content.ContentProvider
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ContentProvider_()
{
InitJNI();
}
internal ContentProvider_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getType1151;
public override global::java.lang.String getType(android.net.Uri arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentProvider_._getType1151, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentProvider_.staticClass, global::android.content.ContentProvider_._getType1151, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _delete1152;
public override int delete(android.net.Uri arg0, java.lang.String arg1, java.lang.String[] arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContentProvider_._delete1152, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContentProvider_.staticClass, global::android.content.ContentProvider_._delete1152, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _insert1153;
public override global::android.net.Uri insert(android.net.Uri arg0, android.content.ContentValues arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentProvider_._insert1153, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.net.Uri;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentProvider_.staticClass, global::android.content.ContentProvider_._insert1153, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.net.Uri;
}
internal static global::MonoJavaBridge.MethodId _query1154;
public override global::android.database.Cursor query(android.net.Uri arg0, java.lang.String[] arg1, java.lang.String arg2, java.lang.String[] arg3, java.lang.String arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentProvider_._query1154, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as android.database.Cursor;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentProvider_.staticClass, global::android.content.ContentProvider_._query1154, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as android.database.Cursor;
}
internal static global::MonoJavaBridge.MethodId _update1155;
public override int update(android.net.Uri arg0, android.content.ContentValues arg1, java.lang.String arg2, java.lang.String[] arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContentProvider_._update1155, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContentProvider_.staticClass, global::android.content.ContentProvider_._update1155, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _onCreate1156;
public override bool onCreate()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.ContentProvider_._onCreate1156);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.ContentProvider_.staticClass, global::android.content.ContentProvider_._onCreate1156);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.content.ContentProvider_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/ContentProvider"));
global::android.content.ContentProvider_._getType1151 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider_.staticClass, "getType", "(Landroid/net/Uri;)Ljava/lang/String;");
global::android.content.ContentProvider_._delete1152 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider_.staticClass, "delete", "(Landroid/net/Uri;Ljava/lang/String;[Ljava/lang/String;)I");
global::android.content.ContentProvider_._insert1153 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider_.staticClass, "insert", "(Landroid/net/Uri;Landroid/content/ContentValues;)Landroid/net/Uri;");
global::android.content.ContentProvider_._query1154 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider_.staticClass, "query", "(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;");
global::android.content.ContentProvider_._update1155 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider_.staticClass, "update", "(Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I");
global::android.content.ContentProvider_._onCreate1156 = @__env.GetMethodIDNoThrow(global::android.content.ContentProvider_.staticClass, "onCreate", "()Z");
}
}
}
| |
#region Foreign-License
/*
Copyright (c) 1997 Cornell University.
Copyright (c) 1997 Sun Microsystems, Inc.
Copyright (c) 2012 Sky Morey
See the file "license.terms" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#endregion
using System;
using System.Collections;
namespace Tcl.Lang
{
/// <summary> This class implements the built-in "info" command in Tcl.</summary>
class InfoCmd : ICommand
{
private static readonly string[] validCmds = new string[] { "args", "body", "cmdcount", "commands", "complete", "default", "exists", "globals", "hostname", "level", "library", "loaded", "locals", "nameofexecutable", "patchlevel", "procs", "script", "sharedlibextension", "tclversion", "vars" };
internal const int OPT_ARGS = 0;
internal const int OPT_BODY = 1;
internal const int OPT_CMDCOUNT = 2;
internal const int OPT_COMMANDS = 3;
internal const int OPT_COMPLETE = 4;
internal const int OPT_DEFAULT = 5;
internal const int OPT_EXISTS = 6;
internal const int OPT_GLOBALS = 7;
internal const int OPT_HOSTNAME = 8;
internal const int OPT_LEVEL = 9;
internal const int OPT_LIBRARY = 10;
internal const int OPT_LOADED = 11;
internal const int OPT_LOCALS = 12;
internal const int OPT_NAMEOFEXECUTABLE = 13;
internal const int OPT_PATCHLEVEL = 14;
internal const int OPT_PROCS = 15;
internal const int OPT_SCRIPT = 16;
internal const int OPT_SHAREDLIBEXTENSION = 17;
internal const int OPT_TCLVERSION = 18;
internal const int OPT_VARS = 19;
/// <summary> Tcl_InfoObjCmd -> InfoCmd.cmdProc
///
/// This procedure is invoked to process the "info" Tcl command.
/// See the user documentation for details on what it does.
///
/// </summary>
/// <param name="interp">the current interpreter.
/// </param>
/// <param name="argv">command arguments.
/// </param>
/// <exception cref=""> TclException if wrong # of args or invalid argument(s).
/// </exception>
public TCL.CompletionCode CmdProc(Interp interp, TclObject[] objv)
{
int index;
if (objv.Length < 2)
{
throw new TclNumArgsException(interp, 1, objv, "option ?arg arg ...?");
}
index = TclIndex.Get(interp, objv[1], validCmds, "option", 0);
switch (index)
{
case OPT_ARGS:
InfoArgsCmd(interp, objv);
break;
case OPT_BODY:
InfoBodyCmd(interp, objv);
break;
case OPT_CMDCOUNT:
InfoCmdCountCmd(interp, objv);
break;
case OPT_COMMANDS:
InfoCommandsCmd(interp, objv);
break;
case OPT_COMPLETE:
InfoCompleteCmd(interp, objv);
break;
case OPT_DEFAULT:
InfoDefaultCmd(interp, objv);
break;
case OPT_EXISTS:
InfoExistsCmd(interp, objv);
break;
case OPT_GLOBALS:
InfoGlobalsCmd(interp, objv);
break;
case OPT_HOSTNAME:
InfoHostnameCmd(interp, objv);
break;
case OPT_LEVEL:
InfoLevelCmd(interp, objv);
break;
case OPT_LIBRARY:
InfoLibraryCmd(interp, objv);
break;
case OPT_LOADED:
InfoLoadedCmd(interp, objv);
break;
case OPT_LOCALS:
InfoLocalsCmd(interp, objv);
break;
case OPT_NAMEOFEXECUTABLE:
InfoNameOfExecutableCmd(interp, objv);
break;
case OPT_PATCHLEVEL:
InfoPatchLevelCmd(interp, objv);
break;
case OPT_PROCS:
InfoProcsCmd(interp, objv);
break;
case OPT_SCRIPT:
InfoScriptCmd(interp, objv);
break;
case OPT_SHAREDLIBEXTENSION:
InfoSharedlibCmd(interp, objv);
break;
case OPT_TCLVERSION:
InfoTclVersionCmd(interp, objv);
break;
case OPT_VARS:
InfoVarsCmd(interp, objv);
break;
}
return TCL.CompletionCode.RETURN;
}
/*
*----------------------------------------------------------------------
*
* InfoArgsCmd --
*
* Called to implement the "info args" command that returns the
* argument list for a procedure. Handles the following syntax:
*
* info args procName
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoArgsCmd(Interp interp, TclObject[] objv)
{
string name;
Procedure proc;
TclObject listObj;
if (objv.Length != 3)
{
throw new TclNumArgsException(interp, 2, objv, "procname");
}
name = objv[2].ToString();
proc = Procedure.findProc(interp, name);
if (proc == null)
{
throw new TclException(interp, "\"" + name + "\" isn't a procedure");
}
// Build a return list containing the arguments.
listObj = TclList.NewInstance();
for (int i = 0; i < proc.ArgList.Length; i++)
{
TclObject s = TclString.NewInstance(proc.ArgList[i][0]);
TclList.Append(interp, listObj, s);
}
interp.SetResult(listObj);
return;
}
/*
*----------------------------------------------------------------------
*
* InfoBodyCmd --
*
* Called to implement the "info body" command that returns the body
* for a procedure. Handles the following syntax:
*
* info body procName
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoBodyCmd(Interp interp, TclObject[] objv)
{
string name;
Procedure proc;
//TclObject body, result;
if (objv.Length != 3)
{
throw new TclNumArgsException(interp, 2, objv, "procname");
}
name = objv[2].ToString();
proc = Procedure.findProc(interp, name);
if (proc == null)
{
throw new TclException(interp, "\"" + name + "\" isn't a procedure");
}
interp.SetResult(proc.body.ToString());
return;
}
/*
*----------------------------------------------------------------------
*
* InfoCmdCountCmd --
*
* Called to implement the "info cmdcount" command that returns the
* number of commands that have been executed. Handles the following
* syntax:
*
* info cmdcount
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoCmdCountCmd(Interp interp, TclObject[] objv)
{
if (objv.Length != 2)
{
throw new TclNumArgsException(interp, 2, objv, null);
}
interp.SetResult(interp._cmdCount);
return;
}
/*
*----------------------------------------------------------------------
*
* InfoCommandsCmd --
*
* Called to implement the "info commands" command that returns the
* list of commands in the interpreter that match an optional pattern.
* The pattern, if any, consists of an optional sequence of namespace
* names separated by "::" qualifiers, which is followed by a
* glob-style pattern that restricts which commands are returned.
* Handles the following syntax:
*
* info commands ?pattern?
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoCommandsCmd(Interp interp, TclObject[] objv)
{
string cmdName, pattern, simplePattern;
IDictionaryEnumerator search;
NamespaceCmd.Namespace ns;
NamespaceCmd.Namespace globalNs = NamespaceCmd.getGlobalNamespace(interp);
NamespaceCmd.Namespace currNs = NamespaceCmd.getCurrentNamespace(interp);
TclObject list, elemObj;
bool specificNsInPattern = false; // Init. to avoid compiler warning.
WrappedCommand cmd;
// Get the pattern and find the "effective namespace" in which to
// list commands.
if (objv.Length == 2)
{
simplePattern = null;
ns = currNs;
specificNsInPattern = false;
}
else if (objv.Length == 3)
{
// From the pattern, get the effective namespace and the simple
// pattern (no namespace qualifiers or ::'s) at the end. If an
// error was found while parsing the pattern, return it. Otherwise,
// if the namespace wasn't found, just leave ns NULL: we will
// return an empty list since no commands there can be found.
pattern = objv[2].ToString();
// Java does not support passing an address so we pass
// an array of size 1 and then assign arr[0] to the value
NamespaceCmd.Namespace[] nsArr = new NamespaceCmd.Namespace[1];
NamespaceCmd.Namespace[] dummy1Arr = new NamespaceCmd.Namespace[1];
NamespaceCmd.Namespace[] dummy2Arr = new NamespaceCmd.Namespace[1];
string[] simplePatternArr = new string[1];
NamespaceCmd.getNamespaceForQualName(interp, pattern, null, 0, nsArr, dummy1Arr, dummy2Arr, simplePatternArr);
// Get the values out of the arrays!
ns = nsArr[0];
simplePattern = simplePatternArr[0];
if (ns != null)
{
// we successfully found the pattern's ns
specificNsInPattern = (simplePattern.CompareTo(pattern) != 0);
}
}
else
{
throw new TclNumArgsException(interp, 2, objv, "?pattern?");
}
// Scan through the effective namespace's command table and create a
// list with all commands that match the pattern. If a specific
// namespace was requested in the pattern, qualify the command names
// with the namespace name.
list = TclList.NewInstance();
if (ns != null)
{
search = ns.cmdTable.GetEnumerator();
while (search.MoveNext())
{
cmdName = ((string)search.Key);
if (((System.Object)simplePattern == null) || Util.StringMatch(cmdName, simplePattern))
{
if (specificNsInPattern)
{
cmd = (WrappedCommand)search.Value;
elemObj = TclString.NewInstance(interp.getCommandFullName(cmd));
}
else
{
elemObj = TclString.NewInstance(cmdName);
}
TclList.Append(interp, list, elemObj);
}
}
// If the effective namespace isn't the global :: namespace, and a
// specific namespace wasn't requested in the pattern, then add in
// all global :: commands that match the simple pattern. Of course,
// we add in only those commands that aren't hidden by a command in
// the effective namespace.
if ((ns != globalNs) && !specificNsInPattern)
{
search = globalNs.cmdTable.GetEnumerator();
while (search.MoveNext())
{
cmdName = ((string)search.Key);
if (((System.Object)simplePattern == null) || Util.StringMatch(cmdName, simplePattern))
{
if (ns.cmdTable[cmdName] == null)
{
TclList.Append(interp, list, TclString.NewInstance(cmdName));
}
}
}
}
}
interp.SetResult(list);
return;
}
/*
*----------------------------------------------------------------------
*
* InfoCompleteCmd --
*
* Called to implement the "info complete" command that determines
* whether a string is a complete Tcl command. Handles the following
* syntax:
*
* info complete command
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoCompleteCmd(Interp interp, TclObject[] objv)
{
if (objv.Length != 3)
{
throw new TclNumArgsException(interp, 2, objv, "command");
}
interp.SetResult(Tcl.Lang.Interp.commandComplete(objv[2].ToString()));
return;
}
/*
*----------------------------------------------------------------------
*
* InfoDefaultCmd --
*
* Called to implement the "info default" command that returns the
* default value for a procedure argument. Handles the following
* syntax:
*
* info default procName arg varName
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoDefaultCmd(Interp interp, TclObject[] objv)
{
string procName, argName, varName;
Procedure proc;
//TclObject valueObj;
if (objv.Length != 5)
{
throw new TclNumArgsException(interp, 2, objv, "procname arg varname");
}
procName = objv[2].ToString();
argName = objv[3].ToString();
proc = Procedure.findProc(interp, procName);
if (proc == null)
{
throw new TclException(interp, "\"" + procName + "\" isn't a procedure");
}
for (int i = 0; i < proc.ArgList.Length; i++)
{
if (argName.Equals(proc.ArgList[i][0].ToString()))
{
varName = objv[4].ToString();
try
{
if (proc.ArgList[i][1] != null)
{
interp.SetVar(varName, proc.ArgList[i][1], 0);
interp.SetResult(1);
}
else
{
interp.SetVar(varName, "", 0);
interp.SetResult(0);
}
}
catch (TclException excp)
{
throw new TclException(interp, "couldn't store default value in variable \"" + varName + "\"");
}
return;
}
}
throw new TclException(interp, "procedure \"" + procName + "\" doesn't have an argument \"" + argName + "\"");
}
/*
*----------------------------------------------------------------------
*
* InfoExistsCmd --
*
* Called to implement the "info exists" command that determines
* whether a variable exists. Handles the following syntax:
*
* info exists varName
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoExistsCmd(Interp interp, TclObject[] objv)
{
string varName;
Var var = null;
if (objv.Length != 3)
{
throw new TclNumArgsException(interp, 2, objv, "varName");
}
varName = objv[2].ToString();
Var[] result = Var.LookupVar(interp, varName, null, 0, "access", false, false);
if (result != null)
{
var = result[0];
}
if ((var != null) && !var.IsVarUndefined())
{
interp.SetResult(true);
}
else
{
interp.SetResult(false);
}
return;
}
/*
*----------------------------------------------------------------------
*
* InfoGlobalsCmd --
*
* Called to implement the "info globals" command that returns the list
* of global variables matching an optional pattern. Handles the
* following syntax:
*
* info globals ?pattern?*
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoGlobalsCmd(Interp interp, TclObject[] objv)
{
string varName, pattern;
NamespaceCmd.Namespace globalNs = NamespaceCmd.getGlobalNamespace(interp);
IDictionaryEnumerator search;
Var var;
TclObject list;
if (objv.Length == 2)
{
pattern = null;
}
else if (objv.Length == 3)
{
pattern = objv[2].ToString();
}
else
{
throw new TclNumArgsException(interp, 2, objv, "?pattern?");
}
// Scan through the global :: namespace's variable table and create a
// list of all global variables that match the pattern.
list = TclList.NewInstance();
for (search = globalNs.varTable.GetEnumerator(); search.MoveNext(); )
{
varName = ((string)search.Key);
var = (Var)search.Value;
if (var.IsVarUndefined())
{
continue;
}
if (((System.Object)pattern == null) || Util.StringMatch(varName, pattern))
{
TclList.Append(interp, list, TclString.NewInstance(varName));
}
}
interp.SetResult(list);
return;
}
/*
*----------------------------------------------------------------------
*
* InfoHostnameCmd --
*
* Called to implement the "info hostname" command that returns the
* host name. Handles the following syntax:
*
* info hostname
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoHostnameCmd(Interp interp, TclObject[] objv)
{
string name;
if (objv.Length != 2)
{
throw new TclNumArgsException(interp, 2, objv, null);
}
// FIXME : how can we find the hostname
name = null;
if ((System.Object)name != null)
{
interp.SetResult(name);
return;
}
else
{
interp.SetResult("unable to determine name of host");
return;
}
}
/*
*----------------------------------------------------------------------
*
* InfoLevelCmd --
*
* Called to implement the "info level" command that returns
* information about the call stack. Handles the following syntax:
*
* info level ?number?
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoLevelCmd(Interp interp, TclObject[] objv)
{
int level;
CallFrame frame;
TclObject list;
if (objv.Length == 2)
{
// just "info level"
if (interp.VarFrame == null)
{
interp.SetResult(0);
}
else
{
interp.SetResult(interp.VarFrame.Level);
}
return;
}
else if (objv.Length == 3)
{
level = TclInteger.Get(interp, objv[2]);
if (level <= 0)
{
if (interp.VarFrame == null)
{
throw new TclException(interp, "bad level \"" + objv[2].ToString() + "\"");
}
level += interp.VarFrame.Level;
}
for (frame = interp.VarFrame; frame != null; frame = frame.CallerVar)
{
if (frame.Level == level)
{
break;
}
}
if ((frame == null) || frame.Objv == null)
{
throw new TclException(interp, "bad level \"" + objv[2].ToString() + "\"");
}
list = TclList.NewInstance();
for (int i = 0; i < frame.Objv.Length; i++)
{
TclList.Append(interp, list, TclString.NewInstance(frame.Objv[i]));
}
interp.SetResult(list);
return;
}
throw new TclNumArgsException(interp, 2, objv, "?number?");
}
/*
*----------------------------------------------------------------------
*
* InfoLibraryCmd --
*
* Called to implement the "info library" command that returns the
* library directory for the Tcl installation. Handles the following
* syntax:
*
* info library
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoLibraryCmd(Interp interp, TclObject[] objv)
{
if (objv.Length != 2)
{
throw new TclNumArgsException(interp, 2, objv, null);
}
try
{
interp.SetResult(interp.GetVar("tcl_library", TCL.VarFlag.GLOBAL_ONLY));
return;
}
catch (TclException e)
{
// If the variable has not been defined
throw new TclException(interp, "no library has been specified for Tcl");
}
}
/*
*----------------------------------------------------------------------
*
* InfoLoadedCmd --
*
* Called to implement the "info loaded" command that returns the
* packages that have been loaded into an interpreter. Handles the
* following syntax:
*
* info loaded ?interp?
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoLoadedCmd(Interp interp, TclObject[] objv)
{
if (objv.Length != 2 && objv.Length != 3)
{
throw new TclNumArgsException(interp, 2, objv, "?interp?");
}
// FIXME : what should "info loaded" return?
throw new TclException(interp, "info loaded not implemented");
}
/*
*----------------------------------------------------------------------
*
* InfoLocalsCmd --
*
* Called to implement the "info locals" command to return a list of
* local variables that match an optional pattern. Handles the
* following syntax:
*
* info locals ?pattern?
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoLocalsCmd(Interp interp, TclObject[] objv)
{
string pattern;
TclObject list;
if (objv.Length == 2)
{
pattern = null;
}
else if (objv.Length == 3)
{
pattern = objv[2].ToString();
}
else
{
throw new TclNumArgsException(interp, 2, objv, "?pattern?");
}
if (interp.VarFrame == null || !interp.VarFrame.IsProcCallFrame)
{
return;
}
// Return a list containing names of first the compiled locals (i.e. the
// ones stored in the call frame), then the variables in the local hash
// table (if one exists).
list = TclList.NewInstance();
AppendLocals(interp, list, pattern, false);
interp.SetResult(list);
return;
}
/*
*----------------------------------------------------------------------
*
* AppendLocals --
*
* Append the local variables for the current frame to the
* specified list object.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
private static void AppendLocals(Interp interp, TclObject list, string pattern, bool includeLinks)
{
Var var;
string varName;
Hashtable localVarTable;
IDictionaryEnumerator search;
localVarTable = interp.VarFrame.VarTable;
// Compiled locals do not exist in Jacl
if (localVarTable != null)
{
for (search = localVarTable.GetEnumerator(); search.MoveNext(); )
{
var = (Var)search.Value;
varName = (string)search.Key;
if (!var.IsVarUndefined() && (includeLinks || !var.IsVarLink()))
{
if (((System.Object)pattern == null) || Util.StringMatch(varName, pattern))
{
TclList.Append(interp, list, TclString.NewInstance(varName));
}
}
}
}
}
/*
*----------------------------------------------------------------------
*
* InfoNameOfExecutableCmd --
*
* Called to implement the "info nameofexecutable" command that returns
* the name of the binary file running this application. Handles the
* following syntax:
*
* info nameofexecutable
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoNameOfExecutableCmd(Interp interp, TclObject[] objv)
{
if (objv.Length != 2)
{
throw new TclNumArgsException(interp, 2, objv, null);
}
// We depend on a user defined property named "JAVA" since
// the JDK provides no means to learn the name of the executable
// that launched the application.
string nameOfExecutable = "nacl";
if ((System.Object)nameOfExecutable != null)
{
TclObject result = TclList.NewInstance();
TclList.Append(interp, result, TclString.NewInstance(nameOfExecutable));
TclList.Append(interp, result, TclString.NewInstance("tcl.lang.Shell"));
interp.SetResult(result);
}
return;
}
/*
*----------------------------------------------------------------------
*
* InfoPatchLevelCmd --
*
* Called to implement the "info patchlevel" command that returns the
* default value for an argument to a procedure. Handles the following
* syntax:
*
* info patchlevel
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoPatchLevelCmd(Interp interp, TclObject[] objv)
{
if (objv.Length != 2)
{
throw new TclNumArgsException(interp, 2, objv, null);
}
interp.SetResult(interp.GetVar("tcl_patchLevel", TCL.VarFlag.GLOBAL_ONLY));
return;
}
/*
*----------------------------------------------------------------------
*
* InfoProcsCmd --
*
* Called to implement the "info procs" command that returns the
* procedures in the current namespace that match an optional pattern.
* Handles the following syntax:
*
* info procs ?pattern?
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoProcsCmd(Interp interp, TclObject[] objv)
{
string cmdName, pattern;
NamespaceCmd.Namespace currNs = NamespaceCmd.getCurrentNamespace(interp);
IDictionaryEnumerator search;
WrappedCommand cmd, realCmd;
TclObject list;
if (objv.Length == 2)
{
pattern = null;
}
else if (objv.Length == 3)
{
pattern = objv[2].ToString();
}
else
{
throw new TclNumArgsException(interp, 2, objv, "?pattern?");
}
// Scan through the current namespace's command table and return a list
// of all procs that match the pattern.
list = TclList.NewInstance();
for (search = currNs.cmdTable.GetEnumerator(); search.MoveNext(); )
{
cmdName = ((string)search.Key);
cmd = (WrappedCommand)search.Value;
// If the command isn't itself a proc, it still might be an
// imported command that points to a "real" proc in a different
// namespace.
realCmd = NamespaceCmd.getOriginalCommand(cmd);
if (Procedure.isProc(cmd) || ((realCmd != null) && Procedure.isProc(realCmd)))
{
if (((System.Object)pattern == null) || Util.StringMatch(cmdName, pattern))
{
TclList.Append(interp, list, TclString.NewInstance(cmdName));
}
}
}
interp.SetResult(list);
return;
}
/*
*----------------------------------------------------------------------
*
* InfoScriptCmd --
*
* Called to implement the "info script" command that returns the
* script file that is currently being evaluated. Handles the
* following syntax:
*
* info script
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoScriptCmd(Interp interp, TclObject[] objv)
{
if (objv.Length != 2)
{
throw new TclNumArgsException(interp, 2, objv, null);
}
interp.SetResult(interp._scriptFile);
return;
}
/*
*----------------------------------------------------------------------
*
* InfoSharedlibCmd --
*
* Called to implement the "info sharedlibextension" command that
* returns the file extension used for shared libraries. Handles the
* following syntax:
*
* info sharedlibextension
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoSharedlibCmd(Interp interp, TclObject[] objv)
{
if (objv.Length != 2)
{
throw new TclNumArgsException(interp, 2, objv, null);
}
interp.SetResult(".jar");
return;
}
/*
*----------------------------------------------------------------------
*
* InfoTclVersionCmd --
*
* Called to implement the "info tclversion" command that returns the
* version number for this Tcl library. Handles the following syntax:
*
* info tclversion
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoTclVersionCmd(Interp interp, TclObject[] objv)
{
if (objv.Length != 2)
{
throw new TclNumArgsException(interp, 2, objv, null);
}
interp.SetResult(interp.GetVar("tcl_version", TCL.VarFlag.GLOBAL_ONLY));
return;
}
/*
*----------------------------------------------------------------------
*
* InfoVarsCmd --
*
* Called to implement the "info vars" command that returns the
* list of variables in the interpreter that match an optional pattern.
* The pattern, if any, consists of an optional sequence of namespace
* names separated by "::" qualifiers, which is followed by a
* glob-style pattern that restricts which variables are returned.
* Handles the following syntax:
*
* info vars ?pattern?
*
* Results:
* Returns if successful, raises TclException otherwise.
*
* Side effects:
* Returns a result in the interpreter's result object.
*
*----------------------------------------------------------------------
*/
private static void InfoVarsCmd(Interp interp, TclObject[] objv)
{
string varName, pattern, simplePattern;
IDictionaryEnumerator search;
Var var;
NamespaceCmd.Namespace ns;
NamespaceCmd.Namespace globalNs = NamespaceCmd.getGlobalNamespace(interp);
NamespaceCmd.Namespace currNs = NamespaceCmd.getCurrentNamespace(interp);
TclObject list, elemObj;
bool specificNsInPattern = false; // Init. to avoid compiler warning.
// Get the pattern and find the "effective namespace" in which to
// list variables. We only use this effective namespace if there's
// no active Tcl procedure frame.
if (objv.Length == 2)
{
simplePattern = null;
ns = currNs;
specificNsInPattern = false;
}
else if (objv.Length == 3)
{
// From the pattern, get the effective namespace and the simple
// pattern (no namespace qualifiers or ::'s) at the end. If an
// error was found while parsing the pattern, return it. Otherwise,
// if the namespace wasn't found, just leave ns = null: we will
// return an empty list since no variables there can be found.
pattern = objv[2].ToString();
// Java does not support passing an address so we pass
// an array of size 1 and then assign arr[0] to the value
NamespaceCmd.Namespace[] nsArr = new NamespaceCmd.Namespace[1];
NamespaceCmd.Namespace[] dummy1Arr = new NamespaceCmd.Namespace[1];
NamespaceCmd.Namespace[] dummy2Arr = new NamespaceCmd.Namespace[1];
string[] simplePatternArr = new string[1];
NamespaceCmd.getNamespaceForQualName(interp, pattern, null, 0, nsArr, dummy1Arr, dummy2Arr, simplePatternArr);
// Get the values out of the arrays!
ns = nsArr[0];
simplePattern = simplePatternArr[0];
if (ns != null)
{
// we successfully found the pattern's ns
specificNsInPattern = (simplePattern.CompareTo(pattern) != 0);
}
}
else
{
throw new TclNumArgsException(interp, 2, objv, "?pattern?");
}
// If the namespace specified in the pattern wasn't found, just return.
if (ns == null)
{
return;
}
list = TclList.NewInstance();
if ((interp.VarFrame == null) || !interp.VarFrame.IsProcCallFrame || specificNsInPattern)
{
// There is no frame pointer, the frame pointer was pushed only
// to activate a namespace, or we are in a procedure call frame
// but a specific namespace was specified. Create a list containing
// only the variables in the effective namespace's variable table.
search = ns.varTable.GetEnumerator();
while (search.MoveNext())
{
varName = ((string)search.Key);
var = (Var)search.Value;
if (!var.IsVarUndefined() || ((var.Flags & VarFlags.NAMESPACE_VAR) != 0))
{
if (((System.Object)simplePattern == null) || Util.StringMatch(varName, simplePattern))
{
if (specificNsInPattern)
{
elemObj = TclString.NewInstance(Var.getVariableFullName(interp, var));
}
else
{
elemObj = TclString.NewInstance(varName);
}
TclList.Append(interp, list, elemObj);
}
}
}
// If the effective namespace isn't the global :: namespace, and a
// specific namespace wasn't requested in the pattern (i.e., the
// pattern only specifies variable names), then add in all global ::
// variables that match the simple pattern. Of course, add in only
// those variables that aren't hidden by a variable in the effective
// namespace.
if ((ns != globalNs) && !specificNsInPattern)
{
search = globalNs.varTable.GetEnumerator();
while (search.MoveNext())
{
varName = ((string)search.Key);
var = (Var)search.Value;
if (!var.IsVarUndefined() || ((var.Flags & VarFlags.NAMESPACE_VAR) != 0))
{
if (((System.Object)simplePattern == null) || Util.StringMatch(varName, simplePattern))
{
// Skip vars defined in current namespace
if (ns.varTable[varName] == null)
{
TclList.Append(interp, list, TclString.NewInstance(varName));
}
}
}
}
}
}
else
{
AppendLocals(interp, list, simplePattern, true);
}
interp.SetResult(list);
return;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// AccountOperations operations.
/// </summary>
internal partial class AccountOperations : IServiceOperations<DataLakeAnalyticsAccountManagementClient>, IAccountOperations
{
/// <summary>
/// Tests whether the specified Azure Storage account is linked to the given Data
/// Lake Analytics account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to test
/// Azure storage account existence.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure Storage account for which to test for existence.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> StorageAccountExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, string storageAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (storageAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "storageAccountName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("storageAccountName", storageAccountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetStorageAccount", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/StorageAccounts/{storageAccountName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName));
_url = _url.Replace("{storageAccountName}", Uri.EscapeDataString(storageAccountName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("ResourceNotFound", StringComparison.OrdinalIgnoreCase))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
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<bool>();
_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)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Tests the existence of the specified Azure Storage container associated with the
/// given Data Lake Analytics and Azure Storage accounts.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account for which to retrieve
/// blob container.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure storage account from which to test the
/// blob container's existence.
/// </param>
/// <param name='containerName'>
/// The name of the Azure storage container to test for existence.
/// </param>
/// <param name='customHeaders'>
/// The 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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> StorageContainerExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, string storageAccountName, string containerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (storageAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "storageAccountName");
}
if (containerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "containerName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("storageAccountName", storageAccountName);
tracingParameters.Add("containerName", containerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetStorageContainer", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/StorageAccounts/{storageAccountName}/Containers/{containerName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName));
_url = _url.Replace("{storageAccountName}", Uri.EscapeDataString(storageAccountName));
_url = _url.Replace("{containerName}", Uri.EscapeDataString(containerName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("ResourceNotFound", StringComparison.OrdinalIgnoreCase))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
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<bool>();
_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)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Tests whether the specified Data Lake Store account is linked to the
/// specified Data Lake Analytics account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to test
/// the existence of the Data Lake Store account.
/// </param>
/// <param name='dataLakeStoreAccountName'>
/// The name of the Data Lake Store account to test for existence
/// </param>
/// <param name='customHeaders'>
/// The 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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> DataLakeStoreAccountExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, string dataLakeStoreAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (dataLakeStoreAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "dataLakeStoreAccountName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("dataLakeStoreAccountName", dataLakeStoreAccountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetDataLakeStoreAccount", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/DataLakeStoreAccounts/{dataLakeStoreAccountName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName));
_url = _url.Replace("{dataLakeStoreAccountName}", Uri.EscapeDataString(dataLakeStoreAccountName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("ResourceNotFound", StringComparison.OrdinalIgnoreCase))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
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<bool>();
_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)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Tests for the existence of the specified Data Lake Analytics account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to test existence of.
/// </param>
/// <param name='customHeaders'>
/// The 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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> ExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("ResourceNotFound", StringComparison.OrdinalIgnoreCase))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
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<bool>();
_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)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace Elasticsearch.Client
{
public partial class ElasticsearchClient
{
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetGet(Stream body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = "/_mget";
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetGetAsync(Stream body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = "/_mget";
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetGet(byte[] body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = "/_mget";
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetGetAsync(byte[] body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = "/_mget";
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetGetString(string body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = "/_mget";
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetGetStringAsync(string body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = "/_mget";
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetPost(Stream body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = "/_mget";
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetPostAsync(Stream body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = "/_mget";
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetPost(byte[] body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = "/_mget";
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetPostAsync(byte[] body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = "/_mget";
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetPostString(string body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = "/_mget";
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetPostStringAsync(string body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = "/_mget";
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetGet(string index, Stream body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/_mget", index);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetGetAsync(string index, Stream body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/_mget", index);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetGet(string index, byte[] body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/_mget", index);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetGetAsync(string index, byte[] body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/_mget", index);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetGetString(string index, string body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/_mget", index);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetGetStringAsync(string index, string body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/_mget", index);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetPost(string index, Stream body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/_mget", index);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetPostAsync(string index, Stream body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/_mget", index);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetPost(string index, byte[] body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/_mget", index);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetPostAsync(string index, byte[] body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/_mget", index);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetPostString(string index, string body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/_mget", index);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetPostStringAsync(string index, string body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/_mget", index);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="type">The type of the document</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetGet(string index, string type, Stream body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mget", index, type);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="type">The type of the document</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetGetAsync(string index, string type, Stream body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mget", index, type);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="type">The type of the document</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetGet(string index, string type, byte[] body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mget", index, type);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="type">The type of the document</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetGetAsync(string index, string type, byte[] body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mget", index, type);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="type">The type of the document</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetGetString(string index, string type, string body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mget", index, type);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="type">The type of the document</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetGetStringAsync(string index, string type, string body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mget", index, type);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="type">The type of the document</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetPost(string index, string type, Stream body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mget", index, type);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="type">The type of the document</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetPostAsync(string index, string type, Stream body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mget", index, type);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="type">The type of the document</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetPost(string index, string type, byte[] body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mget", index, type);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="type">The type of the document</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetPostAsync(string index, string type, byte[] body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mget", index, type);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="type">The type of the document</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MgetPostString(string index, string type, string body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mget", index, type);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-get.html"/></summary>
///<param name="index">The name of the index</param>
///<param name="type">The type of the document</param>
///<param name="body">Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MgetPostStringAsync(string index, string type, string body, Func<MgetParameters, MgetParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mget", index, type);
if (options != null)
{
uri = options.Invoke(new MgetParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Runtime.Serialization;
using System.Xml;
using System.Reflection;
using System.Diagnostics;
using System.Runtime;
namespace System.ServiceModel.Dispatcher
{
class FaultFormatter : IClientFaultFormatter, IDispatchFaultFormatter
{
FaultContractInfo[] faultContractInfos;
internal FaultFormatter(Type[] detailTypes)
{
List<FaultContractInfo> faultContractInfoList = new List<FaultContractInfo>();
for (int i = 0; i < detailTypes.Length; i++)
faultContractInfoList.Add(new FaultContractInfo(MessageHeaders.WildcardAction, detailTypes[i]));
AddInfrastructureFaults(faultContractInfoList);
faultContractInfos = GetSortedArray(faultContractInfoList);
}
internal FaultFormatter(SynchronizedCollection<FaultContractInfo> faultContractInfoCollection)
{
List<FaultContractInfo> faultContractInfoList;
lock (faultContractInfoCollection.SyncRoot)
{
faultContractInfoList = new List<FaultContractInfo>(faultContractInfoCollection);
}
AddInfrastructureFaults(faultContractInfoList);
this.faultContractInfos = GetSortedArray(faultContractInfoList);
}
public MessageFault Serialize(FaultException faultException, out string action)
{
XmlObjectSerializer serializer = null;
Type detailType = null;
string faultExceptionAction = action = faultException.Action;
Type faultExceptionOfT = null;
for (Type faultType = faultException.GetType(); faultType != typeof(FaultException); faultType = faultType.BaseType)
{
if (faultType.IsGenericType && (faultType.GetGenericTypeDefinition() == typeof(FaultException<>)))
{
faultExceptionOfT = faultType;
break;
}
}
if (faultExceptionOfT != null)
{
detailType = faultExceptionOfT.GetGenericArguments()[0];
serializer = GetSerializer(detailType, faultExceptionAction, out action);
}
return CreateMessageFault(serializer, faultException, detailType);
}
public FaultException Deserialize(MessageFault messageFault, string action)
{
if (!messageFault.HasDetail)
return new FaultException(messageFault, action);
return CreateFaultException(messageFault, action);
}
protected virtual XmlObjectSerializer GetSerializer(Type detailType, string faultExceptionAction, out string action)
{
action = faultExceptionAction;
FaultContractInfo faultInfo = null;
for (int i = 0; i < faultContractInfos.Length; i++)
{
if (faultContractInfos[i].Detail == detailType)
{
faultInfo = faultContractInfos[i];
break;
}
}
if (faultInfo != null)
{
if (action == null)
action = faultInfo.Action;
return faultInfo.Serializer;
}
else
return DataContractSerializerDefaults.CreateSerializer(detailType, int.MaxValue /* maxItemsInObjectGraph */ );
}
protected virtual FaultException CreateFaultException(MessageFault messageFault, string action)
{
IList<FaultContractInfo> faultInfos;
if (action != null)
{
faultInfos = new List<FaultContractInfo>();
for (int i = 0; i < faultContractInfos.Length; i++)
{
if (faultContractInfos[i].Action == action || faultContractInfos[i].Action == MessageHeaders.WildcardAction)
{
faultInfos.Add(faultContractInfos[i]);
}
}
}
else
{
faultInfos = faultContractInfos;
}
Type detailType = null;
object detailObj = null;
for (int i = 0; i < faultInfos.Count; i++)
{
FaultContractInfo faultInfo = faultInfos[i];
XmlDictionaryReader detailReader = messageFault.GetReaderAtDetailContents();
XmlObjectSerializer serializer = faultInfo.Serializer;
if (serializer.IsStartObject(detailReader))
{
detailType = faultInfo.Detail;
try
{
detailObj = serializer.ReadObject(detailReader);
FaultException faultException = CreateFaultException(messageFault, action,
detailObj, detailType, detailReader);
if (faultException != null)
return faultException;
}
catch (SerializationException)
{
}
}
}
return new FaultException(messageFault, action);
}
protected FaultException CreateFaultException(MessageFault messageFault, string action,
object detailObj, Type detailType, XmlDictionaryReader detailReader)
{
if (!detailReader.EOF)
{
detailReader.MoveToContent();
if (detailReader.NodeType != XmlNodeType.EndElement && !detailReader.EOF)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.ExtraContentIsPresentInFaultDetail)));
}
bool isDetailObjectValid = true;
if (detailObj == null)
{
isDetailObjectValid = !detailType.IsValueType;
}
else
{
isDetailObjectValid = detailType.IsAssignableFrom(detailObj.GetType());
}
if (isDetailObjectValid)
{
Type knownFaultType = typeof(FaultException<>).MakeGenericType(detailType);
return (FaultException)Activator.CreateInstance(knownFaultType,
detailObj,
messageFault.Reason,
messageFault.Code,
action);
}
return null;
}
static FaultContractInfo[] GetSortedArray(List<FaultContractInfo> faultContractInfoList)
{
FaultContractInfo[] temp = faultContractInfoList.ToArray();
Array.Sort<FaultContractInfo>(temp,
delegate(FaultContractInfo x, FaultContractInfo y)
{ return string.CompareOrdinal(x.Action, y.Action); }
);
return temp;
}
static void AddInfrastructureFaults(List<FaultContractInfo> faultContractInfos)
{
faultContractInfos.Add(new FaultContractInfo(FaultCodeConstants.Actions.NetDispatcher, typeof(ExceptionDetail)));
}
static MessageFault CreateMessageFault(XmlObjectSerializer serializer, FaultException faultException, Type detailType)
{
if (detailType == null)
{
if (faultException.Fault != null)
return faultException.Fault;
return MessageFault.CreateFault(faultException.Code, faultException.Reason);
}
Fx.Assert(serializer != null, "");
Type operationFaultType = typeof(OperationFault<>).MakeGenericType(detailType);
return (MessageFault)Activator.CreateInstance(operationFaultType, serializer, faultException);
}
internal class OperationFault<T> : XmlObjectSerializerFault
{
public OperationFault(XmlObjectSerializer serializer, FaultException<T> faultException) :
base(faultException.Code, faultException.Reason,
faultException.Detail,
serializer,
string.Empty/*actor*/,
string.Empty/*node*/)
{
}
}
}
}
| |
/*
* 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.
*/
// Distributed under the Thrift Software License
//
// See accompanying file LICENSE or visit the Thrift site at:
// http://developers.facebook.com/thrift/
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using Thrift.Collections;
using Thrift.Test; //generated code
using Thrift.Transport;
using Thrift.Protocol;
using Thrift.Server;
using Thrift;
using System.Threading;
using System.Text;
namespace Test
{
public class TestServer
{
public static int _clientID = -1;
public delegate void TestLogDelegate(string msg, params object[] values);
public class TradeServerEventHandler : TServerEventHandler
{
public int callCount = 0;
public void preServe()
{
callCount++;
}
public Object createContext(Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output)
{
callCount++;
return null;
}
public void deleteContext(Object serverContext, Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output)
{
callCount++;
}
public void processContext(Object serverContext, Thrift.Transport.TTransport transport)
{
callCount++;
}
};
public class TestHandler : ThriftTest.Iface, Thrift.TControllingHandler
{
public TServer server { get; set; }
private int handlerID;
private StringBuilder reusableStringBuilder = new StringBuilder();
private TestLogDelegate testLogDelegate;
public TestHandler()
{
handlerID = Interlocked.Increment(ref _clientID);
testLogDelegate += testConsoleLogger;
testLogDelegate.Invoke("New TestHandler instance created");
}
public void testConsoleLogger(string msg, params object[] values)
{
reusableStringBuilder.Clear();
reusableStringBuilder.AppendFormat("handler{0:D3}:",handlerID);
reusableStringBuilder.AppendFormat(msg, values);
reusableStringBuilder.AppendLine();
Console.Write( reusableStringBuilder.ToString() );
}
public void testVoid()
{
testLogDelegate.Invoke("testVoid()");
}
public string testString(string thing)
{
testLogDelegate.Invoke("testString({0})", thing);
return thing;
}
public bool testBool(bool thing)
{
testLogDelegate.Invoke("testBool({0})", thing);
return thing;
}
public sbyte testByte(sbyte thing)
{
testLogDelegate.Invoke("testByte({0})", thing);
return thing;
}
public int testI32(int thing)
{
testLogDelegate.Invoke("testI32({0})", thing);
return thing;
}
public long testI64(long thing)
{
testLogDelegate.Invoke("testI64({0})", thing);
return thing;
}
public double testDouble(double thing)
{
testLogDelegate.Invoke("testDouble({0})", thing);
return thing;
}
public byte[] testBinary(byte[] thing)
{
string hex = BitConverter.ToString(thing).Replace("-", string.Empty);
testLogDelegate.Invoke("testBinary({0:X})", hex);
return thing;
}
public Xtruct testStruct(Xtruct thing)
{
testLogDelegate.Invoke("testStruct({{\"{0}\", {1}, {2}, {3}}})", thing.String_thing, thing.Byte_thing, thing.I32_thing, thing.I64_thing);
return thing;
}
public Xtruct2 testNest(Xtruct2 nest)
{
Xtruct thing = nest.Struct_thing;
testLogDelegate.Invoke("testNest({{{0}, {{\"{1}\", {2}, {3}, {4}, {5}}}}})",
nest.Byte_thing,
thing.String_thing,
thing.Byte_thing,
thing.I32_thing,
thing.I64_thing,
nest.I32_thing);
return nest;
}
public Dictionary<int, int> testMap(Dictionary<int, int> thing)
{
reusableStringBuilder.Clear();
reusableStringBuilder.Append("testMap({{");
bool first = true;
foreach (int key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
reusableStringBuilder.Append(", ");
}
reusableStringBuilder.AppendFormat("{0} => {1}", key, thing[key]);
}
reusableStringBuilder.Append("}})");
testLogDelegate.Invoke(reusableStringBuilder.ToString());
return thing;
}
public Dictionary<string, string> testStringMap(Dictionary<string, string> thing)
{
reusableStringBuilder.Clear();
reusableStringBuilder.Append("testStringMap({{");
bool first = true;
foreach (string key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
reusableStringBuilder.Append(", ");
}
reusableStringBuilder.AppendFormat("{0} => {1}", key, thing[key]);
}
reusableStringBuilder.Append("}})");
testLogDelegate.Invoke(reusableStringBuilder.ToString());
return thing;
}
public THashSet<int> testSet(THashSet<int> thing)
{
reusableStringBuilder.Clear();
reusableStringBuilder.Append("testSet({{");
bool first = true;
foreach (int elem in thing)
{
if (first)
{
first = false;
}
else
{
reusableStringBuilder.Append(", ");
}
reusableStringBuilder.AppendFormat("{0}", elem);
}
reusableStringBuilder.Append("}})");
testLogDelegate.Invoke(reusableStringBuilder.ToString());
return thing;
}
public List<int> testList(List<int> thing)
{
reusableStringBuilder.Clear();
reusableStringBuilder.Append("testList({{");
bool first = true;
foreach (int elem in thing)
{
if (first)
{
first = false;
}
else
{
reusableStringBuilder.Append(", ");
}
reusableStringBuilder.AppendFormat("{0}", elem);
}
reusableStringBuilder.Append("}})");
testLogDelegate.Invoke(reusableStringBuilder.ToString());
return thing;
}
public Numberz testEnum(Numberz thing)
{
testLogDelegate.Invoke("testEnum({0})", thing);
return thing;
}
public long testTypedef(long thing)
{
testLogDelegate.Invoke("testTypedef({0})", thing);
return thing;
}
public Dictionary<int, Dictionary<int, int>> testMapMap(int hello)
{
testLogDelegate.Invoke("testMapMap({0})", hello);
Dictionary<int, Dictionary<int, int>> mapmap =
new Dictionary<int, Dictionary<int, int>>();
Dictionary<int, int> pos = new Dictionary<int, int>();
Dictionary<int, int> neg = new Dictionary<int, int>();
for (int i = 1; i < 5; i++)
{
pos[i] = i;
neg[-i] = -i;
}
mapmap[4] = pos;
mapmap[-4] = neg;
return mapmap;
}
public Dictionary<long, Dictionary<Numberz, Insanity>> testInsanity(Insanity argument)
{
testLogDelegate.Invoke("testInsanity()");
Xtruct hello = new Xtruct();
hello.String_thing = "Hello2";
hello.Byte_thing = 2;
hello.I32_thing = 2;
hello.I64_thing = 2;
Xtruct goodbye = new Xtruct();
goodbye.String_thing = "Goodbye4";
goodbye.Byte_thing = (sbyte)4;
goodbye.I32_thing = 4;
goodbye.I64_thing = (long)4;
Insanity crazy = new Insanity();
crazy.UserMap = new Dictionary<Numberz, long>();
crazy.UserMap[Numberz.EIGHT] = (long)8;
crazy.Xtructs = new List<Xtruct>();
crazy.Xtructs.Add(goodbye);
Insanity looney = new Insanity();
crazy.UserMap[Numberz.FIVE] = (long)5;
crazy.Xtructs.Add(hello);
Dictionary<Numberz, Insanity> first_map = new Dictionary<Numberz, Insanity>();
Dictionary<Numberz, Insanity> second_map = new Dictionary<Numberz, Insanity>(); ;
first_map[Numberz.TWO] = crazy;
first_map[Numberz.THREE] = crazy;
second_map[Numberz.SIX] = looney;
Dictionary<long, Dictionary<Numberz, Insanity>> insane =
new Dictionary<long, Dictionary<Numberz, Insanity>>();
insane[(long)1] = first_map;
insane[(long)2] = second_map;
return insane;
}
public Xtruct testMulti(sbyte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5)
{
testLogDelegate.Invoke("testMulti()");
Xtruct hello = new Xtruct(); ;
hello.String_thing = "Hello2";
hello.Byte_thing = arg0;
hello.I32_thing = arg1;
hello.I64_thing = arg2;
return hello;
}
/**
* Print 'testException(%s)' with arg as '%s'
* @param string arg - a string indication what type of exception to throw
* if arg == "Xception" throw Xception with errorCode = 1001 and message = arg
* elsen if arg == "TException" throw TException
* else do not throw anything
*/
public void testException(string arg)
{
testLogDelegate.Invoke("testException({0})", arg);
if (arg == "Xception")
{
Xception x = new Xception();
x.ErrorCode = 1001;
x.Message = arg;
throw x;
}
if (arg == "TException")
{
throw new Thrift.TException();
}
return;
}
public Xtruct testMultiException(string arg0, string arg1)
{
testLogDelegate.Invoke("testMultiException({0}, {1})", arg0,arg1);
if (arg0 == "Xception")
{
Xception x = new Xception();
x.ErrorCode = 1001;
x.Message = "This is an Xception";
throw x;
}
else if (arg0 == "Xception2")
{
Xception2 x = new Xception2();
x.ErrorCode = 2002;
x.Struct_thing = new Xtruct();
x.Struct_thing.String_thing = "This is an Xception2";
throw x;
}
Xtruct result = new Xtruct();
result.String_thing = arg1;
return result;
}
public void testStop()
{
if (server != null)
{
server.Stop();
}
}
public void testOneway(int arg)
{
testLogDelegate.Invoke("testOneway({0}), sleeping...", arg);
System.Threading.Thread.Sleep(arg * 1000);
testLogDelegate.Invoke("testOneway finished");
}
} // class TestHandler
private enum ServerType
{
TSimpleServer,
TThreadedServer,
TThreadPoolServer,
}
private enum ProcessorFactoryType
{
TSingletonProcessorFactory,
TPrototypeProcessorFactory,
}
public static bool Execute(string[] args)
{
try
{
bool useBufferedSockets = false, useFramed = false, useEncryption = false, compact = false, json = false;
ServerType serverType = ServerType.TSimpleServer;
ProcessorFactoryType processorFactoryType = ProcessorFactoryType.TSingletonProcessorFactory;
int port = 9090;
string pipe = null;
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-pipe") // -pipe name
{
pipe = args[++i];
}
else if (args[i].Contains("--port="))
{
port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
useBufferedSockets = true;
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
useFramed = true;
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
compact = true;
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
json = true;
}
else if (args[i] == "--threaded" || args[i] == "--server-type=threaded")
{
serverType = ServerType.TThreadedServer;
}
else if (args[i] == "--threadpool" || args[i] == "--server-type=threadpool")
{
serverType = ServerType.TThreadPoolServer;
}
else if (args[i] == "--prototype" || args[i] == "--processor=prototype")
{
processorFactoryType = ProcessorFactoryType.TPrototypeProcessorFactory;
}
else if (args[i] == "--ssl")
{
useEncryption = true;
}
}
// Transport
TServerTransport trans;
if (pipe != null)
{
trans = new TNamedPipeServerTransport(pipe);
}
else
{
if (useEncryption)
{
string certPath = "../../../../test/keys/server.p12";
trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath, "thrift"));
}
else
{
trans = new TServerSocket(port, 0, useBufferedSockets);
}
}
TProtocolFactory proto;
if (compact)
proto = new TCompactProtocol.Factory();
else if (json)
proto = new TJSONProtocol.Factory();
else
proto = new TBinaryProtocol.Factory();
TProcessorFactory processorFactory;
if (processorFactoryType == ProcessorFactoryType.TPrototypeProcessorFactory)
{
processorFactory = new TPrototypeProcessorFactory<ThriftTest.Processor, TestHandler>();
}
else
{
// Processor
TestHandler testHandler = new TestHandler();
ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler);
processorFactory = new TSingletonProcessorFactory(testProcessor);
}
TTransportFactory transFactory;
if (useFramed)
transFactory = new TFramedTransport.Factory();
else
transFactory = new TTransportFactory();
TServer serverEngine;
switch (serverType)
{
case ServerType.TThreadPoolServer:
serverEngine = new TThreadPoolServer(processorFactory, trans, transFactory, proto);
break;
case ServerType.TThreadedServer:
serverEngine = new TThreadedServer(processorFactory, trans, transFactory, proto);
break;
default:
serverEngine = new TSimpleServer(processorFactory, trans, transFactory, proto);
break;
}
//Server event handler
TradeServerEventHandler serverEvents = new TradeServerEventHandler();
serverEngine.setEventHandler(serverEvents);
// Run it
string where = (pipe != null ? "on pipe " + pipe : "on port " + port);
Console.WriteLine("Starting the " + serverType.ToString() + " " + where +
(processorFactoryType == ProcessorFactoryType.TPrototypeProcessorFactory ? " with processor prototype factory " : "") +
(useBufferedSockets ? " with buffered socket" : "") +
(useFramed ? " with framed transport" : "") +
(useEncryption ? " with encryption" : "") +
(compact ? " with compact protocol" : "") +
(json ? " with json protocol" : "") +
"...");
serverEngine.Serve();
}
catch (Exception x)
{
Console.Error.Write(x);
return false;
}
Console.WriteLine("done.");
return true;
}
}
}
| |
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;
namespace EZOper.TechTester.OWINOAuthWebSI.Areas.ZApi
{
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;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
namespace System.DirectoryServices.AccountManagement
{
public class PrincipalCollection : ICollection<Principal>, ICollection, IEnumerable<Principal>, IEnumerable
{
//
// ICollection
//
void ICollection.CopyTo(Array array, int index)
{
CheckDisposed();
// Parameter validation
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(SR.PrincipalCollectionNotOneDimensional);
if (index >= array.GetLength(0))
throw new ArgumentException(SR.PrincipalCollectionIndexNotInArray);
ArrayList tempArray = new ArrayList();
lock (_resultSet)
{
ResultSetBookmark bookmark = null;
try
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "CopyTo: bookmarking");
bookmark = _resultSet.BookmarkAndReset();
PrincipalCollectionEnumerator containmentEnumerator =
new PrincipalCollectionEnumerator(
_resultSet,
this,
_removedValuesCompleted,
_removedValuesPending,
_insertedValuesCompleted,
_insertedValuesPending);
int arraySize = array.GetLength(0) - index;
int tempArraySize = 0;
while (containmentEnumerator.MoveNext())
{
tempArray.Add(containmentEnumerator.Current);
checked { tempArraySize++; }
// Make sure the array has enough space, allowing for the "index" offset.
// We check inline, rather than doing a PrincipalCollection.Count upfront,
// because counting is just as expensive as enumerating over all the results, so we
// only want to do it once.
if (arraySize < tempArraySize)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn,
"PrincipalCollection",
"CopyTo: array too small (has {0}, need >= {1}",
arraySize,
tempArraySize);
throw new ArgumentException(SR.PrincipalCollectionArrayTooSmall);
}
}
}
finally
{
if (bookmark != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "CopyTo: restoring from bookmark");
_resultSet.RestoreBookmark(bookmark);
}
}
}
foreach (object o in tempArray)
{
array.SetValue(o, index);
checked { index++; }
}
}
int ICollection.Count
{
get
{
return Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return IsSynchronized;
}
}
object ICollection.SyncRoot
{
get
{
return SyncRoot;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public object SyncRoot
{
get
{
return this;
}
}
//
// IEnumerable
//
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
//
// ICollection<Principal>
//
public void CopyTo(Principal[] array, int index)
{
((ICollection)this).CopyTo((Array)array, index);
}
public bool IsReadOnly
{
get
{
return false;
}
}
public int Count
{
get
{
CheckDisposed();
// Yes, this is potentially quite expensive. Count is unfortunately
// an expensive operation to perform.
lock (_resultSet)
{
ResultSetBookmark bookmark = null;
try
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Count: bookmarking");
bookmark = _resultSet.BookmarkAndReset();
PrincipalCollectionEnumerator containmentEnumerator =
new PrincipalCollectionEnumerator(
_resultSet,
this,
_removedValuesCompleted,
_removedValuesPending,
_insertedValuesCompleted,
_insertedValuesPending);
int count = 0;
// Count all the members (including inserted members, but not including removed members)
while (containmentEnumerator.MoveNext())
{
count++;
}
return count;
}
finally
{
if (bookmark != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Count: restoring from bookmark");
_resultSet.Reset();
_resultSet.RestoreBookmark(bookmark);
}
}
}
}
}
//
// IEnumerable<Principal>
//
public IEnumerator<Principal> GetEnumerator()
{
CheckDisposed();
return new PrincipalCollectionEnumerator(
_resultSet,
this,
_removedValuesCompleted,
_removedValuesPending,
_insertedValuesCompleted,
_insertedValuesPending);
}
//
// Add
//
public void Add(UserPrincipal user)
{
Add((Principal)user);
}
public void Add(GroupPrincipal group)
{
Add((Principal)group);
}
public void Add(ComputerPrincipal computer)
{
Add((Principal)computer);
}
public void Add(Principal principal)
{
CheckDisposed();
if (principal == null)
throw new ArgumentNullException(nameof(principal));
if (Contains(principal))
throw new PrincipalExistsException(SR.PrincipalExistsExceptionText);
MarkChange();
// If the value to be added is an uncommitted remove, just remove the uncommitted remove from the list.
if (_removedValuesPending.Contains(principal))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Add: removing from removedValuesPending");
_removedValuesPending.Remove(principal);
// If they did a Add(x) --> Save() --> Remove(x) --> Add(x), we'll end up with x in neither
// the ResultSet or the insertedValuesCompleted list. This is bad. Avoid that by adding x
// back to the insertedValuesCompleted list here.
//
// Note, this will add x to insertedValuesCompleted even if it's already in the resultSet.
// This is not a problem --- PrincipalCollectionEnumerator will detect such a situation and
// only return x once.
if (!_insertedValuesCompleted.Contains(principal))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Add: adding to insertedValuesCompleted");
_insertedValuesCompleted.Add(principal);
}
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Add: making it a pending insert");
// make it a pending insert
_insertedValuesPending.Add(principal);
// in case the value to be added is also a previous-but-already-committed remove
_removedValuesCompleted.Remove(principal);
}
}
public void Add(PrincipalContext context, IdentityType identityType, string identityValue)
{
CheckDisposed();
if (context == null)
throw new ArgumentNullException(nameof(context));
if (identityValue == null)
throw new ArgumentNullException(nameof(identityValue));
Principal principal = Principal.FindByIdentity(context, identityType, identityValue);
if (principal != null)
{
Add(principal);
}
else
{
// No Principal matching the IdentityReference could be found in the PrincipalContext
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalCollection", "Add(urn/urn): no match");
throw new NoMatchingPrincipalException(SR.NoMatchingPrincipalExceptionText);
}
}
//
// Clear
//
public void Clear()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Clear");
CheckDisposed();
// Ask the StoreCtx to verify that this group can be cleared. Right now, the only
// reason it couldn't is if it's an AD group with one principals that are members of it
// by virtue of their primaryGroupId.
//
// If storeCtxToUse == null, then we must be unpersisted, in which case there clearly
// can't be any such primary group members pointing to this group on the store.
StoreCtx storeCtxToUse = _owningGroup.GetStoreCtxToUse();
string explanation;
Debug.Assert(storeCtxToUse != null || _owningGroup.unpersisted == true);
if ((storeCtxToUse != null) && (!storeCtxToUse.CanGroupBeCleared(_owningGroup, out explanation)))
throw new InvalidOperationException(explanation);
MarkChange();
// We wipe out everything that's been inserted/removed
_insertedValuesPending.Clear();
_removedValuesPending.Clear();
_insertedValuesCompleted.Clear();
_removedValuesCompleted.Clear();
// flag that the collection has been cleared, so the StoreCtx and PrincipalCollectionEnumerator
// can take appropriate action
_clearPending = true;
}
//
// Remove
//
public bool Remove(UserPrincipal user)
{
return Remove((Principal)user);
}
public bool Remove(GroupPrincipal group)
{
return Remove((Principal)group);
}
public bool Remove(ComputerPrincipal computer)
{
return Remove((Principal)computer);
}
public bool Remove(Principal principal)
{
CheckDisposed();
if (principal == null)
throw new ArgumentNullException(nameof(principal));
// Ask the StoreCtx to verify that this member can be removed. Right now, the only
// reason it couldn't is if it's actually a member by virtue of its primaryGroupId
// pointing to this group.
//
// If storeCtxToUse == null, then we must be unpersisted, in which case there clearly
// can't be any such primary group members pointing to this group on the store.
StoreCtx storeCtxToUse = _owningGroup.GetStoreCtxToUse();
string explanation;
Debug.Assert(storeCtxToUse != null || _owningGroup.unpersisted == true);
if ((storeCtxToUse != null) && (!storeCtxToUse.CanGroupMemberBeRemoved(_owningGroup, principal, out explanation)))
throw new InvalidOperationException(explanation);
bool removed = false;
// If the value was previously inserted, we just remove it from insertedValuesPending.
if (_insertedValuesPending.Contains(principal))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Remove: removing from insertedValuesPending");
MarkChange();
_insertedValuesPending.Remove(principal);
removed = true;
// If they did a Remove(x) --> Save() --> Add(x) --> Remove(x), we'll end up with x in neither
// the ResultSet or the removedValuesCompleted list. This is bad. Avoid that by adding x
// back to the removedValuesCompleted list here.
//
// At worst, we end up with x on the removedValuesCompleted list even though it's not even in
// resultSet. That's not a problem. The only thing we use the removedValuesCompleted list for
// is deciding which values in resultSet to skip, anyway.
if (!_removedValuesCompleted.Contains(principal))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Remove: adding to removedValuesCompleted");
_removedValuesCompleted.Add(principal);
}
}
else
{
// They're trying to remove an already-persisted value. We add it to the
// removedValues list. Then, if it's already been loaded into insertedValuesCompleted,
// we remove it from insertedValuesCompleted.
removed = Contains(principal);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Remove: making it a pending remove, removed={0}", removed);
if (removed)
{
MarkChange();
_removedValuesPending.Add(principal);
// in case it's the result of a previous-but-already-committed insert
_insertedValuesCompleted.Remove(principal);
}
}
return removed;
}
public bool Remove(PrincipalContext context, IdentityType identityType, string identityValue)
{
CheckDisposed();
if (context == null)
throw new ArgumentNullException(nameof(context));
if (identityValue == null)
throw new ArgumentNullException(nameof(identityValue));
Principal principal = Principal.FindByIdentity(context, identityType, identityValue);
if (principal == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalCollection", "Remove(urn/urn): no match");
throw new NoMatchingPrincipalException(SR.NoMatchingPrincipalExceptionText);
}
return Remove(principal);
}
//
// Contains
//
private bool ContainsEnumTest(Principal principal)
{
CheckDisposed();
if (principal == null)
throw new ArgumentNullException(nameof(principal));
// Yes, this is potentially quite expensive. Contains is unfortunately
// an expensive operation to perform.
lock (_resultSet)
{
ResultSetBookmark bookmark = null;
try
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsEnumTest: bookmarking");
bookmark = _resultSet.BookmarkAndReset();
PrincipalCollectionEnumerator containmentEnumerator =
new PrincipalCollectionEnumerator(
_resultSet,
this,
_removedValuesCompleted,
_removedValuesPending,
_insertedValuesCompleted,
_insertedValuesPending);
while (containmentEnumerator.MoveNext())
{
Principal p = containmentEnumerator.Current;
if (p.Equals(principal))
return true;
}
}
finally
{
if (bookmark != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsEnumTest: restoring from bookmark");
_resultSet.RestoreBookmark(bookmark);
}
}
}
return false;
}
private bool ContainsNativeTest(Principal principal)
{
CheckDisposed();
if (principal == null)
throw new ArgumentNullException(nameof(principal));
// If they explicitly inserted it, then we certainly contain it
if (_insertedValuesCompleted.Contains(principal) || _insertedValuesPending.Contains(principal))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsNativeTest: found insert");
return true;
}
// If they removed it, we don't contain it, regardless of the group membership on the store
if (_removedValuesCompleted.Contains(principal) || _removedValuesPending.Contains(principal))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsNativeTest: found remove");
return false;
}
// The list was cleared at some point and the principal has not been reinsterted yet
if (_clearPending || _clearCompleted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsNativeTest: Clear pending");
return false;
}
// Otherwise, check the store
if (_owningGroup.unpersisted == false && principal.unpersisted == false)
return _owningGroup.GetStoreCtxToUse().IsMemberOfInStore(_owningGroup, principal);
// We (or the principal) must not be persisted, so there's no store membership to check.
// Out of things to check. We must not contain it.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsNativeTest: no store to check");
return false;
}
public bool Contains(UserPrincipal user)
{
return Contains((Principal)user);
}
public bool Contains(GroupPrincipal group)
{
return Contains((Principal)group);
}
public bool Contains(ComputerPrincipal computer)
{
return Contains((Principal)computer);
}
public bool Contains(Principal principal)
{
StoreCtx storeCtxToUse = _owningGroup.GetStoreCtxToUse();
// If the store has a shortcut for testing membership, use it.
// Otherwise we enumerate all members and look for a match.
if ((storeCtxToUse != null) && (storeCtxToUse.SupportsNativeMembershipTest))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"PrincipalCollection",
"Contains: using native test (store ctx is null = {0})",
(storeCtxToUse == null));
return ContainsNativeTest(principal);
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Contains: using enum test");
return ContainsEnumTest(principal);
}
}
public bool Contains(PrincipalContext context, IdentityType identityType, string identityValue)
{
CheckDisposed();
if (context == null)
throw new ArgumentNullException(nameof(context));
if (identityValue == null)
throw new ArgumentNullException(nameof(identityValue));
bool found = false;
Principal principal = Principal.FindByIdentity(context, identityType, identityValue);
if (principal != null)
found = Contains(principal);
return found;
}
//
// Internal constructor
//
// Constructs a fresh PrincipalCollection based on the supplied ResultSet.
// The ResultSet may not be null (use an EmptySet instead).
internal PrincipalCollection(BookmarkableResultSet results, GroupPrincipal owningGroup)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Ctor");
Debug.Assert(results != null);
_resultSet = results;
_owningGroup = owningGroup;
}
//
// Internal "disposer"
//
// Ideally, we'd like to implement IDisposable, since we need to dispose of the ResultSet.
// But IDisposable would have to be a public interface, and we don't want the apps calling Dispose()
// on us, only the Principal that owns us. So we implement an "internal" form of Dispose().
internal void Dispose()
{
if (!_disposed)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Dispose: disposing");
lock (_resultSet)
{
if (_resultSet != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Dispose: disposing resultSet");
_resultSet.Dispose();
}
}
_disposed = true;
}
}
//
// Private implementation
//
// The group we're a PrincipalCollection of
private GroupPrincipal _owningGroup;
//
// SYNCHRONIZATION
// Access to:
// resultSet
// must be synchronized, since multiple enumerators could be iterating over us at once.
// Synchronize by locking on resultSet.
// Represents the Principals retrieved from the store for this collection
private BookmarkableResultSet _resultSet;
// Contains Principals inserted into this collection for which the insertion has not been persisted to the store
private List<Principal> _insertedValuesCompleted = new List<Principal>();
private List<Principal> _insertedValuesPending = new List<Principal>();
// Contains Principals removed from this collection for which the removal has not been persisted
// to the store
private List<Principal> _removedValuesCompleted = new List<Principal>();
private List<Principal> _removedValuesPending = new List<Principal>();
// Has this collection been cleared?
private bool _clearPending = false;
private bool _clearCompleted = false;
internal bool ClearCompleted
{
get { return _clearCompleted; }
}
// Used so our enumerator can detect changes to the collection and throw an exception
private DateTime _lastChange = DateTime.UtcNow;
internal DateTime LastChange
{
get { return _lastChange; }
}
internal void MarkChange()
{
_lastChange = DateTime.UtcNow;
}
// To support disposal
private bool _disposed = false;
private void CheckDisposed()
{
if (_disposed)
throw new ObjectDisposedException("PrincipalCollection");
}
//
// Load/Store Implementation
//
internal List<Principal> Inserted
{
get
{
return _insertedValuesPending;
}
}
internal List<Principal> Removed
{
get
{
return _removedValuesPending;
}
}
internal bool Cleared
{
get
{
return _clearPending;
}
}
// Return true if the membership has changed (i.e., either insertedValuesPending or removedValuesPending is
// non-empty)
internal bool Changed
{
get
{
return ((_insertedValuesPending.Count > 0) || (_removedValuesPending.Count > 0) || (_clearPending));
}
}
// Resets the change-tracking of the membership to 'unchanged', by moving all pending operations to completed status.
internal void ResetTracking()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ResetTracking");
foreach (Principal p in _removedValuesPending)
{
Debug.Assert(!_removedValuesCompleted.Contains(p));
_removedValuesCompleted.Add(p);
}
_removedValuesPending.Clear();
foreach (Principal p in _insertedValuesPending)
{
Debug.Assert(!_insertedValuesCompleted.Contains(p));
_insertedValuesCompleted.Add(p);
}
_insertedValuesPending.Clear();
if (_clearPending)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ResetTracking: clearing");
_clearCompleted = true;
_clearPending = false;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Rayman {
public abstract class UITweener : MonoBehaviour {
/// <summary>
/// Current tween that triggered the callback function.
/// </summary>
static public UITweener current;
public enum Method {
Linear,
EaseIn,
EaseOut,
EaseInOut,
BounceIn,
BounceOut,
}
public enum Style {
Once,
Loop,
PingPong,
}
/// <summary>
/// Tweening method used.
/// </summary>
[HideInInspector]
public Method method = Method.Linear;
public Style style = Style.Once;
/// <summary>
/// Optional curve to apply to the tween's time factor value.
/// </summary>
[HideInInspector]
public AnimationCurve animationCurve = new AnimationCurve(new Keyframe(0f, 0f, 0f, 1f), new Keyframe(1f, 1f, 1f, 0f));
/// <summary>
/// How long will the tweener wait before starting the tween?
/// </summary>
public float delay = 0f;
/// <summary>
/// How long is the duration of the tween?
/// </summary>
public float duration = 1f;
/// <summary>
/// Whether the tweener will use steeper curves for ease in / out style interpolation.
/// </summary>
[HideInInspector]
public bool steeperCurves = false;
/// <summary>
/// Used by buttons and tween sequences. Group of '0' means not in a sequence.
/// </summary>
[HideInInspector]
public int tweenGroup = 0;
// Deprecated functionality, kept for backwards compatibility
[HideInInspector]
public GameObject eventReceiver;
[HideInInspector]
public string callWhenFinished;
bool mStarted = false;
float mStartTime = 0f;
float mDuration = 0f;
float mAmountPerDelta = 1000f;
float mFactor = 0f;
/// <summary>
/// Amount advanced per delta time.
/// </summary>
public float amountPerDelta {
get {
if (mDuration != duration) {
mDuration = duration;
mAmountPerDelta = Mathf.Abs((duration > 0f) ? 1f / duration : 1000f) * Mathf.Sign(mAmountPerDelta);
}
return mAmountPerDelta;
}
}
/// <summary>
/// Tween factor, 0-1 range.
/// </summary>
public float tweenFactor { get { return mFactor; } set { mFactor = Mathf.Clamp01(value); } }
/// <summary>
/// This function is called by Unity when you add a component. Automatically set the starting values for convenience.
/// </summary>
void Reset() {
if (!mStarted) {
SetStartToCurrentValue();
SetEndToCurrentValue();
}
}
/// <summary>
/// Update as soon as it's started so that there is no delay.
/// </summary>
protected virtual void Start() { Update(); }
/// <summary>
/// Update the tweening factor and call the virtual update function.
/// </summary>
void Update() {
float delta = Time.deltaTime;
float time = Time.time;
if (!mStarted) {
mStarted = true;
mStartTime = time + delay;
}
if (time < mStartTime) return;
// Advance the sampling factor
mFactor += amountPerDelta * delta;
// Loop style simply resets the play factor after it exceeds 1.
if (style == Style.Loop) {
if (mFactor > 1f) {
mFactor -= Mathf.Floor(mFactor);
}
} else if (style == Style.PingPong) {
// Ping-pong style reverses the direction
if (mFactor > 1f) {
mFactor = 1f - (mFactor - Mathf.Floor(mFactor));
mAmountPerDelta = -mAmountPerDelta;
} else if (mFactor < 0f) {
mFactor = -mFactor;
mFactor -= Mathf.Floor(mFactor);
mAmountPerDelta = -mAmountPerDelta;
}
}
// If the factor goes out of range and this is a one-time tweening operation, disable the script
if ((style == Style.Once) && (duration == 0f || mFactor > 1f || mFactor < 0f)) {
mFactor = Mathf.Clamp01(mFactor);
Sample(mFactor, true);
enabled = false;
if (current == null) {
UITweener before = current;
current = this;
// Deprecated legacy functionality support
if (eventReceiver != null && !string.IsNullOrEmpty(callWhenFinished))
eventReceiver.SendMessage(callWhenFinished, this, SendMessageOptions.DontRequireReceiver);
current = before;
}
} else Sample(mFactor, false);
}
void OnDisable() { mStarted = false; }
/// <summary>
/// Sample the tween at the specified factor.
/// </summary>
public void Sample(float factor, bool isFinished) {
// Calculate the sampling value
float val = Mathf.Clamp01(factor);
if (method == Method.EaseIn) {
val = 1f - Mathf.Sin(0.5f * Mathf.PI * (1f - val));
if (steeperCurves) val *= val;
} else if (method == Method.EaseOut) {
val = Mathf.Sin(0.5f * Mathf.PI * val);
if (steeperCurves) {
val = 1f - val;
val = 1f - val * val;
}
} else if (method == Method.EaseInOut) {
const float pi2 = Mathf.PI * 2f;
val = val - Mathf.Sin(val * pi2) / pi2;
if (steeperCurves) {
val = val * 2f - 1f;
float sign = Mathf.Sign(val);
val = 1f - Mathf.Abs(val);
val = 1f - val * val;
val = sign * val * 0.5f + 0.5f;
}
} else if (method == Method.BounceIn) {
val = BounceLogic(val);
} else if (method == Method.BounceOut) {
val = 1f - BounceLogic(1f - val);
}
// Call the virtual update
OnUpdate((animationCurve != null) ? animationCurve.Evaluate(val) : val, isFinished);
}
/// <summary>
/// Main Bounce logic to simplify the Sample function
/// </summary>
float BounceLogic(float val) {
if (val < 0.363636f) // 0.363636 = (1/ 2.75)
{
val = 7.5685f * val * val;
} else if (val < 0.727272f) // 0.727272 = (2 / 2.75)
{
val = 7.5625f * (val -= 0.545454f) * val + 0.75f; // 0.545454f = (1.5 / 2.75)
} else if (val < 0.909090f) // 0.909090 = (2.5 / 2.75)
{
val = 7.5625f * (val -= 0.818181f) * val + 0.9375f; // 0.818181 = (2.25 / 2.75)
} else {
val = 7.5625f * (val -= 0.9545454f) * val + 0.984375f; // 0.9545454 = (2.625 / 2.75)
}
return val;
}
/// <summary>
/// Play the tween.
/// </summary>
[System.Obsolete("Use PlayForward() instead")]
public void Play() { Play(true); }
/// <summary>
/// Play the tween forward.
/// </summary>
public void PlayForward() { Play(true); }
/// <summary>
/// Play the tween in reverse.
/// </summary>
public void PlayReverse() { Play(false); }
/// <summary>
/// Manually activate the tweening process, reversing it if necessary.
/// </summary>
public void Play(bool forward) {
mAmountPerDelta = Mathf.Abs(amountPerDelta);
if (!forward) mAmountPerDelta = -mAmountPerDelta;
enabled = true;
Update();
}
/// <summary>
/// Manually reset the tweener's state to the beginning.
/// If the tween is playing forward, this means the tween's start.
/// If the tween is playing in reverse, this means the tween's end.
/// </summary>
public void ResetToBeginning() {
mStarted = false;
mFactor = (amountPerDelta < 0f) ? 1f : 0f;
Sample(mFactor, false);
}
/// <summary>
/// Manually start the tweening process, reversing its direction.
/// </summary>
public void Toggle() {
if (mFactor > 0f) {
mAmountPerDelta = -amountPerDelta;
} else {
mAmountPerDelta = Mathf.Abs(amountPerDelta);
}
enabled = true;
}
/// <summary>
/// Actual tweening logic should go here.
/// </summary>
abstract protected void OnUpdate(float factor, bool isFinished);
/// <summary>
/// Starts the tweening operation.
/// </summary>
static public T Begin<T>(GameObject go, float duration) where T : UITweener {
T comp = go.GetComponent<T>();
// Find the tween with an unset group ID (group ID of 0).
if (comp != null && comp.tweenGroup != 0) {
comp = null;
T[] comps = go.GetComponents<T>();
for (int i = 0, imax = comps.Length; i < imax; ++i) {
comp = comps[i];
if (comp != null && comp.tweenGroup == 0) break;
comp = null;
}
}
if (comp == null) {
comp = go.AddComponent<T>();
if (comp == null) {
//Debug.LogError("Unable to add " + typeof(T) + " to " + NGUITools.GetHierarchy(go), go);
return null;
}
}
comp.mStarted = false;
comp.duration = duration;
comp.mFactor = 0f;
comp.mAmountPerDelta = Mathf.Abs(comp.amountPerDelta);
comp.style = Style.Once;
comp.animationCurve = new AnimationCurve(new Keyframe(0f, 0f, 0f, 1f), new Keyframe(1f, 1f, 1f, 0f));
comp.eventReceiver = null;
comp.callWhenFinished = null;
comp.enabled = true;
return comp;
}
/// <summary>
/// Set the 'from' value to the current one.
/// </summary>
public virtual void SetStartToCurrentValue() { }
/// <summary>
/// Set the 'to' value to the current one.
/// </summary>
public virtual void SetEndToCurrentValue() { }
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
#if !(NET20 || NET35 || PORTABLE)
using System.Numerics;
#endif
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Tests.TestObjects.Organization;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Linq;
using System.IO;
using System.Collections;
#if !(DNXCORE50)
using System.Web.UI;
#endif
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class JObjectTests : TestFixtureBase
{
#if !(NET35 || NET20 || PORTABLE40) || NETSTANDARD2_0
[Test]
public void EmbedJValueStringInNewJObject()
{
string s = null;
var v = new JValue(s);
dynamic o = JObject.FromObject(new { title = v });
string output = o.ToString();
StringAssert.AreEqual(@"{
""title"": null
}", output);
Assert.AreEqual(null, v.Value);
Assert.IsNull((string)o.title);
}
#endif
[Test]
public void ReadWithSupportMultipleContent()
{
string json = @"{ 'name': 'Admin' }{ 'name': 'Publisher' }";
IList<JObject> roles = new List<JObject>();
JsonTextReader reader = new JsonTextReader(new StringReader(json));
reader.SupportMultipleContent = true;
while (true)
{
JObject role = (JObject)JToken.ReadFrom(reader);
roles.Add(role);
if (!reader.Read())
{
break;
}
}
Assert.AreEqual(2, roles.Count);
Assert.AreEqual("Admin", (string)roles[0]["name"]);
Assert.AreEqual("Publisher", (string)roles[1]["name"]);
}
[Test]
public void JObjectWithComments()
{
string json = @"{ /*comment2*/
""Name"": /*comment3*/ ""Apple"" /*comment4*/, /*comment5*/
""ExpiryDate"": ""\/Date(1230422400000)\/"",
""Price"": 3.99,
""Sizes"": /*comment6*/ [ /*comment7*/
""Small"", /*comment8*/
""Medium"" /*comment9*/,
/*comment10*/ ""Large""
/*comment11*/ ] /*comment12*/
} /*comment13*/";
JToken o = JToken.Parse(json);
Assert.AreEqual("Apple", (string)o["Name"]);
}
[Test]
public void WritePropertyWithNoValue()
{
var o = new JObject();
o.Add(new JProperty("novalue"));
StringAssert.AreEqual(@"{
""novalue"": null
}", o.ToString());
}
[Test]
public void Keys()
{
var o = new JObject();
var d = (IDictionary<string, JToken>)o;
Assert.AreEqual(0, d.Keys.Count);
o["value"] = true;
Assert.AreEqual(1, d.Keys.Count);
}
[Test]
public void TryGetValue()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
JToken t;
Assert.AreEqual(false, o.TryGetValue("sdf", out t));
Assert.AreEqual(null, t);
Assert.AreEqual(false, o.TryGetValue(null, out t));
Assert.AreEqual(null, t);
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
}
[Test]
public void DictionaryItemShouldSet()
{
JObject o = new JObject();
o["PropertyNameValue"] = new JValue(1);
Assert.AreEqual(1, o.Children().Count());
JToken t;
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
o["PropertyNameValue"] = new JValue(2);
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t));
o["PropertyNameValue"] = null;
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(JValue.CreateNull(), t));
}
[Test]
public void Remove()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(false, o.Remove("sdf"));
Assert.AreEqual(false, o.Remove(null));
Assert.AreEqual(true, o.Remove("PropertyNameValue"));
Assert.AreEqual(0, o.Children().Count());
}
[Test]
public void GenericCollectionRemove()
{
JValue v = new JValue(1);
JObject o = new JObject();
o.Add("PropertyNameValue", v);
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))));
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))));
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))));
Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v)));
Assert.AreEqual(0, o.Children().Count());
}
[Test]
public void DuplicatePropertyNameShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o.Add("PropertyNameValue", null);
o.Add("PropertyNameValue", null);
}, "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
public void GenericDictionaryAdd()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, (int)o["PropertyNameValue"]);
o.Add("PropertyNameValue1", null);
Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value);
Assert.AreEqual(2, o.Children().Count());
}
[Test]
public void GenericCollectionAdd()
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).Add(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)));
Assert.AreEqual(1, (int)o["PropertyNameValue"]);
Assert.AreEqual(1, o.Children().Count());
}
[Test]
public void GenericCollectionClear()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
JProperty p = (JProperty)o.Children().ElementAt(0);
((ICollection<KeyValuePair<string, JToken>>)o).Clear();
Assert.AreEqual(0, o.Children().Count());
Assert.AreEqual(null, p.Parent);
}
[Test]
public void GenericCollectionContains()
{
JValue v = new JValue(1);
JObject o = new JObject();
o.Add("PropertyNameValue", v);
Assert.AreEqual(1, o.Children().Count());
bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v));
Assert.AreEqual(true, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>));
Assert.AreEqual(false, contains);
}
[Test]
public void Contains()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
bool contains = o.ContainsKey("PropertyNameValue");
Assert.AreEqual(true, contains);
contains = o.ContainsKey("does not exist");
Assert.AreEqual(false, contains);
ExceptionAssert.Throws<ArgumentNullException>(() =>
{
contains = o.ContainsKey(null);
Assert.AreEqual(false, contains);
}, @"Value cannot be null.
Parameter name: propertyName");
}
[Test]
public void GenericDictionaryContains()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue");
Assert.AreEqual(true, contains);
}
[Test]
public void GenericCollectionCopyTo()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
o.Add("PropertyNameValue3", new JValue(3));
Assert.AreEqual(3, o.Children().Count());
KeyValuePair<string, JToken>[] a = new KeyValuePair<string, JToken>[5];
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1);
Assert.AreEqual(default(KeyValuePair<string, JToken>), a[0]);
Assert.AreEqual("PropertyNameValue", a[1].Key);
Assert.AreEqual(1, (int)a[1].Value);
Assert.AreEqual("PropertyNameValue2", a[2].Key);
Assert.AreEqual(2, (int)a[2].Value);
Assert.AreEqual("PropertyNameValue3", a[3].Key);
Assert.AreEqual(3, (int)a[3].Value);
Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]);
}
[Test]
public void GenericCollectionCopyToNullArrayShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0);
}, @"Value cannot be null.
Parameter name: array");
}
[Test]
public void GenericCollectionCopyToNegativeArrayIndexShouldThrow()
{
ExceptionAssert.Throws<ArgumentOutOfRangeException>(() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1);
}, @"arrayIndex is less than 0.
Parameter name: arrayIndex");
}
[Test]
public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1);
}, @"arrayIndex is equal to or greater than the length of array.");
}
[Test]
public void GenericCollectionCopyToInsufficientArrayCapacity()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
o.Add("PropertyNameValue3", new JValue(3));
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1);
}, @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.");
}
[Test]
public void FromObjectRaw()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
Assert.AreEqual("FirstNameValue", (string)o["first_name"]);
Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type);
Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]);
Assert.AreEqual("LastNameValue", (string)o["last_name"]);
}
[Test]
public void JTokenReader()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
JsonReader reader = new JTokenReader(o);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Raw, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
Assert.IsFalse(reader.Read());
}
[Test]
public void DeserializeFromRaw()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
JsonReader reader = new JTokenReader(o);
JsonSerializer serializer = new JsonSerializer();
raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw));
Assert.AreEqual("FirstNameValue", raw.FirstName);
Assert.AreEqual("LastNameValue", raw.LastName);
Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value);
}
[Test]
public void Parse_ShouldThrowOnUnexpectedToken()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string json = @"[""prop""]";
JObject.Parse(json);
}, "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.");
}
[Test]
public void ParseJavaScriptDate()
{
string json = @"[new Date(1207285200000)]";
JArray a = (JArray)JsonConvert.DeserializeObject(json);
JValue v = (JValue)a[0];
Assert.AreEqual(DateTimeUtils.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v);
}
[Test]
public void GenericValueCast()
{
string json = @"{""foo"":true}";
JObject o = (JObject)JsonConvert.DeserializeObject(json);
bool? value = o.Value<bool?>("foo");
Assert.AreEqual(true, value);
json = @"{""foo"":null}";
o = (JObject)JsonConvert.DeserializeObject(json);
value = o.Value<bool?>("foo");
Assert.AreEqual(null, value);
}
[Test]
public void Blog()
{
ExceptionAssert.Throws<JsonReaderException>(() => { JObject.Parse(@"{
""name"": ""James"",
]!#$THIS IS: BAD JSON![{}}}}]
}"); }, "Invalid property identifier character: ]. Path 'name', line 3, position 4.");
}
[Test]
public void RawChildValues()
{
JObject o = new JObject();
o["val1"] = new JRaw("1");
o["val2"] = new JRaw("1");
string json = o.ToString();
StringAssert.AreEqual(@"{
""val1"": 1,
""val2"": 1
}", json);
}
[Test]
public void Iterate()
{
JObject o = new JObject();
o.Add("PropertyNameValue1", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
JToken t = o;
int i = 1;
foreach (JProperty property in t)
{
Assert.AreEqual("PropertyNameValue" + i, property.Name);
Assert.AreEqual(i, (int)property.Value);
i++;
}
}
[Test]
public void KeyValuePairIterate()
{
JObject o = new JObject();
o.Add("PropertyNameValue1", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
int i = 1;
foreach (KeyValuePair<string, JToken> pair in o)
{
Assert.AreEqual("PropertyNameValue" + i, pair.Key);
Assert.AreEqual(i, (int)pair.Value);
i++;
}
}
[Test]
public void WriteObjectNullStringValue()
{
string s = null;
JValue v = new JValue(s);
Assert.AreEqual(null, v.Value);
Assert.AreEqual(JTokenType.String, v.Type);
JObject o = new JObject();
o["title"] = v;
string output = o.ToString();
StringAssert.AreEqual(@"{
""title"": null
}", output);
}
[Test]
public void Example()
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Small
Assert.AreEqual("Apple", name);
Assert.AreEqual("Small", smallest);
}
[Test]
public void DeserializeClassManually()
{
string jsonText = @"{
""short"":
{
""original"":""http://www.foo.com/"",
""short"":""krehqk"",
""error"":
{
""code"":0,
""msg"":""No action taken""
}
}
}";
JObject json = JObject.Parse(jsonText);
Shortie shortie = new Shortie
{
Original = (string)json["short"]["original"],
Short = (string)json["short"]["short"],
Error = new ShortieException
{
Code = (int)json["short"]["error"]["code"],
ErrorMessage = (string)json["short"]["error"]["msg"]
}
};
Assert.AreEqual("http://www.foo.com/", shortie.Original);
Assert.AreEqual("krehqk", shortie.Short);
Assert.AreEqual(null, shortie.Shortened);
Assert.AreEqual(0, shortie.Error.Code);
Assert.AreEqual("No action taken", shortie.Error.ErrorMessage);
}
[Test]
public void JObjectContainingHtml()
{
JObject o = new JObject();
o["rc"] = new JValue(200);
o["m"] = new JValue("");
o["o"] = new JValue(@"<div class='s1'>" + StringUtils.CarriageReturnLineFeed + @"</div>");
StringAssert.AreEqual(@"{
""rc"": 200,
""m"": """",
""o"": ""<div class='s1'>\r\n</div>""
}", o.ToString());
}
[Test]
public void ImplicitValueConversions()
{
JObject moss = new JObject();
moss["FirstName"] = new JValue("Maurice");
moss["LastName"] = new JValue("Moss");
moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30));
moss["Department"] = new JValue("IT");
moss["JobTitle"] = new JValue("Support");
StringAssert.AreEqual(@"{
""FirstName"": ""Maurice"",
""LastName"": ""Moss"",
""BirthDate"": ""1977-12-30T00:00:00"",
""Department"": ""IT"",
""JobTitle"": ""Support""
}", moss.ToString());
JObject jen = new JObject();
jen["FirstName"] = "Jen";
jen["LastName"] = "Barber";
jen["BirthDate"] = new DateTime(1978, 3, 15);
jen["Department"] = "IT";
jen["JobTitle"] = "Manager";
StringAssert.AreEqual(@"{
""FirstName"": ""Jen"",
""LastName"": ""Barber"",
""BirthDate"": ""1978-03-15T00:00:00"",
""Department"": ""IT"",
""JobTitle"": ""Manager""
}", jen.ToString());
}
[Test]
public void ReplaceJPropertyWithJPropertyWithSameName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
IList l = o;
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p2, l[1]);
JProperty p3 = new JProperty("Test1", "III");
p1.Replace(p3);
Assert.AreEqual(null, p1.Parent);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
Assert.AreEqual(2, l.Count);
Assert.AreEqual(2, o.Properties().Count());
JProperty p4 = new JProperty("Test4", "IV");
p2.Replace(p4);
Assert.AreEqual(null, p2.Parent);
Assert.AreEqual(l, p4.Parent);
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p4, l[1]);
}
#if !(NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
[Test]
public void PropertyChanging()
{
object changing = null;
object changed = null;
int changingCount = 0;
int changedCount = 0;
JObject o = new JObject();
o.PropertyChanging += (sender, args) =>
{
JObject s = (JObject)sender;
changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changingCount++;
};
o.PropertyChanged += (sender, args) =>
{
JObject s = (JObject)sender;
changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changedCount++;
};
o["StringValue"] = "value1";
Assert.AreEqual(null, changing);
Assert.AreEqual("value1", changed);
Assert.AreEqual("value1", (string)o["StringValue"]);
Assert.AreEqual(1, changingCount);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value1";
Assert.AreEqual(1, changingCount);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value2";
Assert.AreEqual("value1", changing);
Assert.AreEqual("value2", changed);
Assert.AreEqual("value2", (string)o["StringValue"]);
Assert.AreEqual(2, changingCount);
Assert.AreEqual(2, changedCount);
o["StringValue"] = null;
Assert.AreEqual("value2", changing);
Assert.AreEqual(null, changed);
Assert.AreEqual(null, (string)o["StringValue"]);
Assert.AreEqual(3, changingCount);
Assert.AreEqual(3, changedCount);
o["NullValue"] = null;
Assert.AreEqual(null, changing);
Assert.AreEqual(null, changed);
Assert.AreEqual(JValue.CreateNull(), o["NullValue"]);
Assert.AreEqual(4, changingCount);
Assert.AreEqual(4, changedCount);
o["NullValue"] = null;
Assert.AreEqual(4, changingCount);
Assert.AreEqual(4, changedCount);
}
#endif
[Test]
public void PropertyChanged()
{
object changed = null;
int changedCount = 0;
JObject o = new JObject();
o.PropertyChanged += (sender, args) =>
{
JObject s = (JObject)sender;
changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changedCount++;
};
o["StringValue"] = "value1";
Assert.AreEqual("value1", changed);
Assert.AreEqual("value1", (string)o["StringValue"]);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value1";
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value2";
Assert.AreEqual("value2", changed);
Assert.AreEqual("value2", (string)o["StringValue"]);
Assert.AreEqual(2, changedCount);
o["StringValue"] = null;
Assert.AreEqual(null, changed);
Assert.AreEqual(null, (string)o["StringValue"]);
Assert.AreEqual(3, changedCount);
o["NullValue"] = null;
Assert.AreEqual(null, changed);
Assert.AreEqual(JValue.CreateNull(), o["NullValue"]);
Assert.AreEqual(4, changedCount);
o["NullValue"] = null;
Assert.AreEqual(4, changedCount);
}
[Test]
public void IListContains()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.IsTrue(l.Contains(p));
Assert.IsFalse(l.Contains(new JProperty("Test", 1)));
}
[Test]
public void IListIndexOf()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.AreEqual(0, l.IndexOf(p));
Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1)));
}
[Test]
public void IListClear()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.AreEqual(1, l.Count);
l.Clear();
Assert.AreEqual(0, l.Count);
}
[Test]
public void IListCopyTo()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
object[] a = new object[l.Count];
l.CopyTo(a, 0);
Assert.AreEqual(p1, a[0]);
Assert.AreEqual(p2, a[1]);
}
[Test]
public void IListAdd()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Add(p3);
Assert.AreEqual(3, l.Count);
Assert.AreEqual(p3, l[2]);
}
[Test]
public void IListAddBadToken()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l.Add(new JValue("Bad!"));
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void IListAddBadValue()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l.Add("Bad!");
}, "Argument is not a JToken.");
}
[Test]
public void IListAddPropertyWithExistingName()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test2", "II");
l.Add(p3);
}, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
public void IListRemove()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
// won't do anything
l.Remove(p3);
Assert.AreEqual(2, l.Count);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
Assert.IsFalse(l.Contains(p1));
Assert.IsTrue(l.Contains(p2));
l.Remove(p2);
Assert.AreEqual(0, l.Count);
Assert.IsFalse(l.Contains(p2));
Assert.AreEqual(null, p2.Parent);
}
[Test]
public void IListRemoveAt()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
// won't do anything
l.RemoveAt(0);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
l.Remove(p2);
Assert.AreEqual(0, l.Count);
}
[Test]
public void IListInsert()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Insert(1, p3);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p3, l[1]);
Assert.AreEqual(p2, l[2]);
}
[Test]
public void IListIsReadOnly()
{
IList l = new JObject();
Assert.IsFalse(l.IsReadOnly);
}
[Test]
public void IListIsFixedSize()
{
IList l = new JObject();
Assert.IsFalse(l.IsFixedSize);
}
[Test]
public void IListSetItem()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
}
[Test]
public void IListSetItemAlreadyExists()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
l[1] = p3;
}, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
public void IListSetItemInvalid()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l[0] = new JValue(true);
}, @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void IListSyncRoot()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
Assert.IsNotNull(l.SyncRoot);
}
[Test]
public void IListIsSynchronized()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
Assert.IsFalse(l.IsSynchronized);
}
[Test]
public void GenericListJTokenContains()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.IsTrue(l.Contains(p));
Assert.IsFalse(l.Contains(new JProperty("Test", 1)));
}
[Test]
public void GenericListJTokenIndexOf()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.AreEqual(0, l.IndexOf(p));
Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1)));
}
[Test]
public void GenericListJTokenClear()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.AreEqual(1, l.Count);
l.Clear();
Assert.AreEqual(0, l.Count);
}
[Test]
public void GenericListJTokenCopyTo()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JToken[] a = new JToken[l.Count];
l.CopyTo(a, 0);
Assert.AreEqual(p1, a[0]);
Assert.AreEqual(p2, a[1]);
}
[Test]
public void GenericListJTokenAdd()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Add(p3);
Assert.AreEqual(3, l.Count);
Assert.AreEqual(p3, l[2]);
}
[Test]
public void GenericListJTokenAddBadToken()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
l.Add(new JValue("Bad!"));
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void GenericListJTokenAddBadValue()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
// string is implicitly converted to JValue
l.Add("Bad!");
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void GenericListJTokenAddPropertyWithExistingName()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test2", "II");
l.Add(p3);
}, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
public void GenericListJTokenRemove()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
// won't do anything
Assert.IsFalse(l.Remove(p3));
Assert.AreEqual(2, l.Count);
Assert.IsTrue(l.Remove(p1));
Assert.AreEqual(1, l.Count);
Assert.IsFalse(l.Contains(p1));
Assert.IsTrue(l.Contains(p2));
Assert.IsTrue(l.Remove(p2));
Assert.AreEqual(0, l.Count);
Assert.IsFalse(l.Contains(p2));
Assert.AreEqual(null, p2.Parent);
}
[Test]
public void GenericListJTokenRemoveAt()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
// won't do anything
l.RemoveAt(0);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
l.Remove(p2);
Assert.AreEqual(0, l.Count);
}
[Test]
public void GenericListJTokenInsert()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Insert(1, p3);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p3, l[1]);
Assert.AreEqual(p2, l[2]);
}
[Test]
public void GenericListJTokenIsReadOnly()
{
IList<JToken> l = new JObject();
Assert.IsFalse(l.IsReadOnly);
}
[Test]
public void GenericListJTokenSetItem()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
}
[Test]
public void GenericListJTokenSetItemAlreadyExists()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
l[1] = p3;
}, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0
[Test]
public void IBindingListSortDirection()
{
IBindingList l = new JObject();
Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection);
}
[Test]
public void IBindingListSortProperty()
{
IBindingList l = new JObject();
Assert.AreEqual(null, l.SortProperty);
}
[Test]
public void IBindingListSupportsChangeNotification()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.SupportsChangeNotification);
}
[Test]
public void IBindingListSupportsSearching()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.SupportsSearching);
}
[Test]
public void IBindingListSupportsSorting()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.SupportsSorting);
}
[Test]
public void IBindingListAllowEdit()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowEdit);
}
[Test]
public void IBindingListAllowNew()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowNew);
}
[Test]
public void IBindingListAllowRemove()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowRemove);
}
[Test]
public void IBindingListAddIndex()
{
IBindingList l = new JObject();
// do nothing
l.AddIndex(null);
}
[Test]
public void IBindingListApplySort()
{
ExceptionAssert.Throws<NotSupportedException>(() =>
{
IBindingList l = new JObject();
l.ApplySort(null, ListSortDirection.Ascending);
}, "Specified method is not supported.");
}
[Test]
public void IBindingListRemoveSort()
{
ExceptionAssert.Throws<NotSupportedException>(() =>
{
IBindingList l = new JObject();
l.RemoveSort();
}, "Specified method is not supported.");
}
[Test]
public void IBindingListRemoveIndex()
{
IBindingList l = new JObject();
// do nothing
l.RemoveIndex(null);
}
[Test]
public void IBindingListFind()
{
ExceptionAssert.Throws<NotSupportedException>(() =>
{
IBindingList l = new JObject();
l.Find(null, null);
}, "Specified method is not supported.");
}
[Test]
public void IBindingListIsSorted()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.IsSorted);
}
[Test]
public void IBindingListAddNew()
{
ExceptionAssert.Throws<JsonException>(() =>
{
IBindingList l = new JObject();
l.AddNew();
}, "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.");
}
[Test]
public void IBindingListAddNewWithEvent()
{
JObject o = new JObject();
o._addingNew += (s, e) => e.NewObject = new JProperty("Property!");
IBindingList l = o;
object newObject = l.AddNew();
Assert.IsNotNull(newObject);
JProperty p = (JProperty)newObject;
Assert.AreEqual("Property!", p.Name);
Assert.AreEqual(o, p.Parent);
}
[Test]
public void ITypedListGetListName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
ITypedList l = new JObject(p1, p2);
Assert.AreEqual(string.Empty, l.GetListName(null));
}
[Test]
public void ITypedListGetItemProperties()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
ITypedList l = new JObject(p1, p2);
PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null);
Assert.IsNull(propertyDescriptors);
}
[Test]
public void ListChanged()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
ListChangedType? changedType = null;
int? index = null;
o.ListChanged += (s, a) =>
{
changedType = a.ListChangedType;
index = a.NewIndex;
};
JProperty p3 = new JProperty("Test3", "III");
o.Add(p3);
Assert.AreEqual(changedType, ListChangedType.ItemAdded);
Assert.AreEqual(index, 2);
Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]);
JProperty p4 = new JProperty("Test4", "IV");
((IList<JToken>)o)[index.Value] = p4;
Assert.AreEqual(changedType, ListChangedType.ItemChanged);
Assert.AreEqual(index, 2);
Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]);
Assert.IsFalse(((IList<JToken>)o).Contains(p3));
Assert.IsTrue(((IList<JToken>)o).Contains(p4));
o["Test1"] = 2;
Assert.AreEqual(changedType, ListChangedType.ItemChanged);
Assert.AreEqual(index, 0);
Assert.AreEqual(2, (int)o["Test1"]);
}
#endif
#if !(NET20 || NET35 || PORTABLE40) || NETSTANDARD2_0
[Test]
public void CollectionChanged()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
NotifyCollectionChangedAction? changedType = null;
int? index = null;
o._collectionChanged += (s, a) =>
{
changedType = a.Action;
index = a.NewStartingIndex;
};
JProperty p3 = new JProperty("Test3", "III");
o.Add(p3);
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add);
Assert.AreEqual(index, 2);
Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]);
JProperty p4 = new JProperty("Test4", "IV");
((IList<JToken>)o)[index.Value] = p4;
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace);
Assert.AreEqual(index, 2);
Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]);
Assert.IsFalse(((IList<JToken>)o).Contains(p3));
Assert.IsTrue(((IList<JToken>)o).Contains(p4));
o["Test1"] = 2;
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace);
Assert.AreEqual(index, 0);
Assert.AreEqual(2, (int)o["Test1"]);
}
#endif
[Test]
public void GetGeocodeAddress()
{
string json = @"{
""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"",
""Status"": {
""code"": 200,
""request"": ""geocode""
},
""Placemark"": [ {
""id"": ""p1"",
""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"",
""AddressDetails"": {
""Accuracy"" : 8,
""Country"" : {
""AdministrativeArea"" : {
""AdministrativeAreaName"" : ""IL"",
""SubAdministrativeArea"" : {
""Locality"" : {
""LocalityName"" : ""Rockford"",
""PostalCode"" : {
""PostalCodeNumber"" : ""61107""
},
""Thoroughfare"" : {
""ThoroughfareName"" : ""435 N Mulford Rd""
}
},
""SubAdministrativeAreaName"" : ""Winnebago""
}
},
""CountryName"" : ""USA"",
""CountryNameCode"" : ""US""
}
},
""ExtendedData"": {
""LatLonBox"": {
""north"": 42.2753076,
""south"": 42.2690124,
""east"": -88.9964645,
""west"": -89.0027597
}
},
""Point"": {
""coordinates"": [ -88.9995886, 42.2721596, 0 ]
}
} ]
}";
JObject o = JObject.Parse(json);
string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"];
Assert.AreEqual("435 N Mulford Rd", searchAddress);
}
[Test]
public void SetValueWithInvalidPropertyName()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o[0] = new JValue(3);
}, "Set JObject values with invalid key value: 0. Object property name expected.");
}
[Test]
public void SetValue()
{
object key = "TestKey";
JObject o = new JObject();
o[key] = new JValue(3);
Assert.AreEqual(3, (int)o[key]);
}
[Test]
public void ParseMultipleProperties()
{
string json = @"{
""Name"": ""Name1"",
""Name"": ""Name2""
}";
JObject o = JObject.Parse(json);
string value = (string)o["Name"];
Assert.AreEqual("Name2", value);
}
[Test]
public void ParseMultipleProperties_EmptySettings()
{
string json = @"{
""Name"": ""Name1"",
""Name"": ""Name2""
}";
JObject o = JObject.Parse(json, new JsonLoadSettings());
string value = (string)o["Name"];
Assert.AreEqual("Name2", value);
}
[Test]
public void ParseMultipleProperties_IgnoreDuplicateSetting()
{
string json = @"{
""Name"": ""Name1"",
""Name"": ""Name2""
}";
JObject o = JObject.Parse(json, new JsonLoadSettings
{
DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Ignore
});
string value = (string)o["Name"];
Assert.AreEqual("Name1", value);
}
[Test]
public void ParseMultipleProperties_ReplaceDuplicateSetting()
{
string json = @"{
""Name"": ""Name1"",
""Name"": ""Name2""
}";
JObject o = JObject.Parse(json, new JsonLoadSettings
{
DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Replace
});
string value = (string)o["Name"];
Assert.AreEqual("Name2", value);
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0
[Test]
public void WriteObjectNullDBNullValue()
{
DBNull dbNull = DBNull.Value;
JValue v = new JValue(dbNull);
Assert.AreEqual(DBNull.Value, v.Value);
Assert.AreEqual(JTokenType.Null, v.Type);
JObject o = new JObject();
o["title"] = v;
string output = o.ToString();
StringAssert.AreEqual(@"{
""title"": null
}", output);
}
#endif
[Test]
public void InvalidValueCastExceptionMessage()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
string json = @"{
""responseData"": {},
""responseDetails"": null,
""responseStatus"": 200
}";
JObject o = JObject.Parse(json);
string name = (string)o["responseData"];
}, "Can not convert Object to String.");
}
[Test]
public void InvalidPropertyValueCastExceptionMessage()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
string json = @"{
""responseData"": {},
""responseDetails"": null,
""responseStatus"": 200
}";
JObject o = JObject.Parse(json);
string name = (string)o.Property("responseData");
}, "Can not convert Object to String.");
}
[Test]
public void ParseIncomplete()
{
ExceptionAssert.Throws<Exception>(() => { JObject.Parse("{ foo:"); }, "Unexpected end of content while loading JObject. Path 'foo', line 1, position 6.");
}
[Test]
public void LoadFromNestedObject()
{
string jsonText = @"{
""short"":
{
""error"":
{
""code"":0,
""msg"":""No action taken""
}
}
}";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
reader.Read();
reader.Read();
reader.Read();
reader.Read();
reader.Read();
JObject o = (JObject)JToken.ReadFrom(reader);
Assert.IsNotNull(o);
StringAssert.AreEqual(@"{
""code"": 0,
""msg"": ""No action taken""
}", o.ToString(Formatting.Indented));
}
[Test]
public void LoadFromNestedObjectIncomplete()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string jsonText = @"{
""short"":
{
""error"":
{
""code"":0";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
reader.Read();
reader.Read();
reader.Read();
reader.Read();
reader.Read();
JToken.ReadFrom(reader);
}, "Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 14.");
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0
[Test]
public void GetProperties()
{
JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}");
ICustomTypeDescriptor descriptor = o;
PropertyDescriptorCollection properties = descriptor.GetProperties();
Assert.AreEqual(4, properties.Count);
PropertyDescriptor prop1 = properties[0];
Assert.AreEqual("prop1", prop1.Name);
Assert.AreEqual(typeof(object), prop1.PropertyType);
Assert.AreEqual(typeof(JObject), prop1.ComponentType);
Assert.AreEqual(false, prop1.CanResetValue(o));
Assert.AreEqual(false, prop1.ShouldSerializeValue(o));
PropertyDescriptor prop2 = properties[1];
Assert.AreEqual("prop2", prop2.Name);
Assert.AreEqual(typeof(object), prop2.PropertyType);
Assert.AreEqual(typeof(JObject), prop2.ComponentType);
Assert.AreEqual(false, prop2.CanResetValue(o));
Assert.AreEqual(false, prop2.ShouldSerializeValue(o));
PropertyDescriptor prop3 = properties[2];
Assert.AreEqual("prop3", prop3.Name);
Assert.AreEqual(typeof(object), prop3.PropertyType);
Assert.AreEqual(typeof(JObject), prop3.ComponentType);
Assert.AreEqual(false, prop3.CanResetValue(o));
Assert.AreEqual(false, prop3.ShouldSerializeValue(o));
PropertyDescriptor prop4 = properties[3];
Assert.AreEqual("prop4", prop4.Name);
Assert.AreEqual(typeof(object), prop4.PropertyType);
Assert.AreEqual(typeof(JObject), prop4.ComponentType);
Assert.AreEqual(false, prop4.CanResetValue(o));
Assert.AreEqual(false, prop4.ShouldSerializeValue(o));
}
#endif
[Test]
public void ParseEmptyObjectWithComment()
{
JObject o = JObject.Parse("{ /* A Comment */ }");
Assert.AreEqual(0, o.Count);
}
[Test]
public void FromObjectTimeSpan()
{
JValue v = (JValue)JToken.FromObject(TimeSpan.FromDays(1));
Assert.AreEqual(v.Value, TimeSpan.FromDays(1));
Assert.AreEqual("1.00:00:00", v.ToString());
}
[Test]
public void FromObjectUri()
{
JValue v = (JValue)JToken.FromObject(new Uri("http://www.stuff.co.nz"));
Assert.AreEqual(v.Value, new Uri("http://www.stuff.co.nz"));
Assert.AreEqual("http://www.stuff.co.nz/", v.ToString());
}
[Test]
public void FromObjectGuid()
{
JValue v = (JValue)JToken.FromObject(new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35"));
Assert.AreEqual(v.Value, new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35"));
Assert.AreEqual("9065acf3-c820-467d-be50-8d4664beaf35", v.ToString());
}
[Test]
public void ParseAdditionalContent()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}, 987987";
JObject o = JObject.Parse(json);
}, "Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 1.");
}
[Test]
public void DeepEqualsIgnoreOrder()
{
JObject o1 = new JObject(
new JProperty("null", null),
new JProperty("integer", 1),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("array", new JArray(1, 2)));
Assert.IsTrue(o1.DeepEquals(o1));
JObject o2 = new JObject(
new JProperty("null", null),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("integer", 1),
new JProperty("array", new JArray(1, 2)));
Assert.IsTrue(o1.DeepEquals(o2));
JObject o3 = new JObject(
new JProperty("null", null),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("integer", 2),
new JProperty("array", new JArray(1, 2)));
Assert.IsFalse(o1.DeepEquals(o3));
JObject o4 = new JObject(
new JProperty("null", null),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("integer", 1),
new JProperty("array", new JArray(2, 1)));
Assert.IsFalse(o1.DeepEquals(o4));
JObject o5 = new JObject(
new JProperty("null", null),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("integer", 1));
Assert.IsFalse(o1.DeepEquals(o5));
Assert.IsFalse(o1.DeepEquals(null));
}
[Test]
public void ToListOnEmptyObject()
{
JObject o = JObject.Parse(@"{}");
IList<JToken> l1 = o.ToList<JToken>();
Assert.AreEqual(0, l1.Count);
IList<KeyValuePair<string, JToken>> l2 = o.ToList<KeyValuePair<string, JToken>>();
Assert.AreEqual(0, l2.Count);
o = JObject.Parse(@"{'hi':null}");
l1 = o.ToList<JToken>();
Assert.AreEqual(1, l1.Count);
l2 = o.ToList<KeyValuePair<string, JToken>>();
Assert.AreEqual(1, l2.Count);
}
[Test]
public void EmptyObjectDeepEquals()
{
Assert.IsTrue(JToken.DeepEquals(new JObject(), new JObject()));
JObject a = new JObject();
JObject b = new JObject();
b.Add("hi", "bye");
b.Remove("hi");
Assert.IsTrue(JToken.DeepEquals(a, b));
Assert.IsTrue(JToken.DeepEquals(b, a));
}
[Test]
public void GetValueBlogExample()
{
JObject o = JObject.Parse(@"{
'name': 'Lower',
'NAME': 'Upper'
}");
string exactMatch = (string)o.GetValue("NAME", StringComparison.OrdinalIgnoreCase);
// Upper
string ignoreCase = (string)o.GetValue("Name", StringComparison.OrdinalIgnoreCase);
// Lower
Assert.AreEqual("Upper", exactMatch);
Assert.AreEqual("Lower", ignoreCase);
}
[Test]
public void GetValue()
{
JObject a = new JObject();
a["Name"] = "Name!";
a["name"] = "name!";
a["title"] = "Title!";
Assert.AreEqual(null, a.GetValue("NAME", StringComparison.Ordinal));
Assert.AreEqual(null, a.GetValue("NAME"));
Assert.AreEqual(null, a.GetValue("TITLE"));
Assert.AreEqual("Name!", (string)a.GetValue("NAME", StringComparison.OrdinalIgnoreCase));
Assert.AreEqual("name!", (string)a.GetValue("name", StringComparison.Ordinal));
Assert.AreEqual(null, a.GetValue(null, StringComparison.Ordinal));
Assert.AreEqual(null, a.GetValue(null));
JToken v;
Assert.IsFalse(a.TryGetValue("NAME", StringComparison.Ordinal, out v));
Assert.AreEqual(null, v);
Assert.IsFalse(a.TryGetValue("NAME", out v));
Assert.IsFalse(a.TryGetValue("TITLE", out v));
Assert.IsTrue(a.TryGetValue("NAME", StringComparison.OrdinalIgnoreCase, out v));
Assert.AreEqual("Name!", (string)v);
Assert.IsTrue(a.TryGetValue("name", StringComparison.Ordinal, out v));
Assert.AreEqual("name!", (string)v);
Assert.IsFalse(a.TryGetValue(null, StringComparison.Ordinal, out v));
}
public class FooJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var token = JToken.FromObject(value, new JsonSerializer
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
if (token.Type == JTokenType.Object)
{
var o = (JObject)token;
o.AddFirst(new JProperty("foo", "bar"));
o.WriteTo(writer);
}
else
{
token.WriteTo(writer);
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotSupportedException("This custom converter only supportes serialization and not deserialization.");
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return true;
}
}
[Test]
public void FromObjectInsideConverterWithCustomSerializer()
{
var p = new Person
{
Name = "Daniel Wertheim",
};
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new FooJsonConverter() },
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var json = JsonConvert.SerializeObject(p, settings);
Assert.AreEqual(@"{""foo"":""bar"",""name"":""Daniel Wertheim"",""birthDate"":""0001-01-01T00:00:00"",""lastModified"":""0001-01-01T00:00:00""}", json);
}
[Test]
public void Parse_NoComments()
{
string json = "{'prop':[1,2/*comment*/,3]}";
JObject o = JObject.Parse(json, new JsonLoadSettings
{
CommentHandling = CommentHandling.Ignore
});
Assert.AreEqual(3, o["prop"].Count());
Assert.AreEqual(1, (int)o["prop"][0]);
Assert.AreEqual(2, (int)o["prop"][1]);
Assert.AreEqual(3, (int)o["prop"][2]);
}
[Test]
public void Parse_ExcessiveContentJustComments()
{
string json = @"{'prop':[1,2,3]}/*comment*/
//Another comment.";
JObject o = JObject.Parse(json);
Assert.AreEqual(3, o["prop"].Count());
Assert.AreEqual(1, (int)o["prop"][0]);
Assert.AreEqual(2, (int)o["prop"][1]);
Assert.AreEqual(3, (int)o["prop"][2]);
}
[Test]
public void Parse_ExcessiveContent()
{
string json = @"{'prop':[1,2,3]}/*comment*/
//Another comment.
[]";
ExceptionAssert.Throws<JsonReaderException>(() => JObject.Parse(json),
"Additional text encountered after finished reading JSON content: [. Path '', line 3, position 0.");
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0
[Test]
public void GetPropertyOwner_ReturnsJObject()
{
ICustomTypeDescriptor o = new JObject
{
["prop1"] = 1
};
PropertyDescriptorCollection properties = o.GetProperties();
Assert.AreEqual(1, properties.Count);
PropertyDescriptor pd = properties[0];
Assert.AreEqual("prop1", pd.Name);
object owner = o.GetPropertyOwner(pd);
Assert.AreEqual(o, owner);
object value = pd.GetValue(owner);
Assert.AreEqual(1, (int)(JToken)value);
}
#endif
[Test]
public void Property()
{
JObject a = new JObject();
a["Name"] = "Name!";
a["name"] = "name!";
a["title"] = "Title!";
Assert.AreEqual(null, a.Property("NAME", StringComparison.Ordinal));
Assert.AreEqual(null, a.Property("NAME"));
Assert.AreEqual(null, a.Property("TITLE"));
Assert.AreEqual(null, a.Property(null, StringComparison.Ordinal));
Assert.AreEqual(null, a.Property(null, StringComparison.OrdinalIgnoreCase));
Assert.AreEqual(null, a.Property(null));
// Return first match when ignoring case
Assert.AreEqual("Name", a.Property("NAME", StringComparison.OrdinalIgnoreCase).Name);
// Return exact match before ignoring case
Assert.AreEqual("name", a.Property("name", StringComparison.OrdinalIgnoreCase).Name);
// Return exact match without ignoring case
Assert.AreEqual("name", a.Property("name", StringComparison.Ordinal).Name);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands;
using Discord;
using Discord.WebSocket;
using NinjaBotCore.Database;
using NinjaBotCore.Services;
using Microsoft.Extensions.Logging;
namespace NinjaBotCore.Modules.Away
{
public class AwayCommands : ModuleBase
{
private static bool _isLinked = false;
private static ChannelCheck _cc = null;
private static DiscordShardedClient _client;
private readonly ILogger _logger;
//Work on way to do this when bot starts
public AwayCommands(DiscordShardedClient client, ILogger<AwayCommands> logger)
{
_logger = logger;
if (!_isLinked)
{
client.MessageReceived += AwayMentionFinder;
_logger.LogInformation($"Hooked into message received for away commands.");
}
_isLinked = true;
if (_cc == null)
{
_cc = new ChannelCheck();
}
if (_client == null)
{
_client = client;
}
}
[Command("away", RunMode = RunMode.Async)]
[Alias("afk")]
[Summary("Set yourself as away, replying to anyone that @mentions you")]
public async Task SetAway([Remainder] string input)
{
try
{
StringBuilder sb = new StringBuilder();
var message = input;
var user = Context.User;
string userName = string.Empty;
string userMentionName = string.Empty;
if (user != null)
{
userName = user.Username;
userMentionName = user.Mention;
}
var data = new AwayData();
var away = new AwaySystem();
var attempt = data.getAwayUser(userName);
if (string.IsNullOrEmpty(message.ToString()))
{
message = "No message set!";
}
if (attempt != null)
{
away.UserName = attempt.UserName;
away.Status = attempt.Status;
if ((bool)away.Status)
{
sb.AppendLine($"You're already away, **{userMentionName}**!");
}
else
{
sb.AppendLine($"Marking you as away, **{userMentionName}**, with the message: *{message.ToString()}*");
away.Status = true;
away.Message = message;
away.UserName = userName;
away.TimeAway = DateTime.Now;
var awayData = new AwayData();
awayData.setAwayUser(away);
}
}
else
{
sb.AppendLine($"Marking you as away, **{userMentionName}**, with the message: *{message.ToString()}*");
away.Status = true;
away.Message = message;
away.UserName = userName;
away.TimeAway = DateTime.Now;
var awayData = new AwayData();
awayData.setAwayUser(away);
}
await _cc.Reply(Context, sb.ToString());
}
catch (Exception ex)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Something went wrong setting you away :(");
_logger.LogError($"Away command error {ex.Message}");
await _cc.Reply(Context, sb.ToString());
}
}
[Command("back", RunMode = RunMode.Async)]
[Summary("Set yourself as back from being away")]
public async Task SetBack(bool forced = false, IGuildUser forceUser = null)
{
try
{
IGuildUser user = null;
StringBuilder sb = new StringBuilder();
var data = new AwayData();
if (forced)
{
user = forceUser;
}
else
{
user = Context.User as IGuildUser;
}
string userName = string.Empty;
string userMentionName = string.Empty;
if (user != null)
{
userName = user.Username;
userMentionName = user.Mention;
}
var attempt = data.getAwayUser(userName);
var away = new AwaySystem();
if (attempt != null)
{
away.UserName = attempt.UserName;
away.Status = attempt.Status;
if (!(bool)away.Status)
{
sb.AppendLine($"You're not even away yet, **{userMentionName}**");
}
else
{
away.Status = false;
away.Message = string.Empty;
var awayData = new AwayData();
awayData.setAwayUser(away);
string awayDuration = string.Empty;
if (attempt.TimeAway.HasValue)
{
var awayTime = DateTime.Now - attempt.TimeAway;
if (awayTime.HasValue)
{
awayDuration = $"**{awayTime.Value.Days}** days, **{awayTime.Value.Hours}** hours, **{awayTime.Value.Minutes}** minutes, and **{awayTime.Value.Seconds}** seconds";
}
}
if (forced)
{
sb.AppendLine($"You're now set as back **{userMentionName}** (forced by: **{Context.User.Username}**)!");
}
else
{
sb.AppendLine($"You're now set as back, **{userMentionName}**!");
}
sb.AppendLine($"You were away for: [{awayDuration}]");
}
await _cc.Reply(Context, sb.ToString());
}
}
catch (Exception ex)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Something went wrong marking you as back :(");
_logger.LogError($"Back command error {ex.Message}");
await _cc.Reply(Context, sb.ToString());
}
}
[Command("set-back", RunMode = RunMode.Async)]
[RequireUserPermission(GuildPermission.KickMembers)]
public async Task SetBack(IGuildUser user)
{
await SetBack(forced: true, forceUser: user);
}
private async Task AwayMentionFinder(SocketMessage messageDetails)
{
await Task.Run(async () =>
{
var message = messageDetails as SocketUserMessage;
if (!messageDetails.Author.IsBot)
{
var userMentioned = messageDetails.MentionedUsers.ToList();
if (userMentioned != null)
{
foreach (var user in userMentioned)
{
var awayData = new AwayData();
var awayUser = awayData.getAwayUser(user.Username);
if (awayUser != null)
{
string awayDuration = string.Empty;
if (awayUser.TimeAway.HasValue)
{
var awayTime = DateTime.Now - awayUser.TimeAway;
if (awayTime.HasValue)
{
awayDuration = $"**{awayTime.Value.Days}** days, **{awayTime.Value.Hours}** hours, **{awayTime.Value.Minutes}** minutes, and **{awayTime.Value.Seconds}** seconds";
}
}
_logger.LogInformation($"Mentioned user {user.Username} -> {awayUser.UserName} -> {awayUser.Status}");
if ((bool)awayUser.Status)
{
if (user.Username == (awayUser.UserName))
{
SocketGuild guild = (message.Channel as SocketGuildChannel)?.Guild;
EmbedBuilder embed = new EmbedBuilder();
embed.WithColor(new Color(0, 71, 171));
if (!string.IsNullOrWhiteSpace(guild.IconUrl))
{
embed.ThumbnailUrl = user.GetAvatarUrl();
}
embed.Title = $":clock: {awayUser.UserName} is away! :clock:";
embed.Description = $"Since: **{awayUser.TimeAway}\n**Duration: {awayDuration}\nMessage: {awayUser.Message}";
await messageDetails.Channel.SendMessageAsync("", false, embed.Build());
}
}
}
}
}
}
});
}
}
}
| |
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Drawing;
using ProjNet.CoordinateSystems.Transformations;
using NetTopologySuite.Geometries;
using SharpMap.Base;
using SharpMap.Styles;
using NetTopologySuite;
namespace SharpMap.Layers
{
/// <summary>
/// Abstract class for common layer properties
/// Implement this class instead of the ILayer interface to save a lot of common code.
/// </summary>
[Serializable]
public abstract partial class Layer : DisposableObject, ILayer
{
#region Events
#region Delegates
/// <summary>
/// EventHandler for event fired when the layer has been rendered
/// </summary>
/// <param name="layer">Layer rendered</param>
/// <param name="g">Reference to graphics object used for rendering</param>
public delegate void LayerRenderedEventHandler(Layer layer, Graphics g);
#endregion
/// <summary>
/// Event fired when the layer has been rendered
/// </summary>
public event LayerRenderedEventHandler LayerRendered;
/// <summary>
/// Event raised when the layer's <see cref="SRID"/> property has changed
/// </summary>
public event EventHandler SRIDChanged;
/// <summary>
/// Method called when <see cref="SRID"/> has changed, to invoke <see cref="E:SharpMap.Layers.Layer.SRIDChanged"/>
/// </summary>
/// <param name="eventArgs">The arguments associated with the event</param>
protected virtual void OnSridChanged(EventArgs eventArgs)
{
_sourceFactory = NtsGeometryServices.Instance.CreateGeometryFactory(SRID);
if (!_shouldNotResetCt)
_coordinateTransform = _reverseCoordinateTransform = null;
var handler = SRIDChanged;
if (handler!= null) handler(this, eventArgs);
}
/// <summary>
/// Event raised when the layer's <see cref="Style"/> property has changed
/// </summary>
public event EventHandler StyleChanged;
/// <summary>
/// Method called when <see cref="Style"/> has changed, to invoke <see cref="E:SharpMap.Layers.Layer.StyleChanged"/>
/// </summary>
/// <param name="eventArgs">The arguments associated with the event</param>
protected virtual void OnStyleChanged(EventArgs eventArgs)
{
var handler = StyleChanged;
if (handler != null) handler(this, eventArgs);
}
/// <summary>
/// Event raised when the layers's <see cref="LayerName"/> property has changed
/// </summary>
public event EventHandler LayerNameChanged;
/// <summary>
/// Method called when <see cref="LayerName"/> has changed, to invoke <see cref="E:SharpMap.Layers.Layer.LayerNameChanged"/>
/// </summary>
/// <param name="eventArgs">The arguments associated with the event</param>
protected virtual void OnLayerNameChanged(EventArgs eventArgs)
{
var handler = LayerNameChanged;
if (handler != null) handler(this, eventArgs);
}
#endregion
private ICoordinateTransformation _coordinateTransform;
private ICoordinateTransformation _reverseCoordinateTransform;
private GeometryFactory _sourceFactory;
private GeometryFactory _targetFactory;
private string _layerName;
private string _layerTitle;
private IStyle _style;
private int _srid = -1;
private int? _targetSrid;
[field:NonSerialized]
private bool _shouldNotResetCt;
// ReSharper disable PublicConstructorInAbstractClass
///<summary>
/// Creates an instance of this class using the given Style
///</summary>
///<param name="style"></param>
public Layer(Style style)
// ReSharper restore PublicConstructorInAbstractClass
{
_style = style;
}
/// <summary>
/// Creates an instance of this class
/// </summary>
protected Layer() //Style style)
{
_style = new Style();
}
/// <summary>
/// Releases managed resources
/// </summary>
protected override void ReleaseManagedResources()
{
_coordinateTransform = null;
_reverseCoordinateTransform = null;
_style = null;
base.ReleaseManagedResources();
}
/// <summary>
/// Gets or sets the <see cref="NetTopologySuite.CoordinateSystems.Transformations.CoordinateTransformation"/> applied
/// to this vectorlayer prior to rendering
/// </summary>
public virtual ICoordinateTransformation CoordinateTransformation
{
get
{
if (_coordinateTransform == null && NeedsTransformation)
{
var css = Session.Instance.CoordinateSystemServices;
_coordinateTransform = css.CreateTransformation(
css.GetCoordinateSystem(SRID), css.GetCoordinateSystem(TargetSRID));
}
return _coordinateTransform;
}
set
{
if (value == _coordinateTransform)
return;
_coordinateTransform = value;
OnCoordinateTransformationChanged(EventArgs.Empty);
}
}
/// <summary>
/// Event raised when the <see cref="CoordinateTransformation"/> has changed
/// </summary>
public event EventHandler CoordinateTransformationChanged;
/// <summary>
/// Event invoker for the <see cref="CoordinateTransformationChanged"/> event
/// </summary>
/// <param name="e">The event's arguments</param>
protected virtual void OnCoordinateTransformationChanged(EventArgs e)
{
_sourceFactory = _targetFactory = NtsGeometryServices.Instance
.CreateGeometryFactory(SRID);
if (CoordinateTransformation != null)
{
// we don't want that by setting SRID we get the CoordinateTransformation resetted
_shouldNotResetCt = true;
try
{
SRID = Convert.ToInt32(CoordinateTransformation.SourceCS.AuthorityCode);
TargetSRID = Convert.ToInt32(CoordinateTransformation.TargetCS.AuthorityCode);
}
finally
{
_shouldNotResetCt = false;
}
}
if (CoordinateTransformationChanged != null)
CoordinateTransformationChanged(this, e);
}
/// <summary>
/// Gets the geometry factory to create source geometries
/// </summary>
protected internal GeometryFactory SourceFactory { get { return _sourceFactory ?? (_sourceFactory = NtsGeometryServices.Instance.CreateGeometryFactory(SRID)); } }
/// <summary>
/// Gets the geometry factory to create target geometries
/// </summary>
protected internal GeometryFactory TargetFactory { get { return _targetFactory ?? _sourceFactory; } }
/// <summary>
/// Certain Transformations cannot be inverted in ProjNet, in those cases use this property to set the reverse <see cref="NetTopologySuite.CoordinateSystems.Transformations.CoordinateTransformation"/> (of CoordinateTransformation) to fetch data from Datasource
///
/// If your CoordinateTransformation can be inverted you can leave this property to null
/// </summary>
public virtual ICoordinateTransformation ReverseCoordinateTransformation
{
get
{
if (_reverseCoordinateTransform == null && NeedsTransformation)
{
var css = Session.Instance.CoordinateSystemServices;
_reverseCoordinateTransform = css.CreateTransformation(
css.GetCoordinateSystem(TargetSRID), css.GetCoordinateSystem(SRID));
}
return _reverseCoordinateTransform;
}
set { _reverseCoordinateTransform= value; }
}
protected bool NeedsTransformation
{
get { return SRID != 0 && TargetSRID != 0 && SRID != TargetSRID; }
}
#region ILayer Members
/// <summary>
/// Gets or sets the name of the layer
/// </summary>
public string LayerName
{
get { return _layerName; }
set { _layerName = value; }
}
/// <summary>
/// Gets or sets the title of the layer
/// </summary>
public string LayerTitle
{
get { return _layerTitle; }
set { _layerTitle = value; }
}
/// <summary>
/// The spatial reference ID (CRS)
/// </summary>
public virtual int SRID
{
get { return _srid; }
set
{
if (value != _srid)
{
_srid = value;
OnSridChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Gets or sets a value indicating the target spatial reference id
/// </summary>
public virtual int TargetSRID
{
get { return _targetSrid.HasValue ? _targetSrid.Value : SRID; }
set
{
_targetSrid = value;
_targetFactory = NtsGeometryServices.Instance.CreateGeometryFactory(value);
}
}
//public abstract SharpMap.CoordinateSystems.CoordinateSystem CoordinateSystem { get; set; }
/// <summary>
/// Renders the layer
/// </summary>
/// <param name="g">Graphics object reference</param>
/// <param name="map">Map which is rendered</param>
[Obsolete("Use Render(Graphics, MapViewport)")]
public virtual void Render(Graphics g, Map map)
{
Render(g, (MapViewport)map);
}
/// <summary>
/// Renders the layer
/// </summary>
/// <param name="g">Graphics object reference</param>
/// <param name="map">Map which is rendered</param>
public virtual void Render(Graphics g, MapViewport map)
{
OnLayerRendered(g);
}
/// <summary>
/// Event invoker for the <see cref="LayerRendered"/> event.
/// </summary>
/// <param name="g">The graphics object</param>
protected virtual void OnLayerRendered(Graphics g)
{
if (LayerRendered != null)
LayerRendered(this, g);
}
/// <summary>
/// Returns the extent of the layer
/// </summary>
/// <returns>Bounding box corresponding to the extent of the features in the layer</returns>
public abstract Envelope Envelope { get; }
#endregion
#region Properties
/// <summary>
/// Proj4 projection definition string
/// </summary>
public string Proj4Projection { get; set; }
/*
private bool _Enabled = true;
private double _MaxVisible = double.MaxValue;
private double _MinVisible = 0;
*/
/// <summary>
/// Minimum visibility zoom, including this value
/// </summary>
public double MinVisible
{
get
{
return _style.MinVisible; // return _MinVisible;
}
set
{
_style.MinVisible = value; // _MinVisible = value;
}
}
/// <summary>
/// Maximum visibility zoom, excluding this value
/// </summary>
public double MaxVisible
{
get
{
//return _MaxVisible;
return _style.MaxVisible;
}
set
{
//_MaxVisible = value;
_style.MaxVisible = value;
}
}
/// <summary>
/// Gets or Sets what kind of units the Min/Max visible properties are defined in
/// </summary>
public VisibilityUnits VisibilityUnits {
get
{
return _style.VisibilityUnits;
}
set
{
_style.VisibilityUnits = value;
}
}
/// <summary>
/// Specified whether the layer is rendered or not
/// </summary>
public bool Enabled
{
get
{
//return _Enabled;
return _style.Enabled;
}
set
{
//_Enabled = value;
_style.Enabled = value;
}
}
/// <summary>
/// Gets or sets the Style for this Layer
/// </summary>
public virtual IStyle Style
{
get { return _style; }
set
{
if (value != _style && !_style.Equals(value))
{
_style = value;
OnStyleChanged(EventArgs.Empty);
}
}
}
#endregion
/// <summary>
/// Returns the name of the layer.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return LayerName;
}
#region Reprojection utility functions
/// <summary>
/// Utility function to transform given envelope using a specific transformation
/// </summary>
/// <param name="envelope">The source envelope</param>
/// <param name="coordinateTransformation">The <see cref="NetTopologySuite.CoordinateSystems.Transformations.CoordinateTransformation"/> to use.</param>
/// <returns>The target envelope</returns>
protected virtual Envelope ToTarget(Envelope envelope, ICoordinateTransformation coordinateTransformation)
{
if (coordinateTransformation == null)
return envelope;
return GeometryTransform.TransformBox(envelope, coordinateTransformation.MathTransform);
}
/// <summary>
/// Utility function to transform given envelope to the target envelope
/// </summary>
/// <param name="envelope">The source envelope</param>
/// <returns>The target envelope</returns>
protected Envelope ToTarget(Envelope envelope)
{
return ToTarget(envelope, CoordinateTransformation);
}
/// <summary>
/// Utility function to transform given envelope to the source envelope
/// </summary>
/// <param name="envelope">The target envelope</param>
/// <returns>The source envelope</returns>
protected virtual Envelope ToSource(Envelope envelope)
{
if (ReverseCoordinateTransformation != null)
{
return GeometryTransform.TransformBox(envelope, ReverseCoordinateTransformation.MathTransform);
}
if (CoordinateTransformation != null)
{
var mt = CoordinateTransformation.MathTransform;
mt.Invert();
var res = GeometryTransform.TransformBox(envelope, mt);
mt.Invert();
return res;
}
// no transformation
return envelope;
}
protected virtual Geometry ToTarget(Geometry geometry)
{
if (geometry.SRID == TargetSRID)
return geometry;
if (CoordinateTransformation != null)
{
return GeometryTransform.TransformGeometry(geometry, CoordinateTransformation.MathTransform, TargetFactory);
}
return geometry;
}
protected virtual Geometry ToSource(Geometry geometry)
{
if (geometry.SRID == SRID)
return geometry;
if (ReverseCoordinateTransformation != null)
{
return GeometryTransform.TransformGeometry(geometry,
ReverseCoordinateTransformation.MathTransform, SourceFactory);
}
if (CoordinateTransformation != null)
{
var mt = CoordinateTransformation.MathTransform;
mt.Invert();
var res = GeometryTransform.TransformGeometry(geometry, mt, SourceFactory);
mt.Invert();
return res;
}
return geometry;
}
#endregion
}
}
| |
//#define SAVE_PNG_BYTES
using System;
using System.Drawing;
using System.Drawing.Imaging;
using OpenTK.Graphics.OpenGL;
using System.Collections.Generic;
namespace GameFramework {
public class TextureManager {
// TextureInstance: Provides a reference counted instance to a texture
// we keep track of the hardware accelerated textureId (glHandle),
// the original path of the texture, it's width and height
// We also keep track of refCount, this is how many times the texture
// is loaded. At the end of the application, refCount should be 0
// if the refCount of a texture is 0, it is no longer in use, we
// know that it's safe to recycle the texture when it's ref count
// is 0
private class TextureInstance {
public int glHandle = -1;
public string path = string.Empty;
public int refCount = 0;
public int width = 0;
public int height = 0;
}
// A list (vector) of all the texture instances currently available
// not every texture instance has a ref count > 0. Look at the
// LoadTexture function for details on how this works.
private List<TextureInstance> managedTextures = null;
// Helper used to warn if any method is called without first
// intilizing the manager
private bool isInitialized = false;
// If set to true, sprites will resize using nearest neighbor algorithm
// nearest neighor = blocky. If false, the resized sprite will become
// anti aliased.
public bool UseNearestFiltering = false;
// The ONLY instance of TextureManager. No class outside of the
// manager can access this instance. This variable, the Instance getter
// and private constructor make this class a singleton.
private static TextureManager instance = null;
// Lazy accessor, no instance of TextureManager exists until the very
// first time a user tries to access Instance. Once Instance is accessed
// a TextureManager will exist until the application quits
public static TextureManager Instance {
get {
if (instance == null) {
instance = new TextureManager();
}
return instance;
}
}
// The constructor is private to prevent anything other than the Instance
// getter from creating a new instance of TextureManager, this is what
// makes this class a singleton.
private TextureManager() {
}
// Utility function to log red text to the console
private void Error(string error) {
ConsoleColor old = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(error);
Console.ForegroundColor = old;
}
// Utility function to log yellow text to the console
private void Warning(string error) {
ConsoleColor old = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(error);
Console.ForegroundColor = old;
}
// Set up all necesary member variables of the texture manager
// The argument this manager takes is ignored, we include it to
// make all managers have a similar interface. Usually you only
// initialize a manager at the start of the application.
public void Initialize(OpenTK.GameWindow window) {
if (isInitialized) {
Error("Trying to double intialize texture manager!");
}
managedTextures = new List<TextureInstance>();
// List.Capacity = Vector.Reserve
// We reserve enough room for 100 textures, if 101
// textures are loaded, room will be reserved for 200
// textures. This will keep doubling as vectors do
managedTextures.Capacity = 100;
isInitialized = true;
}
// Deallocate all memory the texture manager is currently using, flip the
// initialization flag back to false. After calling shutdown the texture
// manager is invalid, unless Initialize is called again. Usually you only
// shut down a manager at the end of the application.
public void Shutdown() {
if (!isInitialized) {
Error("Trying to shut down a non initialized texture manager!");
}
// Loop trough all loaded textures
for (int i = 0; i < managedTextures.Count; ++i) {
// We expect the texture count to be 0, if it's not then the textures
// where not unloaded properly. We will delete them anyway, but the
// user should really, REALLY fix their code.
if (managedTextures[i].refCount != 0) {
Warning("Texture reference is > 0: " + managedTextures[i].path);
}
// Delete the texture from graphics memory
GL.DeleteTexture(managedTextures[i].glHandle);
// This isn't needed, but let's set the textures element in the array
// to null, to give GC a hint that it is to be collected.
managedTextures[i] = null;
}
// .Clear and = null are not both needed. Usually = null is enough. But we
// want to make sure that GC gets the hint, so we agressivley clear the list
managedTextures.Clear();
managedTextures = null;
isInitialized = false;
}
// Helper function to determine if a given texture is a power of two or not
// Graphics cards work a LOT faster when tehy have Power of Two (POT) textures
private bool IsPowerOfTwo(int x) {
// If X was an unsigned long (or int), we could do this:
// return (x & (x - 1)) == 0;
// ^ would be a lot faster. But our handle is an integer, so use a general
// purpose method of figuring this out. 0 will be a POT.
if (x > 1) {
while (x % 2 == 0) {
x >>= 1;
}
}
return x == 1;
}
// Given a file name, this function will load the texture into system memory, then
// upload it to GPU memory, and let the system memory become eligable for garbage collection
// We really only need a reference to the texture on the GPU, as everything we do is going to
// be hardware accelerated (happen on the GPU). The function will return a handle to the GPU
// instance of the texture, as well as the width and height f the texutre
private int LoadGLTexture(string filename, out int width, out int height, bool nearest) {
if (string.IsNullOrEmpty(filename)) {
Error("Load texture file path was null");
throw new ArgumentException(filename);
}
// Generate a handle on the GPU
int id = GL.GenTexture();
// Bind the handle to the be the active texture.
GL.BindTexture(TextureTarget.Texture2D, id);
// Ming & Mag filters are needed to figure out how to interpolate scaling. If you don't
// provide them the GPU will not draw your texture. Trilinear is the nicest looking,
// but most expensive. Linear is kind of standard.
if (nearest) {
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
}
else {
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
}
// Allocate system memory for the image
Bitmap bmp = new Bitmap(filename);
// Load the image into system memory
BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
// If the texture is non POT, or bigger than 2048 warn the user so they can fix
// the texutre during development
if (!IsPowerOfTwo(bmp.Width)) {
Warning("Texture width non power of two: " + filename);
}
if (!IsPowerOfTwo(bmp.Height)) {
Warning("Texture height non power of two: " + filename);
}
if (bmp.Width > 2048) {
Warning("Texture width > 2048: " + filename);
}
if (bmp.Height > 2048) {
Warning("Texture height > 2048: " + filename);
}
// Upload the image data to the GPU
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);
#if SAVE_PNG_BYTES
byte[] byteArray = new byte[bmp_data.Width * bmp_data.Height * 4];
System.Runtime.InteropServices.Marshal.Copy(bmp_data.Scan0, byteArray, 0, byteArray.Length);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("{\n");
for (int i = 0; i < byteArray.Length; ++i) {
sb.Append("0x");
sb.AppendFormat("{0:x2}", byteArray[i]);
if (i != byteArray.Length - 1) {
sb.Append(", ");
}
if (i != 0 && i%16 == 0) {
sb.Append("\n");
}
}
sb.Append("\n};");
string directory = System.IO.Path.GetDirectoryName(filename);
string file = System.IO.Path.GetFileNameWithoutExtension(filename);
System.IO.File.WriteAllText(directory + "/" + file + ".array", sb.ToString());
#endif
// Mark system memory eligable for GC
bmp.UnlockBits(bmp_data);
// Return the textures width, height and GPU ID
width = bmp.Width;
height = bmp.Height;
return id;
}
// Public facing interface for loading a texture. Given a texture path it will return a handle
// (index into managedTextures vector) which can later be used to draw the texture.
public int LoadTexture(string texturePath) {
if (!isInitialized) {
Error("Trying to load texture without intializing texture manager!");
}
// First, check if the texture is already being managed. If it is, increase ref count and
// return the textures index.
for (int i = 0; i < managedTextures.Count; ++i) {
if (managedTextures[i].path == texturePath) {
managedTextures[i].refCount += 1;
return i;
}
}
// If the texture was not being tracked, go trough the list and look for an open space, if an
// open space is found, unload it's texture from GPU memory, and load our new texture, override
// the reference count, path, width, height and texture handle with new values
for (int i = 0; i < managedTextures.Count; ++i) {
if (managedTextures[i].refCount <= 0) {
GL.DeleteTexture(managedTextures[i].glHandle);
managedTextures[i].glHandle = LoadGLTexture(texturePath, out managedTextures[i].width, out managedTextures[i].height, UseNearestFiltering);
managedTextures[i].refCount = 1;
managedTextures[i].path = texturePath;
return i;
}
}
// Finally we get here if the texture we are trying to load is not an already managed texture
// and we have no open spots for new textures to be managed. Here we just create a new texture
// and add it to the managed textures vector
TextureInstance newTexture = new TextureInstance();
newTexture.refCount = 1;
newTexture.glHandle = LoadGLTexture(texturePath, out newTexture.width, out newTexture.height, UseNearestFiltering);
newTexture.path = texturePath;
managedTextures.Add(newTexture);
return managedTextures.Count - 1;
}
// This function decreases the textures reference count. It does not de-allocate the texture
// memory on the GPU. The reason for this is that there is a decent chance that some textures
// will stay around between scene loads. This way if a texture's reference count reaches 0,
// and it hasn't been overwritten yet, if we load it again we get that load for free.
public void UnloadTexture(int textureId) {
if (!isInitialized) {
Error("Trying to unload texture without intializing texture manager!");
}
managedTextures[textureId].refCount -= 1;
// If we go below -1, no problem. But the system is intended to go only to 0, so lets
// warn the user that they cleaned up wrong
if (managedTextures[textureId].refCount < 0) {
Error("Ref count of texture is less than 0: " + managedTextures[textureId].path);
}
}
// Simple getter to access the width of a texture
public int GetTextureWidth(int textureId) {
if (!isInitialized) {
Error("Trying to access texture width without intializing texture manager!");
}
return managedTextures[textureId].width;
}
// Simple getter to access the height of a texture
public int GetTextureHeight(int textureId) {
if (!isInitialized) {
Error("Trying to access texture height without intializing texture manager!");
}
return managedTextures[textureId].height;
}
// Simple getter to access the size of a texture
public Size GetTextureSize(int textureId) {
if (!isInitialized) {
Error("Trying to access texture size without intializing texture manager!");
}
return new Size(managedTextures[textureId].width, managedTextures[textureId].height);
}
// Given a texture id, draw it at the specified screen position. This will draw the
// entire texture at that position, nothing gets cut off
public void Draw(int textureId, Point screenPosition) {
if (!isInitialized) {
Error("Trying to draw texture without intializing texture manager!");
}
// Let the graphics manager know that we are drawing on top of everything else
GraphicsManager.Instance.IncreaseDepth();
// Save the current transform matrix
GL.PushMatrix();
// Build out the rectangle we will be drawing
float left = 0.0f;
float top = 0.0f;
float right = left + managedTextures[textureId].width;
float bottom = top + managedTextures[textureId].height;
// Because blending is enabled, we want to blend the color of the texture with
// just straight white. That way we get the correct color back
GL.Color3(1.0f, 1.0f, 1.0f);
// Bind the texture we want to draw to be active
GL.BindTexture(TextureTarget.Texture2D, managedTextures[textureId].glHandle);
// Offset to the correct position to draw at
GL.Translate(screenPosition.X, screenPosition.Y, GraphicsManager.Instance.Depth);
// Draw a quad
GL.Begin(PrimitiveType.Quads);
GL.TexCoord2(0, 1); // What part of the texture to draw
GL.Vertex3(left, bottom, 0.0f); // Where on screen to draw it
GL.TexCoord2(1, 1);
GL.Vertex3(right, bottom, 0.0f);
GL.TexCoord2(1, 0);
GL.Vertex3(right, top, 0.0f);
GL.TexCoord2(0, 0);
GL.Vertex3(left, top, 0.0f);
GL.End();
// Restore the saved transform matrix
GL.PopMatrix();
// Unbind any active textures
GL.BindTexture(TextureTarget.Texture2D, 0);
}
// Given a texture id, draw it at the specified screen position and scale it.
// This will draw the entire texture at that position, nothing gets cut off,
// but it is possible to scale the image down or up
public void Draw(int textureId, Point screenPosition, float scale) {
if (!isInitialized) {
Error("Trying to draw texture without intializing texture manager!");
}
Draw(textureId, screenPosition, new PointF(scale, scale));
}
// Given a texture id, draw it at the specified screen position and scale it.
// This will draw the entire texture at that position, nothing gets cut off,
// but it is possible to scale the image down or up
public void Draw(int textureId, Point screenPosition, PointF scale) {
if (!isInitialized) {
Error("Trying to draw texture without intializing texture manager!");
}
GraphicsManager.Instance.IncreaseDepth();
GL.PushMatrix();
float left = 0.0f;
float top = 0.0f;
float right = left + managedTextures[textureId].width;
float bottom = top + managedTextures[textureId].height;
GL.Color3(1.0f, 1.0f, 1.0f);
GL.BindTexture(TextureTarget.Texture2D, managedTextures[textureId].glHandle);
GL.Translate(screenPosition.X, screenPosition.Y, GraphicsManager.Instance.Depth);
GL.Scale(scale.X, scale.Y, 1.0f);
GL.Begin(PrimitiveType.Quads);
GL.TexCoord2(0, 1);
GL.Vertex3(left, bottom, 0.0f);
GL.TexCoord2(1, 1);
GL.Vertex3(right, bottom, 0.0f);
GL.TexCoord2(1, 0);
GL.Vertex3(right, top, 0.0f);
GL.TexCoord2(0, 0);
GL.Vertex3(left, top, 0.0f);
GL.End();
GL.PopMatrix();
GL.BindTexture(TextureTarget.Texture2D, 0);
}
// Given a texture id, draw a sub-section of that texture at the specified screen position
// and possibly scale it. This will not draw the whole texture, just a specific rectangle form it
public void Draw(int textureId, Point screenPosition, float scale, Rectangle sourceSection) {
Draw(textureId, screenPosition, new PointF(scale, scale), sourceSection);
}
// Given a texture id, draw a sub-section of that texture at the specified screen position
// and possibly scale it. This will not draw the whole texture, just a specific rectangle form it
public void Draw(int textureId, Point screenPosition, PointF scale, Rectangle sourceSection) {
if (!isInitialized) {
Error("Trying to draw texture without intializing texture manager!");
}
GraphicsManager.Instance.IncreaseDepth();
GL.PushMatrix();
float left = 0;
float top = 0;
float right = left + sourceSection.Width;
float bottom = top + sourceSection.Height;
float wRecip = 1.0f / ((float)managedTextures[textureId].width);
float hRecip = 1.0f / ((float)managedTextures[textureId].height);
float uvLeft = ((float)sourceSection.X) * wRecip;
float uvTop = ((float)sourceSection.Y) * hRecip;
float uvRight = uvLeft + ((float)sourceSection.Width) * wRecip;
float uvBottom = uvTop + ((float)sourceSection.Height) * hRecip;
GL.Color3(1.0f, 1.0f, 1.0f);
GL.BindTexture(TextureTarget.Texture2D, managedTextures[textureId].glHandle);
GL.Translate(screenPosition.X, screenPosition.Y, GraphicsManager.Instance.Depth);
GL.Scale(scale.X, scale.Y, 1.0f);
GL.Begin(PrimitiveType.Quads);
GL.TexCoord2(uvLeft, uvBottom);
GL.Vertex3(left, bottom, 0.0f);
GL.TexCoord2(uvRight, uvBottom);
GL.Vertex3(right, bottom, 0.0f);
GL.TexCoord2(uvRight, uvTop);
GL.Vertex3(right, top, 0.0f);
GL.TexCoord2(uvLeft, uvTop);
GL.Vertex3(left, top, 0.0f);
GL.End();
GL.PopMatrix();
GL.BindTexture(TextureTarget.Texture2D, 0);
}
// Given a texture id, draw a sub-section of that texture at the specified screen position
// and possibly scale it. This will not draw the whole texture, just a specific rectangle form it.
// The resulting image can then be rotated about it's center by any angle.
public void Draw(int textureId, Point screenPosition, float scale, Rectangle sourceSection, float rotation) {
Point rotationCenter = new Point(sourceSection.Width / 2, sourceSection.Height / 2);
Draw(textureId, screenPosition, new PointF(scale, scale), sourceSection, rotationCenter, rotation);
}
// Given a texture id, draw a sub-section of that texture at the specified screen position
// and possibly scale it. This will not draw the whole texture, just a specific rectangle form it.
// The resulting image can then be rotated about it's center by any angle.
public void Draw(int textureId, Point screenPosition, PointF scale, Rectangle sourceSection, float rotation) {
Point rotationCenter = new Point(sourceSection.Width / 2, sourceSection.Height / 2);
Draw(textureId, screenPosition, scale, sourceSection, rotationCenter, rotation);
}
// Given a texture id, draw a sub-section of that texture at the specified screen position
// and possibly scale it. This will not draw the whole texture, just a specific rectangle form it.
// The resulting image can then be rotated about a specified point by any angle.
public void Draw(int textureId, Point screenPosition, float scale, Rectangle sourceSection, Point rotationCenter, float rotation = 0.0f) {
Draw(textureId, screenPosition, new PointF(scale, scale), sourceSection, rotationCenter, rotation);
}
// Given a texture id, draw a sub-section of that texture at the specified screen position
// and possibly scale it. This will not draw the whole texture, just a specific rectangle form it.
// The resulting image can then be rotated about a specified point by any angle.
public void Draw(int textureId, Point screenPosition, PointF scale, Rectangle sourceSection, Point rotationCenter, float rotation = 0.0f) {
if (!isInitialized) {
Error("Trying to draw texture without intializing texture manager!");
}
GraphicsManager.Instance.IncreaseDepth();
GL.PushMatrix();
float left = 0;
float top = 0;
float right = left + sourceSection.Width;
float bottom = top + sourceSection.Height;
float wRecip = 1.0f / ((float)managedTextures[textureId].width);
float hRecip = 1.0f / ((float)managedTextures[textureId].height);
float uvLeft = ((float)sourceSection.X) * wRecip;
float uvTop = ((float)sourceSection.Y) * hRecip;
float uvRight = uvLeft + ((float)sourceSection.Width) * wRecip;
float uvBottom = uvTop + ((float)sourceSection.Height) * hRecip;
GL.Color3(1.0f, 1.0f, 1.0f);
GL.BindTexture(TextureTarget.Texture2D, managedTextures[textureId].glHandle);
GL.Translate(screenPosition.X, screenPosition.Y, GraphicsManager.Instance.Depth);
GL.Translate(((float)rotationCenter.X) * scale.X, ((float)rotationCenter.Y) * scale.Y, 0.0f);
GL.Rotate(rotation, 0.0f, 0.0f, 1.0f);
GL.Translate(-((float)rotationCenter.X) * scale.X, -((float)rotationCenter.Y) * scale.Y, 0.0f);
GL.Scale(scale.X, scale.Y, 1.0f);
GL.Begin(PrimitiveType.Quads);
GL.TexCoord2(uvLeft, uvBottom);
GL.Vertex3(left, bottom, 0.0f);
GL.TexCoord2(uvRight, uvBottom);
GL.Vertex3(right, bottom, 0.0f);
GL.TexCoord2(uvRight, uvTop);
GL.Vertex3(right, top, 0.0f);
GL.TexCoord2(uvLeft, uvTop);
GL.Vertex3(left, top, 0.0f);
GL.End();
GL.PopMatrix();
GL.BindTexture(TextureTarget.Texture2D, 0);
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace LLT
{
public sealed class CoreTexture2D
{
private sealed class PackNode
{
private CoreRect _rect;
private PackNode[] _childs;
private int _padding;
private CoreTexture2D _texture2D;
public CoreRect Rect
{
get
{
return _rect;
}
}
public bool HasTexture
{
get
{
return _texture2D != null;
}
}
public CoreTexture2D Texture
{
get
{
return _texture2D;
}
}
public PackNode(CoreRect rect, int padding)
{
_rect = rect;
_padding = padding;
}
public static PackNode GrowFromRoot(PackNode oldRoot, int growX, int growY)
{
if (oldRoot._rect.Width == 0 && oldRoot._rect.Height == 0)
{
int newSizeX = CoreMath.NextPowerOfTwo(growX);
int newSizeY = CoreMath.NextPowerOfTwo(growY);
return new PackNode(new CoreRect(0, 0, newSizeX, newSizeY), oldRoot._padding);
}
else
{
float newSizeX = oldRoot._rect.Width;
float newSizeY = oldRoot._rect.Height;
if (growY > oldRoot._rect.Height || growX > oldRoot._rect.Width)
{
if (growY > oldRoot._rect.Height)
{
//Grow heigh-wise
newSizeY = oldRoot._rect.Height + growY + oldRoot._padding;
}
if (growX > oldRoot._rect.Width)
{
//Grow width-wise
newSizeX = oldRoot._rect.Width + growX + oldRoot._padding;
}
}
else
{
if (oldRoot._rect.Width > oldRoot._rect.Height)
{
//Grow heigh-wise
newSizeY = oldRoot._rect.Height + growY + oldRoot._padding;
}
else
{
//Grow width-wise
newSizeX = oldRoot._rect.Width + growX + oldRoot._padding;
}
}
newSizeX = CoreMath.NextPowerOfTwo((int)newSizeX);
newSizeY = CoreMath.NextPowerOfTwo((int)newSizeY);
if (newSizeX > _maxTextureSize || newSizeY > _maxTextureSize)
{
return null;
}
var newRoot = new PackNode(new CoreRect(0, 0, newSizeX, newSizeY), oldRoot._padding);
newRoot._childs = new PackNode[2];
newRoot._childs[0] = new PackNode(new CoreRect(0, 0, newSizeX, oldRoot._rect.Height), oldRoot._padding);
newRoot._childs[0]._childs = new PackNode[2];
newRoot._childs[0]._childs[0] = oldRoot;
newRoot._childs[0]._childs[1] = new PackNode(new CoreRect(oldRoot._rect.Width + oldRoot._padding, 0, newSizeX - oldRoot._rect.Width - oldRoot._padding, oldRoot._rect.Height), oldRoot._padding);
newRoot._childs[1] = new PackNode(new CoreRect(0, oldRoot._rect.Height + oldRoot._padding, newSizeX, newSizeY - oldRoot._rect.Height - oldRoot._padding), oldRoot._padding);
return newRoot;
}
}
public bool Insert(CoreTexture2D texture2D)
{
if(texture2D.Width > _maxTextureSize || texture2D.Height > _maxTextureSize)
{
if(_texture2D == null)
{
_rect = new CoreRect(0, 0, texture2D.Width, texture2D.Height);
_texture2D = texture2D;
return true;
}
else
{
return false;
}
}
// Try inserting in childs.
if(_childs != null)
{
return _childs[0].Insert(texture2D) ? true : _childs[1].Insert(texture2D);
}
// Check if it`s the same texture.
if(_texture2D != null )
{
if(_texture2D== texture2D)
{
return true;
}
return false;
}
// Is too big for actual rect.
if (_rect.Width < texture2D.Width || _rect.Height < texture2D.Height)
{
return false;
}
// Is perfect fit insert.
if (_rect.Width == texture2D.Width && _rect.Height == texture2D.Height)
{
_texture2D = texture2D;
return true;
}
// Create new childs and try inserting.
_childs = new PackNode[2];
if (_rect.Width - texture2D.Width < _rect.Height - texture2D.Height)
{
_childs[0] = new PackNode(new CoreRect(_rect.X, _rect.Y, _rect.Width, texture2D.Height), _padding);
_childs[1] = new PackNode(new CoreRect(_rect.X, _rect.Y + texture2D.Height + _padding, _rect.Width, _rect.Height - texture2D.Height - _padding), _padding);
}
else
{
_childs[0] = new PackNode(new CoreRect(_rect.X, _rect.Y, texture2D.Width, _rect.Height), _padding);
_childs[1] = new PackNode(new CoreRect(_rect.X + texture2D.Width + _padding, _rect.Y, _rect.Width - texture2D.Width - _padding, _rect.Height), _padding);
}
return _childs[0].Insert(texture2D);
}
public List<PackNode> PackNodes()
{
List<PackNode> packNodes = new List<PackNode>();
packNodes.Add(this);
if (_childs != null)
{
packNodes.AddRange(_childs[0].PackNodes());
packNodes.AddRange(_childs[1].PackNodes());
}
return packNodes;
}
}
public static Func<string, CoreTexture2D> PngDecoder;
public static Action<string, CoreTexture2D> PngEncoder;
private static int _maxTextureSize = 2048;
private int _width;
private int _height;
private int[] _argb;
public int Width
{
get
{
return _width;
}
}
public int Height
{
get
{
return _height;
}
}
public int[] ARGB
{
get
{
return _argb;
}
}
public CoreTexture2D(int width, int height, int[] argb)
{
_width = width;
_height = height;
_argb = argb;
}
public CoreTexture2D(int width, int height)
{
_width = width;
_height = height;
_argb = new int[width * height];
}
public CoreTexture2D(string path)
{
CoreAssert.Fatal(Path.GetExtension(path) == ".png" && PngDecoder != null);
var texture2D = PngDecoder(path);
_width = texture2D.Width;
_height = texture2D.Height;
_argb = texture2D.ARGB;
}
public void SetPixels(int x, int y, CoreTexture2D other)
{
CoreAssert.Fatal(x + other.Width <= Width && y + other.Height <= Height, "Texture does not fit: " + (x + other.Width) + "x" + (y + other.Height) + " " + Width + "x" + Height);
for(var j = 0; j < other.Height; j++)
{
for (var i = 0; i < other.Width; i++)
{
_argb[(j + y) * Width + i + x] = other.ARGB[j * other.Width + i];
}
}
}
public void Save(string path)
{
CoreAssert.Fatal(Path.GetExtension(path) == ".png" && PngEncoder != null);
PngEncoder(path, this);
}
public static CoreTexture2D[] Pack(CoreTexture2D[] originals, int padding, out CoreTexture2D atlas, out CoreRect[] uv)
{
//var textures = originals.Where(x=>x != null).ToList();
/*textures.Sort((x,y)=>
{
if(x.Width > _maxTextureSize || x.Height > _maxTextureSize)
{
return -1;
}
if(y.Width > _maxTextureSize || y.Height > _maxTextureSize)
{
return 1;
}
var px = 2 * x.Width + 2 * x.Height;
var py = 2 * y.Width + 2 * y.Height;
if((Math.Max(px, py)/(float)Math.Min(px, py)) < 2)
{
//return -1;
}
var retVal = py.CompareTo(px);
return retVal;
}); */
var textures = originals.Where(x=>x != null).OrderByDescending(x=>x.Width > _maxTextureSize ? 1 : 0).ThenByDescending(x=>x.Height > _maxTextureSize ? 1 : 0).ThenByDescending((x) => 2 * x.Width + 2 * x.Height).ToArray();
var temp = textures.ToArray();
if(textures.Length == 0)
{
atlas = null;
uv = new CoreRect[originals.Length];
return originals;
}
var squareness = Math.Max(textures[0].Width, textures[0].Height)/(float)Math.Min(textures[0].Width, textures[0].Height);
if((_maxTextureSize - 2 * padding) < textures[0].Width || (_maxTextureSize - 2 * padding) < textures[0].Height)/* || (squareness < 2 && (textures[0].Width * textures[0].Height > (_maxTextureSize * _maxTextureSize) / 4))*/
{
atlas = textures[0];
uv = new CoreRect[originals.Length];
var originalIndex = Array.IndexOf(originals, atlas);
uv[originalIndex] = new CoreRect(padding / (float)atlas.Width, padding / (float)atlas.Height, (atlas.Width - 2 * padding) / (float)atlas.Width, (atlas.Height - 2 * padding) / (float)atlas.Height);
originals[originalIndex] = null;
return originals;
}
var root = new PackNode(new CoreRect(0, 0, 0, 0), padding);
for ( var index = 0; index < textures.Length; index++)
{
var texture2D = textures[index];
if (!root.Insert(texture2D))
{
// Try growing this root otherwise create a new one.
var grown = PackNode.GrowFromRoot(root, texture2D.Width, texture2D.Height);
if (grown == null)
{
break;
}
else
{
// Reassign root and insert.
root = grown;
if(!root.Insert(texture2D))
{
throw new System.Exception("Problem inserting texture");
}
}
}
}
int width = CoreMath.NextPowerOfTwo(root.Rect.Width);
int height = CoreMath.NextPowerOfTwo(root.Rect.Height);
uv = new CoreRect[originals.Length];
atlas = new CoreTexture2D(width, height);
var packNodes = root.PackNodes();
foreach (PackNode packNode in packNodes)
{
if(!packNode.HasTexture)
continue;
atlas.SetPixels((int)packNode.Rect.X, (int)packNode.Rect.Y, packNode.Texture);
var originalIndex = Array.IndexOf(originals, packNode.Texture);
uv[originalIndex] = new CoreRect((packNode.Rect.X + padding) / (float)atlas.Width, (packNode.Rect.Y+padding)/ (float)atlas.Height, (packNode.Texture.Width-2*padding)/(float)atlas.Width, (packNode.Texture.Height-2*padding)/(float)atlas.Height);
originals[originalIndex] = null;
}
return originals;
}
}
}
| |
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 AspNetIdentityDependencyInjectionSample.Areas.HelpPage.ModelDescriptions;
using AspNetIdentityDependencyInjectionSample.Areas.HelpPage.Models;
namespace AspNetIdentityDependencyInjectionSample.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);
}
}
}
}
| |
//
// StreamContentTest.cs
//
// Authors:
// Marek Safar <marek.safar@gmail.com>
//
// Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.IO;
using System.Net;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MonoTests.System.Net.Http
{
extern alias tpl;
using tpl::System.Threading.Tasks;
using AggregateException = tpl::System.AggregateException;
[TestClass]
public class StreamContentTest
{
class StreamContentMock : StreamContent
{
public Func<long> OnTryComputeLength;
public Action OnSerializeToStreamAsync;
public StreamContentMock (Stream stream)
: base (stream)
{
}
protected override bool TryComputeLength (out long length)
{
if (OnTryComputeLength != null) {
length = OnTryComputeLength ();
return true;
}
return base.TryComputeLength (out length);
}
protected override Task SerializeToStreamAsync (Stream stream, TransportContext context)
{
if (OnSerializeToStreamAsync != null)
OnSerializeToStreamAsync ();
return base.SerializeToStreamAsync (stream, context);
}
}
class ExceptionStream : MemoryStream
{
public ExceptionStream ()
{
base.WriteByte (10);
base.Seek (0, SeekOrigin.Begin);
}
public override int Read (byte[] buffer, int offset, int count)
{
throw new ApplicationException ("Read");
}
public override byte[] GetBuffer ()
{
throw new ApplicationException ("GetBuffer");
}
}
class CannotSeekStream : MemoryStream
{
public CannotSeekStream ()
: base (new byte [11])
{
}
public override bool CanSeek {
get {
return false;
}
}
}
[TestMethod]
public void Ctor_Invalid ()
{
try {
new StreamContent (null);
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
try {
new StreamContent (new MemoryStream (), 0);
Assert.Fail ("#2");
} catch (ArgumentOutOfRangeException) {
}
}
[TestMethod]
public void Ctor ()
{
var ms = new MemoryStream ();
ms.WriteByte (44);
using (var m = new StreamContent (ms)) {
}
}
[TestMethod]
public void CopyToAsync_Invalid ()
{
var m = new MemoryStream ();
var sc = new StreamContent (new MemoryStream ());
try {
sc.CopyToAsync (null);
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
//
// For some reason does not work on .net
//
/*
sc = new StreamContent (new ExceptionStream ());
try {
sc.CopyToAsync (m).Wait ();
Assert.Fail ("#2");
} catch (AggregateException) {
}
*/
}
[TestMethod]
/*
* The .NET runtime hits the "#9" assertion.
* The test succeeds with Mono.
*/
[TestCategory ("NotWorking")]
public void CopyToAsync ()
{
var ms = new MemoryStream ();
ms.WriteByte (4);
ms.WriteByte (2);
ms.Seek (0, SeekOrigin.Begin);
var sc = new StreamContent (ms);
var dest = new MemoryStream ();
var task = sc.CopyToAsync (dest);
task.Wait ();
Assert.AreEqual (2, dest.Length, "#1");
bool hit = false;
dest = new MemoryStream ();
var scm = new StreamContentMock (new ExceptionStream ());
scm.OnSerializeToStreamAsync = () => { hit = true; };
task = scm.CopyToAsync (dest);
try {
task.Wait ();
Assert.Fail ("#9");
} catch (AggregateException) {
}
Assert.IsTrue (hit, "#10");
}
[TestMethod]
public void CopyToAsync_ClosedInput ()
{
var stream = new MemoryStream (new byte[] { 1 });
var content = new StreamContent (stream);
Assert.IsTrue (content.LoadIntoBufferAsync ().Wait (3000), "#1");
stream.Close ();
var stream_out = new MemoryStream (10);
Assert.IsTrue (content.CopyToAsync (stream_out).Wait (3000), "#2");
}
[TestMethod]
public void Headers ()
{
var ms = new MemoryStream ();
ms.WriteByte (4);
ms.WriteByte (2);
ms.Seek (0, SeekOrigin.Begin);
var sc = new StreamContent (ms);
var headers = sc.Headers;
Assert.AreEqual (2, headers.ContentLength, "#1");
headers.ContentLength = 400;
Assert.AreEqual (400, headers.ContentLength, "#1a");
headers.ContentLength = null;
var scm = new StreamContentMock (MemoryStream.Null);
scm.OnTryComputeLength = () => 330;
Assert.AreEqual (330, scm.Headers.ContentLength, "#2");
headers.Allow.Add ("a1");
headers.ContentEncoding.Add ("ce1");
headers.ContentLanguage.Add ("cl1");
headers.ContentLength = 23;
headers.ContentLocation = new Uri ("http://xamarin.com");
headers.ContentMD5 = new byte[] { 3, 5 };
headers.ContentRange = new ContentRangeHeaderValue (88, 444);
headers.ContentType = new MediaTypeHeaderValue ("multipart/*");
headers.Expires = new DateTimeOffset (DateTime.Today);
headers.LastModified = new DateTimeOffset (DateTime.Today);
headers.Add ("allow", "a2");
headers.Add ("content-encoding", "ce3");
headers.Add ("content-language", "cl2");
try {
headers.Add ("content-length", "444");
Assert.Fail ("content-length");
} catch (FormatException) {
}
try {
headers.Add ("content-location", "cl2");
Assert.Fail ("content-location");
} catch (FormatException) {
}
try {
headers.Add ("content-MD5", "cmd5");
Assert.Fail ("content-MD5");
} catch (FormatException) {
}
try {
headers.Add ("content-range", "133");
Assert.Fail ("content-range");
} catch (FormatException) {
}
try {
headers.Add ("content-type", "ctype");
Assert.Fail ("content-type");
} catch (FormatException) {
}
try {
headers.Add ("expires", "ctype");
Assert.Fail ("expires");
} catch (FormatException) {
}
try {
headers.Add ("last-modified", "lmo");
Assert.Fail ("last-modified");
} catch (FormatException) {
}
Assert.IsTrue (headers.Allow.SequenceEqual (
new[] {
"a1",
"a2"
}
));
Assert.IsTrue (headers.ContentEncoding.SequenceEqual (
new[] {
"ce1",
"ce3"
}
));
Assert.IsTrue (headers.ContentLanguage.SequenceEqual (
new[] {
"cl1",
"cl2"
}
));
Assert.AreEqual (23, headers.ContentLength);
Assert.AreEqual (new Uri ("http://xamarin.com"), headers.ContentLocation);
CollectionAssert.AreEqual (new byte[] { 3, 5 }, headers.ContentMD5);
Assert.AreEqual (new ContentRangeHeaderValue (88, 444), headers.ContentRange);
Assert.AreEqual (new MediaTypeHeaderValue ("multipart/*"), headers.ContentType);
Assert.AreEqual (new DateTimeOffset (DateTime.Today), headers.Expires);
Assert.AreEqual (new DateTimeOffset (DateTime.Today), headers.LastModified);
}
[TestMethod]
public void Headers_ToString ()
{
var sc = new StreamContent (new MemoryStream ());
var headers = sc.Headers;
headers.ContentMD5 = new byte[] { 3, 5 };
Assert.AreEqual ("Content-MD5: AwU=\r\n", headers.ToString (), "#1");
}
[TestMethod]
public void Headers_Invalid ()
{
var sc = new StreamContent (MemoryStream.Null);
var h = sc.Headers;
try {
h.Add ("Age", "");
Assert.Fail ("#1");
} catch (InvalidOperationException) {
}
}
[TestMethod]
public void Headers_Multi ()
{
var sc = new StreamContent (MemoryStream.Null);
var headers = sc.Headers;
headers.Add ("Allow", "");
headers.Add ("Allow", "a , b, c");
Assert.AreEqual (3, headers.Allow.Count, "#1a");
Assert.IsTrue (headers.Allow.SequenceEqual (
new[] { "a", "b", "c" }
), "#1b");
}
[TestMethod]
public void LoadIntoBuffer ()
{
var ms = new MemoryStream ();
ms.WriteByte (4);
ms.Seek (0, SeekOrigin.Begin);
var sc = new StreamContent (ms);
Assert.IsTrue (sc.LoadIntoBufferAsync (400).Wait (200));
}
[TestMethod]
public void LoadIntoBuffer_BufferOverflow ()
{
var ms = new MemoryStream ();
ms.Write (new byte[10000], 0, 10000);
ms.Seek (0, SeekOrigin.Begin);
var sc = new StreamContent (ms);
try {
Assert.IsTrue (sc.LoadIntoBufferAsync (50).Wait (200));
Assert.Fail ("#1");
} catch (AggregateException e) {
Assert.IsTrue (e.InnerException is HttpRequestException, "#2");
}
}
[TestMethod]
public void ReadAsByteArrayAsync ()
{
var ms = new MemoryStream ();
ms.WriteByte (4);
ms.WriteByte (55);
var sc = new StreamContent (ms);
var res = sc.ReadAsByteArrayAsync ().Result;
Assert.AreEqual (0, res.Length, "#1");
ms.Seek (0, SeekOrigin.Begin);
sc = new StreamContent (ms);
res = sc.ReadAsByteArrayAsync ().Result;
Assert.AreEqual (2, res.Length, "#10");
Assert.AreEqual (55, res[1], "#11");
}
[TestMethod]
public void ReadAsString ()
{
var ms = new MemoryStream ();
ms.WriteByte (77);
ms.WriteByte (55);
ms.Seek (0, SeekOrigin.Begin);
var sc = new StreamContent (ms);
var res = sc.ReadAsStringAsync ().Result;
Assert.AreEqual ("M7", res, "#1");
}
[TestMethod]
public void ReadAsStream ()
{
var ms = new MemoryStream ();
ms.WriteByte (77);
ms.WriteByte (55);
ms.Seek (0, SeekOrigin.Begin);
var sc = new StreamContent (ms);
var res = sc.ReadAsStreamAsync ().Result;
Assert.AreEqual (77, res.ReadByte (), "#1");
}
[TestMethod]
public void ReadAsStreamAsync_ClosedInput ()
{
var stream = new MemoryStream (new byte[] { 1 });
var content = new StreamContent (stream);
Assert.IsTrue (content.LoadIntoBufferAsync ().Wait (3000), "#1");
stream.Close ();
var stream_read = content.ReadAsStreamAsync ().Result;
Assert.IsTrue (stream_read.CanSeek, "#2");
Assert.AreEqual (0, stream_read.Position, "#3");
Assert.AreEqual (1, stream_read.Length, "#4");
}
[TestMethod]
public void ContentLengthAfterLoad ()
{
var sc = new StreamContent (new CannotSeekStream ());
Assert.IsTrue (sc.LoadIntoBufferAsync ().Wait (3000), "#1");
Assert.AreEqual (11, sc.Headers.ContentLength, "#2");
}
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace System.Collections.Generic
{
/// <summary>
/// Used internally to control behavior of insertion into a <see cref="Dictionary{TKey, TValue}"/>.
/// </summary>
internal enum InsertionBehavior : byte
{
/// <summary>
/// The default insertion behavior.
/// </summary>
None = 0,
/// <summary>
/// Specifies that an existing entry with the same key should be overwritten if encountered.
/// </summary>
OverwriteExisting = 1,
/// <summary>
/// Specifies that if an existing entry with the same key is encountered, an exception should be thrown.
/// </summary>
ThrowOnExisting = 2
}
[DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback where TKey : notnull
{
private struct Entry
{
// 0-based index of next entry in chain: -1 means end of chain
// also encodes whether this entry _itself_ is part of the free list by changing sign and subtracting 3,
// so -2 means end of free list, -3 means index 0 but on free list, -4 means index 1 but on free list, etc.
public int next;
public uint hashCode;
public TKey key; // Key of entry
public TValue value; // Value of entry
}
private int[]? _buckets;
private Entry[]? _entries;
private int _count;
private int _freeList;
private int _freeCount;
private int _version;
private IEqualityComparer<TKey>? _comparer;
private KeyCollection? _keys;
private ValueCollection? _values;
private const int StartOfFreeList = -3;
// constants for serialization
private const string VersionName = "Version"; // Do not rename (binary serialization)
private const string HashSizeName = "HashSize"; // Do not rename (binary serialization). Must save buckets.Length
private const string KeyValuePairsName = "KeyValuePairs"; // Do not rename (binary serialization)
private const string ComparerName = "Comparer"; // Do not rename (binary serialization)
public Dictionary() : this(0, null) { }
public Dictionary(int capacity) : this(capacity, null) { }
public Dictionary(IEqualityComparer<TKey>? comparer) : this(0, comparer) { }
public Dictionary(int capacity, IEqualityComparer<TKey>? comparer)
{
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
if (capacity > 0) Initialize(capacity);
if (comparer != EqualityComparer<TKey>.Default)
{
_comparer = comparer;
}
if (typeof(TKey) == typeof(string) && _comparer == null)
{
// To start, move off default comparer for string which is randomised
_comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default;
}
}
public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { }
public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey>? comparer) :
this(dictionary != null ? dictionary.Count : 0, comparer)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
// It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case,
// avoid the enumerator allocation and overhead by looping through the entries array directly.
// We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain
// back-compat with subclasses that may have overridden the enumerator behavior.
if (dictionary.GetType() == typeof(Dictionary<TKey, TValue>))
{
Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary;
int count = d._count;
Entry[]? entries = d._entries;
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1)
{
Add(entries[i].key, entries[i].value);
}
}
return;
}
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
Add(pair.Key, pair.Value);
}
}
public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(collection, null) { }
public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey>? comparer) :
this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
foreach (KeyValuePair<TKey, TValue> pair in collection)
{
Add(pair.Key, pair.Value);
}
}
protected Dictionary(SerializationInfo info, StreamingContext context)
{
// We can't do anything with the keys and values until the entire graph has been deserialized
// and we have a resonable estimate that GetHashCode is not going to fail. For the time being,
// we'll just cache this. The graph is not valid until OnDeserialization has been called.
HashHelpers.SerializationInfoTable.Add(this, info);
}
public IEqualityComparer<TKey> Comparer =>
(_comparer == null || _comparer is NonRandomizedStringEqualityComparer) ?
EqualityComparer<TKey>.Default :
_comparer;
public int Count => _count - _freeCount;
public KeyCollection Keys => _keys ??= new KeyCollection(this);
ICollection<TKey> IDictionary<TKey, TValue>.Keys => _keys ??= new KeyCollection(this);
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => _keys ??= new KeyCollection(this);
public ValueCollection Values => _values ??= new ValueCollection(this);
ICollection<TValue> IDictionary<TKey, TValue>.Values => _values ??= new ValueCollection(this);
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => _values ??= new ValueCollection(this);
public TValue this[TKey key]
{
get
{
int i = FindEntry(key);
if (i >= 0) return _entries![i].value;
ThrowHelper.ThrowKeyNotFoundException(key);
return default;
}
set
{
bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting);
Debug.Assert(modified);
}
}
public void Add(TKey key, TValue value)
{
bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting);
Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown.
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
=> Add(keyValuePair.Key, keyValuePair.Value);
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
int i = FindEntry(keyValuePair.Key);
if (i >= 0 && EqualityComparer<TValue>.Default.Equals(_entries![i].value, keyValuePair.Value))
{
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
int i = FindEntry(keyValuePair.Key);
if (i >= 0 && EqualityComparer<TValue>.Default.Equals(_entries![i].value, keyValuePair.Value))
{
Remove(keyValuePair.Key);
return true;
}
return false;
}
public void Clear()
{
int count = _count;
if (count > 0)
{
Debug.Assert(_buckets != null, "_buckets should be non-null");
Debug.Assert(_entries != null, "_entries should be non-null");
Array.Clear(_buckets, 0, _buckets.Length);
_count = 0;
_freeList = -1;
_freeCount = 0;
Array.Clear(_entries, 0, count);
}
}
public bool ContainsKey(TKey key)
=> FindEntry(key) >= 0;
public bool ContainsValue(TValue value)
{
Entry[]? entries = _entries;
if (value == null)
{
for (int i = 0; i < _count; i++)
{
if (entries![i].next >= -1 && entries[i].value == null) return true;
}
}
else
{
if (default(TValue)! != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
{
// ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
for (int i = 0; i < _count; i++)
{
if (entries![i].next >= -1 && EqualityComparer<TValue>.Default.Equals(entries[i].value, value)) return true;
}
}
else
{
// Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// https://github.com/dotnet/coreclr/issues/17273
// So cache in a local rather than get EqualityComparer per loop iteration
EqualityComparer<TValue> defaultComparer = EqualityComparer<TValue>.Default;
for (int i = 0; i < _count; i++)
{
if (entries![i].next >= -1 && defaultComparer.Equals(entries[i].value, value)) return true;
}
}
}
return false;
}
private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if ((uint)index > (uint)array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = _count;
Entry[]? entries = _entries;
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1)
{
array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
public Enumerator GetEnumerator()
=> new Enumerator(this, Enumerator.KeyValuePair);
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
=> new Enumerator(this, Enumerator.KeyValuePair);
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
}
info.AddValue(VersionName, _version);
info.AddValue(ComparerName, _comparer ?? EqualityComparer<TKey>.Default, typeof(IEqualityComparer<TKey>));
info.AddValue(HashSizeName, _buckets == null ? 0 : _buckets.Length); // This is the length of the bucket array
if (_buckets != null)
{
var array = new KeyValuePair<TKey, TValue>[Count];
CopyTo(array, 0);
info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[]));
}
}
private int FindEntry(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
int i = -1;
int[]? buckets = _buckets;
Entry[]? entries = _entries;
int collisionCount = 0;
if (buckets != null)
{
Debug.Assert(entries != null, "expected entries to be != null");
IEqualityComparer<TKey>? comparer = _comparer;
if (comparer == null)
{
uint hashCode = (uint)key.GetHashCode();
// Value in _buckets is 1-based
i = buckets[hashCode % (uint)buckets.Length] - 1;
if (default(TKey)! != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
{
// ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
while (true)
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test in if to drop range check for following array access
if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key)))
{
break;
}
i = entries[i].next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
}
}
else
{
// Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// https://github.com/dotnet/coreclr/issues/17273
// So cache in a local rather than get EqualityComparer per loop iteration
EqualityComparer<TKey> defaultComparer = EqualityComparer<TKey>.Default;
while (true)
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test in if to drop range check for following array access
if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && defaultComparer.Equals(entries[i].key, key)))
{
break;
}
i = entries[i].next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
}
}
}
else
{
uint hashCode = (uint)comparer.GetHashCode(key);
// Value in _buckets is 1-based
i = buckets[hashCode % (uint)buckets.Length] - 1;
while (true)
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test in if to drop range check for following array access
if ((uint)i >= (uint)entries.Length ||
(entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)))
{
break;
}
i = entries[i].next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
}
}
}
return i;
}
private int Initialize(int capacity)
{
int size = HashHelpers.GetPrime(capacity);
_freeList = -1;
_buckets = new int[size];
_entries = new Entry[size];
return size;
}
private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (_buckets == null)
{
Initialize(0);
}
Debug.Assert(_buckets != null);
Entry[]? entries = _entries;
Debug.Assert(entries != null, "expected entries to be non-null");
IEqualityComparer<TKey>? comparer = _comparer;
uint hashCode = (uint)((comparer == null) ? key.GetHashCode() : comparer.GetHashCode(key));
int collisionCount = 0;
ref int bucket = ref _buckets[hashCode % (uint)_buckets.Length];
// Value in _buckets is 1-based
int i = bucket - 1;
if (comparer == null)
{
if (default(TKey)! != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
{
// ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
while (true)
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test uint in if rather than loop condition to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
break;
}
if (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
_version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
i = entries[i].next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
}
}
else
{
// Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// https://github.com/dotnet/coreclr/issues/17273
// So cache in a local rather than get EqualityComparer per loop iteration
EqualityComparer<TKey> defaultComparer = EqualityComparer<TKey>.Default;
while (true)
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test uint in if rather than loop condition to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
break;
}
if (entries[i].hashCode == hashCode && defaultComparer.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
_version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
i = entries[i].next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
}
}
}
else
{
while (true)
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test uint in if rather than loop condition to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
break;
}
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
_version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
i = entries[i].next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
}
}
bool updateFreeList = false;
int index;
if (_freeCount > 0)
{
index = _freeList;
updateFreeList = true;
_freeCount--;
}
else
{
int count = _count;
if (count == entries.Length)
{
Resize();
bucket = ref _buckets[hashCode % (uint)_buckets.Length];
}
index = count;
_count = count + 1;
entries = _entries;
}
ref Entry entry = ref entries![index];
if (updateFreeList)
{
Debug.Assert((StartOfFreeList - entries[_freeList].next) >= -1, "shouldn't overflow because `next` cannot underflow");
_freeList = StartOfFreeList - entries[_freeList].next;
}
entry.hashCode = hashCode;
// Value in _buckets is 1-based
entry.next = bucket - 1;
entry.key = key;
entry.value = value;
// Value in _buckets is 1-based
bucket = index + 1;
_version++;
// Value types never rehash
if (default(TKey)! == null && collisionCount > HashHelpers.HashCollisionThreshold && comparer is NonRandomizedStringEqualityComparer) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
{
// If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
// i.e. EqualityComparer<string>.Default.
_comparer = null;
Resize(entries.Length, true);
}
return true;
}
public virtual void OnDeserialization(object? sender)
{
HashHelpers.SerializationInfoTable.TryGetValue(this, out SerializationInfo? siInfo);
if (siInfo == null)
{
// We can return immediately if this function is called twice.
// Note we remove the serialization info from the table at the end of this method.
return;
}
int realVersion = siInfo.GetInt32(VersionName);
int hashsize = siInfo.GetInt32(HashSizeName);
_comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>))!; // When serialized if comparer is null, we use the default.
if (hashsize != 0)
{
Initialize(hashsize);
KeyValuePair<TKey, TValue>[]? array = (KeyValuePair<TKey, TValue>[]?)
siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[]));
if (array == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys);
}
for (int i = 0; i < array.Length; i++)
{
if (array[i].Key == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
}
Add(array[i].Key, array[i].Value);
}
}
else
{
_buckets = null;
}
_version = realVersion;
HashHelpers.SerializationInfoTable.Remove(this);
}
private void Resize()
=> Resize(HashHelpers.ExpandPrime(_count), false);
private void Resize(int newSize, bool forceNewHashCodes)
{
// Value types never rehash
Debug.Assert(!forceNewHashCodes || default(TKey)! == null); // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
Debug.Assert(_entries != null, "_entries should be non-null");
Debug.Assert(newSize >= _entries.Length);
int[] buckets = new int[newSize];
Entry[] entries = new Entry[newSize];
int count = _count;
Array.Copy(_entries, 0, entries, 0, count);
if (default(TKey)! == null && forceNewHashCodes) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
{
for (int i = 0; i < count; i++)
{
if (entries[i].next >= -1)
{
Debug.Assert(_comparer == null);
entries[i].hashCode = (uint)entries[i].key.GetHashCode();
}
}
}
for (int i = 0; i < count; i++)
{
if (entries[i].next >= -1)
{
uint bucket = entries[i].hashCode % (uint)newSize;
// Value in _buckets is 1-based
entries[i].next = buckets[bucket] - 1;
// Value in _buckets is 1-based
buckets[bucket] = i + 1;
}
}
_buckets = buckets;
_entries = entries;
}
// The overload Remove(TKey key, out TValue value) is a copy of this method with one additional
// statement to copy the value for entry being removed into the output parameter.
// Code has been intentionally duplicated for performance reasons.
public bool Remove(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
int[]? buckets = _buckets;
Entry[]? entries = _entries;
int collisionCount = 0;
if (buckets != null)
{
Debug.Assert(entries != null, "entries should be non-null");
uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode());
uint bucket = hashCode % (uint)buckets.Length;
int last = -1;
// Value in buckets is 1-based
int i = buckets[bucket] - 1;
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key)))
{
if (last < 0)
{
// Value in buckets is 1-based
buckets[bucket] = entry.next + 1;
}
else
{
entries[last].next = entry.next;
}
Debug.Assert((StartOfFreeList - _freeList) < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646");
entry.next = StartOfFreeList - _freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
entry.key = default!;
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
entry.value = default!;
}
_freeList = i;
_freeCount++;
return true;
}
last = i;
i = entry.next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
}
}
return false;
}
// This overload is a copy of the overload Remove(TKey key) with one additional
// statement to copy the value for entry being removed into the output parameter.
// Code has been intentionally duplicated for performance reasons.
public bool Remove(TKey key, [MaybeNullWhen(false)] out TValue value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
int[]? buckets = _buckets;
Entry[]? entries = _entries;
int collisionCount = 0;
if (buckets != null)
{
Debug.Assert(entries != null, "entries should be non-null");
uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode());
uint bucket = hashCode % (uint)buckets.Length;
int last = -1;
// Value in buckets is 1-based
int i = buckets[bucket] - 1;
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key)))
{
if (last < 0)
{
// Value in buckets is 1-based
buckets[bucket] = entry.next + 1;
}
else
{
entries[last].next = entry.next;
}
value = entry.value;
Debug.Assert((StartOfFreeList - _freeList) < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646");
entry.next = StartOfFreeList - _freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
entry.key = default!;
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
entry.value = default!;
}
_freeList = i;
_freeCount++;
return true;
}
last = i;
i = entry.next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
}
}
value = default!;
return false;
}
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
{
int i = FindEntry(key);
if (i >= 0)
{
value = _entries![i].value;
return true;
}
value = default!;
return false;
}
public bool TryAdd(TKey key, TValue value)
=> TryInsert(key, value, InsertionBehavior.None);
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => false;
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
=> CopyTo(array, index);
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (array.Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
if (array.GetLowerBound(0) != 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
if ((uint)index > (uint)array.Length)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (array.Length - index < Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
if (array is KeyValuePair<TKey, TValue>[] pairs)
{
CopyTo(pairs, index);
}
else if (array is DictionaryEntry[] dictEntryArray)
{
Entry[]? entries = _entries;
for (int i = 0; i < _count; i++)
{
if (entries![i].next >= -1)
{
dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value);
}
}
}
else
{
object[]? objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try
{
int count = _count;
Entry[]? entries = _entries;
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1)
{
objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(this, Enumerator.KeyValuePair);
/// <summary>
/// Ensures that the dictionary can hold up to 'capacity' entries without any further expansion of its backing storage
/// </summary>
public int EnsureCapacity(int capacity)
{
if (capacity < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
int currentCapacity = _entries == null ? 0 : _entries.Length;
if (currentCapacity >= capacity)
return currentCapacity;
_version++;
if (_buckets == null)
return Initialize(capacity);
int newSize = HashHelpers.GetPrime(capacity);
Resize(newSize, forceNewHashCodes: false);
return newSize;
}
/// <summary>
/// Sets the capacity of this dictionary to what it would be if it had been originally initialized with all its entries
///
/// This method can be used to minimize the memory overhead
/// once it is known that no new elements will be added.
///
/// To allocate minimum size storage array, execute the following statements:
///
/// dictionary.Clear();
/// dictionary.TrimExcess();
/// </summary>
public void TrimExcess()
=> TrimExcess(Count);
/// <summary>
/// Sets the capacity of this dictionary to hold up 'capacity' entries without any further expansion of its backing storage
///
/// This method can be used to minimize the memory overhead
/// once it is known that no new elements will be added.
/// </summary>
public void TrimExcess(int capacity)
{
if (capacity < Count)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
int newSize = HashHelpers.GetPrime(capacity);
Entry[]? oldEntries = _entries;
int currentCapacity = oldEntries == null ? 0 : oldEntries.Length;
if (newSize >= currentCapacity)
return;
int oldCount = _count;
_version++;
Initialize(newSize);
Entry[]? entries = _entries;
int[]? buckets = _buckets;
int count = 0;
for (int i = 0; i < oldCount; i++)
{
uint hashCode = oldEntries![i].hashCode; // At this point, we know we have entries.
if (oldEntries[i].next >= -1)
{
ref Entry entry = ref entries![count];
entry = oldEntries[i];
uint bucket = hashCode % (uint)newSize;
// Value in _buckets is 1-based
entry.next = buckets![bucket] - 1; // If we get here, we have entries, therefore buckets is not null.
// Value in _buckets is 1-based
buckets[bucket] = count + 1;
count++;
}
}
_count = count;
_freeCount = 0;
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => this;
bool IDictionary.IsFixedSize => false;
bool IDictionary.IsReadOnly => false;
ICollection IDictionary.Keys => (ICollection)Keys;
ICollection IDictionary.Values => (ICollection)Values;
object? IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
int i = FindEntry((TKey)key);
if (i >= 0)
{
return _entries![i].value;
}
}
return null;
}
set
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try
{
TKey tempKey = (TKey)key;
try
{
this[tempKey] = (TValue)value!;
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return key is TKey;
}
void IDictionary.Add(object key, object? value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try
{
TKey tempKey = (TKey)key;
try
{
Add(tempKey, (TValue)value!);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
bool IDictionary.Contains(object key)
{
if (IsCompatibleKey(key))
{
return ContainsKey((TKey)key);
}
return false;
}
IDictionaryEnumerator IDictionary.GetEnumerator()
=> new Enumerator(this, Enumerator.DictEntry);
void IDictionary.Remove(object key)
{
if (IsCompatibleKey(key))
{
Remove((TKey)key);
}
}
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>,
IDictionaryEnumerator
{
private readonly Dictionary<TKey, TValue> _dictionary;
private readonly int _version;
private int _index;
private KeyValuePair<TKey, TValue> _current;
private readonly int _getEnumeratorRetType; // What should Enumerator.Current return?
internal const int DictEntry = 1;
internal const int KeyValuePair = 2;
internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_getEnumeratorRetType = getEnumeratorRetType;
_current = new KeyValuePair<TKey, TValue>();
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is int.MaxValue
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries![_index++];
if (entry.next >= -1)
{
_current = new KeyValuePair<TKey, TValue>(entry.key, entry.value);
return true;
}
}
_index = _dictionary._count + 1;
_current = new KeyValuePair<TKey, TValue>();
return false;
}
public KeyValuePair<TKey, TValue> Current => _current;
public void Dispose()
{
}
object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
if (_getEnumeratorRetType == DictEntry)
{
return new DictionaryEntry(_current.Key, _current.Value);
}
else
{
return new KeyValuePair<TKey, TValue>(_current.Key, _current.Value);
}
}
}
void IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_current = new KeyValuePair<TKey, TValue>();
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return new DictionaryEntry(_current.Key, _current.Value);
}
}
object IDictionaryEnumerator.Key
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _current.Key;
}
}
object? IDictionaryEnumerator.Value
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _current.Value;
}
}
}
[DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private readonly Dictionary<TKey, TValue> _dictionary;
public KeyCollection(Dictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
=> new Enumerator(_dictionary);
public void CopyTo(TKey[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < _dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = _dictionary._count;
Entry[]? entries = _dictionary._entries;
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1) array[index++] = entries[i].key;
}
}
public int Count => _dictionary.Count;
bool ICollection<TKey>.IsReadOnly => true;
void ICollection<TKey>.Add(TKey item)
=> ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
void ICollection<TKey>.Clear()
=> ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
bool ICollection<TKey>.Contains(TKey item)
=> _dictionary.ContainsKey(item);
bool ICollection<TKey>.Remove(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
return false;
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
=> new Enumerator(_dictionary);
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(_dictionary);
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (array.Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
if (array.GetLowerBound(0) != 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
if ((uint)index > (uint)array.Length)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (array.Length - index < _dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
if (array is TKey[] keys)
{
CopyTo(keys, index);
}
else
{
object[]? objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = _dictionary._count;
Entry[]? entries = _dictionary._entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1) objects[index++] = entries[i].key;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot;
public struct Enumerator : IEnumerator<TKey>, IEnumerator
{
private readonly Dictionary<TKey, TValue> _dictionary;
private int _index;
private readonly int _version;
[AllowNull, MaybeNull] private TKey _currentKey;
internal Enumerator(Dictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_currentKey = default;
}
public void Dispose()
{
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries![_index++];
if (entry.next >= -1)
{
_currentKey = entry.key;
return true;
}
}
_index = _dictionary._count + 1;
_currentKey = default;
return false;
}
public TKey Current => _currentKey!;
object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _currentKey;
}
}
void IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_currentKey = default;
}
}
}
[DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private readonly Dictionary<TKey, TValue> _dictionary;
public ValueCollection(Dictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
=> new Enumerator(_dictionary);
public void CopyTo(TValue[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if ((uint)index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < _dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = _dictionary._count;
Entry[]? entries = _dictionary._entries;
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1) array[index++] = entries[i].value;
}
}
public int Count => _dictionary.Count;
bool ICollection<TValue>.IsReadOnly => true;
void ICollection<TValue>.Add(TValue item)
=> ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
bool ICollection<TValue>.Remove(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
return false;
}
void ICollection<TValue>.Clear()
=> ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
bool ICollection<TValue>.Contains(TValue item)
=> _dictionary.ContainsValue(item);
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
=> new Enumerator(_dictionary);
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(_dictionary);
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (array.Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
if (array.GetLowerBound(0) != 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
if ((uint)index > (uint)array.Length)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (array.Length - index < _dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
if (array is TValue[] values)
{
CopyTo(values, index);
}
else
{
object[]? objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = _dictionary._count;
Entry[]? entries = _dictionary._entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1) objects[index++] = entries[i].value!;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot;
public struct Enumerator : IEnumerator<TValue>, IEnumerator
{
private readonly Dictionary<TKey, TValue> _dictionary;
private int _index;
private readonly int _version;
[AllowNull, MaybeNull] private TValue _currentValue;
internal Enumerator(Dictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_currentValue = default;
}
public void Dispose()
{
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries![_index++];
if (entry.next >= -1)
{
_currentValue = entry.value;
return true;
}
}
_index = _dictionary._count + 1;
_currentValue = default;
return false;
}
public TValue Current => _currentValue!;
object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _currentValue;
}
}
void IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_currentValue = default;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading;
using System.Diagnostics;
using System.Collections;
using System.Threading.Tasks;
namespace System.Net
{
// LazyAsyncResult - Base class for all IAsyncResult classes that want to take advantage of
// lazily-allocated event handles.
internal class LazyAsyncResult : IAsyncResult
{
private const int HighBit = unchecked((int)0x80000000);
private const int ForceAsyncCount = 50;
// This is to avoid user mistakes when they queue another async op from a callback the completes sync.
[ThreadStatic]
private static ThreadContext s_threadContext;
private static ThreadContext CurrentThreadContext
{
get
{
ThreadContext threadContext = s_threadContext;
if (threadContext == null)
{
threadContext = new ThreadContext();
s_threadContext = threadContext;
}
return threadContext;
}
}
private class ThreadContext
{
internal int _nestedIOCount;
}
#if DEBUG
internal object _debugAsyncChain = null; // Optionally used to track chains of async calls.
private bool _protectState; // Used by ContextAwareResult to prevent some calls.
#endif
private object _asyncObject; // Caller's async object.
private object _asyncState; // Caller's state object.
private AsyncCallback _asyncCallback; // Caller's callback method.
private object _result; // Final IO result to be returned byt the End*() method.
private int _errorCode; // Win32 error code for Win32 IO async calls (that want to throw).
private int _intCompleted; // Sign bit indicates synchronous completion if set.
// Remaining bits count the number of InvokeCallbak() calls.
private bool _endCalled; // True if the user called the End*() method.
private bool _userEvent; // True if the event has been (or is about to be) handed to the user
private object _event; // Lazy allocated event to be returned in the IAsyncResult for the client to wait on.
internal LazyAsyncResult(object myObject, object myState, AsyncCallback myCallBack)
{
_asyncObject = myObject;
_asyncState = myState;
_asyncCallback = myCallBack;
_result = DBNull.Value;
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::.ctor()");
}
}
// Allows creating a pre-completed result with less interlockeds. Beware! Constructor calls the callback.
// If a derived class ever uses this and overloads Cleanup, this may need to change.
internal LazyAsyncResult(object myObject, object myState, AsyncCallback myCallBack, object result)
{
bool globalLogEnabled = GlobalLog.IsEnabled;
if (result == DBNull.Value && globalLogEnabled)
{
GlobalLog.AssertFormat("LazyAsyncResult#{0}::.ctor()|Result can't be set to DBNull - it's a special internal value.", LoggingHash.HashString(this));
}
_asyncObject = myObject;
_asyncState = myState;
_asyncCallback = myCallBack;
_result = result;
_intCompleted = 1;
if (_asyncCallback != null)
{
if (globalLogEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() invoking callback");
}
_asyncCallback(this);
}
else if (globalLogEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() no callback to invoke");
}
if (globalLogEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::.ctor() (pre-completed)");
}
}
// Interface method to return the original async object.
internal object AsyncObject
{
get
{
return _asyncObject;
}
}
// Interface method to return the caller's state object.
public object AsyncState
{
get
{
return _asyncState;
}
}
protected AsyncCallback AsyncCallback
{
get
{
return _asyncCallback;
}
set
{
_asyncCallback = value;
}
}
// Interface property to return a WaitHandle that can be waited on for I/O completion.
//
// This property implements lazy event creation.
//
// If this is used, the event cannot be disposed because it is under the control of the
// application. Internal should use InternalWaitForCompletion instead - never AsyncWaitHandle.
public WaitHandle AsyncWaitHandle
{
get
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_AsyncWaitHandle()");
}
#if DEBUG
// Can't be called when state is protected.
if (_protectState)
{
throw new InvalidOperationException("get_AsyncWaitHandle called in protected state");
}
#endif
ManualResetEvent asyncEvent;
// Indicates that the user has seen the event; it can't be disposed.
_userEvent = true;
// The user has access to this object. Lock-in CompletedSynchronously.
if (_intCompleted == 0)
{
Interlocked.CompareExchange(ref _intCompleted, HighBit, 0);
}
// Because InternalWaitForCompletion() tries to dispose this event, it's
// possible for _event to become null immediately after being set, but only if
// IsCompleted has become true. Therefore it's possible for this property
// to give different (set) events to different callers when IsCompleted is true.
asyncEvent = (ManualResetEvent)_event;
while (asyncEvent == null)
{
LazilyCreateEvent(out asyncEvent);
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_AsyncWaitHandle() _event:" + LoggingHash.HashString(_event));
}
return asyncEvent;
}
}
// Returns true if this call created the event.
// May return with a null handle. That means it thought it got one, but it was disposed in the mean time.
private bool LazilyCreateEvent(out ManualResetEvent waitHandle)
{
waitHandle = new ManualResetEvent(false);
try
{
if (Interlocked.CompareExchange(ref _event, waitHandle, null) == null)
{
if (InternalPeekCompleted)
{
waitHandle.Set();
}
return true;
}
else
{
waitHandle.Dispose();
waitHandle = (ManualResetEvent)_event;
// There's a chance here that _event became null. But the only way is if another thread completed
// in InternalWaitForCompletion and disposed it. If we're in InternalWaitForCompletion, we now know
// IsCompleted is set, so we can avoid the wait when waitHandle comes back null. AsyncWaitHandle
// will try again in this case.
return false;
}
}
catch
{
// This should be very rare, but doing this will reduce the chance of deadlock.
_event = null;
if (waitHandle != null)
{
waitHandle.Dispose();
}
throw;
}
}
// This allows ContextAwareResult to not let anyone trigger the CompletedSynchronously tripwire while the context is being captured.
[Conditional("DEBUG")]
protected void DebugProtectState(bool protect)
{
#if DEBUG
_protectState = protect;
#endif
}
// Interface property, returning synchronous completion status.
public bool CompletedSynchronously
{
get
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_CompletedSynchronously()");
}
#if DEBUG
// Can't be called when state is protected.
if (_protectState)
{
throw new InvalidOperationException("get_CompletedSynchronously called in protected state");
}
#endif
// If this returns greater than zero, it means it was incremented by InvokeCallback before anyone ever saw it.
int result = _intCompleted;
if (result == 0)
{
result = Interlocked.CompareExchange(ref _intCompleted, HighBit, 0);
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_CompletedSynchronously() returns: " + ((result > 0) ? "true" : "false"));
}
return result > 0;
}
}
// Interface property, returning completion status.
public bool IsCompleted
{
get
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_IsCompleted()");
}
#if DEBUG
// Can't be called when state is protected.
if (_protectState)
{
throw new InvalidOperationException("get_IsCompleted called in protected state");
}
#endif
// Verify low bits to see if it's been incremented. If it hasn't, set the high bit
// to show that it's been looked at.
int result = _intCompleted;
if (result == 0)
{
result = Interlocked.CompareExchange(ref _intCompleted, HighBit, 0);
}
return (result & ~HighBit) != 0;
}
}
// Use to see if something's completed without fixing CompletedSynchronously.
internal bool InternalPeekCompleted
{
get
{
return (_intCompleted & ~HighBit) != 0;
}
}
// Internal property for setting the IO result.
internal object Result
{
get
{
return _result == DBNull.Value ? null : _result;
}
set
{
// Ideally this should never be called, since setting
// the result object really makes sense when the IO completes.
//
// But if the result was set here (as a preemptive error or for some other reason),
// then the "result" parameter passed to InvokeCallback() will be ignored.
// It's an error to call after the result has been completed or with DBNull.
if (GlobalLog.IsEnabled)
{
if (value == DBNull.Value)
{
GlobalLog.AssertFormat("LazyAsyncResult#{0}::set_Result()|Result can't be set to DBNull - it's a special internal value.", LoggingHash.HashString(this));
}
if (InternalPeekCompleted)
{
GlobalLog.AssertFormat("LazyAsyncResult#{0}::set_Result()|Called on completed result.", LoggingHash.HashString(this));
}
}
_result = value;
}
}
internal bool EndCalled
{
get
{
return _endCalled;
}
set
{
_endCalled = value;
}
}
// Internal property for setting the Win32 IO async error code.
internal int ErrorCode
{
get
{
return _errorCode;
}
set
{
_errorCode = value;
}
}
// A method for completing the IO with a result and invoking the user's callback.
// Used by derived classes to pass context into an overridden Complete(). Useful
// for determining the 'winning' thread in case several may simultaneously call
// the equivalent of InvokeCallback().
protected void ProtectedInvokeCallback(object result, IntPtr userToken)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::ProtectedInvokeCallback() result = " +
(result is Exception ? ((Exception)result).Message : result == null ? "<null>" : result.ToString()) +
", userToken:" + userToken.ToString());
}
// Critical to disallow DBNull here - it could result in a stuck spinlock in WaitForCompletion.
if (result == DBNull.Value)
{
throw new ArgumentNullException("result");
}
#if DEBUG
// Always safe to ask for the state now.
_protectState = false;
#endif
if ((_intCompleted & ~HighBit) == 0 && (Interlocked.Increment(ref _intCompleted) & ~HighBit) == 1)
{
// DBNull.Value is used to guarantee that the first caller wins,
// even if the result was set to null.
if (_result == DBNull.Value)
{
_result = result;
}
ManualResetEvent asyncEvent = (ManualResetEvent)_event;
if (asyncEvent != null)
{
try
{
asyncEvent.Set();
}
catch (ObjectDisposedException)
{
// Simply ignore this exception - There is apparently a rare race condition
// where the event is disposed before the completion method is called.
}
}
Complete(userToken);
}
}
// Completes the IO with a result and invoking the user's callback.
internal void InvokeCallback(object result)
{
ProtectedInvokeCallback(result, IntPtr.Zero);
}
// Completes the IO without a result and invoking the user's callback.
internal void InvokeCallback()
{
ProtectedInvokeCallback(null, IntPtr.Zero);
}
// NOTE: THIS METHOD MUST NOT BE CALLED DIRECTLY.
//
// This method does the callback's job and is guaranteed to be called exactly once.
// A derived overriding method must call the base class somewhere or the completion is lost.
protected virtual void Complete(IntPtr userToken)
{
bool offloaded = false;
ThreadContext threadContext = CurrentThreadContext;
try
{
bool globalLogEnabled = GlobalLog.IsEnabled;
++threadContext._nestedIOCount;
if (_asyncCallback != null)
{
if (globalLogEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() invoking callback");
}
if (threadContext._nestedIOCount >= ForceAsyncCount)
{
if (globalLogEnabled)
{
GlobalLog.Print("LazyAsyncResult::Complete *** OFFLOADED the user callback ***");
}
Task.Factory.StartNew(
s => WorkerThreadComplete(s),
this,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
offloaded = true;
}
else
{
_asyncCallback(this);
}
}
else if (globalLogEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() no callback to invoke");
}
}
finally
{
--threadContext._nestedIOCount;
// Never call this method unless interlocked _intCompleted check has succeeded (like in this case).
if (!offloaded)
{
Cleanup();
}
}
}
// Only called by the above method.
private static void WorkerThreadComplete(object state)
{
Debug.Assert(state is LazyAsyncResult);
LazyAsyncResult thisPtr = (LazyAsyncResult)state;
try
{
thisPtr._asyncCallback(thisPtr);
}
finally
{
thisPtr.Cleanup();
}
}
// Custom instance cleanup method.
//
// Derived types override this method to release unmanaged resources associated with an IO request.
protected virtual void Cleanup()
{
}
internal object InternalWaitForCompletion()
{
return WaitForCompletion(true);
}
private object WaitForCompletion(bool snap)
{
ManualResetEvent waitHandle = null;
bool createdByMe = false;
bool complete = snap ? IsCompleted : InternalPeekCompleted;
if (!complete)
{
// Not done yet, so wait:
waitHandle = (ManualResetEvent)_event;
if (waitHandle == null)
{
createdByMe = LazilyCreateEvent(out waitHandle);
}
}
if (waitHandle != null)
{
try
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::InternalWaitForCompletion() Waiting for completion _event#" + LoggingHash.HashString(waitHandle));
}
waitHandle.WaitOne(Timeout.Infinite);
}
catch (ObjectDisposedException)
{
// This can occur if this method is called from two different threads.
// This possibility is the trade-off for not locking.
}
finally
{
// We also want to dispose the event although we can't unless we did wait on it here.
if (createdByMe && !_userEvent)
{
// Does _userEvent need to be volatile (or _event set via Interlocked) in order
// to avoid giving a user a disposed event?
ManualResetEvent oldEvent = (ManualResetEvent)_event;
_event = null;
if (!_userEvent)
{
oldEvent.Dispose();
}
}
}
}
// A race condition exists because InvokeCallback sets _intCompleted before _result (so that _result
// can benefit from the synchronization of _intCompleted). That means you can get here before _result got
// set (although rarely - once every eight hours of stress). Handle that case with a spin-lock.
SpinWait sw = new SpinWait();
while (_result == DBNull.Value)
{
sw.SpinOnce();
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::InternalWaitForCompletion() done: " +
(_result is Exception ? ((Exception)_result).Message : _result == null ? "<null>" : _result.ToString()));
}
return _result;
}
// A general interface that is called to release unmanaged resources associated with the class.
// It completes the result but doesn't do any of the notifications.
internal void InternalCleanup()
{
if ((_intCompleted & ~HighBit) == 0 && (Interlocked.Increment(ref _intCompleted) & ~HighBit) == 1)
{
// Set no result so that just in case there are waiters, they don't hang in the spin lock.
_result = null;
Cleanup();
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.OsConfig.V1Alpha.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedOsConfigZonalServiceClientTest
{
[xunit::FactAttribute]
public void GetOSPolicyAssignmentRequestObject()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
};
OSPolicyAssignment expectedResponse = new OSPolicyAssignment
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
Description = "description2cf9da67",
OsPolicies = { new OSPolicy(), },
InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(),
Rollout = new OSPolicyAssignment.Types.Rollout(),
RevisionId = "revision_id8d9ae05d",
RevisionCreateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling,
Baseline = false,
Deleted = true,
Reconciling = false,
Uid = "uida2d37198",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignment response = client.GetOSPolicyAssignment(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOSPolicyAssignmentRequestObjectAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
};
OSPolicyAssignment expectedResponse = new OSPolicyAssignment
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
Description = "description2cf9da67",
OsPolicies = { new OSPolicy(), },
InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(),
Rollout = new OSPolicyAssignment.Types.Rollout(),
RevisionId = "revision_id8d9ae05d",
RevisionCreateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling,
Baseline = false,
Deleted = true,
Reconciling = false,
Uid = "uida2d37198",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignment responseCallSettings = await client.GetOSPolicyAssignmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
OSPolicyAssignment responseCancellationToken = await client.GetOSPolicyAssignmentAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetOSPolicyAssignment()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
};
OSPolicyAssignment expectedResponse = new OSPolicyAssignment
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
Description = "description2cf9da67",
OsPolicies = { new OSPolicy(), },
InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(),
Rollout = new OSPolicyAssignment.Types.Rollout(),
RevisionId = "revision_id8d9ae05d",
RevisionCreateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling,
Baseline = false,
Deleted = true,
Reconciling = false,
Uid = "uida2d37198",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignment response = client.GetOSPolicyAssignment(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOSPolicyAssignmentAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
};
OSPolicyAssignment expectedResponse = new OSPolicyAssignment
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
Description = "description2cf9da67",
OsPolicies = { new OSPolicy(), },
InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(),
Rollout = new OSPolicyAssignment.Types.Rollout(),
RevisionId = "revision_id8d9ae05d",
RevisionCreateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling,
Baseline = false,
Deleted = true,
Reconciling = false,
Uid = "uida2d37198",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignment responseCallSettings = await client.GetOSPolicyAssignmentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
OSPolicyAssignment responseCancellationToken = await client.GetOSPolicyAssignmentAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetOSPolicyAssignmentResourceNames()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
};
OSPolicyAssignment expectedResponse = new OSPolicyAssignment
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
Description = "description2cf9da67",
OsPolicies = { new OSPolicy(), },
InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(),
Rollout = new OSPolicyAssignment.Types.Rollout(),
RevisionId = "revision_id8d9ae05d",
RevisionCreateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling,
Baseline = false,
Deleted = true,
Reconciling = false,
Uid = "uida2d37198",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignment response = client.GetOSPolicyAssignment(request.OSPolicyAssignmentName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOSPolicyAssignmentResourceNamesAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
};
OSPolicyAssignment expectedResponse = new OSPolicyAssignment
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
Description = "description2cf9da67",
OsPolicies = { new OSPolicy(), },
InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(),
Rollout = new OSPolicyAssignment.Types.Rollout(),
RevisionId = "revision_id8d9ae05d",
RevisionCreateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling,
Baseline = false,
Deleted = true,
Reconciling = false,
Uid = "uida2d37198",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignment responseCallSettings = await client.GetOSPolicyAssignmentAsync(request.OSPolicyAssignmentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
OSPolicyAssignment responseCancellationToken = await client.GetOSPolicyAssignmentAsync(request.OSPolicyAssignmentName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInstanceOSPoliciesComplianceRequestObject()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
#pragma warning disable CS0612
GetInstanceOSPoliciesComplianceRequest request = new GetInstanceOSPoliciesComplianceRequest
#pragma warning restore CS0612
{
#pragma warning disable CS0612
InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
#pragma warning restore CS0612
};
#pragma warning disable CS0612
InstanceOSPoliciesCompliance expectedResponse = new InstanceOSPoliciesCompliance
#pragma warning restore CS0612
{
#pragma warning disable CS0612
InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Instance = "instance99a62371",
State = OSPolicyComplianceState.Unknown,
DetailedState = "detailed_state6d8e814a",
DetailedStateReason = "detailed_state_reason493b0c87",
OsPolicyCompliances =
#pragma warning restore CS0612
{
#pragma warning disable CS0612
new InstanceOSPoliciesCompliance.Types.OSPolicyCompliance(),
#pragma warning restore CS0612
},
#pragma warning disable CS0612
LastComplianceCheckTime = new wkt::Timestamp(),
LastComplianceRunId = "last_compliance_run_id45f5c46a",
#pragma warning restore CS0612
};
mockGrpcClient.Setup(x => x.GetInstanceOSPoliciesCompliance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
#pragma warning disable CS0612
InstanceOSPoliciesCompliance response = client.GetInstanceOSPoliciesCompliance(request);
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInstanceOSPoliciesComplianceRequestObjectAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
#pragma warning disable CS0612
GetInstanceOSPoliciesComplianceRequest request = new GetInstanceOSPoliciesComplianceRequest
#pragma warning restore CS0612
{
#pragma warning disable CS0612
InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
#pragma warning restore CS0612
};
#pragma warning disable CS0612
InstanceOSPoliciesCompliance expectedResponse = new InstanceOSPoliciesCompliance
#pragma warning restore CS0612
{
#pragma warning disable CS0612
InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Instance = "instance99a62371",
State = OSPolicyComplianceState.Unknown,
DetailedState = "detailed_state6d8e814a",
DetailedStateReason = "detailed_state_reason493b0c87",
OsPolicyCompliances =
#pragma warning restore CS0612
{
#pragma warning disable CS0612
new InstanceOSPoliciesCompliance.Types.OSPolicyCompliance(),
#pragma warning restore CS0612
},
#pragma warning disable CS0612
LastComplianceCheckTime = new wkt::Timestamp(),
LastComplianceRunId = "last_compliance_run_id45f5c46a",
#pragma warning restore CS0612
};
#pragma warning disable CS0612
mockGrpcClient.Setup(x => x.GetInstanceOSPoliciesComplianceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceOSPoliciesCompliance>(stt::Task.FromResult(expectedResponse), null, null, null, null));
#pragma warning restore CS0612
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
#pragma warning disable CS0612
InstanceOSPoliciesCompliance responseCallSettings = await client.GetInstanceOSPoliciesComplianceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, responseCallSettings);
#pragma warning disable CS0612
InstanceOSPoliciesCompliance responseCancellationToken = await client.GetInstanceOSPoliciesComplianceAsync(request, st::CancellationToken.None);
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInstanceOSPoliciesCompliance()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
#pragma warning disable CS0612
GetInstanceOSPoliciesComplianceRequest request = new GetInstanceOSPoliciesComplianceRequest
#pragma warning restore CS0612
{
#pragma warning disable CS0612
InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
#pragma warning restore CS0612
};
#pragma warning disable CS0612
InstanceOSPoliciesCompliance expectedResponse = new InstanceOSPoliciesCompliance
#pragma warning restore CS0612
{
#pragma warning disable CS0612
InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Instance = "instance99a62371",
State = OSPolicyComplianceState.Unknown,
DetailedState = "detailed_state6d8e814a",
DetailedStateReason = "detailed_state_reason493b0c87",
OsPolicyCompliances =
#pragma warning restore CS0612
{
#pragma warning disable CS0612
new InstanceOSPoliciesCompliance.Types.OSPolicyCompliance(),
#pragma warning restore CS0612
},
#pragma warning disable CS0612
LastComplianceCheckTime = new wkt::Timestamp(),
LastComplianceRunId = "last_compliance_run_id45f5c46a",
#pragma warning restore CS0612
};
mockGrpcClient.Setup(x => x.GetInstanceOSPoliciesCompliance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
#pragma warning disable CS0612
InstanceOSPoliciesCompliance response = client.GetInstanceOSPoliciesCompliance(request.Name);
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInstanceOSPoliciesComplianceAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
#pragma warning disable CS0612
GetInstanceOSPoliciesComplianceRequest request = new GetInstanceOSPoliciesComplianceRequest
#pragma warning restore CS0612
{
#pragma warning disable CS0612
InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
#pragma warning restore CS0612
};
#pragma warning disable CS0612
InstanceOSPoliciesCompliance expectedResponse = new InstanceOSPoliciesCompliance
#pragma warning restore CS0612
{
#pragma warning disable CS0612
InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Instance = "instance99a62371",
State = OSPolicyComplianceState.Unknown,
DetailedState = "detailed_state6d8e814a",
DetailedStateReason = "detailed_state_reason493b0c87",
OsPolicyCompliances =
#pragma warning restore CS0612
{
#pragma warning disable CS0612
new InstanceOSPoliciesCompliance.Types.OSPolicyCompliance(),
#pragma warning restore CS0612
},
#pragma warning disable CS0612
LastComplianceCheckTime = new wkt::Timestamp(),
LastComplianceRunId = "last_compliance_run_id45f5c46a",
#pragma warning restore CS0612
};
#pragma warning disable CS0612
mockGrpcClient.Setup(x => x.GetInstanceOSPoliciesComplianceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceOSPoliciesCompliance>(stt::Task.FromResult(expectedResponse), null, null, null, null));
#pragma warning restore CS0612
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
#pragma warning disable CS0612
InstanceOSPoliciesCompliance responseCallSettings = await client.GetInstanceOSPoliciesComplianceAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, responseCallSettings);
#pragma warning disable CS0612
InstanceOSPoliciesCompliance responseCancellationToken = await client.GetInstanceOSPoliciesComplianceAsync(request.Name, st::CancellationToken.None);
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInstanceOSPoliciesComplianceResourceNames()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
#pragma warning disable CS0612
GetInstanceOSPoliciesComplianceRequest request = new GetInstanceOSPoliciesComplianceRequest
#pragma warning restore CS0612
{
#pragma warning disable CS0612
InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
#pragma warning restore CS0612
};
#pragma warning disable CS0612
InstanceOSPoliciesCompliance expectedResponse = new InstanceOSPoliciesCompliance
#pragma warning restore CS0612
{
#pragma warning disable CS0612
InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Instance = "instance99a62371",
State = OSPolicyComplianceState.Unknown,
DetailedState = "detailed_state6d8e814a",
DetailedStateReason = "detailed_state_reason493b0c87",
OsPolicyCompliances =
#pragma warning restore CS0612
{
#pragma warning disable CS0612
new InstanceOSPoliciesCompliance.Types.OSPolicyCompliance(),
#pragma warning restore CS0612
},
#pragma warning disable CS0612
LastComplianceCheckTime = new wkt::Timestamp(),
LastComplianceRunId = "last_compliance_run_id45f5c46a",
#pragma warning restore CS0612
};
mockGrpcClient.Setup(x => x.GetInstanceOSPoliciesCompliance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
#pragma warning disable CS0612
InstanceOSPoliciesCompliance response = client.GetInstanceOSPoliciesCompliance(request.InstanceOSPoliciesComplianceName);
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInstanceOSPoliciesComplianceResourceNamesAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
#pragma warning disable CS0612
GetInstanceOSPoliciesComplianceRequest request = new GetInstanceOSPoliciesComplianceRequest
#pragma warning restore CS0612
{
#pragma warning disable CS0612
InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
#pragma warning restore CS0612
};
#pragma warning disable CS0612
InstanceOSPoliciesCompliance expectedResponse = new InstanceOSPoliciesCompliance
#pragma warning restore CS0612
{
#pragma warning disable CS0612
InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Instance = "instance99a62371",
State = OSPolicyComplianceState.Unknown,
DetailedState = "detailed_state6d8e814a",
DetailedStateReason = "detailed_state_reason493b0c87",
OsPolicyCompliances =
#pragma warning restore CS0612
{
#pragma warning disable CS0612
new InstanceOSPoliciesCompliance.Types.OSPolicyCompliance(),
#pragma warning restore CS0612
},
#pragma warning disable CS0612
LastComplianceCheckTime = new wkt::Timestamp(),
LastComplianceRunId = "last_compliance_run_id45f5c46a",
#pragma warning restore CS0612
};
#pragma warning disable CS0612
mockGrpcClient.Setup(x => x.GetInstanceOSPoliciesComplianceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceOSPoliciesCompliance>(stt::Task.FromResult(expectedResponse), null, null, null, null));
#pragma warning restore CS0612
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
#pragma warning disable CS0612
InstanceOSPoliciesCompliance responseCallSettings = await client.GetInstanceOSPoliciesComplianceAsync(request.InstanceOSPoliciesComplianceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, responseCallSettings);
#pragma warning disable CS0612
InstanceOSPoliciesCompliance responseCancellationToken = await client.GetInstanceOSPoliciesComplianceAsync(request.InstanceOSPoliciesComplianceName, st::CancellationToken.None);
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetOSPolicyAssignmentReportRequestObject()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentReportRequest request = new GetOSPolicyAssignmentReportRequest
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
};
OSPolicyAssignmentReport expectedResponse = new OSPolicyAssignmentReport
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
Instance = "instance99a62371",
OsPolicyAssignmentAsOSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
OsPolicyCompliances =
{
new OSPolicyAssignmentReport.Types.OSPolicyCompliance(),
},
UpdateTime = new wkt::Timestamp(),
LastRunId = "last_run_ida47e4da8",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignmentReport response = client.GetOSPolicyAssignmentReport(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOSPolicyAssignmentReportRequestObjectAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentReportRequest request = new GetOSPolicyAssignmentReportRequest
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
};
OSPolicyAssignmentReport expectedResponse = new OSPolicyAssignmentReport
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
Instance = "instance99a62371",
OsPolicyAssignmentAsOSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
OsPolicyCompliances =
{
new OSPolicyAssignmentReport.Types.OSPolicyCompliance(),
},
UpdateTime = new wkt::Timestamp(),
LastRunId = "last_run_ida47e4da8",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignmentReport>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignmentReport responseCallSettings = await client.GetOSPolicyAssignmentReportAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
OSPolicyAssignmentReport responseCancellationToken = await client.GetOSPolicyAssignmentReportAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetOSPolicyAssignmentReport()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentReportRequest request = new GetOSPolicyAssignmentReportRequest
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
};
OSPolicyAssignmentReport expectedResponse = new OSPolicyAssignmentReport
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
Instance = "instance99a62371",
OsPolicyAssignmentAsOSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
OsPolicyCompliances =
{
new OSPolicyAssignmentReport.Types.OSPolicyCompliance(),
},
UpdateTime = new wkt::Timestamp(),
LastRunId = "last_run_ida47e4da8",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignmentReport response = client.GetOSPolicyAssignmentReport(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOSPolicyAssignmentReportAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentReportRequest request = new GetOSPolicyAssignmentReportRequest
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
};
OSPolicyAssignmentReport expectedResponse = new OSPolicyAssignmentReport
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
Instance = "instance99a62371",
OsPolicyAssignmentAsOSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
OsPolicyCompliances =
{
new OSPolicyAssignmentReport.Types.OSPolicyCompliance(),
},
UpdateTime = new wkt::Timestamp(),
LastRunId = "last_run_ida47e4da8",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignmentReport>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignmentReport responseCallSettings = await client.GetOSPolicyAssignmentReportAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
OSPolicyAssignmentReport responseCancellationToken = await client.GetOSPolicyAssignmentReportAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetOSPolicyAssignmentReportResourceNames()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentReportRequest request = new GetOSPolicyAssignmentReportRequest
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
};
OSPolicyAssignmentReport expectedResponse = new OSPolicyAssignmentReport
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
Instance = "instance99a62371",
OsPolicyAssignmentAsOSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
OsPolicyCompliances =
{
new OSPolicyAssignmentReport.Types.OSPolicyCompliance(),
},
UpdateTime = new wkt::Timestamp(),
LastRunId = "last_run_ida47e4da8",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignmentReport response = client.GetOSPolicyAssignmentReport(request.OSPolicyAssignmentReportName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOSPolicyAssignmentReportResourceNamesAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentReportRequest request = new GetOSPolicyAssignmentReportRequest
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
};
OSPolicyAssignmentReport expectedResponse = new OSPolicyAssignmentReport
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
Instance = "instance99a62371",
OsPolicyAssignmentAsOSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
OsPolicyCompliances =
{
new OSPolicyAssignmentReport.Types.OSPolicyCompliance(),
},
UpdateTime = new wkt::Timestamp(),
LastRunId = "last_run_ida47e4da8",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignmentReport>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignmentReport responseCallSettings = await client.GetOSPolicyAssignmentReportAsync(request.OSPolicyAssignmentReportName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
OSPolicyAssignmentReport responseCancellationToken = await client.GetOSPolicyAssignmentReportAsync(request.OSPolicyAssignmentReportName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInventoryRequestObject()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInventoryRequest request = new GetInventoryRequest
{
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
View = InventoryView.Basic,
};
Inventory expectedResponse = new Inventory
{
OsInfo = new Inventory.Types.OsInfo(),
Items =
{
{
"key8a0b6e3c",
new Inventory.Types.Item()
},
},
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetInventory(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
Inventory response = client.GetInventory(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInventoryRequestObjectAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInventoryRequest request = new GetInventoryRequest
{
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
View = InventoryView.Basic,
};
Inventory expectedResponse = new Inventory
{
OsInfo = new Inventory.Types.OsInfo(),
Items =
{
{
"key8a0b6e3c",
new Inventory.Types.Item()
},
},
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetInventoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Inventory>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
Inventory responseCallSettings = await client.GetInventoryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Inventory responseCancellationToken = await client.GetInventoryAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInventory()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInventoryRequest request = new GetInventoryRequest
{
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Inventory expectedResponse = new Inventory
{
OsInfo = new Inventory.Types.OsInfo(),
Items =
{
{
"key8a0b6e3c",
new Inventory.Types.Item()
},
},
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetInventory(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
Inventory response = client.GetInventory(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInventoryAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInventoryRequest request = new GetInventoryRequest
{
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Inventory expectedResponse = new Inventory
{
OsInfo = new Inventory.Types.OsInfo(),
Items =
{
{
"key8a0b6e3c",
new Inventory.Types.Item()
},
},
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetInventoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Inventory>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
Inventory responseCallSettings = await client.GetInventoryAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Inventory responseCancellationToken = await client.GetInventoryAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInventoryResourceNames()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInventoryRequest request = new GetInventoryRequest
{
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Inventory expectedResponse = new Inventory
{
OsInfo = new Inventory.Types.OsInfo(),
Items =
{
{
"key8a0b6e3c",
new Inventory.Types.Item()
},
},
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetInventory(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
Inventory response = client.GetInventory(request.InventoryName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInventoryResourceNamesAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInventoryRequest request = new GetInventoryRequest
{
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Inventory expectedResponse = new Inventory
{
OsInfo = new Inventory.Types.OsInfo(),
Items =
{
{
"key8a0b6e3c",
new Inventory.Types.Item()
},
},
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetInventoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Inventory>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
Inventory responseCallSettings = await client.GetInventoryAsync(request.InventoryName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Inventory responseCancellationToken = await client.GetInventoryAsync(request.InventoryName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetVulnerabilityReportRequestObject()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
VulnerabilityReport expectedResponse = new VulnerabilityReport
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Vulnerabilities =
{
new VulnerabilityReport.Types.Vulnerability(),
},
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetVulnerabilityReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
VulnerabilityReport response = client.GetVulnerabilityReport(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetVulnerabilityReportRequestObjectAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
VulnerabilityReport expectedResponse = new VulnerabilityReport
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Vulnerabilities =
{
new VulnerabilityReport.Types.Vulnerability(),
},
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetVulnerabilityReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VulnerabilityReport>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
VulnerabilityReport responseCallSettings = await client.GetVulnerabilityReportAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
VulnerabilityReport responseCancellationToken = await client.GetVulnerabilityReportAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetVulnerabilityReport()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
VulnerabilityReport expectedResponse = new VulnerabilityReport
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Vulnerabilities =
{
new VulnerabilityReport.Types.Vulnerability(),
},
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetVulnerabilityReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
VulnerabilityReport response = client.GetVulnerabilityReport(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetVulnerabilityReportAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
VulnerabilityReport expectedResponse = new VulnerabilityReport
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Vulnerabilities =
{
new VulnerabilityReport.Types.Vulnerability(),
},
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetVulnerabilityReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VulnerabilityReport>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
VulnerabilityReport responseCallSettings = await client.GetVulnerabilityReportAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
VulnerabilityReport responseCancellationToken = await client.GetVulnerabilityReportAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetVulnerabilityReportResourceNames()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
VulnerabilityReport expectedResponse = new VulnerabilityReport
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Vulnerabilities =
{
new VulnerabilityReport.Types.Vulnerability(),
},
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetVulnerabilityReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
VulnerabilityReport response = client.GetVulnerabilityReport(request.VulnerabilityReportName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetVulnerabilityReportResourceNamesAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
VulnerabilityReport expectedResponse = new VulnerabilityReport
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Vulnerabilities =
{
new VulnerabilityReport.Types.Vulnerability(),
},
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetVulnerabilityReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VulnerabilityReport>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
VulnerabilityReport responseCallSettings = await client.GetVulnerabilityReportAsync(request.VulnerabilityReportName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
VulnerabilityReport responseCancellationToken = await client.GetVulnerabilityReportAsync(request.VulnerabilityReportName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
#region License
// Copyright (c) 2018, FluentMigrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Linq;
using System.Reflection;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner.Conventions;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Runner.VersionTableInfo;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace FluentMigrator.Runner
{
/// <summary>
/// Extension methods for the <see cref="IMigrationRunnerBuilder"/> interface
/// </summary>
public static class MigrationRunnerBuilderExtensions
{
/// <summary>
/// Sets configuration action for global processor options
/// </summary>
/// <param name="builder">The runner builder</param>
/// <param name="configureAction">The configuration action</param>
/// <returns>The runner builder</returns>
public static IMigrationRunnerBuilder ConfigureGlobalProcessorOptions(
this IMigrationRunnerBuilder builder,
Action<ProcessorOptions> configureAction)
{
builder.Services.Configure(configureAction);
return builder;
}
/// <summary>
/// Sets the global connection string
/// </summary>
/// <param name="builder">The runner builder</param>
/// <param name="connectionStringOrName">The connection string or name to use</param>
/// <returns>The runner builder</returns>
public static IMigrationRunnerBuilder WithGlobalConnectionString(
this IMigrationRunnerBuilder builder,
string connectionStringOrName)
{
builder.Services.Configure<ProcessorOptions>(opt => opt.ConnectionString = connectionStringOrName);
return builder;
}
/// <summary>
/// Sets the global connection string
/// </summary>
/// <param name="builder">The runner builder</param>
/// <param name="configureConnectionString">The function that creates the connection string.</param>
/// <returns>The runner builder</returns>
public static IMigrationRunnerBuilder WithGlobalConnectionString(
this IMigrationRunnerBuilder builder, Func<IServiceProvider, string> configureConnectionString)
{
builder.Services
.AddSingleton<IConfigureOptions<ProcessorOptions>>(
s =>
{
return new ConfigureNamedOptions<ProcessorOptions>(
Options.DefaultName,
opt => opt.ConnectionString = configureConnectionString(s));
});
return builder;
}
/// <summary>
/// Sets the global command timeout
/// </summary>
/// <param name="builder">The runner builder</param>
/// <param name="commandTimeout">The global command timeout</param>
/// <returns>The runner builder</returns>
public static IMigrationRunnerBuilder WithGlobalCommandTimeout(
this IMigrationRunnerBuilder builder,
TimeSpan commandTimeout)
{
builder.Services.Configure<ProcessorOptions>(opt => opt.Timeout = commandTimeout);
return builder;
}
/// <summary>
/// Sets the global strip comment
/// </summary>
/// <param name="builder">The runner builder</param>
/// <param name="stripComments">The global strip comments</param>
/// <returns>The runner builder</returns>
public static IMigrationRunnerBuilder WithGlobalStripComments(
this IMigrationRunnerBuilder builder,
bool stripComments)
{
builder.Services.Configure<ProcessorOptions>(opt => opt.StripComments = stripComments);
return builder;
}
/// <summary>
/// Sets the global preview mode
/// </summary>
/// <param name="builder">The runner builder</param>
/// <param name="preview">The global preview mode</param>
/// <returns>The runner builder</returns>
public static IMigrationRunnerBuilder AsGlobalPreview(
this IMigrationRunnerBuilder builder,
bool preview = true)
{
builder.Services.Configure<ProcessorOptions>(opt => opt.PreviewOnly = preview);
return builder;
}
/// <summary>
/// Sets the version table meta data
/// </summary>
/// <param name="builder">The runner builder</param>
/// <param name="versionTableMetaData">The version table meta data</param>
/// <returns>The runner builder</returns>
public static IMigrationRunnerBuilder WithVersionTable(
this IMigrationRunnerBuilder builder,
IVersionTableMetaData versionTableMetaData)
{
builder.Services
.AddScoped<IVersionTableMetaDataAccessor>(
_ => new PassThroughVersionTableMetaDataAccessor(versionTableMetaData));
return builder;
}
/// <summary>
/// Sets the migration runner conventions
/// </summary>
/// <param name="builder">The runner builder</param>
/// <param name="conventions">The migration runner conventions</param>
/// <returns>The runner builder</returns>
public static IMigrationRunnerBuilder WithRunnerConventions(
this IMigrationRunnerBuilder builder,
IMigrationRunnerConventions conventions)
{
builder.Services
.AddSingleton<IMigrationRunnerConventionsAccessor>(
new PassThroughMigrationRunnerConventionsAccessor(conventions));
return builder;
}
/// <summary>
/// Adds the migrations
/// </summary>
/// <param name="builder">The runner builder</param>
/// <param name="assemblies">The target assemblies</param>
/// <returns>The runner builder</returns>
public static IMigrationRunnerBuilder WithMigrationsIn(
this IMigrationRunnerBuilder builder,
[NotNull, ItemNotNull] params Assembly[] assemblies)
{
builder.Services
.AddSingleton<IMigrationSourceItem>(new AssemblyMigrationSourceItem(assemblies));
return builder;
}
/// <summary>
/// Scans for types in the given assemblies
/// </summary>
/// <param name="builder">The runner builder</param>
/// <param name="assemblies">The assemblies to scan</param>
/// <returns>The next step</returns>
public static IScanInBuilder ScanIn(
this IMigrationRunnerBuilder builder,
[NotNull, ItemNotNull] params Assembly[] assemblies)
{
var sourceItem = new AssemblySourceItem(assemblies);
return new ScanInBuilder(builder, sourceItem);
}
private class ScanInBuilder : IScanInBuilder, IScanInForBuilder
{
private readonly IMigrationRunnerBuilder _builder;
public ScanInBuilder(IMigrationRunnerBuilder builder, IAssemblySourceItem currentSourceItem)
{
if (builder.DanglingAssemblySourceItem != null)
{
builder.Services
.AddSingleton(builder.DanglingAssemblySourceItem);
}
_builder = builder;
_builder.DanglingAssemblySourceItem = currentSourceItem;
SourceItem = currentSourceItem;
}
private ScanInBuilder(
IMigrationRunnerBuilder builder,
IAssemblySourceItem currentSourceItem,
IMigrationSourceItem sourceItem)
{
_builder = builder;
SourceItem = currentSourceItem;
_builder.DanglingAssemblySourceItem = null;
Services.AddSingleton(sourceItem);
}
private ScanInBuilder(
IMigrationRunnerBuilder builder,
IAssemblySourceItem currentSourceItem,
IVersionTableMetaDataSourceItem sourceItem)
{
_builder = builder;
SourceItem = currentSourceItem;
_builder.DanglingAssemblySourceItem = null;
Services.AddSingleton(sourceItem);
}
private ScanInBuilder(
IMigrationRunnerBuilder builder,
IAssemblySourceItem currentSourceItem,
ITypeSourceItem<IConventionSet> sourceItem)
{
_builder = builder;
SourceItem = currentSourceItem;
_builder.DanglingAssemblySourceItem = null;
Services.AddSingleton(sourceItem);
}
private ScanInBuilder(
IMigrationRunnerBuilder builder,
IAssemblySourceItem currentSourceItem,
IEmbeddedResourceProvider sourceItem)
{
_builder = builder;
SourceItem = currentSourceItem;
_builder.DanglingAssemblySourceItem = null;
Services.AddSingleton(sourceItem);
}
/// <inheritdoc />
public IServiceCollection Services => _builder.Services;
/// <inheritdoc />
public IAssemblySourceItem DanglingAssemblySourceItem
{
get => _builder.DanglingAssemblySourceItem;
set => _builder.DanglingAssemblySourceItem = value;
}
/// <inheritdoc />
public IAssemblySourceItem SourceItem { get; }
/// <inheritdoc />
public IScanInForBuilder For => this;
/// <inheritdoc />
public IScanInBuilder Migrations()
{
var sourceItem = new AssemblyMigrationSourceItem(SourceItem.Assemblies.ToList());
return new ScanInBuilder(_builder, SourceItem, sourceItem);
}
/// <inheritdoc />
public IScanInBuilder VersionTableMetaData()
{
var sourceItem = new AssemblyVersionTableMetaDataSourceItem(SourceItem.Assemblies.ToArray());
return new ScanInBuilder(_builder, SourceItem, sourceItem);
}
/// <inheritdoc />
public IScanInBuilder ConventionSet()
{
var sourceItem = new AssemblySourceItem<IConventionSet>(SourceItem.Assemblies.ToArray());
return new ScanInBuilder(_builder, SourceItem, sourceItem);
}
/// <inheritdoc />
public IScanInBuilder EmbeddedResources()
{
var sourceItem = new DefaultEmbeddedResourceProvider(SourceItem.Assemblies.ToArray());
return new ScanInBuilder(_builder, SourceItem, sourceItem);
}
/// <inheritdoc />
public IMigrationRunnerBuilder All()
{
Services.AddSingleton(SourceItem);
_builder.DanglingAssemblySourceItem = null;
return _builder;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dwolla.Checkout.Validators;
using FluentAssertions;
using FluentValidation.TestHelper;
using NUnit.Framework;
namespace Dwolla.Checkout.Tests.ValidationTests
{
[TestFixture]
public class DwollaPurchaseOrderValidatorTests
{
private DwollaPurchaseOrderValidator validator;
[SetUp]
public void BeforeEachTest()
{
validator = new DwollaPurchaseOrderValidator();
}
[Test]
public void notes_validation()
{
//require length to be less than or equal to 250 chars
validator.ShouldHaveValidationErrorFor( po => po.Notes,
"aasdfasddfsadfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdffffffffffff" );
validator.ShouldNotHaveValidationErrorFor( po => po.Notes, null as string );
validator.ShouldNotHaveValidationErrorFor( po => po.Notes, "" );
validator.ShouldNotHaveValidationErrorFor( po => po.Notes, "Foo" );
}
[Test]
public void destination_id_property_validation()
{
validator.ShouldNotHaveValidationErrorFor( po => po.DestinationId, "812-111-1111" );
validator.ShouldHaveValidationErrorFor( po => po.DestinationId, "" );
validator.ShouldHaveValidationErrorFor( po => po.DestinationId, null as string );
}
[Test]
public void discount_property_validation()
{
validator.ShouldNotHaveValidationErrorFor( po => po.Discount, -5.00m );
validator.ShouldNotHaveValidationErrorFor( po => po.Discount, 0.00m );
validator.ShouldHaveValidationErrorFor( po => po.Discount, 5.00m );
}
[Test]
public void shipping_property_validation()
{
validator.ShouldNotHaveValidationErrorFor( po => po.Shipping, 0.00m );
validator.ShouldNotHaveValidationErrorFor( po => po.Shipping, 5.00m );
validator.ShouldHaveValidationErrorFor( po => po.Shipping, -5.00m );
}
[Test]
public void tax_property_validation()
{
validator.ShouldNotHaveValidationErrorFor( po => po.Tax, 0.00m );
validator.ShouldNotHaveValidationErrorFor( po => po.Tax, 5.00m );
validator.ShouldHaveValidationErrorFor( po => po.Tax, -5.00m );
}
[Test]
public void order_items_should_have_a_child_validator_to_validate_individual_order_items()
{
validator.ShouldHaveChildValidator( po => po.OrderItems, typeof(DwollaOrderItemValidator) );
}
[Test]
public void order_items_should_have_at_least_one_order_item()
{
validator.ShouldHaveValidationErrorFor( po => po.OrderItems, new DwollaPurchaseOrder() );
}
[Test]
public void order_items_with_at_least_one_order_item_is_okay()
{
var goodOrder = new DwollaPurchaseOrder()
{
OrderItems = {new DwollaOrderItem("foo", 5.00m, 1)}
};
validator.ShouldNotHaveValidationErrorFor( po => po.OrderItems, goodOrder );
}
[Test]
public void total_validation()
{
var order = new DwollaPurchaseOrder
{
OrderItems =
{
new DwollaOrderItem("Candy Bar", 25.00m, 1)
{
Description = "Super Expensive Candy Bar"
},
new DwollaOrderItem("Lolly Pop", 30.00m, 2)
{
Description = "Super Expensive Lolly Pop"
},
}
};
validator.ShouldNotHaveValidationErrorFor( po => po.Total, order );
order.OrderItems.Skip( 1 ).First().Price = -12.49m;
validator.ShouldHaveValidationErrorFor( po => po.Total, order );
}
[Test]
public void facilitator_validation()
{
var order = new DwollaPurchaseOrder
{
OrderItems =
{
new DwollaOrderItem( price: 25.00m, quantity: 1, name: "Candy Bar" )
{
Description = "Super Expensive Candy Bar"
}
},
FacilitatorAmount = 5.00m
};
validator.ShouldNotHaveValidationErrorFor( po => po.FacilitatorAmount, order );
order.FacilitatorAmount = 6.25m; // max facilitator fee for the total
validator.ShouldHaveValidationErrorFor( po => po.FacilitatorAmount, order );
}
[Test]
public void ensure_customerinfo_property_has_a_validator()
{
validator.ShouldHaveChildValidator( po => po.CustomerInfo, typeof(DwollaCustomerInfoValidator) );
}
[Test]
public void ensure_valid_metadata()
{
validator.ShouldHaveChildValidator(po => po.Metadata, typeof(DwollaMetadataValidator));
var order = new DwollaPurchaseOrder
{
CustomerInfo = new DwollaCustomerInfo
{
FirstName = "Brian",
LastName = "Chavez",
City = "Beverly Hills",
State = "CA",
Zip = "90210",
Email = "bchavez@valid.com",
},
OrderItems =
{
new DwollaOrderItem( price: 25.00m, quantity: 1, name: "Candy Bar" )
{
Description = "Super Expensive Candy Bar"
}
},
DestinationId = "123-123-1234",
FacilitatorAmount = 5.00m,
};
order.Metadata.Add("f",
"asdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdf");
validator.Validate(order).IsValid.Should().BeFalse();
order.Metadata.Clear();
order.Metadata.Add("asdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdfasdfasdfasdfjwjwfjwjfwahsdfasdf","v");
validator.Validate(order).IsValid.Should().BeFalse();
order.Metadata.Clear();
order.Metadata.Add("key", "value");
validator.Validate(order).IsValid.Should().BeTrue();
}
[Test]
[Explicit]
public void error_message_output()
{
var order = new DwollaPurchaseOrder
{
CustomerInfo = new DwollaCustomerInfo
{
FirstName = "Brian",
LastName = "Chavez",
City = "Beverly Hills",
State = "CA",
Zip = "90210",
Email = "bchavez@valid.com",
},
OrderItems =
{
new DwollaOrderItem( price: 25.00m, quantity: 1, name: "Candy Bar" )
{
Description = "Super Expensive Candy Bar"
}
},
DestinationId = "123-123-1234",
FacilitatorAmount = 5.00m,
};
//order.Metadata.Add("zzzzzzzzzzzzzzzz", "fffffffffff");
var vr = validator.Validate( order );
vr.Errors.ToList().ForEach( x => Console.WriteLine( x.ToString() ) );
vr.IsValid.Should().BeTrue();
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using MurphyPA.H2D.Interfaces;
using System.IO;
using System.Xml;
using System.Reflection;
namespace MurphyPA.H2D.TestApp
{
/// <summary>
/// Summary description for ConvertToXml.
/// </summary>
public class ConvertToXml : ConvertToCodeBase
{
public ConvertToXml(DiagramModel model)
: base (model.GetGlyphsList ())
{
}
public class PropertyVisitor : IGlyphVisitor
{
XmlTextWriter _Writer;
public PropertyVisitor (XmlTextWriter writer)
{
_Writer = writer;
}
protected bool AcceptablePropertyType (PropertyInfo pinfo)
{
bool acceptable = pinfo.PropertyType.IsPrimitive;
acceptable = acceptable || pinfo.PropertyType == typeof (string);
return acceptable;
}
protected void VisitInner (IGlyph glyph)
{
foreach (PropertyInfo pinfo in glyph.GetType ().GetProperties ())
{
if (AcceptablePropertyType (pinfo))
{
try
{
object value = pinfo.GetValue (glyph, null);
string sv = string.Format ("{0}", value);
_Writer.WriteElementString (pinfo.Name, sv);
}
catch (Exception ex)
{
_Writer.WriteElementString (pinfo.Name, "EXCEPTION: " + ex.ToString ());
}
}
}
}
protected void WriteDefaults (IGlyph glyph)
{
_Writer.WriteAttributeString ("Name", glyph.Name);
_Writer.WriteAttributeString ("Id", glyph.Id);
_Writer.WriteAttributeString ("DoNotInstrument", glyph.DoNotInstrument.ToString ());
_Writer.WriteElementString ("Note", glyph.Note);
if (glyph.Owner != null)
{
_Writer.WriteElementString ("OwnerId", glyph.Owner.Id);
}
if (glyph.Parent != null)
{
_Writer.WriteElementString ("ParentId", glyph.Parent.Id);
}
}
#region IGlyphVisitor Members
public void Visit(IPortLinkGlyph portLink)
{
WriteDefaults (portLink);
_Writer.WriteElementString ("FromPortName", portLink.FromPortName);
_Writer.WriteElementString ("SendIndex", portLink.SendIndex);
_Writer.WriteElementString ("ToPortName", portLink.ToPortName);
foreach (IPortLinkContactPointGlyph contactPoint in portLink.ContactPoints)
{
if (contactPoint.Parent != null)
{
IComponentGlyph comp = contactPoint.Parent as IComponentGlyph;
System.Diagnostics.Debug.Assert (comp != null);
_Writer.WriteStartElement ("Component");
try
{
_Writer.WriteElementString ("Id", comp.Id);
_Writer.WriteElementString ("Name", comp.Name);
}
finally
{
_Writer.WriteEndElement ();
}
}
}
}
public void Visit(IPortLinkContactPointGlyph portLinkContactPoint)
{
}
public void Visit(ITransitionContactPointGlyph transitionContactPoint)
{
}
public void Visit(ITransitionGlyph transition)
{
WriteDefaults (transition);
_Writer.WriteElementString ("EventSignal", transition.EventSignal);
_Writer.WriteElementString ("EventSource", transition.EventSource);
_Writer.WriteElementString ("GuardCondition", transition.GuardCondition);
_Writer.WriteElementString ("Action", transition.Action);
_Writer.WriteElementString ("EvaluationOrderPriority", transition.EvaluationOrderPriority.ToString ());
_Writer.WriteElementString ("EventType", transition.EventType);
_Writer.WriteElementString ("IsInnerTransition", transition.IsInnerTransition.ToString ());
_Writer.WriteElementString ("TimeOutExpression", transition.TimeOutExpression);
_Writer.WriteElementString ("TransitionType", transition.TransitionType.ToString ());
foreach (ITransitionContactPointGlyph contactPoint in transition.ContactPoints)
{
if (contactPoint.Parent != null)
{
IStateGlyph state = contactPoint.Parent as IStateGlyph;
System.Diagnostics.Debug.Assert (state != null);
_Writer.WriteStartElement ("State");
try
{
_Writer.WriteElementString ("Id", state.Id);
_Writer.WriteElementString ("Name", state.Name);
}
finally
{
_Writer.WriteEndElement ();
}
}
}
}
public void Visit (IComponentGlyph component)
{
WriteDefaults (component);
_Writer.WriteElementString ("TypeName", component.TypeName);
_Writer.WriteElementString ("IsMultiInstance", component.IsMultiInstance.ToString ());
}
public void Visit (IStateTransitionPortGlyph port)
{
WriteDefaults (port);
_Writer.WriteElementString ("IsMultiPort", port.IsMultiPort.ToString ());
}
public void Visit(IStateGlyph state)
{
WriteDefaults (state);
_Writer.WriteElementString ("IsStartState", state.IsStartState.ToString ());
_Writer.WriteElementString ("EntryAction", state.EntryAction);
_Writer.WriteElementString ("ExitAction", state.ExitAction);
_Writer.WriteStartElement ("StateCommands");
try
{
foreach (string cmd in state.StateCommands)
{
if (cmd != null && cmd.Trim ().Length > 0)
{
_Writer.WriteElementString ("Command", cmd);
}
}
}
finally
{
_Writer.WriteEndElement ();
}
}
public void Visit(IGroupGlyph group)
{
}
public void Visit(ICompositeGlyph composite)
{
}
public void Visit(IGlyph glyph)
{
}
#endregion
}
protected void WriteGlyphProperties (XmlTextWriter writer, IGlyph glyph)
{
IGlyphVisitor visitor = new PropertyVisitor (writer);
glyph.Accept (visitor);
}
protected void WriteGlyphXml (XmlTextWriter writer, IGlyph glyph)
{
writer.WriteStartElement (glyph.GetType ().Name);
try
{
WriteGlyphProperties (writer, glyph);
foreach (IGlyph child in glyph.Children)
{
// only internal glyphs are owned i.e. contact points, etc. - so skip them.
if (child.Owner == null)
{
WriteGlyphXml (writer, child);
}
}
}
finally
{
writer.WriteEndElement ();
}
}
public string Convert ()
{
PrepareGlyphs ();
MemoryStream ms = new MemoryStream ();
XmlTextWriter writer = new XmlTextWriter (ms, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument (true);
writer.WriteStartElement ("Glyphs");
try
{
foreach (IGlyph glyph in _Glyphs)
{
if (glyph.Parent == null && glyph.Owner == null)
{
WriteGlyphXml (writer, glyph);
}
}
}
finally
{
writer.WriteEndElement ();
writer.WriteEndDocument ();
}
writer.Flush ();
ms.Seek (0, SeekOrigin.Begin);
StreamReader sr = new StreamReader (ms);
string result = sr.ReadToEnd ();
sr.Close ();
writer.Close ();
return result;
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace AppointmentSchedulerWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.38.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Cloud Shell API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://cloud.google.com/shell/docs/'>Cloud Shell API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20190202 (1493)
* <tr><th>API Docs
* <td><a href='https://cloud.google.com/shell/docs/'>
* https://cloud.google.com/shell/docs/</a>
* <tr><th>Discovery Name<td>cloudshell
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Cloud Shell API can be found at
* <a href='https://cloud.google.com/shell/docs/'>https://cloud.google.com/shell/docs/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.CloudShell.v1
{
/// <summary>The CloudShell Service.</summary>
public class CloudShellService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public CloudShellService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public CloudShellService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
operations = new OperationsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "cloudshell"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://cloudshell.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://cloudshell.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Cloud Shell API.</summary>
public class Scope
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Cloud Shell API.</summary>
public static class ScopeConstants
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
private readonly OperationsResource operations;
/// <summary>Gets the Operations resource.</summary>
public virtual OperationsResource Operations
{
get { return operations; }
}
}
///<summary>A base abstract class for CloudShell requests.</summary>
public abstract class CloudShellBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new CloudShellBaseServiceRequest instance.</summary>
protected CloudShellBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes CloudShell parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "operations" collection of methods.</summary>
public class OperationsResource
{
private const string Resource = "operations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public OperationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether
/// the cancellation succeeded or whether the operation completed despite cancellation. On successful
/// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value
/// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the operation resource to be cancelled.</param>
public virtual CancelRequest Cancel(Google.Apis.CloudShell.v1.Data.CancelOperationRequest body, string name)
{
return new CancelRequest(service, body, name);
}
/// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether
/// the cancellation succeeded or whether the operation completed despite cancellation. On successful
/// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value
/// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.</summary>
public class CancelRequest : CloudShellBaseServiceRequest<Google.Apis.CloudShell.v1.Data.Empty>
{
/// <summary>Constructs a new Cancel request.</summary>
public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudShell.v1.Data.CancelOperationRequest body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the operation resource to be cancelled.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudShell.v1.Data.CancelOperationRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "cancel"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}:cancel"; }
}
/// <summary>Initializes Cancel parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^operations/.+$",
});
}
}
/// <summary>Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`.</summary>
/// <param name="name">The name of the operation resource to be deleted.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`.</summary>
public class DeleteRequest : CloudShellBaseServiceRequest<Google.Apis.CloudShell.v1.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource to be deleted.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^operations/.+$",
});
}
}
/// <summary>Gets the latest state of a long-running operation. Clients can use this method to poll the
/// operation result at intervals as recommended by the API service.</summary>
/// <param name="name">The name of the operation resource.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets the latest state of a long-running operation. Clients can use this method to poll the
/// operation result at intervals as recommended by the API service.</summary>
public class GetRequest : CloudShellBaseServiceRequest<Google.Apis.CloudShell.v1.Data.Operation>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^operations/.+$",
});
}
}
/// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`.
///
/// NOTE: the `name` binding allows API services to override the binding to use different resource name schemes,
/// such as `users/operations`. To override the binding, API services can add a binding such as
/// `"/v1/{name=users}/operations"` to their service configuration. For backwards compatibility, the default
/// name includes the operations collection id, however overriding users must ensure the name binding is the
/// parent resource, without the operations collection id.</summary>
/// <param name="name">The name of the operation's parent resource.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`.
///
/// NOTE: the `name` binding allows API services to override the binding to use different resource name schemes,
/// such as `users/operations`. To override the binding, API services can add a binding such as
/// `"/v1/{name=users}/operations"` to their service configuration. For backwards compatibility, the default
/// name includes the operations collection id, however overriding users must ensure the name binding is the
/// parent resource, without the operations collection id.</summary>
public class ListRequest : CloudShellBaseServiceRequest<Google.Apis.CloudShell.v1.Data.ListOperationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation's parent resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>The standard list filter.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>The standard list page token.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>The standard list page size.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^operations$",
});
RequestParameters.Add(
"filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.CloudShell.v1.Data
{
/// <summary>The request message for Operations.CancelOperation.</summary>
public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A
/// typical example is to use it as the request or the response type of an API method. For instance:
///
/// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
///
/// The JSON representation for `Empty` is empty JSON object `{}`.</summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A Cloud Shell environment, which is defined as the combination of a Docker image specifying what is
/// installed on the environment and a home directory containing the user's data that will remain across sessions.
/// Each user has a single environment with the ID "default".</summary>
public class Environment : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Full path to the Docker image used to run this environment, e.g. "gcr.io/dev-con/cloud-
/// devshell:latest".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("dockerImage")]
public virtual string DockerImage { get; set; }
/// <summary>Output only. The environment's identifier, which is always "default".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>Output only. Full name of this resource, in the format
/// `users/{owner_email}/environments/{environment_id}`. `{owner_email}` is the email address of the user to
/// whom this environment belongs, and `{environment_id}` is the identifier of this environment. For example,
/// `users/someone@example.com/environments/default`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Output only. Public keys associated with the environment. Clients can connect to this environment
/// via SSH only if they possess a private key corresponding to at least one of these public keys. Keys can be
/// added to or removed from the environment using the CreatePublicKey and DeletePublicKey methods.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("publicKeys")]
public virtual System.Collections.Generic.IList<PublicKey> PublicKeys { get; set; }
/// <summary>Output only. Host to which clients can connect to initiate SSH sessions with the
/// environment.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sshHost")]
public virtual string SshHost { get; set; }
/// <summary>Output only. Port to which clients can connect to initiate SSH sessions with the
/// environment.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sshPort")]
public virtual System.Nullable<int> SshPort { get; set; }
/// <summary>Output only. Username that clients should use when initiating SSH sessions with the
/// environment.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sshUsername")]
public virtual string SshUsername { get; set; }
/// <summary>Output only. Current execution state of this environment.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Operations.ListOperations.</summary>
public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of operations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("operations")]
public virtual System.Collections.Generic.IList<Operation> Operations { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This resource represents a long-running operation that is the result of a network API call.</summary>
public class Operation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>If the value is `false`, it means the operation is still in progress. If `true`, the operation is
/// completed, and either `error` or `response` is available.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>The error result of the operation in case of failure or cancellation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual Status Error { get; set; }
/// <summary>Service-specific metadata associated with the operation. It typically contains progress
/// information and common metadata such as create time. Some services might not provide such metadata. Any
/// method that returns a long-running operation should document the metadata type, if any.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string,object> Metadata { get; set; }
/// <summary>The server-assigned name, which is only unique within the same service that originally returns it.
/// If you use the default HTTP mapping, the `name` should have the format of
/// `operations/some/unique/name`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The normal response of the operation in case of success. If the original method returns no data on
/// success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have
/// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name
/// is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string,object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A public SSH key, corresponding to a private SSH key held by the client.</summary>
public class PublicKey : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Format of this key's content.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("format")]
public virtual string Format { get; set; }
/// <summary>Required. Content of this key.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("key")]
public virtual string Key { get; set; }
/// <summary>Output only. Full name of this resource, in the format
/// `users/{owner_email}/environments/{environment_id}/publicKeys/{key_id}`. `{owner_email}` is the email
/// address of the user to whom the key belongs. `{environment_id}` is the identifier of the environment to
/// which the key grants access. `{key_id}` is the unique identifier of the key. For example,
/// `users/someone@example.com/environments/default/publicKeys/myKey`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Message included in the metadata field of operations returned from StartEnvironment.</summary>
public class StartEnvironmentMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Current state of the environment being started.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Message included in the response field of operations returned from StartEnvironment once the operation
/// is complete.</summary>
public class StartEnvironmentResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Environment that was started.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("environment")]
public virtual Environment Environment { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The `Status` type defines a logical error model that is suitable for different programming
/// environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model
/// is designed to be:
///
/// - Simple to use and understand for most users - Flexible enough to meet unexpected needs
///
/// # Overview
///
/// The `Status` message contains three pieces of data: error code, error message, and error details. The error code
/// should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error
/// message should be a developer-facing English message that helps developers *understand* and *resolve* the error.
/// If a localized user-facing error message is needed, put the localized message in the error details or localize
/// it in the client. The optional error details may contain arbitrary information about the error. There is a
/// predefined set of error detail types in the package `google.rpc` that can be used for common error conditions.
///
/// # Language mapping
///
/// The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire
/// format. When the `Status` message is exposed in different client libraries and different wire protocols, it can
/// be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped
/// to some error codes in C.
///
/// # Other uses
///
/// The error model and the `Status` message can be used in a variety of environments, either with or without APIs,
/// to provide a consistent developer experience across different environments.
///
/// Example uses of this error model include:
///
/// - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the
/// normal response to indicate the partial errors.
///
/// - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error
/// reporting.
///
/// - Batch operations. If a client uses batch request and batch response, the `Status` message should be used
/// directly inside batch response, one for each error sub-response.
///
/// - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of
/// those operations should be represented directly using the `Status` message.
///
/// - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any
/// stripping needed for security/privacy reasons.</summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>A list of messages that carry the error details. There is a common set of message types for APIs
/// to use.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> Details { get; set; }
/// <summary>A developer-facing error message, which should be in English. Any user-facing error message should
/// be localized and sent in the google.rpc.Status.details field, or localized by the client.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventLogWatcher
**
** Purpose:
** This public class is used for subscribing to event record
** notifications from event log.
**
============================================================*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading;
using System.Security.Permissions;
using Microsoft.Win32;
namespace System.Diagnostics.Eventing.Reader {
/// <summary>
/// Used for subscribing to event record notifications from
/// event log.
/// </summary>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class EventLogWatcher : IDisposable {
public event EventHandler<EventRecordWrittenEventArgs> EventRecordWritten;
private EventLogQuery eventQuery;
private EventBookmark bookmark;
private bool readExistingEvents;
private EventLogHandle handle;
private IntPtr[] eventsBuffer;
private int numEventsInBuffer;
private bool isSubscribing;
private int callbackThreadId;
AutoResetEvent subscriptionWaitHandle;
AutoResetEvent unregisterDoneHandle;
RegisteredWaitHandle registeredWaitHandle;
/// <summary>
/// Maintains cached display / metadata information returned from
/// EventRecords that were obtained from this reader.
/// </summary>
ProviderMetadataCachedInformation cachedMetadataInformation;
EventLogException asyncException;
public EventLogWatcher(string path)
: this(new EventLogQuery(path, PathType.LogName), null, false) {
}
public EventLogWatcher(EventLogQuery eventQuery)
: this(eventQuery, null, false) {
}
public EventLogWatcher(EventLogQuery eventQuery, EventBookmark bookmark)
: this(eventQuery, bookmark, false) {
}
public EventLogWatcher(EventLogQuery eventQuery, EventBookmark bookmark, bool readExistingEvents) {
if (eventQuery == null)
throw new ArgumentNullException("eventQuery");
if (bookmark != null)
readExistingEvents = false;
//explicit data
this.eventQuery = eventQuery;
this.readExistingEvents = readExistingEvents;
if (this.eventQuery.ReverseDirection)
throw new InvalidOperationException();
this.eventsBuffer = new IntPtr[64];
this.cachedMetadataInformation = new ProviderMetadataCachedInformation(eventQuery.Session, null, 50);
this.bookmark = bookmark;
}
public bool Enabled {
get {
return isSubscribing;
}
set {
if (value && !isSubscribing) {
StartSubscribing();
}
else if (!value && isSubscribing) {
StopSubscribing();
}
}
}
[System.Security.SecuritySafeCritical]
internal void StopSubscribing() {
EventLogPermissionHolder.GetEventLogPermission().Demand();
//
// need to set isSubscribing to false before waiting for completion of callback.
//
this.isSubscribing = false;
if (this.registeredWaitHandle != null) {
this.registeredWaitHandle.Unregister( this.unregisterDoneHandle );
if (this.callbackThreadId != Thread.CurrentThread.ManagedThreadId) {
//
// not calling Stop from within callback - wait for
// any outstanding callbacks to complete.
//
if ( this.unregisterDoneHandle != null )
this.unregisterDoneHandle.WaitOne();
}
this.registeredWaitHandle = null;
}
if (this.unregisterDoneHandle != null) {
this.unregisterDoneHandle.Close();
this.unregisterDoneHandle = null;
}
if (this.subscriptionWaitHandle != null) {
this.subscriptionWaitHandle.Close();
this.subscriptionWaitHandle = null;
}
for (int i = 0; i < this.numEventsInBuffer; i++) {
if (eventsBuffer[i] != IntPtr.Zero) {
NativeWrapper.EvtClose(eventsBuffer[i]);
eventsBuffer[i] = IntPtr.Zero;
}
}
this.numEventsInBuffer = 0;
if (handle != null && !handle.IsInvalid)
handle.Dispose();
}
[System.Security.SecuritySafeCritical]
internal void StartSubscribing() {
if (this.isSubscribing)
throw new InvalidOperationException();
int flag = 0;
if (bookmark != null)
flag |= (int)UnsafeNativeMethods.EvtSubscribeFlags.EvtSubscribeStartAfterBookmark;
else if (this.readExistingEvents)
flag |= (int)UnsafeNativeMethods.EvtSubscribeFlags.EvtSubscribeStartAtOldestRecord;
else
flag |= (int)UnsafeNativeMethods.EvtSubscribeFlags.EvtSubscribeToFutureEvents;
if (this.eventQuery.TolerateQueryErrors)
flag |= (int)UnsafeNativeMethods.EvtSubscribeFlags.EvtSubscribeTolerateQueryErrors;
EventLogPermissionHolder.GetEventLogPermission().Demand();
this.callbackThreadId = -1;
this.unregisterDoneHandle = new AutoResetEvent(false);
this.subscriptionWaitHandle = new AutoResetEvent(false);
EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark);
using (bookmarkHandle) {
handle = NativeWrapper.EvtSubscribe(this.eventQuery.Session.Handle,
this.subscriptionWaitHandle.SafeWaitHandle,
this.eventQuery.Path,
this.eventQuery.Query,
bookmarkHandle,
IntPtr.Zero,
IntPtr.Zero,
flag);
}
this.isSubscribing = true;
RequestEvents();
this.registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(
this.subscriptionWaitHandle,
new WaitOrTimerCallback(SubscribedEventsAvailableCallback),
null,
-1,
false);
}
internal void SubscribedEventsAvailableCallback(object state, bool timedOut) {
this.callbackThreadId = Thread.CurrentThread.ManagedThreadId;
try {
RequestEvents();
}
finally {
this.callbackThreadId = -1;
}
}
[System.Security.SecuritySafeCritical]
private void RequestEvents() {
EventLogPermissionHolder.GetEventLogPermission().Demand();
this.asyncException = null;
Debug.Assert(this. numEventsInBuffer == 0);
bool results = false;
do {
if (!this.isSubscribing)
break;
try {
results = NativeWrapper.EvtNext(this.handle, this.eventsBuffer.Length, this.eventsBuffer, 0, 0, ref this. numEventsInBuffer);
if (!results)
return;
}
catch (Exception e) {
this.asyncException = new EventLogException();
this.asyncException.Data.Add("RealException", e);
}
HandleEventsRequestCompletion();
} while (results);
}
private void IssueCallback(EventRecordWrittenEventArgs eventArgs) {
if (EventRecordWritten != null) {
EventRecordWritten(this, eventArgs);
}
}
// marked as SecurityCritical because allocates SafeHandles.
[System.Security.SecurityCritical]
private void HandleEventsRequestCompletion() {
if (this.asyncException != null) {
EventRecordWrittenEventArgs args = new EventRecordWrittenEventArgs(this.asyncException.Data["RealException"] as Exception);
IssueCallback(args);
}
for (int i = 0; i < this. numEventsInBuffer; i++) {
if (!this.isSubscribing)
break;
EventLogRecord record = new EventLogRecord(new EventLogHandle(this.eventsBuffer[i], true), this.eventQuery.Session, this.cachedMetadataInformation);
EventRecordWrittenEventArgs args = new EventRecordWrittenEventArgs(record);
this.eventsBuffer[i] = IntPtr.Zero; // user is responsible for calling Dispose().
IssueCallback(args);
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing) {
if (disposing) {
StopSubscribing();
return;
}
for (int i = 0; i < this.numEventsInBuffer; i++) {
if (eventsBuffer[i] != IntPtr.Zero) {
NativeWrapper.EvtClose(eventsBuffer[i]);
eventsBuffer[i] = IntPtr.Zero;
}
}
this.numEventsInBuffer = 0;
}
}
}
| |
/* Copyright notice and license
Copyright 2007-2010 WebDriver committers
Copyright 2007-2010 Google Inc.
Portions copyright 2007 ThoughtWorks, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using Selenium.Internal.SeleniumEmulation;
namespace Selenium
{
/// <summary>
/// Provides an implementation the ICommandProcessor interface which uses WebDriver to complete
/// the Selenium commands.
/// </summary>
public class WebDriverCommandProcessor : ICommandProcessor
{
#region Private members
private IWebDriver driver;
private Uri baseUrl;
private Dictionary<string, SeleneseCommand> seleneseMethods = new Dictionary<string, SeleneseCommand>();
private ElementFinder elementFinder = new ElementFinder();
private SeleniumOptionSelector select;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="WebDriverCommandProcessor"/> class.
/// </summary>
/// <param name="baseUrl">The base URL of the Selenium server.</param>
/// <param name="baseDriver">The IWebDriver object used for executing commands.</param>
public WebDriverCommandProcessor(string baseUrl, IWebDriver baseDriver)
: this(new Uri(baseUrl), baseDriver)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebDriverCommandProcessor"/> class.
/// </summary>
/// <param name="baseUrl">The base URL of the Selenium server.</param>
/// <param name="baseDriver">The IWebDriver object used for executing commands.</param>
public WebDriverCommandProcessor(Uri baseUrl, IWebDriver baseDriver)
{
this.driver = baseDriver;
this.baseUrl = baseUrl;
this.select = new SeleniumOptionSelector(elementFinder);
}
/// <summary>
/// Gets the <see cref="IWebDriver"/> object that executes the commands for this command processor.
/// </summary>
public IWebDriver UnderlyingWebDriver
{
get { return this.driver; }
}
/// <summary>
/// Sends the specified remote command to the browser to be performed
/// </summary>
/// <param name="command">The remote command verb.</param>
/// <param name="args">The arguments to the remote command (depends on the verb).</param>
/// <returns>the command result, defined by the remote JavaScript. "getX" style
/// commands may return data from the browser</returns>
public string DoCommand(string command, string[] args)
{
object val = Execute(command, args);
if (val == null)
{
return null;
}
return val.ToString();
}
public void SetExtensionJs(string extensionJs)
{
throw new NotImplementedException();
}
public void Start()
{
PopulateSeleneseMethods();
}
public void Stop()
{
driver.Quit();
}
public string GetString(string command, string[] args)
{
return (string)Execute(command, args);
}
public string[] GetStringArray(string command, string[] args)
{
throw new NotImplementedException();
}
public decimal GetNumber(string command, string[] args)
{
return (decimal)Execute(command, args);
}
public decimal[] GetNumberArray(string command, string[] args)
{
throw new NotImplementedException();
}
public bool GetBoolean(string command, string[] args)
{
return (bool)Execute(command, args);
}
public bool[] GetBooleanArray(string command, string[] args)
{
throw new NotImplementedException();
}
private object Execute(string commandName, string[] args)
{
SeleneseCommand command;
if (!seleneseMethods.TryGetValue(commandName, out command))
{
throw new NotSupportedException(commandName);
}
return command.Apply(driver, args);
}
private void PopulateSeleneseMethods()
{
KeyState keyState = new KeyState();
WindowSelector windows = new WindowSelector(driver);
// Note the we use the names used by the CommandProcessor
seleneseMethods.Add("addLocationStrategy", new AddLocationStrategy(elementFinder));
seleneseMethods.Add("addSelection", new AddSelection(elementFinder, select));
seleneseMethods.Add("altKeyDown", new AltKeyDown(keyState));
seleneseMethods.Add("altKeyUp", new AltKeyUp(keyState));
seleneseMethods.Add("assignId", new AssignId(elementFinder));
seleneseMethods.Add("attachFile", new AttachFile(elementFinder));
seleneseMethods.Add("captureScreenshotToString", new CaptureScreenshotToString());
seleneseMethods.Add("click", new Click(elementFinder));
seleneseMethods.Add("check", new Check(elementFinder));
seleneseMethods.Add("close", new Close());
seleneseMethods.Add("createCookie", new CreateCookie());
seleneseMethods.Add("controlKeyDown", new ControlKeyDown(keyState));
seleneseMethods.Add("controlKeyUp", new ControlKeyUp(keyState));
seleneseMethods.Add("deleteAllVisibleCookies", new DeleteAllVisibleCookies());
seleneseMethods.Add("deleteCookie", new DeleteCookie());
seleneseMethods.Add("doubleClick", new DoubleClick(elementFinder));
seleneseMethods.Add("dragdrop", new DragAndDrop(elementFinder));
seleneseMethods.Add("dragAndDrop", new DragAndDrop(elementFinder));
seleneseMethods.Add("dragAndDropToObject", new DragAndDropToObject(elementFinder));
seleneseMethods.Add("fireEvent", new FireEvent(elementFinder));
seleneseMethods.Add("focus", new FireNamedEvent(elementFinder, "focus"));
seleneseMethods.Add("getAllButtons", new GetAllButtons());
seleneseMethods.Add("getAllFields", new GetAllFields());
seleneseMethods.Add("getAllLinks", new GetAllLinks());
seleneseMethods.Add("getAllWindowTitles", new GetAllWindowTitles());
seleneseMethods.Add("getAttribute", new GetAttribute(elementFinder));
seleneseMethods.Add("getAttributeFromAllWindows", new GetAttributeFromAllWindows());
seleneseMethods.Add("getBodyText", new GetBodyText());
seleneseMethods.Add("getCookie", new GetCookie());
seleneseMethods.Add("getCookieByName", new GetCookieByName());
seleneseMethods.Add("getElementHeight", new GetElementHeight(elementFinder));
seleneseMethods.Add("getElementIndex", new GetElementIndex(elementFinder));
seleneseMethods.Add("getElementPositionLeft", new GetElementPositionLeft(elementFinder));
seleneseMethods.Add("getElementPositionTop", new GetElementPositionTop(elementFinder));
seleneseMethods.Add("getElementWidth", new GetElementWidth(elementFinder));
seleneseMethods.Add("getEval", new GetEval(baseUrl));
seleneseMethods.Add("getHtmlSource", new GetHtmlSource());
seleneseMethods.Add("getLocation", new GetLocation());
seleneseMethods.Add("getSelectedId", new FindFirstSelectedOptionProperty(select, SeleniumOptionSelector.Property.ID));
seleneseMethods.Add("getSelectedIds", new FindSelectedOptionProperties(select, SeleniumOptionSelector.Property.ID));
seleneseMethods.Add("getSelectedIndex", new FindFirstSelectedOptionProperty(select, SeleniumOptionSelector.Property.Index));
seleneseMethods.Add("getSelectedIndexes", new FindSelectedOptionProperties(select, SeleniumOptionSelector.Property.Index));
seleneseMethods.Add("getSelectedLabel", new FindFirstSelectedOptionProperty(select, SeleniumOptionSelector.Property.Text));
seleneseMethods.Add("getSelectedLabels", new FindSelectedOptionProperties(select, SeleniumOptionSelector.Property.Text));
seleneseMethods.Add("getSelectedValue", new FindFirstSelectedOptionProperty(select, SeleniumOptionSelector.Property.Value));
seleneseMethods.Add("getSelectedValues", new FindSelectedOptionProperties(select, SeleniumOptionSelector.Property.Value));
seleneseMethods.Add("getSelectOptions", new GetSelectOptions(select));
seleneseMethods.Add("getSpeed", new NoOp("0"));
seleneseMethods.Add("getTable", new GetTable(elementFinder));
seleneseMethods.Add("getText", new GetText(elementFinder));
seleneseMethods.Add("getTitle", new GetTitle());
seleneseMethods.Add("getValue", new GetValue(elementFinder));
seleneseMethods.Add("getXpathCount", new GetXpathCount());
seleneseMethods.Add("goBack", new GoBack());
seleneseMethods.Add("highlight", new Highlight(elementFinder));
seleneseMethods.Add("isChecked", new IsChecked(elementFinder));
seleneseMethods.Add("isCookiePresent", new IsCookiePresent());
seleneseMethods.Add("isEditable", new IsEditable(elementFinder));
seleneseMethods.Add("isElementPresent", new IsElementPresent(elementFinder));
seleneseMethods.Add("isOrdered", new IsOrdered(elementFinder));
seleneseMethods.Add("isSomethingSelected", new IsSomethingSelected(select));
seleneseMethods.Add("isTextPresent", new IsTextPresent());
seleneseMethods.Add("isVisible", new IsVisible(elementFinder));
seleneseMethods.Add("keyDown", new KeyEvent(elementFinder, keyState, "doKeyDown"));
seleneseMethods.Add("keyPress", new TypeKeys(elementFinder));
seleneseMethods.Add("keyUp", new KeyEvent(elementFinder, keyState, "doKeyUp"));
seleneseMethods.Add("metaKeyDown", new MetaKeyDown(keyState));
seleneseMethods.Add("metaKeyUp", new MetaKeyUp(keyState));
seleneseMethods.Add("mouseOver", new MouseEvent(elementFinder, "mouseover"));
seleneseMethods.Add("mouseOut", new MouseEvent(elementFinder, "mouseout"));
seleneseMethods.Add("mouseDown", new MouseEvent(elementFinder, "mousedown"));
seleneseMethods.Add("mouseDownAt", new MouseEventAt(elementFinder, "mousedown"));
seleneseMethods.Add("mouseMove", new MouseEvent(elementFinder, "mousemove"));
seleneseMethods.Add("mouseMoveAt", new MouseEventAt(elementFinder, "mousemove"));
seleneseMethods.Add("mouseUp", new MouseEvent(elementFinder, "mouseup"));
seleneseMethods.Add("mouseUpAt", new MouseEventAt(elementFinder, "mouseup"));
seleneseMethods.Add("open", new Open(baseUrl));
seleneseMethods.Add("openWindow", new OpenWindow(new GetEval(baseUrl)));
seleneseMethods.Add("refresh", new Refresh());
seleneseMethods.Add("removeAllSelections", new RemoveAllSelections(elementFinder));
seleneseMethods.Add("removeSelection", new RemoveSelection(elementFinder, select));
seleneseMethods.Add("runScript", new RunScript());
seleneseMethods.Add("select", new SelectOption(select));
seleneseMethods.Add("selectFrame", new SelectFrame(windows));
seleneseMethods.Add("selectWindow", new SelectWindow(windows));
seleneseMethods.Add("setBrowserLogLevel", new NoOp(null));
seleneseMethods.Add("setContext", new NoOp(null));
seleneseMethods.Add("setSpeed", new NoOp(null));
////seleneseMethods.Add("setTimeout", new SetTimeout(timer));
seleneseMethods.Add("shiftKeyDown", new ShiftKeyDown(keyState));
seleneseMethods.Add("shiftKeyUp", new ShiftKeyUp(keyState));
seleneseMethods.Add("submit", new Submit(elementFinder));
seleneseMethods.Add("type", new Selenium.Internal.SeleniumEmulation.Type(elementFinder, keyState));
seleneseMethods.Add("typeKeys", new TypeKeys(elementFinder));
seleneseMethods.Add("uncheck", new Uncheck(elementFinder));
seleneseMethods.Add("useXpathLibrary", new NoOp(null));
seleneseMethods.Add("waitForCondition", new WaitForCondition());
seleneseMethods.Add("waitForFrameToLoad", new NoOp(null));
seleneseMethods.Add("waitForPageToLoad", new WaitForPageToLoad());
seleneseMethods.Add("waitForPopUp", new WaitForPopup(windows));
seleneseMethods.Add("windowFocus", new WindowFocus());
seleneseMethods.Add("windowMaximize", new WindowMaximize());
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class TernaryNullableTests
{
#region Test methods
[Fact]
public static void CheckTernaryNullableBoolTest()
{
bool[] array1 = new bool[] { false, true };
bool?[] array2 = new bool?[] { null, true, false };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableBool(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableByteTest()
{
bool[] array1 = new bool[] { false, true };
byte?[] array2 = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableByte(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableCharTest()
{
bool[] array1 = new bool[] { false, true };
char?[] array2 = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableChar(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableDecimalTest()
{
bool[] array1 = new bool[] { false, true };
decimal?[] array2 = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableDecimal(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableDoubleTest()
{
bool[] array1 = new bool[] { false, true };
double?[] array2 = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableDouble(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableEnumTest()
{
bool[] array1 = new bool[] { false, true };
E?[] array2 = new E?[] { null, (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableEnum(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableEnumLongTest()
{
bool[] array1 = new bool[] { false, true };
El?[] array2 = new El?[] { null, (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableEnumLong(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableFloatTest()
{
bool[] array1 = new bool[] { false, true };
float?[] array2 = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableFloat(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableIntTest()
{
bool[] array1 = new bool[] { false, true };
int?[] array2 = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableInt(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableLongTest()
{
bool[] array1 = new bool[] { false, true };
long?[] array2 = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableLong(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableStructTest()
{
bool[] array1 = new bool[] { false, true };
S?[] array2 = new S?[] { null, default(S), new S() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableStruct(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableSByteTest()
{
bool[] array1 = new bool[] { false, true };
sbyte?[] array2 = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableSByte(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableStructWithStringTest()
{
bool[] array1 = new bool[] { false, true };
Sc?[] array2 = new Sc?[] { null, default(Sc), new Sc(), new Sc(null) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableStructWithString(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableStructWithStringAndFieldTest()
{
bool[] array1 = new bool[] { false, true };
Scs?[] array2 = new Scs?[] { null, default(Scs), new Scs(), new Scs(null, new S()) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableStructWithStringAndField(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableShortTest()
{
bool[] array1 = new bool[] { false, true };
short?[] array2 = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableShort(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableStructWithTwoValuesTest()
{
bool[] array1 = new bool[] { false, true };
Sp?[] array2 = new Sp?[] { null, default(Sp), new Sp(), new Sp(5, 5.0) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableStructWithTwoValues(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableStructWithValueTest()
{
bool[] array1 = new bool[] { false, true };
Ss?[] array2 = new Ss?[] { null, default(Ss), new Ss(), new Ss(new S()) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableStructWithValue(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableUIntTest()
{
bool[] array1 = new bool[] { false, true };
uint?[] array2 = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableUInt(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableULongTest()
{
bool[] array1 = new bool[] { false, true };
ulong?[] array2 = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableULong(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableUShortTest()
{
bool[] array1 = new bool[] { false, true };
ushort?[] array2 = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableUShort(array1[i], array2[j], array2[k]);
}
}
}
}
[Fact]
public static void CheckTernaryNullableGenericWithStructRestrictionWithEnumTest()
{
CheckTernaryNullableGenericWithStructRestrictionHelper<E>();
}
[Fact]
public static void CheckTernaryNullableGenericWithStructRestrictionWithStructTest()
{
CheckTernaryNullableGenericWithStructRestrictionHelper<S>();
}
[Fact]
public static void CheckTernaryNullableGenericWithStructRestrictionWithStructWithStringAndFieldTest()
{
CheckTernaryNullableGenericWithStructRestrictionHelper<Scs>();
}
#endregion
#region Generic helpers
private static void CheckTernaryNullableGenericWithStructRestrictionHelper<Ts>() where Ts : struct
{
bool[] array1 = new bool[] { false, true };
Ts?[] array2 = new Ts?[] { default(Ts), new Ts() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyNullableGenericWithStructRestriction<Ts>(array1[i], array2[j], array2[k]);
}
}
}
}
#endregion
#region Test verifiers
private static void VerifyNullableBool(bool condition, bool? a, bool? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(bool?)),
Expression.Constant(b, typeof(bool?))),
Enumerable.Empty<ParameterExpression>());
Func<bool?> f = e.Compile();
bool? result = default(bool?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
bool? expected = default(bool?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableByte(bool condition, byte? a, byte? b)
{
Expression<Func<byte?>> e =
Expression.Lambda<Func<byte?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?))),
Enumerable.Empty<ParameterExpression>());
Func<byte?> f = e.Compile();
byte? result = default(byte?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
byte? expected = default(byte?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableChar(bool condition, char? a, char? b)
{
Expression<Func<char?>> e =
Expression.Lambda<Func<char?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?))),
Enumerable.Empty<ParameterExpression>());
Func<char?> f = e.Compile();
char? result = default(char?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
char? expected = default(char?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableDecimal(bool condition, decimal? a, decimal? b)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f = e.Compile();
decimal? result = default(decimal?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
decimal? expected = default(decimal?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableDouble(bool condition, double? a, double? b)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))),
Enumerable.Empty<ParameterExpression>());
Func<double?> f = e.Compile();
double? result = default(double?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
double? expected = default(double?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableEnum(bool condition, E? a, E? b)
{
Expression<Func<E?>> e =
Expression.Lambda<Func<E?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(E?)),
Expression.Constant(b, typeof(E?))),
Enumerable.Empty<ParameterExpression>());
Func<E?> f = e.Compile();
E? result = default(E?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
E? expected = default(E?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableEnumLong(bool condition, El? a, El? b)
{
Expression<Func<El?>> e =
Expression.Lambda<Func<El?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(El?)),
Expression.Constant(b, typeof(El?))),
Enumerable.Empty<ParameterExpression>());
Func<El?> f = e.Compile();
El? result = default(El?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
El? expected = default(El?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableFloat(bool condition, float? a, float? b)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))),
Enumerable.Empty<ParameterExpression>());
Func<float?> f = e.Compile();
float? result = default(float?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
float? expected = default(float?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableInt(bool condition, int? a, int? b)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))),
Enumerable.Empty<ParameterExpression>());
Func<int?> f = e.Compile();
int? result = default(int?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
int? expected = default(int?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableLong(bool condition, long? a, long? b)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))),
Enumerable.Empty<ParameterExpression>());
Func<long?> f = e.Compile();
long? result = default(long?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
long? expected = default(long?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableStruct(bool condition, S? a, S? b)
{
Expression<Func<S?>> e =
Expression.Lambda<Func<S?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(S?)),
Expression.Constant(b, typeof(S?))),
Enumerable.Empty<ParameterExpression>());
Func<S?> f = e.Compile();
S? result = default(S?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
S? expected = default(S?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableSByte(bool condition, sbyte? a, sbyte? b)
{
Expression<Func<sbyte?>> e =
Expression.Lambda<Func<sbyte?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?))),
Enumerable.Empty<ParameterExpression>());
Func<sbyte?> f = e.Compile();
sbyte? result = default(sbyte?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
sbyte? expected = default(sbyte?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableStructWithString(bool condition, Sc? a, Sc? b)
{
Expression<Func<Sc?>> e =
Expression.Lambda<Func<Sc?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Sc?)),
Expression.Constant(b, typeof(Sc?))),
Enumerable.Empty<ParameterExpression>());
Func<Sc?> f = e.Compile();
Sc? result = default(Sc?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
Sc? expected = default(Sc?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableStructWithStringAndField(bool condition, Scs? a, Scs? b)
{
Expression<Func<Scs?>> e =
Expression.Lambda<Func<Scs?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Scs?)),
Expression.Constant(b, typeof(Scs?))),
Enumerable.Empty<ParameterExpression>());
Func<Scs?> f = e.Compile();
Scs? result = default(Scs?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
Scs? expected = default(Scs?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableShort(bool condition, short? a, short? b)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))),
Enumerable.Empty<ParameterExpression>());
Func<short?> f = e.Compile();
short? result = default(short?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
short? expected = default(short?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableStructWithTwoValues(bool condition, Sp? a, Sp? b)
{
Expression<Func<Sp?>> e =
Expression.Lambda<Func<Sp?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Sp?)),
Expression.Constant(b, typeof(Sp?))),
Enumerable.Empty<ParameterExpression>());
Func<Sp?> f = e.Compile();
Sp? result = default(Sp?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
Sp? expected = default(Sp?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableStructWithValue(bool condition, Ss? a, Ss? b)
{
Expression<Func<Ss?>> e =
Expression.Lambda<Func<Ss?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Ss?)),
Expression.Constant(b, typeof(Ss?))),
Enumerable.Empty<ParameterExpression>());
Func<Ss?> f = e.Compile();
Ss? result = default(Ss?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
Ss? expected = default(Ss?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableUInt(bool condition, uint? a, uint? b)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f = e.Compile();
uint? result = default(uint?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
uint? expected = default(uint?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableULong(bool condition, ulong? a, ulong? b)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f = e.Compile();
ulong? result = default(ulong?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
ulong? expected = default(ulong?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableUShort(bool condition, ushort? a, ushort? b)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f = e.Compile();
ushort? result = default(ushort?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
ushort? expected = default(ushort?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyNullableGenericWithStructRestriction<Ts>(bool condition, Ts? a, Ts? b) where Ts : struct
{
Expression<Func<Ts?>> e =
Expression.Lambda<Func<Ts?>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Ts?)),
Expression.Constant(b, typeof(Ts?))),
Enumerable.Empty<ParameterExpression>());
Func<Ts?> f = e.Compile();
Ts? result = default(Ts?);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
Ts? expected = default(Ts?);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
#endregion
}
}
| |
using System;
using System.Text;
/// <summary>
/// Encoding.GetChars(byte[],Int32,Int32,char[],Int32)
/// </summary>
public class EncodingGetChars3
{
public static int Main()
{
EncodingGetChars3 enGetChars3 = new EncodingGetChars3();
TestLibrary.TestFramework.BeginTestCase("EncodingGetChars3");
if (enGetChars3.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;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
retVal = NegTest8() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the GetChars method 1");
try
{
byte[] bytes = new byte[0];
Encoding myEncode = Encoding.GetEncoding("utf-16");
int byteIndex = 0;
int bytecount = 0;
char[] chars = new char[] { TestLibrary.Generator.GetChar(-55)};
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount,chars, 0);
if (intVal != 0 || chars.Length != 1)
{
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 the GetChars method 2");
try
{
string myStr = "za\u0306\u01fd\u03b2";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = 0;
char[] chars = new char[] { TestLibrary.Generator.GetChar(-55) };
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
if (intVal != 0 || chars.Length != 1)
{
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 the GetChars method 3");
try
{
string myStr = "za\u0306\u01fd\u03b2";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length;
char[] chars = new char[myStr.Length];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
if (intVal != myStr.Length || chars.Length != myStr.Length)
{
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 the GetChars method 4");
try
{
string myStr = "za\u0306\u01fd\u03b2";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length;
char[] chars = new char[myStr.Length + myStr.Length];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, myStr.Length - 1);
string subchars = null;
for (int i = 0; i < myStr.Length - 1; i++)
{
subchars += chars[i].ToString();
}
if (intVal != myStr.Length || subchars != "\0\0\0\0")
{
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;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5:Invoke the GetChars method 5");
try
{
string myStr = "za\u0306\u01fd\u03b2";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length - 2;
char[] chars = new char[myStr.Length -1];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
string strVal = new string(chars);
if (intVal != myStr.Length - 1 || strVal != "za\u0306\u01fd")
{
TestLibrary.TestFramework.LogError("009", "the ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1:the byte array is null");
try
{
byte[] bytes = null;
Encoding myEncode = Encoding.GetEncoding("utf-16");
int byteIndex = 0;
int bytecount = 0;
char[] chars = new char[0];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
TestLibrary.TestFramework.LogError("N001", "the byte array 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 char array is null");
try
{
byte[] bytes = new byte[0];
Encoding myEncode = Encoding.GetEncoding("utf-16");
int byteIndex = 0;
int bytecount = 0;
char[] chars = null;
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
TestLibrary.TestFramework.LogError("N003", "the char array is null but not throw exception");
retVal = false;
}
catch (ArgumentNullException) { }
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 char array has no enough capacity to hold the chars");
try
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length;
char[] chars = new char[0];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
TestLibrary.TestFramework.LogError("N005", "the char array has no enough capacity to hold the chars but not throw exception");
retVal = false;
}
catch (ArgumentException) { }
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 byteIndex is less than zero");
try
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = -1;
int bytecount = bytes.Length;
char[] chars = new char[myStr.Length];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
TestLibrary.TestFramework.LogError("N007", "the byteIndex is less than zero but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5:the bytecount is less than zero");
try
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = -1;
char[] chars = new char[myStr.Length];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
TestLibrary.TestFramework.LogError("N009", "the byteIndex is less than zero but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N010", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6:the charIndex is less than zero");
try
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length;
char[] chars = new char[myStr.Length];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, -1);
TestLibrary.TestFramework.LogError("N011", "the charIndex is less than zero but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N012", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest7:the charIndex is not valid index in chars array");
try
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length;
char[] chars = new char[myStr.Length];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, myStr.Length + 1);
TestLibrary.TestFramework.LogError("N013", "the charIndex is not valid index in chars array but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N014", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest8:the byteIndex and bytecount do not denote valid range of the bytes arry");
try
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length + 1;
char[] chars = new char[myStr.Length];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, myStr.Length + 1);
TestLibrary.TestFramework.LogError("N015", "the byteIndex and bytecount do not denote valid range of the bytes arry but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N016", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using System;
using System.Security;
[SecuritySafeCritical]
class TestApp {
//***** TEST CODE *****
static double test_0_0(double num, AA init, AA zero) {
return init.q;
}
static double test_0_1(double num, AA init, AA zero) {
zero.q=num;
return zero.q;
}
static double test_0_2(double num, AA init, AA zero) {
return init.q+zero.q;
}
static double test_0_3(double num, AA init, AA zero) {
return checked(init.q-zero.q);
}
static double test_0_4(double num, AA init, AA zero) {
zero.q+=num; return zero.q;
}
static double test_0_5(double num, AA init, AA zero) {
zero.q+=init.q; return zero.q;
}
static double test_0_6(double num, AA init, AA zero) {
if (init.q==num)
return 100;
else
return zero.q;
}
static double test_0_7(double num, AA init, AA zero) {
return init.q<num+1 ? 100 : -1;
}
static double test_0_8(double num, AA init, AA zero) {
return (init.q>zero.q?1:0)+99;
}
static double test_0_9(double num, AA init, AA zero) {
object bb=init.q;
return (double)bb;
}
static double test_0_10(double num, AA init, AA zero) {
double dbl=init.q;
return (double)dbl;
}
static double test_0_11(double num, AA init, AA zero) {
return AA.call_target(init.q);
}
static double test_0_12(double num, AA init, AA zero) {
return AA.call_target_ref(ref init.q);
}
static double test_1_0(double num, ref AA r_init, ref AA r_zero) {
return r_init.q;
}
static double test_1_1(double num, ref AA r_init, ref AA r_zero) {
r_zero.q=num;
return r_zero.q;
}
static double test_1_2(double num, ref AA r_init, ref AA r_zero) {
return r_init.q+r_zero.q;
}
static double test_1_3(double num, ref AA r_init, ref AA r_zero) {
return checked(r_init.q-r_zero.q);
}
static double test_1_4(double num, ref AA r_init, ref AA r_zero) {
r_zero.q+=num; return r_zero.q;
}
static double test_1_5(double num, ref AA r_init, ref AA r_zero) {
r_zero.q+=r_init.q; return r_zero.q;
}
static double test_1_6(double num, ref AA r_init, ref AA r_zero) {
if (r_init.q==num)
return 100;
else
return r_zero.q;
}
static double test_1_7(double num, ref AA r_init, ref AA r_zero) {
return r_init.q<num+1 ? 100 : -1;
}
static double test_1_8(double num, ref AA r_init, ref AA r_zero) {
return (r_init.q>r_zero.q?1:0)+99;
}
static double test_1_9(double num, ref AA r_init, ref AA r_zero) {
object bb=r_init.q;
return (double)bb;
}
static double test_1_10(double num, ref AA r_init, ref AA r_zero) {
double dbl=r_init.q;
return (double)dbl;
}
static double test_1_11(double num, ref AA r_init, ref AA r_zero) {
return AA.call_target(r_init.q);
}
static double test_1_12(double num, ref AA r_init, ref AA r_zero) {
return AA.call_target_ref(ref r_init.q);
}
static double test_2_0(double num) {
return AA.a_init[(int)num].q;
}
static double test_2_1(double num) {
AA.a_zero[(int)num].q=num;
return AA.a_zero[(int)num].q;
}
static double test_2_2(double num) {
return AA.a_init[(int)num].q+AA.a_zero[(int)num].q;
}
static double test_2_3(double num) {
return checked(AA.a_init[(int)num].q-AA.a_zero[(int)num].q);
}
static double test_2_4(double num) {
AA.a_zero[(int)num].q+=num; return AA.a_zero[(int)num].q;
}
static double test_2_5(double num) {
AA.a_zero[(int)num].q+=AA.a_init[(int)num].q; return AA.a_zero[(int)num].q;
}
static double test_2_6(double num) {
if (AA.a_init[(int)num].q==num)
return 100;
else
return AA.a_zero[(int)num].q;
}
static double test_2_7(double num) {
return AA.a_init[(int)num].q<num+1 ? 100 : -1;
}
static double test_2_8(double num) {
return (AA.a_init[(int)num].q>AA.a_zero[(int)num].q?1:0)+99;
}
static double test_2_9(double num) {
object bb=AA.a_init[(int)num].q;
return (double)bb;
}
static double test_2_10(double num) {
double dbl=AA.a_init[(int)num].q;
return (double)dbl;
}
static double test_2_11(double num) {
return AA.call_target(AA.a_init[(int)num].q);
}
static double test_2_12(double num) {
return AA.call_target_ref(ref AA.a_init[(int)num].q);
}
static double test_3_0(double num) {
return AA.aa_init[0,(int)num-1,(int)num/100].q;
}
static double test_3_1(double num) {
AA.aa_zero[0,(int)num-1,(int)num/100].q=num;
return AA.aa_zero[0,(int)num-1,(int)num/100].q;
}
static double test_3_2(double num) {
return AA.aa_init[0,(int)num-1,(int)num/100].q+AA.aa_zero[0,(int)num-1,(int)num/100].q;
}
static double test_3_3(double num) {
return checked(AA.aa_init[0,(int)num-1,(int)num/100].q-AA.aa_zero[0,(int)num-1,(int)num/100].q);
}
static double test_3_4(double num) {
AA.aa_zero[0,(int)num-1,(int)num/100].q+=num; return AA.aa_zero[0,(int)num-1,(int)num/100].q;
}
static double test_3_5(double num) {
AA.aa_zero[0,(int)num-1,(int)num/100].q+=AA.aa_init[0,(int)num-1,(int)num/100].q; return AA.aa_zero[0,(int)num-1,(int)num/100].q;
}
static double test_3_6(double num) {
if (AA.aa_init[0,(int)num-1,(int)num/100].q==num)
return 100;
else
return AA.aa_zero[0,(int)num-1,(int)num/100].q;
}
static double test_3_7(double num) {
return AA.aa_init[0,(int)num-1,(int)num/100].q<num+1 ? 100 : -1;
}
static double test_3_8(double num) {
return (AA.aa_init[0,(int)num-1,(int)num/100].q>AA.aa_zero[0,(int)num-1,(int)num/100].q?1:0)+99;
}
static double test_3_9(double num) {
object bb=AA.aa_init[0,(int)num-1,(int)num/100].q;
return (double)bb;
}
static double test_3_10(double num) {
double dbl=AA.aa_init[0,(int)num-1,(int)num/100].q;
return (double)dbl;
}
static double test_3_11(double num) {
return AA.call_target(AA.aa_init[0,(int)num-1,(int)num/100].q);
}
static double test_3_12(double num) {
return AA.call_target_ref(ref AA.aa_init[0,(int)num-1,(int)num/100].q);
}
static double test_4_0(double num) {
return BB.f_init.q;
}
static double test_4_1(double num) {
BB.f_zero.q=num;
return BB.f_zero.q;
}
static double test_4_2(double num) {
return BB.f_init.q+BB.f_zero.q;
}
static double test_4_3(double num) {
return checked(BB.f_init.q-BB.f_zero.q);
}
static double test_4_4(double num) {
BB.f_zero.q+=num; return BB.f_zero.q;
}
static double test_4_5(double num) {
BB.f_zero.q+=BB.f_init.q; return BB.f_zero.q;
}
static double test_4_6(double num) {
if (BB.f_init.q==num)
return 100;
else
return BB.f_zero.q;
}
static double test_4_7(double num) {
return BB.f_init.q<num+1 ? 100 : -1;
}
static double test_4_8(double num) {
return (BB.f_init.q>BB.f_zero.q?1:0)+99;
}
static double test_4_9(double num) {
object bb=BB.f_init.q;
return (double)bb;
}
static double test_4_10(double num) {
double dbl=BB.f_init.q;
return (double)dbl;
}
static double test_4_11(double num) {
return AA.call_target(BB.f_init.q);
}
static double test_4_12(double num) {
return AA.call_target_ref(ref BB.f_init.q);
}
static double test_5_0(double num) {
return ((AA)AA.b_init).q;
}
static unsafe double test_7_0(double num, void *ptr_init, void *ptr_zero) {
return (*((AA*)ptr_init)).q;
}
static unsafe double test_7_1(double num, void *ptr_init, void *ptr_zero) {
(*((AA*)ptr_zero)).q=num;
return (*((AA*)ptr_zero)).q;
}
static unsafe double test_7_2(double num, void *ptr_init, void *ptr_zero) {
return (*((AA*)ptr_init)).q+(*((AA*)ptr_zero)).q;
}
static unsafe double test_7_3(double num, void *ptr_init, void *ptr_zero) {
return checked((*((AA*)ptr_init)).q-(*((AA*)ptr_zero)).q);
}
static unsafe double test_7_4(double num, void *ptr_init, void *ptr_zero) {
(*((AA*)ptr_zero)).q+=num; return (*((AA*)ptr_zero)).q;
}
static unsafe double test_7_5(double num, void *ptr_init, void *ptr_zero) {
(*((AA*)ptr_zero)).q+=(*((AA*)ptr_init)).q; return (*((AA*)ptr_zero)).q;
}
static unsafe double test_7_6(double num, void *ptr_init, void *ptr_zero) {
if ((*((AA*)ptr_init)).q==num)
return 100;
else
return (*((AA*)ptr_zero)).q;
}
static unsafe double test_7_7(double num, void *ptr_init, void *ptr_zero) {
return (*((AA*)ptr_init)).q<num+1 ? 100 : -1;
}
static unsafe double test_7_8(double num, void *ptr_init, void *ptr_zero) {
return ((*((AA*)ptr_init)).q>(*((AA*)ptr_zero)).q?1:0)+99;
}
static unsafe double test_7_9(double num, void *ptr_init, void *ptr_zero) {
object bb=(*((AA*)ptr_init)).q;
return (double)bb;
}
static unsafe double test_7_10(double num, void *ptr_init, void *ptr_zero) {
double dbl=(*((AA*)ptr_init)).q;
return (double)dbl;
}
static unsafe double test_7_11(double num, void *ptr_init, void *ptr_zero) {
return AA.call_target((*((AA*)ptr_init)).q);
}
static unsafe double test_7_12(double num, void *ptr_init, void *ptr_zero) {
return AA.call_target_ref(ref (*((AA*)ptr_init)).q);
}
//***** MAIN CODE *****
static unsafe int Main() {
AA.reset();
if (test_0_0(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_0() failed.");
return 101;
}
AA.verify_all(); AA.reset();
if (test_0_1(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_1() failed.");
return 102;
}
AA.verify_all(); AA.reset();
if (test_0_2(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_2() failed.");
return 103;
}
AA.verify_all(); AA.reset();
if (test_0_3(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_3() failed.");
return 104;
}
AA.verify_all(); AA.reset();
if (test_0_4(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_4() failed.");
return 105;
}
AA.verify_all(); AA.reset();
if (test_0_5(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_5() failed.");
return 106;
}
AA.verify_all(); AA.reset();
if (test_0_6(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_6() failed.");
return 107;
}
AA.verify_all(); AA.reset();
if (test_0_7(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_7() failed.");
return 108;
}
AA.verify_all(); AA.reset();
if (test_0_8(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_8() failed.");
return 109;
}
AA.verify_all(); AA.reset();
if (test_0_9(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_9() failed.");
return 110;
}
AA.verify_all(); AA.reset();
if (test_0_10(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_10() failed.");
return 111;
}
AA.verify_all(); AA.reset();
if (test_0_11(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_11() failed.");
return 112;
}
AA.verify_all(); AA.reset();
if (test_0_12(100, new AA(100), new AA(0)) != 100) {
Console.WriteLine("test_0_12() failed.");
return 113;
}
AA.verify_all(); AA.reset();
if (test_1_0(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_0() failed.");
return 114;
}
AA.verify_all(); AA.reset();
if (test_1_1(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_1() failed.");
return 115;
}
AA.verify_all(); AA.reset();
if (test_1_2(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_2() failed.");
return 116;
}
AA.verify_all(); AA.reset();
if (test_1_3(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_3() failed.");
return 117;
}
AA.verify_all(); AA.reset();
if (test_1_4(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_4() failed.");
return 118;
}
AA.verify_all(); AA.reset();
if (test_1_5(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_5() failed.");
return 119;
}
AA.verify_all(); AA.reset();
if (test_1_6(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_6() failed.");
return 120;
}
AA.verify_all(); AA.reset();
if (test_1_7(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_7() failed.");
return 121;
}
AA.verify_all(); AA.reset();
if (test_1_8(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_8() failed.");
return 122;
}
AA.verify_all(); AA.reset();
if (test_1_9(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_9() failed.");
return 123;
}
AA.verify_all(); AA.reset();
if (test_1_10(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_10() failed.");
return 124;
}
AA.verify_all(); AA.reset();
if (test_1_11(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_11() failed.");
return 125;
}
AA.verify_all(); AA.reset();
if (test_1_12(100, ref AA._init, ref AA._zero) != 100) {
Console.WriteLine("test_1_12() failed.");
return 126;
}
AA.verify_all(); AA.reset();
if (test_2_0(100) != 100) {
Console.WriteLine("test_2_0() failed.");
return 127;
}
AA.verify_all(); AA.reset();
if (test_2_1(100) != 100) {
Console.WriteLine("test_2_1() failed.");
return 128;
}
AA.verify_all(); AA.reset();
if (test_2_2(100) != 100) {
Console.WriteLine("test_2_2() failed.");
return 129;
}
AA.verify_all(); AA.reset();
if (test_2_3(100) != 100) {
Console.WriteLine("test_2_3() failed.");
return 130;
}
AA.verify_all(); AA.reset();
if (test_2_4(100) != 100) {
Console.WriteLine("test_2_4() failed.");
return 131;
}
AA.verify_all(); AA.reset();
if (test_2_5(100) != 100) {
Console.WriteLine("test_2_5() failed.");
return 132;
}
AA.verify_all(); AA.reset();
if (test_2_6(100) != 100) {
Console.WriteLine("test_2_6() failed.");
return 133;
}
AA.verify_all(); AA.reset();
if (test_2_7(100) != 100) {
Console.WriteLine("test_2_7() failed.");
return 134;
}
AA.verify_all(); AA.reset();
if (test_2_8(100) != 100) {
Console.WriteLine("test_2_8() failed.");
return 135;
}
AA.verify_all(); AA.reset();
if (test_2_9(100) != 100) {
Console.WriteLine("test_2_9() failed.");
return 136;
}
AA.verify_all(); AA.reset();
if (test_2_10(100) != 100) {
Console.WriteLine("test_2_10() failed.");
return 137;
}
AA.verify_all(); AA.reset();
if (test_2_11(100) != 100) {
Console.WriteLine("test_2_11() failed.");
return 138;
}
AA.verify_all(); AA.reset();
if (test_2_12(100) != 100) {
Console.WriteLine("test_2_12() failed.");
return 139;
}
AA.verify_all(); AA.reset();
if (test_3_0(100) != 100) {
Console.WriteLine("test_3_0() failed.");
return 140;
}
AA.verify_all(); AA.reset();
if (test_3_1(100) != 100) {
Console.WriteLine("test_3_1() failed.");
return 141;
}
AA.verify_all(); AA.reset();
if (test_3_2(100) != 100) {
Console.WriteLine("test_3_2() failed.");
return 142;
}
AA.verify_all(); AA.reset();
if (test_3_3(100) != 100) {
Console.WriteLine("test_3_3() failed.");
return 143;
}
AA.verify_all(); AA.reset();
if (test_3_4(100) != 100) {
Console.WriteLine("test_3_4() failed.");
return 144;
}
AA.verify_all(); AA.reset();
if (test_3_5(100) != 100) {
Console.WriteLine("test_3_5() failed.");
return 145;
}
AA.verify_all(); AA.reset();
if (test_3_6(100) != 100) {
Console.WriteLine("test_3_6() failed.");
return 146;
}
AA.verify_all(); AA.reset();
if (test_3_7(100) != 100) {
Console.WriteLine("test_3_7() failed.");
return 147;
}
AA.verify_all(); AA.reset();
if (test_3_8(100) != 100) {
Console.WriteLine("test_3_8() failed.");
return 148;
}
AA.verify_all(); AA.reset();
if (test_3_9(100) != 100) {
Console.WriteLine("test_3_9() failed.");
return 149;
}
AA.verify_all(); AA.reset();
if (test_3_10(100) != 100) {
Console.WriteLine("test_3_10() failed.");
return 150;
}
AA.verify_all(); AA.reset();
if (test_3_11(100) != 100) {
Console.WriteLine("test_3_11() failed.");
return 151;
}
AA.verify_all(); AA.reset();
if (test_3_12(100) != 100) {
Console.WriteLine("test_3_12() failed.");
return 152;
}
AA.verify_all(); AA.reset();
if (test_4_0(100) != 100) {
Console.WriteLine("test_4_0() failed.");
return 153;
}
AA.verify_all(); AA.reset();
if (test_4_1(100) != 100) {
Console.WriteLine("test_4_1() failed.");
return 154;
}
AA.verify_all(); AA.reset();
if (test_4_2(100) != 100) {
Console.WriteLine("test_4_2() failed.");
return 155;
}
AA.verify_all(); AA.reset();
if (test_4_3(100) != 100) {
Console.WriteLine("test_4_3() failed.");
return 156;
}
AA.verify_all(); AA.reset();
if (test_4_4(100) != 100) {
Console.WriteLine("test_4_4() failed.");
return 157;
}
AA.verify_all(); AA.reset();
if (test_4_5(100) != 100) {
Console.WriteLine("test_4_5() failed.");
return 158;
}
AA.verify_all(); AA.reset();
if (test_4_6(100) != 100) {
Console.WriteLine("test_4_6() failed.");
return 159;
}
AA.verify_all(); AA.reset();
if (test_4_7(100) != 100) {
Console.WriteLine("test_4_7() failed.");
return 160;
}
AA.verify_all(); AA.reset();
if (test_4_8(100) != 100) {
Console.WriteLine("test_4_8() failed.");
return 161;
}
AA.verify_all(); AA.reset();
if (test_4_9(100) != 100) {
Console.WriteLine("test_4_9() failed.");
return 162;
}
AA.verify_all(); AA.reset();
if (test_4_10(100) != 100) {
Console.WriteLine("test_4_10() failed.");
return 163;
}
AA.verify_all(); AA.reset();
if (test_4_11(100) != 100) {
Console.WriteLine("test_4_11() failed.");
return 164;
}
AA.verify_all(); AA.reset();
if (test_4_12(100) != 100) {
Console.WriteLine("test_4_12() failed.");
return 165;
}
AA.verify_all(); AA.reset();
if (test_5_0(100) != 100) {
Console.WriteLine("test_5_0() failed.");
return 166;
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_0(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_0() failed.");
return 168;
}
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_1(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_1() failed.");
return 169;
}
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_2(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_2() failed.");
return 170;
}
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_3(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_3() failed.");
return 171;
}
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_4(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_4() failed.");
return 172;
}
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_5(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_5() failed.");
return 173;
}
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_6(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_6() failed.");
return 174;
}
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_7(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_7() failed.");
return 175;
}
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_8(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_8() failed.");
return 176;
}
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_9(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_9() failed.");
return 177;
}
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_10(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_10() failed.");
return 178;
}
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_11(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_11() failed.");
return 179;
}
}
AA.verify_all(); AA.reset();
fixed (void *p_init = &AA._init, p_zero = &AA._zero) {
if (test_7_12(100, p_init, p_zero) != 100) {
Console.WriteLine("test_7_12() failed.");
return 180;
}
}
AA.verify_all(); Console.WriteLine("All tests passed.");
return 100;
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using WOSI.CallButler.Data;
namespace CallButler.Telecom
{
public struct AudioCodecInformation
{
public string Name;
public bool Enabled;
public object Tag;
}
public class LineEventArgs : EventArgs
{
public int LineNumber = 0;
public object Tag;
public LineEventArgs(int lineNumber)
{
this.LineNumber = lineNumber;
}
public LineEventArgs(int lineNumber, object tag)
{
this.LineNumber = lineNumber;
this.Tag = tag;
}
}
public class CallFailureEventArgs : LineEventArgs
{
public int ReasonCode = 0;
public string Reason = "";
public CallFailureEventArgs(int lineNumber, int reasonCode, string reason)
: base(lineNumber)
{
this.ReasonCode = reasonCode;
this.Reason = reason;
}
}
public class CallEventArgs : LineEventArgs
{
public string CallerDisplayName = "";
public string CallerPhoneNumber = "";
public string CallerIPAddress = "";
public int CallerPort = 0;
public string CallerMiscInfo = "";
public string CallingToNumber = "";
public string CallingToMiscInfo = "";
public object Tag = null;
public bool Outbound = false;
public CallEventArgs(int lineNumber, string callingToNumber, string callingToMiscInfo, string callerDisplayName, string callerPhoneNumber, string callerIPAddress, int callerPort, string callerMiscInfo, bool outbound, object tag)
: base(lineNumber)
{
CallerDisplayName = callerDisplayName;
CallerPhoneNumber = callerPhoneNumber;
CallerIPAddress = callerIPAddress;
CallerPort = callerPort;
CallerMiscInfo = callerMiscInfo;
CallingToNumber = callingToNumber;
CallingToMiscInfo = callingToMiscInfo;
Tag = tag;
Outbound = outbound;
}
}
public class TransferEventArgs : CallEventArgs
{
public string ReplacesID = null;
public int ReplacementLineNumber = 0;
public TransferEventArgs(int lineNumber, string callingToNumber, string callingToMiscInfo, string callerDisplayName, string callerPhoneNumber, string callerIPAddress, int callerPort, string callerMiscInfo, int replacementLineNumber, string replacesID, bool outbound, object tag)
: base(lineNumber, callingToNumber, callingToMiscInfo, callerDisplayName, callerPhoneNumber, callerIPAddress, callerPort, callerMiscInfo, outbound, tag)
{
this.ReplacesID = replacesID;
this.ReplacementLineNumber = replacementLineNumber;
}
}
public class BusyCallEventArgs : CallEventArgs
{
public string CallID = "";
public BusyCallEventArgs(string callID, string callingToNumber, string callingToMiscInfo, string callerDisplayName, string callerPhoneNumber, string callerIPAddress, int callerPort, string callerMiscInfo, bool outbound, object tag)
: base(0, callingToNumber, callingToMiscInfo, callerDisplayName, callerPhoneNumber, callerIPAddress, callerPort, callerMiscInfo, outbound, tag)
{
CallID = callID;
}
}
public class CallInputEventArgs : LineEventArgs
{
public string InputString = "";
public bool InAudio = false;
public CallInputEventArgs(int lineNumber, string inputString)
: base(lineNumber)
{
InputString = inputString;
}
public CallInputEventArgs(int lineNumber, string inputString, bool inAudio)
: base(lineNumber)
{
InputString = inputString;
InAudio = inAudio;
}
}
public class ErrorEventArgs : EventArgs
{
public string ErrorMessage = "";
public string ErrorDetail = "";
public ErrorEventArgs(string errorMessage, string errorDetail)
{
this.ErrorMessage = errorMessage;
this.ErrorDetail = errorDetail;
}
}
public abstract class TelecomProviderBase
{
public event EventHandler<CallEventArgs> IncomingCall;
public event EventHandler<BusyCallEventArgs> IncomingBusyCall;
public event EventHandler<CallEventArgs> CallConnected;
public event EventHandler<LineEventArgs> CallEnded;
public event EventHandler<CallFailureEventArgs> CallFailed;
public event EventHandler<CallInputEventArgs> DTMFToneRecognized;
public event EventHandler<LineEventArgs> FaxToneDetected;
public event EventHandler<LineEventArgs> FinishedSpeaking;
public event EventHandler<LineEventArgs> SoundFinishedPlaying;
public event EventHandler<CallInputEventArgs> SpeechRecognized;
public event EventHandler<LineEventArgs> TransferFailed;
public event EventHandler<LineEventArgs> TransferSucceeded;
public event EventHandler<LineEventArgs> RemoteOnHold;
public event EventHandler<LineEventArgs> RemoteOffHold;
public event EventHandler<ErrorEventArgs> Error;
public event EventHandler<TransferEventArgs> IncomingTransfer;
public event EventHandler<CallEventArgs> CallTemporarilyMoved;
public event EventHandler<LineEventArgs> AnswerDetectHuman;
public event EventHandler<LineEventArgs> AnswerDetectMachine;
public event EventHandler<LineEventArgs> AnswerDetectMachineGreetingFinished;
protected System.Windows.Forms.ToolStripMenuItem contextMenu;
protected System.Windows.Forms.NotifyIcon notifyIcon;
public TelecomProviderBase(System.Windows.Forms.ToolStripMenuItem contextMenu, System.Windows.Forms.NotifyIcon notifyIcon, params object[] initializationParams)
{
this.contextMenu = contextMenu;
this.notifyIcon = notifyIcon;
}
#region Startup/Shutdown Methods
public void Startup()
{
OnStartup();
}
public void Shutdown()
{
OnShutdown();
}
protected virtual void OnStartup()
{
}
protected virtual void OnShutdown()
{
}
#endregion
#region Properties
public virtual int LineCount
{
get
{
return 0;
}
}
public virtual object BaseProviderObject
{
get
{
return null;
}
}
public virtual int AudioInputRate
{
get
{
return 8000;
}
}
public virtual string LocalIPAddress
{
get
{
return WOSI.Utilities.NetworkUtils.GetHostIPAddress(System.Net.Dns.GetHostName(), System.Net.Sockets.AddressFamily.InterNetwork).ToString();
}
}
#endregion
#region Call Control Functions
/*public virtual void Call(int lineNumber, string number, string fromCallerID, object profile)
{
}*/
public virtual void Call(int lineNumber, string number, string fromCallerID, string fromCallerNumber, bool requestAutoAnswer, WOSI.CallButler.Data.CallButlerDataset.ProvidersRow provider)
{
}
public virtual void Call(int lineNumber, string number, string fromCallerID, string fromCallerNumber, string replacesID, string referredBy, bool requestAutoAnswer, WOSI.CallButler.Data.CallButlerDataset.ProvidersRow provider)
{
}
public virtual void CallBlast(int lineNumber, string[] numbers, string fromCallerID, string fromCallerNumber, WOSI.CallButler.Data.CallButlerDataset.ProvidersRow[] providers)
{
}
public virtual void AnswerCall(int lineNumber, bool autoDetectAudio)
{
}
public virtual void DeclineCall(int lineNumber)
{
}
public virtual void RedirectCall(int lineNumber, string redirectLocation)
{
}
public virtual void RedirectBusyCall(string callID, string redirectLocation)
{
}
public virtual void DeclineBusyCall(string callID)
{
}
public virtual void EndCall(int lineNumber)
{
}
public virtual void TransferCall(int lineNumber, string transferToNumber)
{
}
public virtual void TransferCallAttended(int lineNumber1, int lineNumber2, bool useBridge)
{
}
public virtual bool IsLineInUse(int lineNumber)
{
return false;
}
public virtual void CallHold(int lineNumber, bool putOnHold, bool keepAudioAlive)
{
}
public virtual int ConferenceLines(params int[] lines)
{
return -1;
}
public virtual void MuteConferenceLine(int conferenceID, int lineNumber, bool mute)
{
}
public virtual void EndConference(int conferenceID, bool hangUp)
{
}
public virtual void AddLineToConference(int conferenceID, int lineNumber)
{
}
public virtual void RemoveLineFromConference(int lineNumber)
{
}
public virtual void LockLine(int lineNumber)
{
}
public virtual void UnlockLine(int lineNumber)
{
}
#endregion
#region Sound Functions
public virtual void PlaySound(int lineNumber, byte[] soundBytes)
{
}
public virtual void PlaySound(int lineNumber, string filename, bool loop)
{
}
public virtual void StopSound(int lineNumber)
{
}
public virtual void StartRecording(int lineNumber, string filename, string format)
{
}
public virtual void StopRecording(int lineNumber, string comments)
{
}
public virtual void SetSoundVolume(int lineNumber, int volume)
{
}
public virtual void SetSpeechVolume(int lineNumber, int volume)
{
}
public virtual void SetRecordVolume(int lineNumber, int volume)
{
}
public virtual void Hold(int lineNumber, bool onHold)
{
}
#endregion
#region Codec Functions
public virtual AudioCodecInformation[] GetAudioCodecs()
{
return new AudioCodecInformation[0];
}
public virtual void SetAudioCodecs(AudioCodecInformation[] codecs)
{
}
#endregion
#region Misc Functions
public virtual void SendDTMF(int lineNumber, string dtmfString, bool inAudio)
{
}
public virtual void EnableAnsweringMachineDetection(int lineNumber, bool enable)
{
}
public virtual void SetAnsweringMachineDetectionSettings(int lineNumber, string settingsData)
{
}
#endregion
#region Speech Functions
public virtual void SpeakText(int lineNumber, string textToSpeak)
{
}
public virtual void StopSpeaking(int lineNumber)
{
}
public virtual void ListenForSpeech(int lineNumber, string[] phrases)
{
}
public virtual void StopListeningForSpeech(int lineNumber)
{
}
public virtual void ClearSpeechRecoPhrases(int lineNumber)
{
}
#endregion
#region Event Raisers
protected void RaiseIncomingTransfer(TransferEventArgs e)
{
if (IncomingTransfer != null)
IncomingTransfer(this, e);
}
protected void RaiseCallTemporarilyMoved(CallEventArgs e)
{
if (CallTemporarilyMoved != null)
CallTemporarilyMoved(this, e);
}
protected void RaiseIncomingCall(CallEventArgs e)
{
if (IncomingCall != null)
IncomingCall(this, e);
}
protected void RaiseIncomingBusyCall(BusyCallEventArgs e)
{
if (IncomingBusyCall != null)
IncomingBusyCall(this, e);
}
protected void RaiseCallConnected(CallEventArgs e)
{
if (CallConnected != null)
CallConnected(this, e);
}
protected void RaiseCallEnded(LineEventArgs e)
{
if (CallEnded != null)
CallEnded(this, e);
}
protected void RaiseDTMFToneRecognized(CallInputEventArgs e)
{
if (DTMFToneRecognized != null)
DTMFToneRecognized(this, e);
}
protected void RaiseFaxToneDetected(LineEventArgs e)
{
if(FaxToneDetected != null)
FaxToneDetected(this, e);
}
protected void RaiseFinishedSpeaking(LineEventArgs e)
{
if (FinishedSpeaking != null)
FinishedSpeaking(this, e);
}
protected void RaiseSoundFinishedPlaying(LineEventArgs e)
{
if (SoundFinishedPlaying != null)
SoundFinishedPlaying(this, e);
}
protected void RaiseSpeechRecognized(CallInputEventArgs e)
{
if (SpeechRecognized != null)
SpeechRecognized(this, e);
}
protected void RaiseTransferFailed(LineEventArgs e)
{
if (TransferFailed != null)
TransferFailed(this, e);
}
protected void RaiseTransferSucceeded(LineEventArgs e)
{
if (TransferSucceeded != null)
TransferSucceeded(this, e);
}
protected void RaiseCallFailed(CallFailureEventArgs e)
{
if (CallFailed != null)
CallFailed(this, e);
}
protected void RaiseError(ErrorEventArgs e)
{
if (Error != null)
Error(this, e);
}
protected void RaiseRemoteOnHold(LineEventArgs e)
{
if (RemoteOnHold != null)
RemoteOnHold(this, e);
}
protected void RaiseRemoteOffHold(LineEventArgs e)
{
if (RemoteOffHold != null)
RemoteOffHold(this, e);
}
protected void RaiseAnswerDetectHuman(LineEventArgs e)
{
if (AnswerDetectHuman != null)
AnswerDetectHuman(this, e);
}
protected void RaiseAnswerDetectMachine(LineEventArgs e)
{
if (AnswerDetectMachine != null)
AnswerDetectMachine(this, e);
}
protected void RaiseAnswerDetectMachineGreetingFinished(LineEventArgs e)
{
if (AnswerDetectMachineGreetingFinished != null)
AnswerDetectMachineGreetingFinished(this, e);
}
#endregion
#region Network Registration Functions
public virtual void Register(Guid registrationID, object registrationParams)
{
}
public virtual void Unregister(Guid registrationID)
{
}
public virtual string GetRegistrationState(Guid registrationID)
{
return "";
}
#endregion
#region Misc Functions
public virtual void SendingToVoicemail(int lineNumber)
{
}
#endregion
}
}
| |
//---------------------------------------------------------------------
// Author: Keith Hill
//
// Description: Class to implement some generic error utilities.
//
// Creation Date: Sept 12, 2006
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Pscx.Interop;
using System.Globalization;
using System.ComponentModel;
namespace Pscx
{
public static class Utils
{
private const int MaxPath = 260;
public static FileSystemInfo GetFileOrDirectory(String path)
{
var fi = new FileInfo(path);
if (fi.Exists)
{
return fi;
}
var di = new DirectoryInfo(path);
if (di.Exists)
{
return di;
}
return null;
}
public static string GetShortPathName(FileSystemInfo info)
{
PscxArgumentException.ThrowIfIsNull(info);
if (!info.Exists)
{
if (info is DirectoryInfo)
{
throw new DirectoryNotFoundException();
}
throw new FileNotFoundException();
}
StringBuilder buffer = new StringBuilder(MaxPath);
bool result = NativeMethods.GetShortPathName(info.FullName, buffer, (uint)(buffer.Capacity));
if (!result)
{
throw new Win32Exception();
}
return buffer.ToString();
}
public static string GetShortPathName(string path)
{
PscxArgumentException.ThrowIfIsNull(path);
FileSystemInfo info = GetFileOrDirectory(path);
if (info == null)
{
throw new FileNotFoundException();
}
return GetShortPathName(info);
}
public static void AdjustTokenPrivileges(SafeTokenHandle hToken, TokenPrivilegeCollection privileges)
{
byte[] buffer = privileges.ToTOKEN_PRIVILEGES();
if (!NativeMethods.AdjustTokenPrivileges(hToken,
false,
buffer,
buffer.Length,
IntPtr.Zero,
IntPtr.Zero))
{
throw PscxException.LastWin32Exception();
}
}
public static T GetAttribute<T>(ICustomAttributeProvider provider)
where T : Attribute
{
return GetAttribute<T>(provider, false);
}
public static T GetAttribute<T>(ICustomAttributeProvider provider, bool inherit)
where T : Attribute
{
T[] attrs = GetAttributes<T>(provider, inherit);
if (attrs == null || attrs.Length == 0)
{
return null;
}
return attrs[0];
}
public static T[] GetAttributes<T>(ICustomAttributeProvider provider, bool inherit)
{
object[] attrs = provider.GetCustomAttributes(typeof(T), inherit);
if (attrs.Length == 0)
{
return null;
}
return attrs as T[];
}
public static T PtrToStructure<T>(IntPtr ptr) where T : struct
{
return (T)(Marshal.PtrToStructure(ptr, typeof(T)));
}
public static IntPtr IncrementPointer<T>(IntPtr ptr) where T : struct
{
return new IntPtr(ptr.ToInt64() + Marshal.SizeOf(typeof(T)));
}
public static IEnumerable<T> ReadNativeArray<T>(IntPtr ptr, int length) where T : struct
{
IntPtr current = ptr;
for (int i = 0; i < length; i++)
{
yield return PtrToStructure<T>(current);
current = IncrementPointer<T>(current);
}
}
public static long MakeLong(uint high, uint low)
{
return (high << 32) | (low);
}
public static int HighWord(int value)
{
return value >> 16;
}
public static int LowWord(int value)
{
return value & 0xffff;
}
public static TEnum ParseEnumOrThrow<TEnum>(string value)
{
PscxArgumentException.ThrowIfIsNotDefined(typeof(TEnum), value);
return (TEnum)(Enum.Parse(typeof(TEnum), value));
}
public static string GetEnumName(Enum value)
{
return Enum.GetName(value.GetType(), value);
}
public static void DoubleCheckInit<T>(ref T obj, object syncRoot, Producer<T> init)
{
if (Equals(obj, default(T)))
{
Thread.MemoryBarrier();
lock (syncRoot)
{
if (Equals(obj, default(T)))
{
obj = init();
}
}
}
}
public static string FormatInvariant(string format, params object[] args)
{
return String.Format(CultureInfo.InvariantCulture, format, args);
}
public static void SplitString(string str, int middlePoint, out string left, out string right)
{
left = right = string.Empty;
if (!string.IsNullOrEmpty(str))
{
if (middlePoint <= 0)
{
right = str;
}
else if (middlePoint >= str.Length - 1)
{
left = str;
}
else
{
left = str.Substring(0, middlePoint);
right = str.Substring(middlePoint + 1);
}
}
}
public static object UnwrapPSObject(object wrappedObject)
{
return UnwrapPSObject<object>(wrappedObject);
}
public static T UnwrapPSObject<T>(object wrappedObject)
{
if (wrappedObject != null)
{
if (wrappedObject is PSObject)
{
// ensure incoming object is fully unwrapped
// bugs in powershell mean that incoming objects may
// or may not have a PSObject wrapper.
object immediateBaseObject;
var temp = (PSObject) wrappedObject;
do
{
immediateBaseObject = temp.ImmediateBaseObject;
temp = immediateBaseObject as PSObject;
} while (temp != null);
wrappedObject = immediateBaseObject;
}
}
return (T)wrappedObject;
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace DotSpatial.Data.Forms
{
/// <summary>
/// This component allows customization of how log messages are sent.
/// </summary>
public class LogManager : ILogManager
{
#region Fields
// the actual collection of ILoggers
private readonly IDictionary<int, ILogger> _loggers;
// increments so that each addition increments the active key.
private int _currentKey;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LogManager"/> class.
/// </summary>
public LogManager()
{
InitializeComponent();
_loggers = new Dictionary<int, ILogger>();
_currentKey = 0;
DefaultLogManager = this;
}
#endregion
#region Properties
/// <summary>
/// Gets the default log manager. This ensures that there will always be some kind of log manager.
/// When a new LogManager is created, this static is set to be that instance.
/// Controlling the DefaultLogManager will control which log manager
/// is actively in use.
/// </summary>
public static ILogManager DefaultLogManager { get; private set; } = new LogManager();
/// <summary>
/// Gets a required designer variable.
/// </summary>
public IContainer Components { get; private set; }
/// <summary>
/// Gets or sets the list of string directories that may contain dlls with ILogManagers.
/// </summary>
public List<string> Directories { get; set; }
#endregion
#region Methods
/// <summary>
/// To begin logging, create an implementation of the ILogHandler interface, or use the DefaultLogger class that is already implemented in this project.
/// Then, call this function to add that logger to the list of active loggers.
/// This function will return an integer key that you can use to keep track of your specific logger.
/// </summary>
/// <param name="logger">The logger that should be added to the list of active loggers.</param>
/// <returns>Integer key of this logger.</returns>
public int AddLogger(ILogger logger)
{
// The current key will keep going up even if loggers are removed, just so we don't get into trouble with redundancies.
_loggers.Add(_currentKey, logger);
_currentKey++;
return _currentKey - 1;
}
/// <summary>
/// Adds all the loggers from directories.
/// </summary>
/// <returns>A list of added loggers.</returns>
public List<ILogger> AddLoggersFromDirectories()
{
return null;
// TO DO: treat this like DataManager does
}
/// <summary>
/// The Complete exception is passed here. To get the stack
/// trace, be sure to call ex.ToString().
/// </summary>
/// <param name="ex">The exception that was thrown by DotSpatial.</param>
public void Exception(Exception ex)
{
foreach (KeyValuePair<int, ILogger> logger in _loggers)
{
logger.Value.Exception(ex);
}
}
/// <summary>
/// This method echoes information about input boxes to all the loggers.
/// </summary>
/// <param name="text">The string message that appeared on the InputBox</param>
/// <param name="result">The ystem.Windows.Forms.DialogResult describing if the value was cancelled </param>
/// <param name="value">The string containing the value entered.</param>
public void LogInput(string text, DialogResult result, string value)
{
foreach (KeyValuePair<int, ILogger> logger in _loggers)
{
logger.Value.InputBoxShown(text, result, value);
}
}
/// <summary>
/// Displays an InputBox form given the specified text string. The result is returned byref.
/// A DialogResult is returned to show whether the user cancelled the form without providing input.
/// </summary>
/// <param name="text">The string text to use as an input prompt.</param>
/// <param name="result">The string result that was typed into the dialog.</param>
/// <returns>A DialogResult showing the outcome.</returns>
public DialogResult LogInputBox(string text, out string result)
{
InputBox frm = new InputBox(text);
result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result;
LogInput(text, frm.DialogResult, result);
return frm.DialogResult;
}
/// <summary>
/// Displays an InputBox form given the specified text string. The result is returned byref.
/// A DialogResult is returned to show whether the user cancelled the form without providing input.
/// </summary>
/// <param name="text">The string text to use as an input prompt.</param>
/// <param name="caption">The string to use in the title bar of the InputBox.</param>
/// <param name="result">The string result that was typed into the dialog.</param>
/// <returns>A DialogResult showing the outcome.</returns>
public DialogResult LogInputBox(string text, string caption, out string result)
{
InputBox frm = new InputBox(text, caption);
result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result;
LogInput(text, frm.DialogResult, result);
return frm.DialogResult;
}
/// <summary>
/// Displays an InputBox form given the specified text string. The result is returned byref.
/// A DialogResult is returned to show whether the user cancelled the form without providing input.
/// </summary>
/// <param name="text">The string text to use as an input prompt.</param>
/// <param name="caption">The string to use in the title bar of the InputBox.</param>
/// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param>
/// <param name="result">The string result that was typed into the dialog.</param>
/// <returns>A DialogResult showing the outcome.</returns>
public DialogResult LogInputBox(string text, string caption, ValidationType validation, out string result)
{
InputBox frm = new InputBox(text, caption, validation);
result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result;
LogInput(text, frm.DialogResult, result);
return frm.DialogResult;
}
/// <summary>
/// Displays an InputBox form given the specified text string. The result is returned byref.
/// A DialogResult is returned to show whether the user cancelled the form without providing input.
/// </summary>
/// <param name="text">The string text to use as an input prompt.</param>
/// <param name="caption">The string to use in the title bar of the InputBox.</param>
/// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param>
/// <param name="icon">Specifies an icon to display on this form.</param>
/// <param name="result">The string result that was typed into the dialog.</param>
/// <returns>A DialogResult showing the outcome.</returns>
public DialogResult LogInputBox(string text, string caption, ValidationType validation, Icon icon, out string result)
{
InputBox frm = new InputBox(text, caption, validation, icon);
result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result;
LogInput(text, frm.DialogResult, result);
return frm.DialogResult;
}
/// <summary>
/// Displays an InputBox form given the specified text string. The result is returned byref.
/// A DialogResult is returned to show whether the user cancelled the form without providing input.
/// </summary>
/// <param name="owner">The window that owns this modal dialog.</param>
/// <param name="text">The string text to use as an input prompt.</param>
/// <param name="result">The string result that was typed into the dialog.</param>
/// <returns>A DialogResult showing the outcome.</returns>
public DialogResult LogInputBox(Form owner, string text, out string result)
{
InputBox frm = new InputBox(owner, text);
result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result;
LogInput(text, frm.DialogResult, result);
return frm.DialogResult;
}
/// <summary>
/// Displays an InputBox form given the specified text string. The result is returned byref.
/// A DialogResult is returned to show whether the user cancelled the form without providing input.
/// </summary>
/// <param name="owner">The window that owns this modal dialog.</param>
/// <param name="text">The string text to use as an input prompt.</param>
/// <param name="caption">The string to use in the title bar of the InputBox.</param>
/// <param name="result">The string result that was typed into the dialog.</param>
/// <returns>A DialogResult showing the outcome.</returns>
public DialogResult LogInputBox(Form owner, string text, string caption, out string result)
{
InputBox frm = new InputBox(owner, text, caption);
result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result;
LogInput(text, frm.DialogResult, result);
return frm.DialogResult;
}
/// <summary>
/// Displays an InputBox form given the specified text string. The result is returned byref.
/// A DialogResult is returned to show whether the user cancelled the form without providing input.
/// </summary>
/// <param name="owner">The window that owns this modal dialog.</param>
/// <param name="text">The string text to use as an input prompt.</param>
/// <param name="caption">The string to use in the title bar of the InputBox.</param>
/// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param>
/// <param name="result">The string result that was typed into the dialog.</param>
/// <returns>A DialogResult showing the outcome.</returns>
public DialogResult LogInputBox(Form owner, string text, string caption, ValidationType validation, out string result)
{
InputBox frm = new InputBox(owner, text, caption, validation);
result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result;
LogInput(text, frm.DialogResult, result);
return frm.DialogResult;
}
/// <summary>
/// Displays an InputBox form given the specified text string. The result is returned byref.
/// A DialogResult is returned to show whether the user cancelled the form without providing input.
/// </summary>
/// <param name="owner">The window that owns this modal dialog.</param>
/// <param name="text">The string text to use as an input prompt.</param>
/// <param name="caption">The string to use in the title bar of the InputBox.</param>
/// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param>
/// <param name="icon">Specifies an icon to display on this form.</param>
/// <param name="result">The string result that was typed into the dialog.</param>
/// <returns>A DialogResult showing the outcome.</returns>
public DialogResult LogInputBox(Form owner, string text, string caption, ValidationType validation, Icon icon, out string result)
{
InputBox frm = new InputBox(owner, text, caption, validation, icon);
result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result;
LogInput(text, frm.DialogResult, result);
return frm.DialogResult;
}
/// <summary>
/// This is called by each of the LogMessageBox methods automatically, but if the user wants to use
/// a custom messagebox and then log the message and result directly this is the technique.
/// </summary>
/// <param name="text">The string text of the message that needs to be logged.</param>
/// <param name="result">The dialog result from the shown messagebox.</param>
public void LogMessage(string text, DialogResult result)
{
foreach (KeyValuePair<int, ILogger> logger in _loggers)
{
logger.Value.MessageBoxShown(text, result);
}
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="owner">An implementation of the IWin32Window that will own the modal form dialog box.</param>
/// <param name="text">The text to display in the MessageBox</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(IWin32Window owner, string text)
{
DialogResult res = MessageBox.Show(owner, text);
LogMessage(text, res);
return res;
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="owner">An implementation of the IWin32Window that will own the modal form dialog box.</param>
/// <param name="text">The text to display in the MessageBox</param>
/// <param name="caption">The text to display in the title bar of the MessageBox</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(IWin32Window owner, string text, string caption)
{
DialogResult res = MessageBox.Show(owner, text, caption);
LogMessage(text, res);
return res;
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="owner">An implementation of the IWin32Window that will own the modal form dialog box.</param>
/// <param name="text">The text to display in the MessageBox</param>
/// <param name="caption">The text to display in the title bar of the MessageBox</param>
/// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(IWin32Window owner, string text, string caption, MessageBoxButtons buttons)
{
DialogResult res = MessageBox.Show(owner, text, caption, buttons);
LogMessage(text, res);
return res;
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="owner">An implementation of the IWin32Window that will own the modal form dialog box.</param>
/// <param name="text">The text to display in the MessageBox</param>
/// <param name="caption">The text to display in the title bar of the MessageBox</param>
/// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox</param>
/// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
DialogResult res = MessageBox.Show(owner, text, caption, buttons, icon);
LogMessage(text, res);
return res;
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="owner">An implementation of the IWin32Window that will own the modal form dialog box.</param>
/// <param name="text">The text to display in the MessageBox</param>
/// <param name="caption">The text to display in the title bar of the MessageBox</param>
/// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox</param>
/// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox</param>
/// <param name="defaultButton">One of the MessageBoxDefaultButtons that describes the default button for the MessageBox</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton)
{
DialogResult res = MessageBox.Show(owner, text, caption, buttons, icon, defaultButton);
LogMessage(text, res);
return res;
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="owner">An implementation of the IWin32Window that will own the modal form dialog box.</param>
/// <param name="text">The text to display in the MessageBox</param>
/// <param name="caption">The text to display in the title bar of the MessageBox</param>
/// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox</param>
/// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox</param>
/// <param name="defaultButton">One of the MessageBoxDefaultButtons that describes the default button for the MessageBox</param>
/// <param name="options">One of the MessageBoxOptions that describes which display and association options to use for the MessageBox. You may pass 0 if you wish to use the defaults.</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options)
{
DialogResult res = MessageBox.Show(owner, text, caption, buttons, icon, defaultButton, options);
LogMessage(text, res);
return res;
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="text">The text to display in the MessageBox</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(string text)
{
DialogResult res = MessageBox.Show(text);
LogMessage(text, res);
return res;
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="text">The text to display in the MessageBox</param>
/// <param name="caption">The text to display in the title bar of the MessageBox</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(string text, string caption)
{
DialogResult res = MessageBox.Show(text, caption);
LogMessage(text, res);
return res;
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="text">The text to display in the MessageBox</param>
/// <param name="caption">The text to display in the title bar of the MessageBox</param>
/// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(string text, string caption, MessageBoxButtons buttons)
{
DialogResult res = MessageBox.Show(text, caption, buttons);
LogMessage(text, res);
return res;
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="text">The text to display in the MessageBox</param>
/// <param name="caption">The text to display in the title bar of the MessageBox</param>
/// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox</param>
/// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
DialogResult res = MessageBox.Show(text, caption, buttons, icon);
LogMessage(text, res);
return res;
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="text">The text to display in the MessageBox</param>
/// <param name="caption">The text to display in the title bar of the MessageBox</param>
/// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox</param>
/// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox</param>
/// <param name="defaultButton">One of the MessageBoxDefaultButtons that describes the default button for the MessageBox</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton)
{
DialogResult res = MessageBox.Show(text, caption, buttons, icon, defaultButton);
LogMessage(text, res);
return res;
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="text">The text to display in the MessageBox</param>
/// <param name="caption">The text to display in the title bar of the MessageBox</param>
/// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox</param>
/// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox</param>
/// <param name="defaultButton">One of the MessageBoxDefaultButtons that describes the default button for the MessageBox</param>
/// <param name="options">One of the MessageBoxOptions that describes which display and association options to use for the MessageBox. You may pass 0 if you wish to use the defaults.</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options)
{
DialogResult res = MessageBox.Show(text, caption, buttons, icon, defaultButton, options);
LogMessage(text, res);
return res;
}
/// <summary>
/// Shows a MessageBox, logs the text of the text and the result chosen by the user.
/// </summary>
/// <param name="text">The text to display in the MessageBox</param>
/// <param name="caption">The text to display in the title bar of the MessageBox</param>
/// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox</param>
/// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox</param>
/// <param name="defaultButton">One of the MessageBoxDefaultButtons that describes the default button for the MessageBox</param>
/// <param name="options">One of the MessageBoxOptions that describes which display and association options to use for the MessageBox. You may pass 0 if you wish to use the defaults.</param>
/// <param name="displayHelpButton">A boolean indicating whether or not to display a help button on the messagebox</param>
/// <returns>A DialogResult showing the user input from this messagebox.</returns>
public DialogResult LogMessageBox(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, bool displayHelpButton)
{
DialogResult res = MessageBox.Show(text, caption, buttons, icon, defaultButton, options, displayHelpButton);
LogMessage(text, res);
return res;
}
/// <summary>
/// A progress message, generally as part of a long loop was sent. It is a bad
/// idea to log these to a file as there may be thousands of them.
/// </summary>
/// <param name="baseMessage">The status part of the progress message with no percent information</param>
/// <param name="percent">The integer percent from 0 to 100</param>
/// <param name="message">The complete message, showing both status and completion percent</param>
public void Progress(string baseMessage, int percent, string message)
{
foreach (KeyValuePair<int, ILogger> logger in _loggers)
{
logger.Value.Progress(baseMessage, percent, message);
}
}
/// <summary>
/// This event will allow the registering of an entrance into a public Method of a "tools" related
/// action to register its entrance into a function as well as logging the parameter names
/// and a type specific indicator of their value.
/// </summary>
/// <param name="methodName">The string name of the method</param>
/// <param name="parameters">The List<string> of Parameter names and string form values</param>
public void PublicMethodEntered(string methodName, List<string> parameters)
{
foreach (KeyValuePair<int, ILogger> logger in _loggers)
{
logger.Value.PublicMethodEntered(methodName, parameters);
}
}
/// <summary>
/// This event will allow the registering of the exit from each public method
/// </summary>
/// <param name="methodName">The Method name of the method being left</param>
public void PublicMethodLeft(string methodName)
{
foreach (KeyValuePair<int, ILogger> logger in _loggers)
{
logger.Value.PublicMethodLeft(methodName);
}
}
/// <summary>
/// The key specified here is the key that was returned by the AddLogger method.
/// </summary>
/// <param name="key">The integer key of the logger to remove.</param>
/// <returns>True if the logger was successfully removed, or false if the key could not be found</returns>
/// <exception cref="System.ArgumentNullException">key is null</exception>
public bool RemoveLogger(int key)
{
return _loggers.Remove(key);
}
/// <summary>
/// A status message was sent. Complex methods that have a few major steps will
/// call a status message to show which step the process is in. Loops will call the progress method instead.
/// </summary>
/// <param name="message">The string message that was posted.</param>
public void Status(string message)
{
foreach (KeyValuePair<int, ILogger> logger in _loggers)
{
logger.Value.Status(message);
}
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
Components = new Container();
}
#endregion
}
}
| |
#if !NOT_UNITY3D
using System;
using System.Collections.Generic;
using System.Linq;
using ModestTree;
using ModestTree.Util;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.SceneManagement;
using Zenject.Internal;
namespace Zenject
{
public class SceneContext : Context
{
public static Action<DiContainer> ExtraBindingsInstallMethod;
public static DiContainer ParentContainer;
[FormerlySerializedAs("ParentNewObjectsUnderRoot")]
[Tooltip("When true, objects that are created at runtime will be parented to the SceneContext")]
[SerializeField]
bool _parentNewObjectsUnderRoot = false;
[Tooltip("Optional contract names for this SceneContext, allowing contexts in subsequently loaded scenes to depend on it and be parented to it, and also for previously loaded decorators to be included")]
[SerializeField]
List<string> _contractNames = new List<string>();
[Tooltip("Optional contract name of a SceneContext in a previously loaded scene that this context depends on and to which it must be parented")]
[SerializeField]
string _parentContractName;
[Tooltip("When false, wait until run method is explicitly called. Otherwise run on awake")]
[SerializeField]
bool _autoRun = true;
DiContainer _container;
readonly List<object> _dependencyRoots = new List<object>();
readonly List<SceneDecoratorContext> _decoratorContexts = new List<SceneDecoratorContext>();
bool _hasInstalled;
bool _hasResolved;
static bool _staticAutoRun = true;
public override DiContainer Container
{
get { return _container; }
}
public bool IsValidating
{
get
{
#if UNITY_EDITOR
return ProjectContext.Instance.Container.IsValidating;
#else
return false;
#endif
}
}
public IEnumerable<string> ContractNames
{
get { return _contractNames; }
set
{
_contractNames.Clear();
_contractNames.AddRange(value);
}
}
public string ParentContractName
{
get { return _parentContractName; }
set
{
_parentContractName = value;
}
}
public bool ParentNewObjectsUnderRoot
{
get { return _parentNewObjectsUnderRoot; }
set { _parentNewObjectsUnderRoot = value; }
}
public void Awake()
{
// We always want to initialize ProjectContext as early as possible
ProjectContext.Instance.EnsureIsInitialized();
if (_staticAutoRun && _autoRun)
{
Run();
}
else
{
// True should always be default
_staticAutoRun = true;
}
}
#if UNITY_EDITOR
public void Validate()
{
Assert.That(IsValidating);
Install();
Resolve();
_container.ValidateValidatables();
}
#endif
public void Run()
{
Assert.That(!IsValidating);
Install();
Resolve();
}
public override IEnumerable<GameObject> GetRootGameObjects()
{
return ZenUtilInternal.GetRootGameObjects(gameObject.scene);
}
DiContainer GetParentContainer()
{
if (string.IsNullOrEmpty(_parentContractName))
{
if (ParentContainer != null)
{
var tempParentContainer = ParentContainer;
// Always reset after using it - it is only used to pass the reference
// between scenes via ZenjectSceneLoader
ParentContainer = null;
return tempParentContainer;
}
return ProjectContext.Instance.Container;
}
Assert.IsNull(ParentContainer,
"Scene cannot have both a parent scene context name set and also an explicit parent container given");
var sceneContexts = UnityUtil.AllLoadedScenes
.Except(gameObject.scene)
.SelectMany(scene => scene.GetRootGameObjects())
.SelectMany(root => root.GetComponentsInChildren<SceneContext>())
.Where(sceneContext => sceneContext.ContractNames.Contains(_parentContractName))
.ToList();
Assert.That(sceneContexts.Any(), () => string.Format(
"SceneContext on object {0} of scene {1} requires contract {2}, but none of the loaded SceneContexts implements that contract.",
gameObject.name,
gameObject.scene.name,
_parentContractName));
Assert.That(sceneContexts.Count == 1, () => string.Format(
"SceneContext on object {0} of scene {1} requires a single implementation of contract {2}, but multiple were found.",
gameObject.name,
gameObject.scene.name,
_parentContractName));
return sceneContexts.Single().Container;
}
List<SceneDecoratorContext> LookupDecoratorContexts()
{
if (_contractNames.IsEmpty())
{
return new List<SceneDecoratorContext>();
}
return UnityUtil.AllLoadedScenes
.Except(gameObject.scene)
.SelectMany(scene => scene.GetRootGameObjects())
.SelectMany(root => root.GetComponentsInChildren<SceneDecoratorContext>())
.Where(decoratorContext => _contractNames.Contains(decoratorContext.DecoratedContractName))
.ToList();
}
public void Install()
{
#if !UNITY_EDITOR
Assert.That(!IsValidating);
#endif
Assert.That(!_hasInstalled);
_hasInstalled = true;
Assert.IsNull(_container);
_container = GetParentContainer().CreateSubContainer();
Assert.That(_decoratorContexts.IsEmpty());
_decoratorContexts.AddRange(LookupDecoratorContexts());
Log.Debug("SceneContext: Running installers...");
if (_parentNewObjectsUnderRoot)
{
_container.DefaultParent = this.transform;
}
else
{
// This is necessary otherwise we inherit the project root DefaultParent
_container.DefaultParent = null;
}
// Record all the injectable components in the scene BEFORE installing the installers
// This is nice for cases where the user calls InstantiatePrefab<>, etc. in their installer
// so that it doesn't inject on the game object twice
// InitialComponentsInjecter will also guarantee that any component that is injected into
// another component has itself been injected
foreach (var instance in GetInjectableMonoBehaviours().Cast<object>())
{
_container.QueueForInject(instance);
}
foreach (var decoratorContext in _decoratorContexts)
{
decoratorContext.Initialize(_container);
}
_container.IsInstalling = true;
try
{
InstallBindings();
}
finally
{
_container.IsInstalling = false;
}
}
public void Resolve()
{
Log.Debug("SceneContext: Injecting components in the scene...");
Assert.That(_hasInstalled);
Assert.That(!_hasResolved);
_hasResolved = true;
_container.FlushInjectQueue();
Log.Debug("SceneContext: Resolving dependency roots...");
Assert.That(_dependencyRoots.IsEmpty());
_dependencyRoots.AddRange(_container.ResolveDependencyRoots());
Log.Debug("SceneContext: Initialized successfully");
}
void InstallBindings()
{
_container.Bind(typeof(Context), typeof(SceneContext)).To<SceneContext>().FromInstance(this);
foreach (var decoratorContext in _decoratorContexts)
{
decoratorContext.InstallDecoratorSceneBindings();
}
InstallSceneBindings();
_container.Bind<SceneKernel>().FromNewComponentOn(this.gameObject).AsSingle().NonLazy();
_container.Bind<ZenjectSceneLoader>().AsSingle();
if (ExtraBindingsInstallMethod != null)
{
ExtraBindingsInstallMethod(_container);
// Reset extra bindings for next time we change scenes
ExtraBindingsInstallMethod = null;
}
// Always install the installers last so they can be injected with
// everything above
foreach (var decoratorContext in _decoratorContexts)
{
decoratorContext.InstallDecoratorInstallers();
}
InstallInstallers();
}
protected override IEnumerable<MonoBehaviour> GetInjectableMonoBehaviours()
{
return ZenUtilInternal.GetInjectableMonoBehaviours(this.gameObject.scene);
}
// These methods can be used for cases where you need to create the SceneContext entirely in code
// Note that if you use these methods that you have to call Run() yourself
// This is useful because it allows you to create a SceneContext and configure it how you want
// and add what installers you want before kicking off the Install/Resolve
public static SceneContext Create()
{
return CreateComponent(
new GameObject("SceneContext"));
}
public static SceneContext CreateComponent(GameObject gameObject)
{
_staticAutoRun = false;
var result = gameObject.AddComponent<SceneContext>();
Assert.That(_staticAutoRun); // Should be reset
return result;
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using gView.Framework.Geometry;
namespace gView.Framework.OGC
{
public class OGC
{
public enum WkbByteOrder : byte
{
/// <summary>
/// XDR (Big Endian) Encoding of Numeric Types
/// </summary>
/// <remarks>
/// <para>The XDR representation of an Unsigned Integer is Big Endian (most significant byte first).</para>
/// <para>The XDR representation of a Double is Big Endian (sign bit is first byte).</para>
/// </remarks>
Xdr = 0,
/// <summary>
/// NDR (Little Endian) Encoding of Numeric Types
/// </summary>
/// <remarks>
/// <para>The NDR representation of an Unsigned Integer is Little Endian (least significant byte first).</para>
/// <para>The NDR representation of a Double is Little Endian (sign bit is last byte).</para>
/// </remarks>
Ndr = 1
}
/// <summary>
/// Enumeration to determine geometrytype in Well-known Binary
/// </summary>
internal enum WKBGeometryType : uint
{
wkbPoint = 1,
wkbLineString = 2,
wkbPolygon = 3,
wkbMultiPoint = 4,
wkbMultiLineString = 5,
wkbMultiPolygon = 6,
wkbGeometryCollection = 7
}
public readonly static System.Globalization.NumberFormatInfo numberFormat_EnUS = new System.Globalization.CultureInfo("en-US", false).NumberFormat;
public static string Envelope2box2(IEnvelope envelope, ISpatialReference sRef)
{
if (envelope == null) return "";
if (sRef == null)
{
string box2 = "box2d('BOX3D(" +
envelope.minx.ToString(numberFormat_EnUS) + " " +
envelope.miny.ToString(numberFormat_EnUS) + "," +
envelope.maxx.ToString(numberFormat_EnUS) + " " +
envelope.maxy.ToString(numberFormat_EnUS) + ")'::box3d)";
return box2;
}
else
{
string[] srid = sRef.Name.Split(':');
string box2 = "st_setsrid(box2d('BOX3D(" +
envelope.minx.ToString(numberFormat_EnUS) + " " +
envelope.miny.ToString(numberFormat_EnUS) + "," +
envelope.maxx.ToString(numberFormat_EnUS) + " " +
envelope.maxy.ToString(numberFormat_EnUS) + ")'::box3d)," + srid[srid.Length - 1] + ")";
return box2;
}
}
public static IGeometry WKBToGeometry(byte[] bytes)
{
using (MemoryStream ms = new MemoryStream(bytes))
using (BinaryReader reader = new BinaryReader(ms))
{
return WKBToGeometry(reader);
}
}
public static IGeometry WKBToGeometry(BinaryReader reader)
{
// Get the first byte in the array. This specifies if the WKB is in
// XDR (big-endian) format of NDR (little-endian) format.
byte byteOrder = reader.ReadByte();
if (!Enum.IsDefined(typeof(WkbByteOrder), byteOrder))
{
throw new ArgumentException("Byte order not recognized");
}
return WKBToGeometry(reader, (WkbByteOrder)byteOrder);
}
private static IGeometry WKBToGeometry(BinaryReader reader, WkbByteOrder byteOrder)
{
// Get the type of this geometry.
uint type = (uint)ReadUInt32(reader, (WkbByteOrder)byteOrder);
bool hasZ = false, hasM = false;
if (type >= 1000 && type < 2000)
{
hasZ = true;
type -= 1000;
}
else if (type >= 2000 && type < 3000)
{
hasM = true;
type -= 2000;
}
else if (type >= 3000 && type < 4000)
{
hasZ = hasM = true;
type -= 3000;
}
if (!Enum.IsDefined(typeof(WKBGeometryType), type))
throw new ArgumentException("Geometry type not recognized");
switch ((WKBGeometryType)type)
{
case WKBGeometryType.wkbPoint:
return CreatePoint(reader, byteOrder, hasZ, hasM);
case WKBGeometryType.wkbLineString:
return CreateLineString(reader, byteOrder, hasZ, hasM);
case WKBGeometryType.wkbPolygon:
return CreatePolygon(reader, byteOrder, hasZ, hasM);
case WKBGeometryType.wkbMultiPoint:
return CreateMultiPoint(reader, byteOrder, hasZ, hasM);
case WKBGeometryType.wkbMultiLineString:
return CreateMultiLineString(reader, byteOrder, hasZ, hasM);
case WKBGeometryType.wkbMultiPolygon:
return CreateMultiPolygon(reader, byteOrder, hasZ, hasM);
case WKBGeometryType.wkbGeometryCollection:
return CreateGeometryCollection(reader, byteOrder, hasZ, hasM);
default:
throw new NotSupportedException("Geometry type '" + type.ToString() + "' not supported");
}
}
public static string BytesToHexString(byte[] bytes)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in bytes)
{
byte b1 = (byte)((b & 0xf0) >> 4);
byte b2 = (byte)(b & 0x0f);
sb.Append(HexChar(b1));
sb.Append(HexChar(b2));
}
return sb.ToString();
}
private static char HexChar(byte b)
{
switch (b & 0x0f)
{
case 0:
return '0';
case 1:
return '1';
case 2:
return '2';
case 3:
return '3';
case 4:
return '4';
case 5:
return '5';
case 6:
return '6';
case 7:
return '7';
case 8:
return '8';
case 9:
return '9';
case 10:
return 'A';
case 11:
return 'B';
case 12:
return 'C';
case 13:
return 'D';
case 14:
return 'E';
case 15:
return 'F';
}
return '0';
}
public static byte[] GeometryToWKB(IGeometry geometry, int srid, WkbByteOrder byteOrder)
{
return GeometryToWKB(geometry, srid, byteOrder, String.Empty);
}
public static byte[] GeometryToWKB(IGeometry geometry, int srid, WkbByteOrder byteOrder, string typeString)
{
MemoryStream ms = new MemoryStream();
using (BinaryWriter writer = new BinaryWriter(ms))
{
writer.Write((byte)byteOrder);
if (geometry is IPoint)
{
if (srid == 0)
{
writer.Write((uint)WKBGeometryType.wkbPoint);
}
else // Gstalt (PostGIS) ??!!
{
writer.Write((uint)WKBGeometryType.wkbPoint + (uint)0x20000000);
writer.Write((uint)srid);
}
WritePoint((IPoint)geometry, writer, byteOrder);
}
else if (geometry is IMultiPoint)
{
if (srid == 0)
{
writer.Write((uint)WKBGeometryType.wkbMultiPoint);
}
else // Gstalt (PostGIS) ??!!
{
writer.Write((uint)WKBGeometryType.wkbMultiPoint + (uint)0x20000000);
writer.Write((uint)srid);
}
WriteMultiPoint((IMultiPoint)geometry, writer, byteOrder);
}
else if (geometry is IPolyline)
{
if (typeString == "LINESTRING" && ((IPolyline)geometry).PathCount == 1)
{
if (srid == 0)
{
writer.Write((uint)WKBGeometryType.wkbLineString);
}
else // Gstalt (PostGIS) ??!!
{
writer.Write((uint)WKBGeometryType.wkbLineString + (uint)0x20000000);
writer.Write((uint)srid);
}
WriteLineString(((IPolyline)geometry)[0], writer, byteOrder);
}
else
{
if (srid == 0)
{
writer.Write((uint)WKBGeometryType.wkbMultiLineString);
}
else // Gstalt (PostGIS) ??!!
{
writer.Write((uint)WKBGeometryType.wkbMultiLineString + (uint)0x20000000);
writer.Write((uint)srid);
}
WriteMultiLineString((IPolyline)geometry, writer, byteOrder);
}
}
else if (geometry is IPolygon)
{
if (typeString == "POLYGON")
{
if (srid == 0)
{
writer.Write((uint)WKBGeometryType.wkbPolygon);
}
else // Gstalt (PostGIS) ??!!
{
writer.Write((uint)WKBGeometryType.wkbPolygon + (uint)0x20000000);
writer.Write((uint)srid);
}
WritePolygon((IPolygon)geometry, writer, byteOrder);
}
else
{
if (srid == 0)
{
writer.Write((uint)WKBGeometryType.wkbMultiPolygon);
}
else // Gstalt (PostGIS) ??!!
{
writer.Write((uint)WKBGeometryType.wkbMultiPolygon + (uint)0x20000000);
writer.Write((uint)srid);
}
WriteMultiPolygon((IPolygon)geometry, writer, byteOrder);
}
}
else if (geometry is IAggregateGeometry)
{
if (srid == 0)
{
writer.Write((uint)WKBGeometryType.wkbGeometryCollection);
}
else // Gstalt (PostGIS) ??!!
{
writer.Write((uint)WKBGeometryType.wkbGeometryCollection + (uint)0x20000000);
writer.Write((uint)srid);
}
WriteGeometryCollection((IAggregateGeometry)geometry, writer, byteOrder);
}
else
{
throw new NotSupportedException("Geometry type is not supported");
}
ms.Position = 0;
byte[] g = new byte[ms.Length];
ms.Read(g, 0, g.Length);
return g;
}
}
private static Point CreatePoint(BinaryReader reader, WkbByteOrder byteOrder, bool hasZ, bool hasM)
{
// Create and return the point.
Point p= new Point(ReadDouble(reader, byteOrder), ReadDouble(reader, byteOrder));
if (hasZ == true && hasM == true)
{
p.Z = ReadDouble(reader, byteOrder);
p.M = ReadDouble(reader, byteOrder);
}
else if (hasM == true)
{
p.M = ReadDouble(reader, byteOrder);
}
else if (hasZ == true)
{
p.Z = ReadDouble(reader, byteOrder);
}
return p;
}
private static void WritePoint(IPoint point, BinaryWriter writer, WkbByteOrder byteOrder)
{
WriteDouble(point.X, writer, byteOrder);
WriteDouble(point.Y, writer, byteOrder);
}
private static void ReadPointCollection(BinaryReader reader, WkbByteOrder byteOrder, IPointCollection pColl, bool hasZ, bool hasM)
{
if (pColl == null) return;
// Get the number of points in this linestring.
int numPoints = (int)ReadUInt32(reader, byteOrder);
// Loop on the number of points in the ring.
for (int i = 0; i < numPoints; i++)
{
// Add the coordinate.
Point p=new Point(ReadDouble(reader, byteOrder), ReadDouble(reader, byteOrder));
pColl.AddPoint(p);
if (hasZ == true && hasM == true)
{
p.Z = ReadDouble(reader, byteOrder);
p.M = ReadDouble(reader, byteOrder);
}
else if (hasM == true)
{
p.M = ReadDouble(reader, byteOrder);
}
else if (hasZ == true)
{
p.Z = ReadDouble(reader, byteOrder);
}
}
}
private static void WritePointCollection(IPointCollection pColl, BinaryWriter writer, WkbByteOrder byteOrder)
{
if (pColl == null) return;
WriteUInt32((uint)pColl.PointCount, writer, byteOrder);
for (int i = 0; i < pColl.PointCount; i++)
{
WritePoint(pColl[i], writer, byteOrder);
}
}
private static MultiPoint CreateMultiPoint(BinaryReader reader, WkbByteOrder byteOrder, bool hasZ, bool hasM)
{
// Get the number of points in this multipoint.
int numPoints = (int)ReadUInt32(reader, byteOrder);
// Create a new array for the points.
MultiPoint points = new MultiPoint();
// Loop on the number of points.
for (int i = 0; i < numPoints; i++)
{
// Read point header
reader.ReadByte();
ReadUInt32(reader, byteOrder);
// Create the next point and add it to the point array.
points.AddPoint(CreatePoint(reader, byteOrder, hasZ, hasM));
}
return points;
}
private static void WriteMultiPoint(IMultiPoint mpoint, BinaryWriter writer, WkbByteOrder byteOrder)
{
WritePointCollection(mpoint, writer, byteOrder);
}
private static Polyline CreateLineString(BinaryReader reader, WkbByteOrder byteOrder, bool hasZ,bool hasM)
{
Polyline pline = new Polyline();
gView.Framework.Geometry.Path path = new gView.Framework.Geometry.Path();
ReadPointCollection(reader, byteOrder, path, hasZ, hasM);
pline.AddPath(path);
return pline;
}
private static void WriteLineString(IPath path, BinaryWriter writer, WkbByteOrder byteOrder)
{
WritePointCollection(path, writer, byteOrder);
}
private static Polyline CreateMultiLineString(BinaryReader reader, WkbByteOrder byteOrder, bool hasZ, bool hasM)
{
// Get the number of linestrings in this multilinestring.
int numLineStrings = (int)ReadUInt32(reader, byteOrder);
// Create a new array for the linestrings .
Polyline pline = new Polyline();
// Loop on the number of linestrings.
for (int i = 0; i < numLineStrings; i++)
{
// Read linestring header
reader.ReadByte();
ReadUInt32(reader, byteOrder);
Polyline p = CreateLineString(reader, byteOrder, hasZ, hasM);
for (int r = 0; r < p.PathCount; r++)
pline.AddPath(p[r]);
}
// Create and return the MultiLineString.
return pline;
}
private static void WriteMultiLineString(IPolyline polyline, BinaryWriter writer, WkbByteOrder byteOrder)
{
WriteUInt32((uint)polyline.PathCount, writer, byteOrder);
for (int i = 0; i < polyline.PathCount; i++)
{
// Header
writer.Write((byte)byteOrder);
writer.Write((uint)WKBGeometryType.wkbLineString);
WritePointCollection(polyline[i], writer, byteOrder);
}
}
private static Polygon CreatePolygon(BinaryReader reader, WkbByteOrder byteOrder, bool hasZ, bool hasM)
{
// Get the Number of rings in this Polygon.
int numRings = (int)ReadUInt32(reader, byteOrder);
Polygon polygon = new Polygon();
for (int i = 0; i < numRings; i++)
{
Ring ring = new Ring();
ReadPointCollection(reader, byteOrder, ring, hasZ, hasM);
polygon.AddRing(ring);
}
return polygon;
}
private static void WritePolygon(IPolygon polygon, BinaryWriter writer, WkbByteOrder byteOrder)
{
WriteUInt32((uint)polygon.RingCount, writer, byteOrder);
for (int i = 0; i < polygon.RingCount; i++)
{
WritePointCollection(polygon[i], writer, byteOrder);
}
}
private static void WriteGeometryCollection(IAggregateGeometry aGeometry, BinaryWriter writer, WkbByteOrder byteOrder)
{
WriteUInt32((uint)aGeometry.GeometryCount, writer, byteOrder);
for (int i = 0; i < aGeometry.GeometryCount; i++)
{
IGeometry geometry = aGeometry[i];
if (geometry == null) continue;
if (geometry is IPoint)
{
writer.Write((uint)WKBGeometryType.wkbPoint);
WritePoint((IPoint)geometry, writer, byteOrder);
}
else if (geometry is IMultiPoint)
{
writer.Write((uint)WKBGeometryType.wkbMultiPoint);
WriteMultiPoint((IMultiPoint)geometry, writer, byteOrder);
}
else if (geometry is IPolyline)
{
writer.Write((uint)WKBGeometryType.wkbMultiLineString);
WriteMultiLineString((IPolyline)geometry, writer, byteOrder);
}
else if (geometry is IPolygon)
{
writer.Write((uint)WKBGeometryType.wkbMultiPolygon);
WriteMultiPolygon((IPolygon)geometry, writer, byteOrder);
}
else if (geometry is IAggregateGeometry)
{
writer.Write((uint)WKBGeometryType.wkbGeometryCollection);
WriteGeometryCollection((IAggregateGeometry)geometry, writer, byteOrder);
}
else
{
throw new NotSupportedException("Geometry type is not supported");
}
}
}
private static Polygon CreateMultiPolygon(BinaryReader reader, WkbByteOrder byteOrder, bool hasZ, bool hasM)
{
int numPolygons = (int)ReadUInt32(reader, byteOrder);
// Create a new array for the Polygons.
Polygon polygon = new Polygon();
// Loop on the number of polygons.
for (int i = 0; i < numPolygons; i++)
{
// read polygon header
reader.ReadByte();
ReadUInt32(reader, byteOrder);
// TODO: Validate type
Polygon p = CreatePolygon(reader, byteOrder, hasZ, hasM);
for (int r = 0; r < p.RingCount; r++)
polygon.AddRing(p[r]);
}
return polygon;
}
private static void WriteMultiPolygon(IPolygon polygon, BinaryWriter writer, WkbByteOrder byteOrder)
{
//int count = 0;
//for (int i = 0; i < polygon.RingCount; i++)
//{
// if (polygon[0] == null || polygon[i].PointCount < 3) continue;
// count++;
//}
//WriteUInt32((uint)count, writer, byteOrder);
//for (int i = 0; i < polygon.RingCount; i++)
//{
// if (polygon[0] == null || polygon[i].PointCount < 3) continue;
// // Header
// writer.Write((byte)byteOrder);
// writer.Write((uint)WKBGeometryType.wkbPolygon);
// WritePolygon(polygon[i], writer, byteOrder);
//}
WriteUInt32((uint)1, writer, byteOrder);
// Header
writer.Write((byte)byteOrder);
writer.Write((uint)WKBGeometryType.wkbPolygon);
WritePolygon(polygon, writer, byteOrder);
}
private static IAggregateGeometry CreateGeometryCollection(BinaryReader reader, WkbByteOrder byteOrder, bool hasZ, bool hasM)
{
// Get the Number of Geometries in this Polygon.
int numGeometries = (int)ReadUInt32(reader, byteOrder);
AggregateGeometry aGeometry = new AggregateGeometry();
try
{
for (int g = 0; g < numGeometries; g++)
{
IGeometry geometry = WKBToGeometry(reader);
if (geometry != null)
aGeometry.AddGeometry(geometry);
}
}
catch { }
return aGeometry;
}
private static uint ReadUInt32(BinaryReader reader, WkbByteOrder byteOrder)
{
if (byteOrder == WkbByteOrder.Xdr)
{
byte[] bytes = BitConverter.GetBytes(reader.ReadUInt32());
Array.Reverse(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
else
return reader.ReadUInt32();
}
private static void WriteUInt32(uint val, BinaryWriter writer, WkbByteOrder byteOrder)
{
if (byteOrder == WkbByteOrder.Xdr)
{
byte[] bytes = BitConverter.GetBytes(val);
Array.Reverse(bytes);
writer.Write(bytes);
}
else
writer.Write(val);
}
private static double ReadDouble(BinaryReader reader, WkbByteOrder byteOrder)
{
if (byteOrder == WkbByteOrder.Xdr)
{
byte[] bytes = BitConverter.GetBytes(reader.ReadDouble());
Array.Reverse(bytes);
return BitConverter.ToDouble(bytes, 0);
}
else
return reader.ReadDouble();
}
private static void WriteDouble(double val, BinaryWriter writer, WkbByteOrder byteOrder)
{
if (byteOrder == WkbByteOrder.Xdr)
{
byte[] bytes = BitConverter.GetBytes(val);
Array.Reverse(bytes);
writer.Write(bytes);
}
else
writer.Write(val);
}
public static double ToDouble(string number)
{
double ret = 0D;
try
{
ret = Convert.ToDouble(number, gView.Framework.OGC.OGC.numberFormat_EnUS);
}
catch(OverflowException)
{
if (number.Trim().StartsWith("-"))
return double.MinValue;
return double.MaxValue;
}
catch
{
return 0D;
}
return ret;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
/// <summary>
/// System.DateTime.ToString(System.String)
/// </summary>
public class DateTimeToString3
{
public static int Main(string[] args)
{
DateTimeToString3 myDateTime = new DateTimeToString3();
TestLibrary.TestFramework.BeginTestCase("Testing System.DateTime.ToString(System.String)...");
if (myDateTime.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;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
retVal = PosTest12() && retVal;
retVal = PosTest13() && retVal;
retVal = PosTest14() && retVal;
retVal = PosTest15() && retVal;
retVal = PosTest16() && retVal;
retVal = PosTest17() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as M/d/yyyy hh:mm:ss tt...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"M/d/yyyy hh:mm:ss tt";
DateTime myDateTime = new DateTime(1978, 08, 29);
string dateString = myDateTime.ToString(format);
char[] splitors = { '/', ' ', ':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 7)
{
TestLibrary.TestFramework.LogError("001", "The component parts are not correct!");
retVal = false;
}
else
{
if (parts[0] != "1978" && parts[1] != "08" && parts[2] != "29" && parts[3] != "00"
&& parts[4] != "00" && parts[5] != "00" && parts[6]!="AM")
{
TestLibrary.TestFramework.LogError("002", "The content is not correct!");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as M-d-yyyy hh:mm:ss tt...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"M-d-yyyy hh:mm:ss tt";
DateTime myDateTime = new DateTime(1978, 08, 29);
string dateString = myDateTime.ToString(format);
char[] splitors = { '-', ' ', ':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 7)
{
TestLibrary.TestFramework.LogError("004", "The component parts are not correct!");
retVal = false;
}
else
{
if (parts[0] != "1978" && parts[1] != "08" && parts[2] != "29" && parts[3] != "00"
&& parts[4] != "00" && parts[5] != "00" && parts[6]!="AM")
{
TestLibrary.TestFramework.LogError("005", "The content is not correct!");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as M-d-yyyy hh:mm:ss...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"M-d-yyyy hh:mm:ss";
DateTime myDateTime = new DateTime(1978, 08, 29);
string dateString = myDateTime.ToString(format);
char[] splitors = { '-', ' ', ':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 6)
{
TestLibrary.TestFramework.LogError("007", "The component parts are not correct!");
retVal = false;
}
else
{
if (parts[0] != "1978" && parts[1] != "08" && parts[2] != "29" && parts[3] != "00"
&& parts[4] != "00" && parts[5] != "00")
{
TestLibrary.TestFramework.LogError("008", "The content is not correct!");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("009", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as d...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"d";
DateTime myDateTime = new DateTime(1978, 08, 29);
string dateString = myDateTime.ToString(format);
char[] splitors = { '/'};
string[] parts = dateString.Split(splitors);
if (parts.Length != 3)
{
TestLibrary.TestFramework.LogError("010", "The component parts are not correct!");
retVal = false;
}
else
{
if (parts[0] != "29" && parts[1] != "08" && parts[2] != "1978")
{
TestLibrary.TestFramework.LogError("011", "The content is not correct!");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as D...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"D";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = { ' ' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 4)
{
TestLibrary.TestFramework.LogError("013", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as f...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"f";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = { ' ',':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 6)
{
TestLibrary.TestFramework.LogError("015", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as F...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"F";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = { ' ', ':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 7)
{
TestLibrary.TestFramework.LogError("017", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as g...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"g";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = { '/',' ', ':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 5)
{
TestLibrary.TestFramework.LogError("019", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as G...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"G";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = { '/', ' ', ':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 6)
{
TestLibrary.TestFramework.LogError("021", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("022", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest10()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as m...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"m";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = {' '};
string[] parts = dateString.Split(splitors);
if (parts.Length != 2)
{
TestLibrary.TestFramework.LogError("023", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("024", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest11()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as r...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"r";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = { ',',' ',':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 9)
{
TestLibrary.TestFramework.LogError("025", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("026", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest12()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as s...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"s";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = { '-', 'T', ':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 6)
{
TestLibrary.TestFramework.LogError("027", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("028", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest13()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as t...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"t";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = {':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 2)
{
TestLibrary.TestFramework.LogError("029", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("030", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest14()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as T...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"T";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = { ':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 3)
{
TestLibrary.TestFramework.LogError("031", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("032", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest15()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as u...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"u";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = {'-',' ', ':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 6)
{
TestLibrary.TestFramework.LogError("033", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("034", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest16()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as U...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"U";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = {' ', ':' };
string[] parts = dateString.Split(splitors);
if (parts.Length != 7)
{
TestLibrary.TestFramework.LogError("035", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("036", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest17()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("Testing DateTime.ToString(System.String) using format as y...");
try
{
TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
string format = @"y";
DateTime myDateTime = DateTime.Now;
string dateString = myDateTime.ToString(format);
char[] splitors = { ' '};
string[] parts = dateString.Split(splitors);
if (parts.Length != 2)
{
TestLibrary.TestFramework.LogError("037", "The component parts are not correct!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("038", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
}
| |
/*
* Project: SerialPort Terminal
* Company: Coad .NET, http://coad.net
* Author: Noah Coad, http://coad.net/noah
* Created: March 2005
*
* Notes: This was created to demonstrate how to use the SerialPort control for
* communicating with your PC's Serial RS-232 COM Port
*
* It is for educational purposes only and not sanctified for industrial use. :)
* Written to support the blog post article at: http://msmvps.com/blogs/coad/archive/2005/03/23/39466.aspx
*
* Search for "comport" to see how I'm using the SerialPort control.
*
* ******Modfied for Drone Mission Planning Software by: Taylor Trabun
*/
#region Namespace Inclusions
using System;
using System.Linq;
using System.Data;
using System.Text;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using SerialPortTerminal.Properties;
using System.Threading;
using System.IO;
#endregion
namespace SerialPortTerminal
{
#region Public Enumerations
public enum DataMode { Text, Hex }
public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
#endregion
public partial class frmTerminal : Form
{
#region Local Variables
// Keep track of ticking down. If the counter reaches 0,
// the connection to the Arudino is considered lost
private const int COUNT_DOWN = 2;
// for the utility
Util m_util;
// for the hud
hud heads_up;
// for GUI
GUIform GUIWin;
//for Instrument Panel
DemoWinow InstrumentWin;
// for the XBee services
Xbee_service xbee_service;
// The main control for communicating through the RS-232 port
private SerialPort comport = new SerialPort();
// Various colors for logging info
private Color[] LogMsgTypeColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red };
// Temp holder for whether a key was pressed
private bool KeyHandled = false;
private Settings settings = Settings.Default;
//buffer for building a complete set of drone vitals data
private StringBuilder incoming_text_buffer = new StringBuilder(200);
#endregion
#region Constructor
public frmTerminal()
{
// Load user settings
settings.Reload();
// Build the form
InitializeComponent();
// Restore the users settings
InitializeControlValues();
// Enable/disable controls based on the current state
EnableControls();
m_util = new Util();
heads_up = new hud(this);
xbee_service = new Xbee_service();
// show the hud
heads_up.Show();
// When data is recieved through the port, call this method
comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
comport.PinChanged += new SerialPinChangedEventHandler(comport_PinChanged);
}
void comport_PinChanged(object sender, SerialPinChangedEventArgs e)
{
// Show the state of the pins
UpdatePinState();
}
private void UpdatePinState()
{
this.Invoke(new ThreadStart(() => {
// Show the state of the pins
chkCD.Checked = comport.CDHolding;
chkCTS.Checked = comport.CtsHolding;
chkDSR.Checked = comport.DsrHolding;
}));
}
#endregion
#region Local Methods
/// <summary> Save the user's settings. </summary>
private void SaveSettings()
{
settings.BaudRate = int.Parse(cmbBaudRate.Text);
settings.DataBits = int.Parse(cmbDataBits.Text);
settings.DataMode = CurrentDataMode;
settings.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
settings.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
settings.PortName = cmbPortName.Text;
settings.ClearOnOpen = chkClearOnOpen.Checked;
settings.ClearWithDTR = chkClearWithDTR.Checked;
settings.Save();
}
/// <summary> Populate the form's controls with default settings. </summary>
private void InitializeControlValues()
{
cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));
cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));
cmbParity.Text = settings.Parity.ToString();
cmbStopBits.Text = settings.StopBits.ToString();
cmbDataBits.Text = settings.DataBits.ToString();
cmbParity.Text = settings.Parity.ToString();
cmbBaudRate.Text = settings.BaudRate.ToString();
CurrentDataMode = settings.DataMode;
RefreshComPortList();
chkClearOnOpen.Checked = settings.ClearOnOpen;
chkClearWithDTR.Checked = settings.ClearWithDTR;
// If it is still avalible, select the last com port used
if (cmbPortName.Items.Contains(settings.PortName)) cmbPortName.Text = settings.PortName;
else if (cmbPortName.Items.Count > 0) cmbPortName.SelectedIndex = cmbPortName.Items.Count - 1;
else
{
MessageBox.Show(this, "There are no COM Ports detected on this computer.\nPlease install a COM Port and restart this app.", "No COM Ports Installed", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
}
/// <summary> Enable/disable controls based on the app's current state. </summary>
private void EnableControls()
{
// Enable/disable controls based on whether the port is open or not
gbPortSettings.Enabled = !comport.IsOpen;
txtSendData.Enabled = btnSend.Enabled = comport.IsOpen;
//chkDTR.Enabled = chkRTS.Enabled = comport.IsOpen;
if (comport.IsOpen) btnOpenPort.Text = "&Close Port";
else btnOpenPort.Text = "&Open Port";
}
/// <summary> Log data to the terminal window. </summary>
/// <param name="msgtype"> The type of message to be written. </param>
/// <param name="msg"> The string containing the message to be shown. </param>
private void Log(LogMsgType msgtype, string msg)
{
rtfTerminal.Invoke(new EventHandler(delegate
{
rtfTerminal.SelectedText = string.Empty;
rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold);
rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
rtfTerminal.AppendText(msg);
rtfTerminal.ScrollToCaret();
}));
}
/// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
/// <param name="s"> The string containing the hex digits (with or without spaces). </param>
/// <returns> Returns an array of bytes. </returns>
private byte[] HexStringToByteArray(string s)
{
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}
/// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
/// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
/// <returns> Returns a well formatted string of hex digits with spacing. </returns>
private string ByteArrayToHexString(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
return sb.ToString().ToUpper();
}
private void build_incoming_text(string data)
{
Int32 delim = 2;
string temp = incoming_text_buffer.Append(data).ToString();
if (temp.Contains(Environment.NewLine))
{
string[] each_msg = temp.Split(new string[] { Environment.NewLine }, delim, StringSplitOptions.None);
// Log(LogMsgType.Incoming, "&&&" + each_msg[0] + "\n");
update_instrument_panel(each_msg[0]);
incoming_text_buffer.Length = 0;
incoming_text_buffer.Append(each_msg[1]);
}
}
private void update_instrument_panel(string data) {
if (data[0] == 'R')
{
string[] parser = data.Split(new Char[] { ';' }, 4);
string[] roll_string = parser[0].Split(new Char[] { ' ' }, 2);
string[] pitch_string = parser[1].Split(new Char[] { ' ' }, 3);
string[] heading_string = parser[2].Split(new Char[] { ' ' }, 3);
// Log(LogMsgType.Incoming, "\n" + roll_string[1] + "/" + pitch_string[2] + "/" + heading_string[2] + "\n");
double roll_value = Convert.ToDouble(roll_string[1]);
double pitch_value = Convert.ToDouble(pitch_string[2]);
int heading_value = (int)Convert.ToDouble(heading_string[2]);
InstrumentWin.udpateHeading((heading_value+180)%360);
InstrumentWin.updatePitchRoll(pitch_value*(-1.0), roll_value);
}
else
{
return;
}
}
#endregion
#region Local Properties
private DataMode CurrentDataMode
{
get
{
if (rbHex.Checked) return DataMode.Hex;
else return DataMode.Text;
}
set
{
if (value == DataMode.Text) rbText.Checked = true;
else rbHex.Checked = true;
}
}
#endregion
#region Event Handlers
private void lnkAbout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// Show the user the about dialog
(new frmAbout()).ShowDialog(this);
}
private void frmTerminal_Shown(object sender, EventArgs e)
{
Log(LogMsgType.Normal, String.Format("Application Started at {0}\n", DateTime.Now));
}
private void frmTerminal_FormClosing(object sender, FormClosingEventArgs e)
{
// The form is closing, save the user's preferences
SaveSettings();
}
private void rbText_CheckedChanged(object sender, EventArgs e)
{ if (rbText.Checked) CurrentDataMode = DataMode.Text; }
private void rbHex_CheckedChanged(object sender, EventArgs e)
{ if (rbHex.Checked) CurrentDataMode = DataMode.Hex; }
private void cmbBaudRate_Validating(object sender, CancelEventArgs e)
{ int x; e.Cancel = !int.TryParse(cmbBaudRate.Text, out x); }
private void cmbDataBits_Validating(object sender, CancelEventArgs e)
{ int x; e.Cancel = !int.TryParse(cmbDataBits.Text, out x); }
private void btnOpenPort_Click(object sender, EventArgs e)
{
bool error = false;
/* The following code is for testing GUI without hardware */
// Open GUI Window
GUIWin = new GUIform(this);
GUIWin.Show();
// Open Avionics Instrument Window
//InstrumentWin = new DemoWinow(this);
//InstrumentWin.Show();
// If the port is open, close it.
if (comport.IsOpen) comport.Close();
else
{
// Set the port's settings
comport.BaudRate = int.Parse(cmbBaudRate.Text);
comport.DataBits = int.Parse(cmbDataBits.Text);
comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
comport.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
comport.PortName = cmbPortName.Text;
try
{
// Open the port
comport.Open();
}
catch (UnauthorizedAccessException) { error = true; }
catch (IOException) { error = true; }
catch (ArgumentException) { error = true; }
if (error) MessageBox.Show(this, "Could not open the COM port. Most likely it is already in use, has been removed, or is unavailable.", "COM Port Unavalible", MessageBoxButtons.OK, MessageBoxIcon.Stop);
else
{
// Show the initial pin states
UpdatePinState();
chkDTR.Checked = comport.DtrEnable;
chkRTS.Checked = comport.RtsEnable;
// Open GUI Window
GUIWin = new GUIform(this);
GUIWin.Show();
InstrumentWin = new DemoWinow(this);
InstrumentWin.Show();
}
}
// Change the state of the form's controls
EnableControls();
// If the port is open, send focus to the send data box
if (comport.IsOpen)
{
txtSendData.Focus();
if (chkClearOnOpen.Checked) ClearTerminal();
}
}
private void btnSend_Click(object sender, EventArgs e)
{ SendData_lcd_TUN(); }
//*********************************************************************************************************************
//*********************************************************************************************************************
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] b_array;
int result = 0;
// If the com port has been closed, do nothing
if (!comport.IsOpen) return;
// This method will be called when there is data waiting in the port's buffer
// Determain which mode (string or binary) the user is in
if (CurrentDataMode == DataMode.Text)
{
// Read all the data waiting in the buffer
string data = comport.ReadExisting();
// convert to byte array
b_array = m_util.GetBytes(data);
// process all the bytes
foreach (byte b in b_array)
{
// filter the byte
result = (int)xbee_service.TUN_filter_packet(b);
// process if there is a packet waiting
process_TUN_packet();
}
build_incoming_text(data);
// Display the text to the user in the terminal
InstrumentWin.Invoke((Action)delegate { InstrumentWin.horizon_refresh(); });
InstrumentWin.Invoke((Action)delegate { InstrumentWin.heading_refresh(); });
Log(LogMsgType.Incoming, data);
}
else
{
// Obtain the number of bytes waiting in the port's buffer
int bytes = comport.BytesToRead;
// Create a byte array buffer to hold the incoming data
byte[] buffer = new byte[bytes];
// Read the data from the port and store it in our buffer
comport.Read(buffer, 0, bytes);
foreach (byte b in buffer)
{
// filter the byte
xbee_service.TUN_filter_packet(b);
// process if there is a packet waiting
process_TUN_packet();
}
// Show the user the incoming data in hex format
Log(LogMsgType.Incoming, ByteArrayToHexString(buffer));
}
}
//*********************************************************************************************************************
//*********************************************************************************************************************
private void txtSendData_KeyDown(object sender, KeyEventArgs e)
{
// If the user presses [ENTER], send the data now
if (KeyHandled = e.KeyCode == Keys.Enter) { e.Handled = true; SendData(); }
}
private void txtSendData_KeyPress(object sender, KeyPressEventArgs e)
{ e.Handled = KeyHandled; }
#endregion
//*******************************************************************
//******************************************************************
private void chkDTR_CheckedChanged(object sender, EventArgs e)
{
comport.DtrEnable = chkDTR.Checked;
if (chkDTR.Checked && chkClearWithDTR.Checked) ClearTerminal();
}
//*******************************************************************
//*******************************************************************
private void chkRTS_CheckedChanged(object sender, EventArgs e)
{
comport.RtsEnable = chkRTS.Checked;
}
//*******************************************************************
//*******************************************************************
private void btnClear_Click(object sender, EventArgs e)
{
ClearTerminal();
}
//*******************************************************************
//*******************************************************************
private void ClearTerminal()
{
rtfTerminal.Clear();
}
//*******************************************************************
//*******************************************************************
private void tmrCheckComPorts_Tick(object sender, EventArgs e)
{
// checks to see if COM ports have been added or removed
// since it is quite common now with USB-to-Serial adapters
RefreshComPortList();
}
//*******************************************************************
//*******************************************************************
private void RefreshComPortList()
{
// Determain if the list of com port names has changed since last checked
string selected = RefreshComPortList(cmbPortName.Items.Cast<string>(), cmbPortName.SelectedItem as string, comport.IsOpen);
// If there was an update, then update the control showing the user the list of port names
if (!String.IsNullOrEmpty(selected))
{
cmbPortName.Items.Clear();
cmbPortName.Items.AddRange(OrderedPortNames());
cmbPortName.SelectedItem = selected;
}
}
//*******************************************************************
//*******************************************************************
private string[] OrderedPortNames()
{
// Just a placeholder for a successful parsing of a string to an integer
int num;
// Order the serial port names in numberic order (if possible)
return SerialPort.GetPortNames().OrderBy(a => a.Length > 3 && int.TryParse(a.Substring(3), out num) ? num : 0).ToArray();
}
//*******************************************************************
//*******************************************************************
private string RefreshComPortList(IEnumerable<string> PreviousPortNames, string CurrentSelection, bool PortOpen)
{
// Create a new return report to populate
string selected = null;
// Retrieve the list of ports currently mounted by the operating system (sorted by name)
string[] ports = SerialPort.GetPortNames();
// First determain if there was a change (any additions or removals)
bool updated = PreviousPortNames.Except(ports).Count() > 0 || ports.Except(PreviousPortNames).Count() > 0;
// If there was a change, then select an appropriate default port
if (updated)
{
// Use the correctly ordered set of port names
ports = OrderedPortNames();
// Find newest port if one or more were added
string newest = SerialPort.GetPortNames().Except(PreviousPortNames).OrderBy(a => a).LastOrDefault();
// If the port was already open... (see logic notes and reasoning in Notes.txt)
if (PortOpen)
{
if (ports.Contains(CurrentSelection)) selected = CurrentSelection;
else if (!String.IsNullOrEmpty(newest)) selected = newest;
else selected = ports.LastOrDefault();
}
else
{
if (!String.IsNullOrEmpty(newest)) selected = newest;
else if (ports.Contains(CurrentSelection)) selected = CurrentSelection;
else selected = ports.LastOrDefault();
}
}
// If there was a change to the port list, return the recommended default selection
return selected;
}
//*******************************************************************
//*******************************************************************
private void frmTerminal_Load(object sender, EventArgs e)
{
}
//*******************************************************************
//*******************************************************************
// Sends raw text via serial. This will not work for sending data
// to the Serial_service on the Arduino. It must be in the TUN packet
// format.
/// <summary> Send the user's data currently entered in the 'send' box.</summary>
private void SendData()
{
if (CurrentDataMode == DataMode.Text)
{
// Send the user's text straight out the port
comport.Write(txtSendData.Text);
// Show in the terminal window the user's text
Log(LogMsgType.Outgoing, txtSendData.Text + "\n");
}
else
{
try
{
// Convert the user's string of hex digits (ex: B4 CA E2) to a byte array
byte[] data = HexStringToByteArray(txtSendData.Text);
// Send the binary data out the port
comport.Write(data, 0, data.Length);
// Show the hex digits on in the terminal window
Log(LogMsgType.Outgoing, ByteArrayToHexString(data) + "\n");
}
catch (FormatException)
{
// Inform the user if the hex string was not properly formatted
Log(LogMsgType.Error, "Not properly formatted hex string: " + txtSendData.Text + "\n");
}
}
txtSendData.SelectAll();
}
//*******************************************************************
//*******************************************************************
// This routine creates a simple TUN packet to display
// text on the local LCD
private void SendData_lcd_TUN()
{
// storage for the packet
string packet;
string raw_text = txtSendData.Text.Replace("\0", string.Empty);
// create the packet
int returnSz = m_util.create_LCD_TUN_packet((int)TUN_types.TUN_TYPE_LOCAL_LCD_MSG, raw_text, out packet);
Log(LogMsgType.Outgoing, "packet created\n");
if (returnSz == 0)
{
Log(LogMsgType.Outgoing, "packet 0 len\n");
}
// must remove null bytes from string
string result = packet.Replace("\0", string.Empty);
//Log(LogMsgType.Outgoing, "packet null replaced\n");
// Send the user's text straight out the port
comport.Write(result);
//Log(LogMsgType.Outgoing, "packet written\n");
// display the packet
Log(LogMsgType.Outgoing, result + "\n");
}
//*******************************************************************
//*******************************************************************
// Public routine for sending LCD_TUN packet intended for use by GUI
// Author: Taylor Trabun
public void SendString_LCD(String input)
{
// storage for the packet
string packet;
string raw_text = input.Replace("\0", string.Empty);
// create the packet
int returnSz = m_util.create_LCD_TUN_packet((int)TUN_types.TUN_TYPE_LOCAL_LCD_MSG, raw_text, out packet);
Log(LogMsgType.Outgoing, "packet created\n");
if (returnSz == 0)
{
Log(LogMsgType.Outgoing, "packet 0 len\n");
}
// must remove null bytes from string
string result = packet.Replace("\0", string.Empty);
//Log(LogMsgType.Outgoing, "packet null replaced\n");
// Send the user's text straight out the port
comport.Write(result);
//Log(LogMsgType.Outgoing, "packet written\n");
// display the packet
//Log(LogMsgType.Outgoing, result + "\n");
}
//*******************************************************************
// Public routine for sending TUN land drone packet intended for use by GUI
// Author: Taylor Trabun
public void Send_land_packet()
{
// storage for the packet
string packet;
//string raw_text = input.Replace("\0", string.Empty);
// create the packet
int returnSz = m_util.create_land_TUN_packet((int)TUN_types.TUN_TYPE_EXTERNAL_LAND, out packet);
//int returnSz = m_util.create_LCD_TUN_packet((int)TUN_types.TUN_TYPE_LOCAL_LCD_MSG, raw_text, out packet);
// must remove null bytes from string
string result = packet.Replace("\0", string.Empty);
// Send the user's text straight out the port
comport.Write(result);
// display the packet
Log(LogMsgType.Outgoing, result + "\n");
}
//*******************************************************************
// Public routine for sending TUN land drone packet intended for use by GUI
// Args: altitude (altitude at which the drone should reach)
// Author: Taylor Trabun
public void Send_takeoff_packet(int altitude)
{
// storage for the packet
string packet;
//string raw_text = input.Replace("\0", string.Empty);
// create the packet
int returnSz = m_util.create_takeoff_TUN_packet((int)TUN_types.TUN_TYPE_EXTERNAL_TAKEOFF, altitude, out packet);
//int returnSz = m_util.create_LCD_TUN_packet((int)TUN_types.TUN_TYPE_LOCAL_LCD_MSG, raw_text, out packet);
// must remove null bytes from string
string result = packet.Replace("\0", string.Empty);
// Send the user's text straight out the port
comport.Write(result);
// display the packet
Log(LogMsgType.Outgoing, result + "\n");
}
//*******************************************************************
// Public routine for sending TUN move specific (left,right,forward,backwards)
// drone packet intended for use by GUI
// Args: moveType (use DRONE_movement_dir), metricType(DRONE_movement_metric), moveAmount
// Author: Taylor Trabun
public void Send_move_specifc(int moveType, int metricType, int moveAmount)
{
// storage for the packet
string packet;
//string raw_text = input.Replace("\0", string.Empty);
// create the packet
int returnSz = m_util.create_specific_move_TUN_packet((int)TUN_types.TUN_TYPE_EXTERNAL_DO_MOVE, moveType, metricType,
moveAmount, out packet);
//int returnSz = m_util.create_LCD_TUN_packet((int)TUN_types.TUN_TYPE_LOCAL_LCD_MSG, raw_text, out packet);
// must remove null bytes from string
string result = packet.Replace("\0", string.Empty);
// Send the user's text straight out the port
comport.Write(result);
// display the packet
Log(LogMsgType.Outgoing, result + "\n");
}
//*******************************************************************
// Public routine for sending TUN arm message (true/false) (arm/disarm)
// drone packet intended for use by GUI
// Args: bool armDrone
// Author: Taylor Trabun
public void Send_arm_message(bool armDrone)
{
// storage for the packet
string packet;
//string raw_text = input.Replace("\0", string.Empty);
// create the packet
int returnSz = m_util.create_arm_TUN_packet((int)TUN_types.TUN_TYPE_EXTERNAL_ARM, armDrone, out packet);
//int returnSz = m_util.create_LCD_TUN_packet((int)TUN_types.TUN_TYPE_LOCAL_LCD_MSG, raw_text, out packet);
// must remove null bytes from string
string result = packet.Replace("\0", string.Empty);
// Send the user's text straight out the port
comport.Write(result);
// display the packet
Log(LogMsgType.Outgoing, result + "\n");
}
//*******************************************************************
// Public routine for sending TUN altHold message (true/false) (on/off)
// drone packet intended for use by GUI
// Args: bool setHold
// Author: Taylor Trabun
public void Send_altHold_message(bool setHold)
{
// storage for the packet
string packet;
//string raw_text = input.Replace("\0", string.Empty);
// create the packet
int returnSz = m_util.create_altHold_TUN_packet((int)TUN_types.TUN_TYPE_EXTERNAL_ALT_HOLD, setHold, out packet);
//int returnSz = m_util.create_LCD_TUN_packet((int)TUN_types.TUN_TYPE_LOCAL_LCD_MSG, raw_text, out packet);
// must remove null bytes from string
string result = packet.Replace("\0", string.Empty);
// Send the user's text straight out the port
comport.Write(result);
// display the packet
Log(LogMsgType.Outgoing, result + "\n");
}
//*******************************************************************
// Public routine for sending TUN headingHold message
// drone packet intended for use by GUI
// Args: int setHold
// (0: enable longitude hold, 1: disable longitude hold,
// 2: enable latitude hold, 3: disable latitude hold)
// Author: Taylor Trabun
public void Send_headingHold_message(int setHold)
{
// storage for the packet
string packet;
//string raw_text = input.Replace("\0", string.Empty);
// create the packet
int returnSz = m_util.create_headingHold_TUN_packet((int)TUN_types.TUN_TYPE_EXTERNAL_HEADING_HOLD, setHold, out packet);
//int returnSz = m_util.create_LCD_TUN_packet((int)TUN_types.TUN_TYPE_LOCAL_LCD_MSG, raw_text, out packet);
// must remove null bytes from string
string result = packet.Replace("\0", string.Empty);
// Send the user's text straight out the port
comport.Write(result);
// display the packet
Log(LogMsgType.Outgoing, result + "\n");
}
//*******************************************************************
// Public routine for sending TUN set heading message with heading int
// drone packet intended for use by GUI
// Args: int heading (must be 0-360)
// Author: Taylor Trabun
public void Send_setHeading_message(int heading)
{
// storage for the packet
string packet;
//string raw_text = input.Replace("\0", string.Empty);
// create the packet
int returnSz = m_util.create_heading_TUN_packet((int)TUN_types.TUN_TYPE_EXTERNAL_SET_HEADING, heading, out packet);
//int returnSz = m_util.create_LCD_TUN_packet((int)TUN_types.TUN_TYPE_LOCAL_LCD_MSG, raw_text, out packet);
// must remove null bytes from string
string result = packet.Replace("\0", string.Empty);
// Send the user's text straight out the port
comport.Write(result);
// display the packet
Log(LogMsgType.Outgoing, result + "\n");
}
//*******************************************************************
//*******************************************************************
// Updates the count down (-1), and if <=0, the heads up
// display will show red
public void process_TUN_packet()
{
byte[] p_array;
byte[] payload;
int p_array_sz = 0;
// see if a packet is ready
if (xbee_service.is_rx_packet_ready())
{
// extract the payload
p_array_sz = xbee_service.get_rx_packet(out p_array);
// extract the payload
m_util.get_TUN_payload(p_array, out payload);
heads_up.debug_msg(payload);
}
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using Spring.Globalization;
using Spring.Validation;
namespace Spring.DataBinding
{
/// <summary>
/// Base implementation of the <see cref="IBindingContainer"/>.
/// </summary>
/// <author>Aleksandar Seovic</author>
public class BaseBindingContainer : IBindingContainer
{
#region Fields
private IList<IBinding> bindings = new List<IBinding>();
#endregion
#region Constructor(s)
/// <summary>
/// Creates a new instance of <see cref="BaseBindingContainer"/>.
/// </summary>
public BaseBindingContainer()
{ }
#endregion
#region Properties
/// <summary>
/// Gets a list of bindings for this container.
/// </summary>
/// <value>
/// A list of bindings for this container.
/// </value>
protected IList<IBinding> Bindings
{
get { return bindings; }
}
#endregion
#region IBindingContainer Implementation
/// <summary>
/// Gets a value indicating whether this instance has bindings.
/// </summary>
/// <value>
/// <c>true</c> if this instance has bindings; otherwise, <c>false</c>.
/// </value>
public bool HasBindings
{
get { return bindings.Count > 0; }
}
/// <summary>
/// Adds the binding.
/// </summary>
/// <param name="binding">
/// Binding definition to add.
/// </param>
/// <returns>
/// Added <see cref="IBinding"/> instance.
/// </returns>
public IBinding AddBinding(IBinding binding)
{
bindings.Add(binding);
return binding;
}
/// <summary>
/// Adds the <see cref="SimpleExpressionBinding"/> binding with a default
/// binding direction of <see cref="BindingDirection.Bidirectional"/>.
/// </summary>
/// <param name="sourceExpression">
/// The source expression.
/// </param>
/// <param name="targetExpression">
/// The target expression.
/// </param>
/// <returns>
/// Added <see cref="SimpleExpressionBinding"/> instance.
/// </returns>
public IBinding AddBinding(string sourceExpression, string targetExpression)
{
return AddBinding(sourceExpression, targetExpression, BindingDirection.Bidirectional, null);
}
/// <summary>
/// Adds the <see cref="SimpleExpressionBinding"/> binding.
/// </summary>
/// <param name="sourceExpression">
/// The source expression.
/// </param>
/// <param name="targetExpression">
/// The target expression.
/// </param>
/// <param name="direction">
/// Binding direction.
/// </param>
/// <returns>
/// Added <see cref="SimpleExpressionBinding"/> instance.
/// </returns>
public IBinding AddBinding(string sourceExpression, string targetExpression, BindingDirection direction)
{
return AddBinding(sourceExpression, targetExpression, direction, null);
}
/// <summary>
/// Adds the <see cref="SimpleExpressionBinding"/> binding with a default
/// binding direction of <see cref="BindingDirection.Bidirectional"/>.
/// </summary>
/// <param name="sourceExpression">
/// The source expression.
/// </param>
/// <param name="targetExpression">
/// The target expression.
/// </param>
/// <param name="formatter">
/// <see cref="IFormatter"/> to use for value formatting and parsing.
/// </param>
/// <returns>
/// Added <see cref="SimpleExpressionBinding"/> instance.
/// </returns>
public IBinding AddBinding(string sourceExpression, string targetExpression, IFormatter formatter)
{
return AddBinding(sourceExpression, targetExpression, BindingDirection.Bidirectional, formatter);
}
/// <summary>
/// Adds the <see cref="SimpleExpressionBinding"/> binding.
/// </summary>
/// <param name="sourceExpression">
/// The source expression.
/// </param>
/// <param name="targetExpression">
/// The target expression.
/// </param>
/// <param name="direction">
/// Binding direction.
/// </param>
/// <param name="formatter">
/// <see cref="IFormatter"/> to use for value formatting and parsing.
/// </param>
/// <returns>
/// Added <see cref="SimpleExpressionBinding"/> instance.
/// </returns>
public virtual IBinding AddBinding(string sourceExpression, string targetExpression,
BindingDirection direction, IFormatter formatter)
{
SimpleExpressionBinding binding = new SimpleExpressionBinding(sourceExpression, targetExpression);
binding.Direction = direction;
binding.Formatter = formatter;
bindings.Add(binding);
return binding;
}
#endregion
#region IBinding Implementation
/// <summary>
/// Binds source object to target object.
/// </summary>
/// <param name="source">
/// The source object.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
/// <param name="validationErrors">
/// Validation errors collection that type conversion errors should be added to.
/// </param>
public virtual void BindSourceToTarget(object source, object target, IValidationErrors validationErrors)
{
BindSourceToTarget(source, target, validationErrors, null);
}
/// <summary>
/// Binds source object to target object.
/// </summary>
/// <param name="source">
/// The source object.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
/// <param name="validationErrors">
/// Validation errors collection that type conversion errors should be added to.
/// </param>
/// <param name="variables">
/// Variables that should be used during expression evaluation.
/// </param>
public virtual void BindSourceToTarget(object source, object target, IValidationErrors validationErrors, IDictionary<string, object> variables)
{
foreach (IBinding binding in bindings)
{
binding.BindSourceToTarget(source, target, validationErrors, variables);
}
}
/// <summary>
/// Binds target object to source object.
/// </summary>
/// <param name="source">
/// The source object.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
/// <param name="validationErrors">
/// Validation errors collection that type conversion errors should be added to.
/// </param>
public virtual void BindTargetToSource(object source, object target, IValidationErrors validationErrors)
{
BindTargetToSource(source, target, validationErrors, null);
}
/// <summary>
/// Binds target object to source object.
/// </summary>
/// <param name="source">
/// The source object.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
/// <param name="validationErrors">
/// Validation errors collection that type conversion errors should be added to.
/// </param>
/// <param name="variables">
/// Variables that should be used during expression evaluation.
/// </param>
public virtual void BindTargetToSource(object source, object target, IValidationErrors validationErrors, IDictionary<string, object> variables)
{
foreach (IBinding binding in bindings)
{
binding.BindTargetToSource(source, target, validationErrors, variables);
}
}
/// <summary>
/// Implemented as a NOOP for containers.
/// of a non-fatal binding error.
/// </summary>
/// <param name="messageId">
/// Resource ID of the error message.
/// </param>
/// <param name="errorProviders">
/// List of error providers message should be added to.
/// </param>
public virtual void SetErrorMessage(string messageId, params string[] errorProviders)
{ }
#endregion
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// 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.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
namespace OpenGL
{
/// <summary>
/// Class for scoping those methods conflicting with other fields/enums.
/// </summary>
public partial class Gl
{
public static class VB
{
/// <summary>
/// <para>
/// [GL4|GLES3.2] glClear: clear buffers to preset values
/// </para>
/// </summary>
/// <param name="mask">
/// Bitwise OR of masks that indicate the buffers to be cleared. The three masks are Gl.COLOR_BUFFER_BIT,
/// Gl.DEPTH_BUFFER_BIT, and Gl.STENCIL_BUFFER_BIT.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")]
[RequiredByFeature("GL_ES_VERSION_2_0", Api = "gles2")]
[RequiredByFeature("GL_SC_VERSION_2_0", Api = "glsc2")]
public static void Clear(ClearBufferMask mask)
{
Debug.Assert(Delegates.pglClear != null, "pglClear not implemented");
Delegates.pglClear((uint)mask);
LogCommand("glClear", null, mask );
DebugCheckErrors(null);
}
/// <summary>
/// <para>
/// [GL2.1|GLES1.1] glViewport: set the viewport
/// </para>
/// </summary>
/// <param name="x">
/// Specify the lower left corner of the viewport rectangle, in pixels. The initial value is (0,0).
/// </param>
/// <param name="y">
/// Specify the lower left corner of the viewport rectangle, in pixels. The initial value is (0,0).
/// </param>
/// <param name="width">
/// Specify the width and height of the viewport. When a GL context is first attached to a window, <paramref name="width"/>
/// and <paramref name="height"/> are set to the dimensions of that window.
/// </param>
/// <param name="height">
/// Specify the width and height of the viewport. When a GL context is first attached to a window, <paramref name="width"/>
/// and <paramref name="height"/> are set to the dimensions of that window.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")]
[RequiredByFeature("GL_ES_VERSION_2_0", Api = "gles2")]
[RequiredByFeature("GL_SC_VERSION_2_0", Api = "glsc2")]
public static void Viewport(int x, int y, int width, int height)
{
Debug.Assert(Delegates.pglViewport != null, "pglViewport not implemented");
Delegates.pglViewport(x, y, width, height);
LogCommand("glViewport", null, x, y, width, height );
DebugCheckErrors(null);
}
/// <summary>
/// [GL2.1] glBitmap: draw a bitmap
/// </summary>
/// <param name="width">
/// Specify the pixel width and height of the bitmap image.
/// </param>
/// <param name="height">
/// Specify the pixel width and height of the bitmap image.
/// </param>
/// <param name="xorig">
/// Specify the location of the origin in the bitmap image. The origin is measured from the lower left corner of the bitmap,
/// with right and up being the positive axes.
/// </param>
/// <param name="yorig">
/// Specify the location of the origin in the bitmap image. The origin is measured from the lower left corner of the bitmap,
/// with right and up being the positive axes.
/// </param>
/// <param name="xmove">
/// Specify the x and y offsets to be added to the current raster position after the bitmap is drawn.
/// </param>
/// <param name="ymove">
/// Specify the x and y offsets to be added to the current raster position after the bitmap is drawn.
/// </param>
/// <param name="bitmap">
/// Specifies the address of the bitmap image.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Bitmap(int width, int height, float xorig, float yorig, float xmove, float ymove, byte[] bitmap)
{
unsafe {
fixed (byte* p_bitmap = bitmap)
{
Debug.Assert(Delegates.pglBitmap != null, "pglBitmap not implemented");
Delegates.pglBitmap(width, height, xorig, yorig, xmove, ymove, p_bitmap);
LogCommand("glBitmap", null, width, height, xorig, yorig, xmove, ymove, bitmap );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL2.1] glIndexd: set the current color index
/// </summary>
/// <param name="c">
/// Specifies the new value for the current color index.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Index(double c)
{
Debug.Assert(Delegates.pglIndexd != null, "pglIndexd not implemented");
Delegates.pglIndexd(c);
LogCommand("glIndexd", null, c );
}
/// <summary>
/// [GL2.1] glIndexdv: set the current color index
/// </summary>
/// <param name="c">
/// Specifies the new value for the current color index.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Index(double[] c)
{
Debug.Assert(c.Length >= 1);
unsafe {
fixed (double* p_c = c)
{
Debug.Assert(Delegates.pglIndexdv != null, "pglIndexdv not implemented");
Delegates.pglIndexdv(p_c);
LogCommand("glIndexdv", null, c );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL2.1] glIndexf: set the current color index
/// </summary>
/// <param name="c">
/// Specifies the new value for the current color index.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Index(float c)
{
Debug.Assert(Delegates.pglIndexf != null, "pglIndexf not implemented");
Delegates.pglIndexf(c);
LogCommand("glIndexf", null, c );
}
/// <summary>
/// [GL2.1] glIndexfv: set the current color index
/// </summary>
/// <param name="c">
/// Specifies the new value for the current color index.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Index(float[] c)
{
Debug.Assert(c.Length >= 1);
unsafe {
fixed (float* p_c = c)
{
Debug.Assert(Delegates.pglIndexfv != null, "pglIndexfv not implemented");
Delegates.pglIndexfv(p_c);
LogCommand("glIndexfv", null, c );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL2.1] glIndexi: set the current color index
/// </summary>
/// <param name="c">
/// Specifies the new value for the current color index.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Index(int c)
{
Debug.Assert(Delegates.pglIndexi != null, "pglIndexi not implemented");
Delegates.pglIndexi(c);
LogCommand("glIndexi", null, c );
}
/// <summary>
/// [GL2.1] glIndexiv: set the current color index
/// </summary>
/// <param name="c">
/// Specifies the new value for the current color index.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Index(int[] c)
{
Debug.Assert(c.Length >= 1);
unsafe {
fixed (int* p_c = c)
{
Debug.Assert(Delegates.pglIndexiv != null, "pglIndexiv not implemented");
Delegates.pglIndexiv(p_c);
LogCommand("glIndexiv", null, c );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL2.1] glIndexs: set the current color index
/// </summary>
/// <param name="c">
/// Specifies the new value for the current color index.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Index(short c)
{
Debug.Assert(Delegates.pglIndexs != null, "pglIndexs not implemented");
Delegates.pglIndexs(c);
LogCommand("glIndexs", null, c );
}
/// <summary>
/// [GL2.1] glIndexsv: set the current color index
/// </summary>
/// <param name="c">
/// Specifies the new value for the current color index.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Index(short[] c)
{
Debug.Assert(c.Length >= 1);
unsafe {
fixed (short* p_c = c)
{
Debug.Assert(Delegates.pglIndexsv != null, "pglIndexsv not implemented");
Delegates.pglIndexsv(p_c);
LogCommand("glIndexsv", null, c );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// <para>
/// [GL2.1|GLES1.1] glFogf: specify fog parameters
/// </para>
/// </summary>
/// <param name="pname">
/// Specifies a single-valued fog parameter. Gl.FOG_MODE, Gl.FOG_DENSITY, Gl.FOG_START, Gl.FOG_END, Gl.FOG_INDEX, and
/// Gl.FOG_COORD_SRC are accepted.
/// </param>
/// <param name="param">
/// Specifies the value that <paramref name="pname"/> will be set to.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Fog(FogParameter pname, float param)
{
Debug.Assert(Delegates.pglFogf != null, "pglFogf not implemented");
Delegates.pglFogf((int)pname, param);
LogCommand("glFogf", null, pname, param );
DebugCheckErrors(null);
}
/// <summary>
/// <para>
/// [GL2.1|GLES1.1] glFogfv: specify fog parameters
/// </para>
/// </summary>
/// <param name="pname">
/// Specifies a single-valued fog parameter. Gl.FOG_MODE, Gl.FOG_DENSITY, Gl.FOG_START, Gl.FOG_END, Gl.FOG_INDEX, and
/// Gl.FOG_COORD_SRC are accepted.
/// </param>
/// <param name="params">
/// A <see cref="T:float[]"/>.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Fog(FogParameter pname, float[] @params)
{
unsafe {
fixed (float* p_params = @params)
{
Debug.Assert(Delegates.pglFogfv != null, "pglFogfv not implemented");
Delegates.pglFogfv((int)pname, p_params);
LogCommand("glFogfv", null, pname, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL2.1] glFogi: specify fog parameters
/// </summary>
/// <param name="pname">
/// Specifies a single-valued fog parameter. Gl.FOG_MODE, Gl.FOG_DENSITY, Gl.FOG_START, Gl.FOG_END, Gl.FOG_INDEX, and
/// Gl.FOG_COORD_SRC are accepted.
/// </param>
/// <param name="param">
/// Specifies the value that <paramref name="pname"/> will be set to.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Fog(FogParameter pname, int param)
{
Debug.Assert(Delegates.pglFogi != null, "pglFogi not implemented");
Delegates.pglFogi((int)pname, param);
LogCommand("glFogi", null, pname, param );
DebugCheckErrors(null);
}
/// <summary>
/// [GL2.1] glFogiv: specify fog parameters
/// </summary>
/// <param name="pname">
/// Specifies a single-valued fog parameter. Gl.FOG_MODE, Gl.FOG_DENSITY, Gl.FOG_START, Gl.FOG_END, Gl.FOG_INDEX, and
/// Gl.FOG_COORD_SRC are accepted.
/// </param>
/// <param name="params">
/// A <see cref="T:int[]"/>.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Fog(FogParameter pname, int[] @params)
{
unsafe {
fixed (int* p_params = @params)
{
Debug.Assert(Delegates.pglFogiv != null, "pglFogiv not implemented");
Delegates.pglFogiv((int)pname, p_params);
LogCommand("glFogiv", null, pname, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL2.1] glAccum: operate on the accumulation buffer
/// </summary>
/// <param name="op">
/// Specifies the accumulation buffer operation. Symbolic constants Gl.ACCUM, Gl.LOAD, Gl.ADD, Gl.MULT, and Gl.RETURN are
/// accepted.
/// </param>
/// <param name="value">
/// Specifies a floating-point value used in the accumulation buffer operation. <paramref name="op"/> determines how
/// <paramref name="value"/> is used.
/// </param>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Accum(AccumOp op, float value)
{
Debug.Assert(Delegates.pglAccum != null, "pglAccum not implemented");
Delegates.pglAccum((int)op, value);
LogCommand("glAccum", null, op, value );
DebugCheckErrors(null);
}
/// <summary>
/// [GL2.1] glIndexub: set the current color index
/// </summary>
/// <param name="c">
/// Specifies the new value for the current color index.
/// </param>
[RequiredByFeature("GL_VERSION_1_1")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Index(byte c)
{
Debug.Assert(Delegates.pglIndexub != null, "pglIndexub not implemented");
Delegates.pglIndexub(c);
LogCommand("glIndexub", null, c );
}
/// <summary>
/// [GL2.1] glIndexubv: set the current color index
/// </summary>
/// <param name="c">
/// Specifies the new value for the current color index.
/// </param>
[RequiredByFeature("GL_VERSION_1_1")]
[RemovedByFeature("GL_VERSION_3_2", Profile = "core")]
public static void Index(byte[] c)
{
Debug.Assert(c.Length >= 1);
unsafe {
fixed (byte* p_c = c)
{
Debug.Assert(Delegates.pglIndexubv != null, "pglIndexubv not implemented");
Delegates.pglIndexubv(p_c);
LogCommand("glIndexubv", null, c );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GLES1.1] glFogx: specify fog parameters
/// </summary>
/// <param name="pname">
/// Specifies a single-valued fog parameter. Gl.FOG_MODE, Gl.FOG_DENSITY, Gl.FOG_START, and Gl.FOG_END are accepted.
/// </param>
/// <param name="param">
/// Specifies the value that <paramref name="pname"/> will be set to.
/// </param>
[RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")]
public static void Fog(FogPName pname, IntPtr param)
{
Debug.Assert(Delegates.pglFogx != null, "pglFogx not implemented");
Delegates.pglFogx((int)pname, param);
LogCommand("glFogx", null, pname, param );
DebugCheckErrors(null);
}
/// <summary>
/// [GLES1.1] glFogxv: specify fog parameters
/// </summary>
/// <param name="pname">
/// Specifies a single-valued fog parameter. Gl.FOG_MODE, Gl.FOG_DENSITY, Gl.FOG_START, and Gl.FOG_END are accepted.
/// </param>
/// <param name="param">
/// Specifies the value that <paramref name="pname"/> will be set to.
/// </param>
[RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")]
public static void Fog(FogPName pname, IntPtr[] param)
{
unsafe {
fixed (IntPtr* p_param = param)
{
Debug.Assert(Delegates.pglFogxv != null, "pglFogxv not implemented");
Delegates.pglFogxv((int)pname, p_param);
LogCommand("glFogxv", null, pname, param );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL2.1] glHistogram: define histogram table
/// </summary>
/// <param name="target">
/// The histogram whose parameters are to be set. Must be one of Gl.HISTOGRAM or Gl.PROXY_HISTOGRAM.
/// </param>
/// <param name="width">
/// The number of entries in the histogram table. Must be a power of 2.
/// </param>
/// <param name="internalformat">
/// The format of entries in the histogram table. Must be one of Gl.ALPHA, Gl.ALPHA4, Gl.ALPHA8, Gl.ALPHA12, Gl.ALPHA16,
/// Gl.LUMINANCE, Gl.LUMINANCE4, Gl.LUMINANCE8, Gl.LUMINANCE12, Gl.LUMINANCE16, Gl.LUMINANCE_ALPHA, Gl.LUMINANCE4_ALPHA4,
/// Gl.LUMINANCE6_ALPHA2, Gl.LUMINANCE8_ALPHA8, Gl.LUMINANCE12_ALPHA4, Gl.LUMINANCE12_ALPHA12, Gl.LUMINANCE16_ALPHA16,
/// Gl.R3_G3_B2, Gl.RGB, Gl.RGB4, Gl.RGB5, Gl.RGB8, Gl.RGB10, Gl.RGB12, Gl.RGB16, Gl.RGBA, Gl.RGBA2, Gl.RGBA4, Gl.RGB5_A1,
/// Gl.RGBA8, Gl.RGB10_A2, Gl.RGBA12, or Gl.RGBA16.
/// </param>
/// <param name="sink">
/// If Gl.TRUE, pixels will be consumed by the histogramming process and no drawing or texture loading will take place. If
/// Gl.FALSE, pixels will proceed to the minmax process after histogramming.
/// </param>
[RequiredByFeature("GL_ARB_imaging", Profile = "compatibility")]
[RequiredByFeature("GL_EXT_histogram")]
public static void Histogram(HistogramTarget target, int width, InternalFormat internalformat, bool sink)
{
Debug.Assert(Delegates.pglHistogram != null, "pglHistogram not implemented");
Delegates.pglHistogram((int)target, width, (int)internalformat, sink);
LogCommand("glHistogram", null, target, width, internalformat, sink );
DebugCheckErrors(null);
}
/// <summary>
/// [GL2.1] glMinmax: define minmax table
/// </summary>
/// <param name="target">
/// The minmax table whose parameters are to be set. Must be Gl.MINMAX.
/// </param>
/// <param name="internalformat">
/// The format of entries in the minmax table. Must be one of Gl.ALPHA, Gl.ALPHA4, Gl.ALPHA8, Gl.ALPHA12, Gl.ALPHA16,
/// Gl.LUMINANCE, Gl.LUMINANCE4, Gl.LUMINANCE8, Gl.LUMINANCE12, Gl.LUMINANCE16, Gl.LUMINANCE_ALPHA, Gl.LUMINANCE4_ALPHA4,
/// Gl.LUMINANCE6_ALPHA2, Gl.LUMINANCE8_ALPHA8, Gl.LUMINANCE12_ALPHA4, Gl.LUMINANCE12_ALPHA12, Gl.LUMINANCE16_ALPHA16,
/// Gl.R3_G3_B2, Gl.RGB, Gl.RGB4, Gl.RGB5, Gl.RGB8, Gl.RGB10, Gl.RGB12, Gl.RGB16, Gl.RGBA, Gl.RGBA2, Gl.RGBA4, Gl.RGB5_A1,
/// Gl.RGBA8, Gl.RGB10_A2, Gl.RGBA12, or Gl.RGBA16.
/// </param>
/// <param name="sink">
/// If Gl.TRUE, pixels will be consumed by the minmax process and no drawing or texture loading will take place. If
/// Gl.FALSE, pixels will proceed to the final conversion process after minmax.
/// </param>
[RequiredByFeature("GL_ARB_imaging", Profile = "compatibility")]
[RequiredByFeature("GL_EXT_histogram")]
public static void Minmax(MinmaxTarget target, InternalFormat internalformat, bool sink)
{
Debug.Assert(Delegates.pglMinmax != null, "pglMinmax not implemented");
Delegates.pglMinmax((int)target, (int)internalformat, sink);
LogCommand("glMinmax", null, target, internalformat, sink );
DebugCheckErrors(null);
}
}
public static class VBEnum
{
/// <summary>
/// [GL] Value of GL_CLEAR symbol.
/// </summary>
[RequiredByFeature("GL_VERSION_1_0")]
[RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")]
public const int CLEAR = 0x1500;
/// <summary>
/// <para>
/// [GL4] Gl.Get: When used with non-indexed variants of glGet (such as glGetIntegerv), data returns four values: the x and
/// y window coordinates of the viewport, followed by its width and height. Initially the x and y window coordinates are
/// both set to 0, and the width and height are set to the width and height of the window into which the GL will do its
/// rendering. See Gl.Viewport. When used with indexed variants of glGet (such as glGetIntegeri_v), data returns four
/// values: the x and y window coordinates of the indexed viewport, followed by its width and height. Initially the x and y
/// window coordinates are both set to 0, and the width and height are set to the width and height of the window into which
/// the GL will do its rendering. See glViewportIndexedf.
/// </para>
/// <para>
/// [GLES3.2] Gl.Get: data returns four values: the x and y window coordinates of the viewport, followed by its width and
/// height. Initially the x and y window coordinates are both set to 0, and the width and height are set to the width and
/// height of the window into which the GL will do its rendering. See Gl.Viewport.
/// </para>
/// </summary>
[RequiredByFeature("GL_VERSION_1_0")]
[RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")]
[RequiredByFeature("GL_ES_VERSION_2_0", Api = "gles2")]
[RequiredByFeature("GL_SC_VERSION_2_0", Api = "glsc2")]
[RequiredByFeature("GL_ARB_viewport_array", Api = "gl|glcore")]
[RequiredByFeature("GL_NV_viewport_array", Api = "gles2")]
[RequiredByFeature("GL_OES_viewport_array", Api = "gles2")]
public const int VIEWPORT = 0x0BA2;
/// <summary>
/// [GL] Value of GL_BITMAP symbol (DEPRECATED).
/// </summary>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2")]
public const int BITMAP = 0x1A00;
/// <summary>
/// [GL] Value of GL_INDEX symbol (DEPRECATED).
/// </summary>
[RequiredByFeature("GL_VERSION_3_0")]
[RequiredByFeature("GL_ARB_framebuffer_object", Api = "gl|glcore")]
[RemovedByFeature("GL_VERSION_3_2")]
public const int INDEX = 0x8222;
/// <summary>
/// <para>
/// [GL2.1] Gl.Enable: If enabled and no fragment shader is active, blend a fog color into the post-texturing color. See
/// Gl.Fog.
/// </para>
/// <para>
/// [GL2.1] Gl.Get: params returns a single boolean value indicating whether fogging is enabled. The initial value is
/// Gl.FALSE. See Gl.Fog.
/// </para>
/// <para>
/// [GLES1.1] Gl.Enable: If enabled, blend a fog color into the posttexturing color. See Gl.Fog.
/// </para>
/// <para>
/// [GLES1.1] Gl.Get: params returns a single boolean value indicating whether fog is enabled. The initial value is
/// Gl.FALSE. See Gl.Fog.
/// </para>
/// </summary>
[RequiredByFeature("GL_VERSION_1_0")]
[RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")]
[RequiredByFeature("GL_NV_register_combiners")]
[RemovedByFeature("GL_VERSION_3_2")]
public const int FOG = 0x0B60;
/// <summary>
/// [GL2.1] Gl.Accum: Obtains R, G, B, and A values from the buffer currently selected for reading (see Gl.ReadBuffer). Each
/// component value is divided by 2n-1, where n is the number of bits allocated to each color component in the currently
/// selected buffer. The result is a floating-point value in the range 01, which is multiplied by value and added to the
/// corresponding pixel component in the accumulation buffer, thereby updating the accumulation buffer.
/// </summary>
[RequiredByFeature("GL_VERSION_1_0")]
[RemovedByFeature("GL_VERSION_3_2")]
public const int ACCUM = 0x0100;
/// <summary>
/// <para>
/// [GL2.1] Gl.Enable: If enabled, histogram incoming RGBA color values. See Gl.Histogram.
/// </para>
/// <para>
/// [GL2.1] Gl.Get: params returns a single boolean value indicating whether histogram is enabled. The initial value is
/// Gl.FALSE. See Gl.Histogram.
/// </para>
/// </summary>
[RequiredByFeature("GL_ARB_imaging", Api = "gl|glcore")]
[RequiredByFeature("GL_EXT_histogram")]
public const int HISTOGRAM = 0x8024;
/// <summary>
/// <para>
/// [GL2.1] Gl.Enable: If enabled, compute the minimum and maximum values of incoming RGBA color values. See Gl.Minmax.
/// </para>
/// <para>
/// [GL2.1] Gl.Get: params returns a single boolean value indicating whether pixel minmax values are computed. The initial
/// value is Gl.FALSE. See Gl.Minmax.
/// </para>
/// </summary>
[RequiredByFeature("GL_ARB_imaging", Api = "gl|glcore")]
[RequiredByFeature("GL_EXT_histogram")]
public const int MINMAX = 0x802E;
}
}
}
| |
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/
//
// 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 Castle.Components.Validator
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Castle.Components.Validator.Contibutors;
/// <summary>
/// Coordinates the gathering and execution of validators.
/// <seealso cref="IValidatorRegistry"/>
/// </summary>
/// <remarks>
/// This class is not thread safe and should not be shared. It should only be
/// used in small scopes and discarded.
/// </remarks>
/// <example>
/// ValidatorRunner runner = new ValidatorRunner(new CachedValidationRegistry());
///
/// if (!runner.IsValid(customer))
/// {
/// // do something as the Customer instance is not valid
/// }
/// </example>
public class ValidatorRunner : IValidatorRunner
{
/// <summary>
/// Default settings value being used for constructor or method overloads
/// </summary>
public static class DefaultSettings {
/// <summary>
/// Default setting is false: the validation runner will not infer validators based on data types
/// </summary>
public const bool InferValidators = false;
/// <summary>
///
/// </summary>
public static readonly IValidationPerformer DefaultValidationPerformer = new DefaultValidationPerformer();
/// <summary>
///
/// </summary>
public static IValidationContributor[] DefaultContributors =
new IValidationContributor[]
{
new SelfValidationContributor(),
new ValidatorContainerInterfaceValidationContributor()
};
}
private readonly static IDictionary<Type, Type> type2Validator;
private readonly IDictionary extendedProperties = new Hashtable();
private readonly IDictionary<object, ErrorSummary> errorPerInstance;
private readonly bool inferValidators;
private readonly IValidatorRegistry registry;
private readonly List<IValidationContributor> contributors = new List<IValidationContributor>();
private readonly IValidationPerformer validationPerformer;
static ValidatorRunner()
{
type2Validator = new Dictionary<Type, Type>();
type2Validator[typeof(Int16)] = typeof(IntegerValidator);
type2Validator[typeof(Nullable<Int16>)] = typeof(IntegerValidator);
type2Validator[typeof(Int32)] = typeof(IntegerValidator);
type2Validator[typeof(Nullable<Int32>)] = typeof(IntegerValidator);
type2Validator[typeof(Int64)] = typeof(IntegerValidator);
type2Validator[typeof(Nullable<Int64>)] = typeof(IntegerValidator);
type2Validator[typeof(Decimal)] = typeof(DecimalValidator);
type2Validator[typeof(Nullable<Decimal>)] = typeof(DecimalValidator);
type2Validator[typeof(Single)] = typeof(SingleValidator);
type2Validator[typeof(Nullable<Single>)] = typeof(SingleValidator);
type2Validator[typeof(Double)] = typeof(DoubleValidator);
type2Validator[typeof(Nullable<Double>)] = typeof(DoubleValidator);
type2Validator[typeof(DateTime)] = typeof(DateTimeValidator);
type2Validator[typeof(Nullable<DateTime>)] = typeof(DateTimeValidator);
}
/// <summary>
/// Initializes a new instance of the <see cref="ValidatorRunner"/> class.
/// </summary>
/// <param name="registry">The registry.</param>
public ValidatorRunner(IValidatorRegistry registry)
: this(DefaultSettings.InferValidators, registry)
{}
/// <summary>
/// Initializes a new instance of the <see cref="ValidatorRunner"/> class.
/// </summary>
/// <param name="inferValidators">If true, the runner will try to infer the validators based on data types</param>
/// <param name="registry">The registry.</param>
public ValidatorRunner(bool inferValidators, IValidatorRegistry registry)
: this(inferValidators, registry, DefaultSettings.DefaultContributors)
{}
/// <summary>
/// Initializes a new instance of the <see cref="ValidatorRunner"/> class.
/// </summary>
/// <param name="contributors">The contributors.</param>
/// <param name="registry">The registry.</param>
public ValidatorRunner(IValidationContributor[] contributors, IValidatorRegistry registry)
: this(DefaultSettings.InferValidators, registry, contributors)
{}
/// <summary>
/// Initializes a new instance of the <see cref="ValidatorRunner"/> class.
/// </summary>
/// <param name="inferValidators">If true, the runner will try to infer the validators based on data types</param>
/// <param name="registry">The registry.</param>
/// <param name="contributors">The contributors.</param>
public ValidatorRunner(bool inferValidators, IValidatorRegistry registry, IValidationContributor[] contributors) {
if (registry == null) throw new ArgumentNullException("registry");
this.inferValidators = inferValidators;
validationPerformer = DefaultSettings.DefaultValidationPerformer;
errorPerInstance = new Dictionary<object, ErrorSummary>();
this.registry = registry;
this.contributors.AddRange(contributors);
// resolve contributor dependencies if needed
foreach(IValidationContributor contributor in this.contributors)
{
IHasValidationPerformerDependency hasPerformerDependency = (contributor as IHasValidationPerformerDependency);
if (hasPerformerDependency != null)
hasPerformerDependency.ValidationPerformer = this.validationPerformer;
IHasValidatorRunnerDependency hasValidatorRunnerDependency = contributor as IHasValidatorRunnerDependency;
if (hasValidatorRunnerDependency != null)
hasValidatorRunnerDependency.ValidatorRunner = this;
IHasValidatorRegistryDependency hasValidatorRegistryDependency = (contributor as IHasValidatorRegistryDependency);
if (hasValidatorRegistryDependency != null)
hasValidatorRegistryDependency.ValidatorRegistry = registry;
}
}
/// <summary>
/// Determines whether the specified instance is valid.
/// <para>
/// All validators are run.
/// </para>
/// </summary>
/// <param name="objectInstance">The object instance to be validated (cannot be null).</param>
/// <returns>
/// <see langword="true"/> if the specified obj is valid; otherwise, <see langword="false"/>.
/// </returns>
public bool IsValid(object objectInstance)
{
return IsValid(objectInstance, RunWhen.Everytime);
}
/// <summary>
/// Determines whether the specified instance is valid.
/// <para>
/// All validators are run for the specified <see cref="RunWhen"/> phase.
/// </para>
/// </summary>
/// <param name="objectInstance">The object instance to be validated (cannot be null).</param>
/// <param name="runWhen">Restrict the set returned to the phase specified</param>
/// <returns>
/// <see langword="true"/> if the specified instance is valid; otherwise, <see langword="false"/>.
/// </returns>
public bool IsValid(object objectInstance, RunWhen runWhen)
{
if (objectInstance == null) throw new ArgumentNullException("objectInstance");
bool isValid;
ErrorSummary summary = new ErrorSummary();
IValidator[] validators = GetValidators(objectInstance, runWhen);
SortValidators(validators);
isValid = validationPerformer.PerformValidation(
objectInstance,
validators,
contributors,
runWhen,
summary);
SetErrorSummaryForInstance(objectInstance, summary);
return isValid;
}
/// <summary>
/// Gets the registered validators.
/// </summary>
/// <param name="parentType">Type of the parent.</param>
/// <param name="property">The property.</param>
/// <returns></returns>
public IValidator[] GetValidators(Type parentType, PropertyInfo property)
{
return GetValidators(parentType, property, RunWhen.Everytime);
}
/// <summary>
/// Gets the registered validators.
/// </summary>
/// <param name="parentType">Type of the parent.</param>
/// <param name="property">The property.</param>
/// <param name="runWhenPhase">The run when phase.</param>
/// <returns></returns>
public IValidator[] GetValidators(Type parentType, PropertyInfo property, RunWhen runWhenPhase)
{
if (parentType == null) throw new ArgumentNullException("parentType");
if (property == null) throw new ArgumentNullException("property");
IValidator[] validators = registry.GetValidators(this, parentType, property, runWhenPhase);
if (inferValidators && validators.Length == 0)
{
Type defaultValidatorForType = (Type) type2Validator[property.PropertyType];
if (defaultValidatorForType != null)
{
validators = new IValidator[] {(IValidator) Activator.CreateInstance(defaultValidatorForType)};
validators[0].Initialize(registry, property);
}
}
SortValidators(validators);
return validators;
}
/// <summary>
/// Gets the error list per instance.
/// </summary>
/// <param name="instance">The instance.</param>
/// <returns></returns>
public bool HasErrors(object instance)
{
ErrorSummary summary = GetErrorSummary(instance);
if (summary == null) return false;
return summary.ErrorsCount != 0;
}
/// <summary>
/// Gets the error list per instance.
/// </summary>
/// <param name="instance">The instance.</param>
/// <returns></returns>
public ErrorSummary GetErrorSummary(object instance)
{
return errorPerInstance.ContainsKey(instance) ? errorPerInstance[instance] : null;
}
/// <summary>
/// Gets the extended properties, which allows <see cref="IValidator"/>
/// implementation to store additional information to track state.
/// </summary>
/// <value>The extended properties.</value>
public IDictionary ExtendedProperties
{
get { return extendedProperties; }
}
/// <summary>
/// associate error summary to the object instance
/// </summary>
/// <param name="objectInstance">object instance to associate validation error summary with</param>
/// <param name="summary">error summary to be associated with object instance</param>
protected void SetErrorSummaryForInstance(object objectInstance, ErrorSummary summary)
{
errorPerInstance[objectInstance] = summary;
}
/// <summary>
/// provide read access to validator registry
/// </summary>
protected IValidatorRegistry Registry { get { return registry; } }
/// <summary>
/// Sort given validators with default algorithm
/// </summary>
/// <param name="validators"></param>
protected virtual void SortValidators(IValidator[] validators)
{
Array.Sort(validators, ValidatorComparer.Instance);
}
private IValidator[] GetValidators(object objectInstance, RunWhen runWhen)
{
if (objectInstance == null) throw new ArgumentNullException("objectInstance");
IValidator[] validators = GetValidatorsForDeclaringType(objectInstance.GetType(), runWhen);
return validators;
}
/// <summary>
///
/// </summary>
/// <param name="declaringType"></param>
/// <param name="runWhen"></param>
/// <returns></returns>
protected IValidator[] GetValidatorsForDeclaringType(Type declaringType, RunWhen runWhen)
{
IValidator[] validators = registry.GetValidators(this, declaringType, runWhen);
SortValidators(validators);
return validators;
}
private class ValidatorComparer : IComparer
{
private static readonly ValidatorComparer instance = new ValidatorComparer();
public int Compare(object x, object y)
{
IValidator left = (IValidator) x;
IValidator right = (IValidator) y;
return left.ExecutionOrder - right.ExecutionOrder;
}
public static ValidatorComparer Instance
{
get { return instance; }
}
}
}
}
| |
using OpenTK;
namespace Bearded.Utilities.Math
{
/// <summary>
/// Interpolation functions.
/// </summary>
public static class Interpolate
{
#region Bezier 2D
/// <summary>
/// Performs a first order Bezier curve interpolation.
/// </summary>
/// <param name="p0"></param>
/// <param name="p1"></param>
/// <param name="t">The amount of interpolation (between 0 and 1).</param>
/// <returns>The result of the Bezier curve interpolation.</returns>
public static Vector2 Bezier(Vector2 p0, Vector2 p1, float t)
{
if (t <= 0)
return p0;
if (t >= 1)
return p1;
return Interpolate.bezier(p0, p1, t);
}
private static Vector2 bezier(Vector2 p0, Vector2 p1, float t)
{
return p0 + (p1 - p0) * t;
}
/// <summary>
/// Performs a second order Bezier curve interpolation.
/// </summary>
/// <param name="p0"></param>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <param name="t">The amount of interpolation (between 0 and 1).</param>
/// <returns>The result of the Bezier curve interpolation.</returns>
public static Vector2 Bezier(Vector2 p0, Vector2 p1, Vector2 p2, float t)
{
if (t <= 0)
return p0;
if (t >= 1)
return p2;
return Interpolate.bezier(p0, p1, p2, t);
}
private static Vector2 bezier(Vector2 p0, Vector2 p1, Vector2 p2, float t)
{
return Interpolate.bezier(Interpolate.bezier(p0, p1, t), Interpolate.bezier(p1, p2, t), t);
}
/// <summary>
/// Performs a third order Bezier curve interpolation.
/// </summary>
/// <param name="p0"></param>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <param name="p3"></param>
/// <param name="t">The amount of interpolation (between 0 and 1).</param>
/// <returns>The result of the Bezier curve interpolation.</returns>
public static Vector2 Bezier(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3, float t)
{
if (t <= 0)
return p0;
if (t >= 1)
return p3;
return Interpolate.bezier(p0, p1, p2, p3, t);
}
private static Vector2 bezier(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3, float t)
{
return Interpolate.bezier(Interpolate.bezier(p0, p1, p2, t), Interpolate.bezier(p1, p2, p3, t), t);
}
#endregion
#region Bezier 3D
/// <summary>
/// Performs a first order Bezier curve interpolation.
/// </summary>
/// <param name="p0"></param>
/// <param name="p1"></param>
/// <param name="t">The amount of interpolation (between 0 and 1).</param>
/// <returns>The result of the Bezier curve interpolation.</returns>
public static Vector3 Bezier(Vector3 p0, Vector3 p1, float t)
{
if (t <= 0)
return p0;
if (t >= 1)
return p1;
return Interpolate.bezier(p0, p1, t);
}
private static Vector3 bezier(Vector3 p0, Vector3 p1, float t)
{
return p0 + (p1 - p0) * t;
}
/// <summary>
/// Performs a second order Bezier curve interpolation.
/// </summary>
/// <param name="p0"></param>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <param name="t">The amount of interpolation (between 0 and 1).</param>
/// <returns>The result of the Bezier curve interpolation.</returns>
public static Vector3 Bezier(Vector3 p0, Vector3 p1, Vector3 p2, float t)
{
if (t <= 0)
return p0;
if (t >= 1)
return p2;
return Interpolate.bezier(p0, p1, p2, t);
}
private static Vector3 bezier(Vector3 p0, Vector3 p1, Vector3 p2, float t)
{
return Interpolate.bezier(Interpolate.bezier(p0, p1, t), Interpolate.bezier(p1, p2, t), t);
}
/// <summary>
/// Performs a third order Bezier curve interpolation.
/// </summary>
/// <param name="p0"></param>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <param name="p3"></param>
/// <param name="t">The amount of interpolation (between 0 and 1).</param>
/// <returns>The result of the Bezier curve interpolation.</returns>
public static Vector3 Bezier(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
if (t <= 0)
return p0;
if (t >= 1)
return p3;
return Interpolate.bezier(p0, p1, p2, p3, t);
}
private static Vector3 bezier(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
return Interpolate.bezier(Interpolate.bezier(p0, p1, p2, t), Interpolate.bezier(p1, p2, p3, t), t);
}
#endregion
#region Smooth
/// <summary>
/// Performs a clamped Hermite spline interpolation.
/// </summary>
/// <param name="from">From position.</param>
/// <param name="fromTangent">From tangent.</param>
/// <param name="to">To position.</param>
/// <param name="toTangent">To tangent.</param>
/// <param name="t">The amount of interpolation (between 0 and 1).</param>
/// <returns>The result of the Hermite spline interpolation.</returns>
public static float Hermite(float from, float fromTangent, float to, float toTangent, float t)
{
if (t <= 0)
return from;
if (t >= 1)
return to;
var d = from - to;
return ((
(2 * d + fromTangent + toTangent) * t
- 3 * d - 2 * fromTangent - toTangent) * t +
fromTangent) * t +
from;
}
/// <summary>
/// Performs a cubic interpolation between two values.
/// </summary>
/// <param name="from">The first value.</param>
/// <param name="to">The second value.</param>
/// <param name="t">The amount of interpolation (between 0 and 1).</param>
/// <returns>The interpolated value.</returns>
public static float SmoothStep(float from, float to, float t)
{
if (t <= 0)
return from;
if (t >= 1)
return to;
return (2 * t - 3) * t * t * (from - to) + from;
}
#endregion
#region Linear
/// <summary>
/// Performs a linear interpolation between two values.
/// </summary>
/// <param name="from">The first value.</param>
/// <param name="to">The second value.</param>
/// <param name="t">The amount of interpolation (between 0 and 1).</param>
/// <returns>The interpolated value.</returns>
public static float Lerp(float from, float to, float t)
{
if (t <= 0)
return from;
if (t >= 1)
return to;
return from + (to - from) * t;
}
/// <summary>
/// Performs a bilinear interpolation between four values.
/// </summary>
/// <param name="value00">The first value.</param>
/// <param name="value10">The second value.</param>
/// <param name="value01">The third value.</param>
/// <param name="value11">The fourth value.</param>
/// <param name="u">Parameter in first dimension (between 0 and 1).</param>
/// <param name="v">Parameter in second dimension (between 0 and 1).</param>
/// <returns>The interpolated value.</returns>
public static float BiLerp(float value00, float value10, float value01, float value11, float u, float v)
{
float first, second;
if (u <= 0)
{
first = value00;
second = value01;
}
else if(u >= 1)
{
first = value10;
second = value11;
}
else
{
first = value00 + (value10 - value00) * u;
second = value01 + (value11 - value01) * u;
}
if (v <= 0)
return first;
if (v >= 1)
return second;
return first + (second - first) * v;
}
/// <summary>
/// Performs a bilinear interpolation between four values.
/// </summary>
/// <param name="value00">The first value.</param>
/// <param name="value10">The second value.</param>
/// <param name="value01">The third value.</param>
/// <param name="value11">The fourth value.</param>
/// <param name="u">Parameter in first dimension (between 0 and 1).</param>
/// <param name="v">Parameter in second dimension (between 0 and 1).</param>
/// <returns>The interpolated value.</returns>
public static Vector2 BiLerp(Vector2 value00, Vector2 value10, Vector2 value01, Vector2 value11, float u, float v)
{
Vector2 first, second;
if (u <= 0)
{
first = value00;
second = value01;
}
else if (u >= 1)
{
first = value10;
second = value11;
}
else
{
first = value00 + (value10 - value00) * u;
second = value01 + (value11 - value01) * u;
}
if (v <= 0)
return first;
if (v >= 1)
return second;
return first + (second - first) * v;
}
#endregion
}
}
| |
namespace android.graphics.drawable
{
[global::MonoJavaBridge.JavaClass()]
public partial class GradientDrawable : android.graphics.drawable.Drawable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static GradientDrawable()
{
InitJNI();
}
protected GradientDrawable(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class Orientation : java.lang.Enum
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Orientation()
{
InitJNI();
}
internal Orientation(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _values4013;
public static global::android.graphics.drawable.GradientDrawable.Orientation[] values()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.graphics.drawable.GradientDrawable.Orientation>(@__env.CallStaticObjectMethod(android.graphics.drawable.GradientDrawable.Orientation.staticClass, global::android.graphics.drawable.GradientDrawable.Orientation._values4013)) as android.graphics.drawable.GradientDrawable.Orientation[];
}
internal static global::MonoJavaBridge.MethodId _valueOf4014;
public static global::android.graphics.drawable.GradientDrawable.Orientation valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.graphics.drawable.GradientDrawable.Orientation.staticClass, global::android.graphics.drawable.GradientDrawable.Orientation._valueOf4014, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.GradientDrawable.Orientation;
}
internal static global::MonoJavaBridge.FieldId _BL_TR4015;
public static global::android.graphics.drawable.GradientDrawable.Orientation BL_TR
{
get
{
return default(global::android.graphics.drawable.GradientDrawable.Orientation);
}
}
internal static global::MonoJavaBridge.FieldId _BOTTOM_TOP4016;
public static global::android.graphics.drawable.GradientDrawable.Orientation BOTTOM_TOP
{
get
{
return default(global::android.graphics.drawable.GradientDrawable.Orientation);
}
}
internal static global::MonoJavaBridge.FieldId _BR_TL4017;
public static global::android.graphics.drawable.GradientDrawable.Orientation BR_TL
{
get
{
return default(global::android.graphics.drawable.GradientDrawable.Orientation);
}
}
internal static global::MonoJavaBridge.FieldId _LEFT_RIGHT4018;
public static global::android.graphics.drawable.GradientDrawable.Orientation LEFT_RIGHT
{
get
{
return default(global::android.graphics.drawable.GradientDrawable.Orientation);
}
}
internal static global::MonoJavaBridge.FieldId _RIGHT_LEFT4019;
public static global::android.graphics.drawable.GradientDrawable.Orientation RIGHT_LEFT
{
get
{
return default(global::android.graphics.drawable.GradientDrawable.Orientation);
}
}
internal static global::MonoJavaBridge.FieldId _TL_BR4020;
public static global::android.graphics.drawable.GradientDrawable.Orientation TL_BR
{
get
{
return default(global::android.graphics.drawable.GradientDrawable.Orientation);
}
}
internal static global::MonoJavaBridge.FieldId _TOP_BOTTOM4021;
public static global::android.graphics.drawable.GradientDrawable.Orientation TOP_BOTTOM
{
get
{
return default(global::android.graphics.drawable.GradientDrawable.Orientation);
}
}
internal static global::MonoJavaBridge.FieldId _TR_BL4022;
public static global::android.graphics.drawable.GradientDrawable.Orientation TR_BL
{
get
{
return default(global::android.graphics.drawable.GradientDrawable.Orientation);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.drawable.GradientDrawable.Orientation.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/GradientDrawable$Orientation"));
global::android.graphics.drawable.GradientDrawable.Orientation._values4013 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, "values", "()[Landroid/graphics/drawable/GradientDrawable/Orientation;");
global::android.graphics.drawable.GradientDrawable.Orientation._valueOf4014 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/graphics/drawable/GradientDrawable$Orientation;");
}
}
internal static global::MonoJavaBridge.MethodId _setSize4023;
public virtual void setSize(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setSize4023, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setSize4023, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _inflate4024;
public override void inflate(android.content.res.Resources arg0, org.xmlpull.v1.XmlPullParser arg1, android.util.AttributeSet arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._inflate4024, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._inflate4024, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _draw4025;
public override void draw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._draw4025, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._draw4025, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getChangingConfigurations4026;
public override int getChangingConfigurations()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._getChangingConfigurations4026);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._getChangingConfigurations4026);
}
internal static global::MonoJavaBridge.MethodId _setDither4027;
public override void setDither(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setDither4027, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setDither4027, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setAlpha4028;
public override void setAlpha(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setAlpha4028, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setAlpha4028, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setColorFilter4029;
public override void setColorFilter(android.graphics.ColorFilter arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setColorFilter4029, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setColorFilter4029, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getOpacity4030;
public override int getOpacity()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._getOpacity4030);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._getOpacity4030);
}
internal static global::MonoJavaBridge.MethodId _onLevelChange4031;
protected override bool onLevelChange(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._onLevelChange4031, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._onLevelChange4031, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onBoundsChange4032;
protected override void onBoundsChange(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._onBoundsChange4032, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._onBoundsChange4032, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getIntrinsicWidth4033;
public override int getIntrinsicWidth()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._getIntrinsicWidth4033);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._getIntrinsicWidth4033);
}
internal static global::MonoJavaBridge.MethodId _getIntrinsicHeight4034;
public override int getIntrinsicHeight()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._getIntrinsicHeight4034);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._getIntrinsicHeight4034);
}
internal static global::MonoJavaBridge.MethodId _getPadding4035;
public override bool getPadding(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._getPadding4035, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._getPadding4035, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _mutate4036;
public override global::android.graphics.drawable.Drawable mutate()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._mutate4036)) as android.graphics.drawable.Drawable;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._mutate4036)) as android.graphics.drawable.Drawable;
}
internal static global::MonoJavaBridge.MethodId _getConstantState4037;
public override global::android.graphics.drawable.Drawable.ConstantState getConstantState()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._getConstantState4037)) as android.graphics.drawable.Drawable.ConstantState;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._getConstantState4037)) as android.graphics.drawable.Drawable.ConstantState;
}
internal static global::MonoJavaBridge.MethodId _setColor4038;
public virtual void setColor(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setColor4038, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setColor4038, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setCornerRadii4039;
public virtual void setCornerRadii(float[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setCornerRadii4039, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setCornerRadii4039, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setCornerRadius4040;
public virtual void setCornerRadius(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setCornerRadius4040, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setCornerRadius4040, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setStroke4041;
public virtual void setStroke(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setStroke4041, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setStroke4041, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setStroke4042;
public virtual void setStroke(int arg0, int arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setStroke4042, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setStroke4042, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _setShape4043;
public virtual void setShape(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setShape4043, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setShape4043, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setGradientType4044;
public virtual void setGradientType(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setGradientType4044, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setGradientType4044, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setGradientCenter4045;
public virtual void setGradientCenter(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setGradientCenter4045, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setGradientCenter4045, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setGradientRadius4046;
public virtual void setGradientRadius(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setGradientRadius4046, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setGradientRadius4046, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setUseLevel4047;
public virtual void setUseLevel(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable._setUseLevel4047, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._setUseLevel4047, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _GradientDrawable4048;
public GradientDrawable(android.graphics.drawable.GradientDrawable.Orientation arg0, int[] arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._GradientDrawable4048, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _GradientDrawable4049;
public GradientDrawable() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._GradientDrawable4049);
Init(@__env, handle);
}
public static int RECTANGLE
{
get
{
return 0;
}
}
public static int OVAL
{
get
{
return 1;
}
}
public static int LINE
{
get
{
return 2;
}
}
public static int RING
{
get
{
return 3;
}
}
public static int LINEAR_GRADIENT
{
get
{
return 0;
}
}
public static int RADIAL_GRADIENT
{
get
{
return 1;
}
}
public static int SWEEP_GRADIENT
{
get
{
return 2;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.drawable.GradientDrawable.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/GradientDrawable"));
global::android.graphics.drawable.GradientDrawable._setSize4023 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setSize", "(II)V");
global::android.graphics.drawable.GradientDrawable._inflate4024 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "inflate", "(Landroid/content/res/Resources;Lorg/xmlpull/v1/XmlPullParser;Landroid/util/AttributeSet;)V");
global::android.graphics.drawable.GradientDrawable._draw4025 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "draw", "(Landroid/graphics/Canvas;)V");
global::android.graphics.drawable.GradientDrawable._getChangingConfigurations4026 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "getChangingConfigurations", "()I");
global::android.graphics.drawable.GradientDrawable._setDither4027 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setDither", "(Z)V");
global::android.graphics.drawable.GradientDrawable._setAlpha4028 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setAlpha", "(I)V");
global::android.graphics.drawable.GradientDrawable._setColorFilter4029 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setColorFilter", "(Landroid/graphics/ColorFilter;)V");
global::android.graphics.drawable.GradientDrawable._getOpacity4030 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "getOpacity", "()I");
global::android.graphics.drawable.GradientDrawable._onLevelChange4031 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "onLevelChange", "(I)Z");
global::android.graphics.drawable.GradientDrawable._onBoundsChange4032 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "onBoundsChange", "(Landroid/graphics/Rect;)V");
global::android.graphics.drawable.GradientDrawable._getIntrinsicWidth4033 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "getIntrinsicWidth", "()I");
global::android.graphics.drawable.GradientDrawable._getIntrinsicHeight4034 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "getIntrinsicHeight", "()I");
global::android.graphics.drawable.GradientDrawable._getPadding4035 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "getPadding", "(Landroid/graphics/Rect;)Z");
global::android.graphics.drawable.GradientDrawable._mutate4036 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "mutate", "()Landroid/graphics/drawable/Drawable;");
global::android.graphics.drawable.GradientDrawable._getConstantState4037 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "getConstantState", "()Landroid/graphics/drawable/Drawable$ConstantState;");
global::android.graphics.drawable.GradientDrawable._setColor4038 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setColor", "(I)V");
global::android.graphics.drawable.GradientDrawable._setCornerRadii4039 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setCornerRadii", "([F)V");
global::android.graphics.drawable.GradientDrawable._setCornerRadius4040 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setCornerRadius", "(F)V");
global::android.graphics.drawable.GradientDrawable._setStroke4041 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setStroke", "(II)V");
global::android.graphics.drawable.GradientDrawable._setStroke4042 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setStroke", "(IIFF)V");
global::android.graphics.drawable.GradientDrawable._setShape4043 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setShape", "(I)V");
global::android.graphics.drawable.GradientDrawable._setGradientType4044 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setGradientType", "(I)V");
global::android.graphics.drawable.GradientDrawable._setGradientCenter4045 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setGradientCenter", "(FF)V");
global::android.graphics.drawable.GradientDrawable._setGradientRadius4046 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setGradientRadius", "(F)V");
global::android.graphics.drawable.GradientDrawable._setUseLevel4047 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "setUseLevel", "(Z)V");
global::android.graphics.drawable.GradientDrawable._GradientDrawable4048 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "<init>", "(Landroid/graphics/drawable/GradientDrawable$Orientation;[I)V");
global::android.graphics.drawable.GradientDrawable._GradientDrawable4049 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "<init>", "()V");
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G05Level111Child (editable child object).<br/>
/// This is a generated base class of <see cref="G05Level111Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="G04Level11"/> collection.
/// </remarks>
[Serializable]
public partial class G05Level111Child : BusinessBase<G05Level111Child>
{
#region State Fields
[NotUndoable]
private byte[] _rowVersion = new byte[] {};
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_Child_Name, "Level_1_1_1 Child Name");
/// <summary>
/// Gets or sets the Level_1_1_1 Child Name.
/// </summary>
/// <value>The Level_1_1_1 Child Name.</value>
public string Level_1_1_1_Child_Name
{
get { return GetProperty(Level_1_1_1_Child_NameProperty); }
set { SetProperty(Level_1_1_1_Child_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CMarentID1"/> property.
/// </summary>
public static readonly PropertyInfo<int> CMarentID1Property = RegisterProperty<int>(p => p.CMarentID1, "CMarent ID1");
/// <summary>
/// Gets or sets the CMarent ID1.
/// </summary>
/// <value>The CMarent ID1.</value>
public int CMarentID1
{
get { return GetProperty(CMarentID1Property); }
set { SetProperty(CMarentID1Property, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G05Level111Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G05Level111Child"/> object.</returns>
internal static G05Level111Child NewG05Level111Child()
{
return DataPortal.CreateChild<G05Level111Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="G05Level111Child"/> object, based on given parameters.
/// </summary>
/// <param name="cMarentID1">The CMarentID1 parameter of the G05Level111Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="G05Level111Child"/> object.</returns>
internal static G05Level111Child GetG05Level111Child(int cMarentID1)
{
return DataPortal.FetchChild<G05Level111Child>(cMarentID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G05Level111Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private G05Level111Child()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G05Level111Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="G05Level111Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="cMarentID1">The CMarent ID1.</param>
protected void Child_Fetch(int cMarentID1)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetG05Level111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CMarentID1", cMarentID1).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, cMarentID1);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="G05Level111Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_Child_Name"));
LoadProperty(CMarentID1Property, dr.GetInt32("CMarentID1"));
_rowVersion = (dr.GetValue("RowVersion")) as byte[];
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="G05Level111Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(G04Level11 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddG05Level111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
_rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value;
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G05Level111Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(G04Level11 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateG05Level111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@CMarentID1", ReadProperty(CMarentID1Property)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RowVersion", _rowVersion).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
_rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value;
}
}
}
/// <summary>
/// Self deletes the <see cref="G05Level111Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(G04Level11 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteG05Level111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="JsonReaderExtensions.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
#if SPATIAL
namespace Microsoft.Data.Spatial
#else
namespace Microsoft.OData.Core.Json
#endif
{
#region Namespaces
using System;
using System.Diagnostics;
using Microsoft.OData.Core.JsonLight;
#if SPATIAL
using Microsoft.Spatial;
#endif
#endregion Namespaces
/// <summary>
/// Extension methods for the JSON reader.
/// </summary>
internal static class JsonReaderExtensions
{
/// <summary>
/// Reads the next node from the <paramref name="jsonReader"/> and verifies that it is a StartObject node.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
internal static void ReadStartObject(this JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
ReadNext(jsonReader, JsonNodeType.StartObject);
}
/// <summary>
/// Reads the next node from the <paramref name="jsonReader"/> and verifies that it is an EndObject node.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
internal static void ReadEndObject(this JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
ReadNext(jsonReader, JsonNodeType.EndObject);
}
/// <summary>
/// Reads the next node from the <paramref name="jsonReader"/> and verifies that it is an StartArray node.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
internal static void ReadStartArray(this JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
ReadNext(jsonReader, JsonNodeType.StartArray);
}
/// <summary>
/// Reads the next node from the <paramref name="jsonReader"/> and verifies that it is an EndArray node.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
internal static void ReadEndArray(this JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
ReadNext(jsonReader, JsonNodeType.EndArray);
}
/// <summary>
/// Verifies that the current node is a property node and returns the property name.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
/// <returns>The property name of the current property node.</returns>
internal static string GetPropertyName(this JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
Debug.Assert(jsonReader.NodeType == JsonNodeType.Property, "jsonReader.NodeType == JsonNodeType.Property");
// NOTE: the JSON reader already verifies that property names are strings and not null/empty
string propertyName = (string)jsonReader.Value;
return propertyName;
}
/// <summary>
/// Reads the next node from the <paramref name="jsonReader"/>, verifies that it is a Property node and returns the property name.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
/// <returns>The property name of the property node read.</returns>
internal static string ReadPropertyName(this JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
jsonReader.ValidateNodeType(JsonNodeType.Property);
string propertyName = jsonReader.GetPropertyName();
jsonReader.ReadNext();
return propertyName;
}
/// <summary>
/// Reads the next node from the <paramref name="jsonReader"/> and verifies that it is a PrimitiveValue node.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
/// <returns>The primitive value read from the reader.</returns>
internal static object ReadPrimitiveValue(this JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
object value = jsonReader.Value;
ReadNext(jsonReader, JsonNodeType.PrimitiveValue);
return value;
}
/// <summary>
/// Reads the next node from the <paramref name="jsonReader"/> and verifies that it is a PrimitiveValue node of type string.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
/// <returns>The string value read from the reader; throws an exception if no string value could be read.</returns>
internal static string ReadStringValue(this JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
object value = jsonReader.ReadPrimitiveValue();
string stringValue = value as string;
if (value == null || stringValue != null)
{
return stringValue;
}
throw CreateException(Strings.JsonReaderExtensions_CannotReadValueAsString(value));
}
/// <summary>
/// Reads the next node from the <paramref name="jsonReader"/> and verifies that it is a PrimitiveValue node of type string.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="propertyName">The name of the property for which to read the string; used in error messages only.</param>
/// <returns>The string value read from the reader; throws an exception if no string value could be read.</returns>
internal static string ReadStringValue(this JsonReader jsonReader, string propertyName)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
object value = jsonReader.ReadPrimitiveValue();
string stringValue = value as string;
if (value == null || stringValue != null)
{
return stringValue;
}
throw CreateException(Strings.JsonReaderExtensions_CannotReadPropertyValueAsString(value, propertyName));
}
/// <summary>
/// Reads the next node from the <paramref name="jsonReader"/> and verifies that it is a PrimitiveValue node of type double.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
/// <returns>The double value read from the reader; throws an exception if no double value could be read.</returns>
internal static double? ReadDoubleValue(this JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
object value = jsonReader.ReadPrimitiveValue();
double? doubleValue = value as double?;
if (value == null || doubleValue != null)
{
return doubleValue;
}
int? intValue = value as int?;
if (intValue != null)
{
return (double)intValue;
}
decimal? decimalValue = value as decimal?;
if (decimalValue != null)
{
return (double)decimalValue;
}
throw CreateException(Strings.JsonReaderExtensions_CannotReadValueAsDouble(value));
}
/// <summary>
/// Skips over a JSON value (primitive, object or array).
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
/// <remarks>
/// Pre-Condition: JsonNodeType.PrimitiveValue, JsonNodeType.StartArray or JsonNodeType.StartObject
/// Post-Condition: JsonNodeType.PrimitiveValue, JsonNodeType.EndArray or JsonNodeType.EndObject
/// </remarks>
internal static void SkipValue(this JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
int depth = 0;
do
{
switch (jsonReader.NodeType)
{
case JsonNodeType.PrimitiveValue:
break;
case JsonNodeType.StartArray:
case JsonNodeType.StartObject:
depth++;
break;
case JsonNodeType.EndArray:
case JsonNodeType.EndObject:
Debug.Assert(depth > 0, "Seen too many scope ends.");
depth--;
break;
default:
Debug.Assert(
jsonReader.NodeType != JsonNodeType.EndOfInput,
"We should not have reached end of input, since the scopes should be well formed. Otherwise JsonReader should have failed by now.");
break;
}
jsonReader.ReadNext();
}
while (depth > 0);
}
/// <summary>
/// Reads the next node. Use this instead of the direct call to Read since this asserts that there actually is a next node.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
/// <returns>The node type of the node that reader is positioned on after reading.</returns>
internal static JsonNodeType ReadNext(this JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
#if DEBUG
bool result = jsonReader.Read();
Debug.Assert(result, "JsonReader.Read returned false in an unexpected place.");
#else
jsonReader.Read();
#endif
return jsonReader.NodeType;
}
/// <summary>
/// Determines if the reader is on a value node.
/// </summary>
/// <param name="jsonReader">The reader to inspect.</param>
/// <returns>true if the reader is on PrimitiveValue, StartObject or StartArray node, false otherwise.</returns>
internal static bool IsOnValueNode(this JsonReader jsonReader)
{
JsonNodeType nodeType = jsonReader.NodeType;
return nodeType == JsonNodeType.PrimitiveValue || nodeType == JsonNodeType.StartObject || nodeType == JsonNodeType.StartArray;
}
#if !SPATIAL
/// <summary>
/// Asserts that the reader is not buffer.
/// </summary>
/// <param name="bufferedJsonReader">The <see cref="BufferingJsonReader"/> to read from.</param>
[Conditional("DEBUG")]
internal static void AssertNotBuffering(this BufferingJsonReader bufferedJsonReader)
{
#if DEBUG
Debug.Assert(!bufferedJsonReader.IsBuffering, "!bufferedJsonReader.IsBuffering");
#endif
}
/// <summary>
/// Asserts that the reader is buffer.
/// </summary>
/// <param name="bufferedJsonReader">The <see cref="BufferingJsonReader"/> to read from.</param>
[Conditional("DEBUG")]
internal static void AssertBuffering(this BufferingJsonReader bufferedJsonReader)
{
#if DEBUG
Debug.Assert(bufferedJsonReader.IsBuffering, "bufferedJsonReader.IsBuffering");
#endif
}
#endif
/// <summary>
/// Creates an exception instance that is appropriate for the current library being built.
/// Allows the code in this class to be shared between ODataLib and the common spatial library.
/// </summary>
/// <param name="exceptionMessage">String to use for the exception messag.</param>
/// <returns>Exception to be thrown.</returns>
#if SPATIAL
internal static FormatException CreateException(string exceptionMessage)
{
return new FormatException(exceptionMessage);
}
#else
internal static ODataException CreateException(string exceptionMessage)
{
return new ODataException(exceptionMessage);
}
#endif
/// <summary>
/// Reads the next node from the <paramref name="jsonReader"/> and verifies that it is of the expected node type.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="expectedNodeType">The expected <see cref="JsonNodeType"/> of the read node.</param>
private static void ReadNext(this JsonReader jsonReader, JsonNodeType expectedNodeType)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
Debug.Assert(expectedNodeType != JsonNodeType.None, "expectedNodeType != JsonNodeType.None");
jsonReader.ValidateNodeType(expectedNodeType);
jsonReader.Read();
}
/// <summary>
/// Validates that the reader is positioned on the specified node type.
/// </summary>
/// <param name="jsonReader">The <see cref="JsonReader"/> to use.</param>
/// <param name="expectedNodeType">The expected node type.</param>
private static void ValidateNodeType(this JsonReader jsonReader, JsonNodeType expectedNodeType)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
Debug.Assert(expectedNodeType != JsonNodeType.None, "expectedNodeType != JsonNodeType.None");
if (jsonReader.NodeType != expectedNodeType)
{
throw CreateException(Strings.JsonReaderExtensions_UnexpectedNodeDetected(expectedNodeType, jsonReader.NodeType));
}
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Runtime.Loader
{
public partial class AssemblyLoadContext
{
private enum InternalState
{
/// <summary>
/// The ALC is alive (default)
/// </summary>
Alive,
/// <summary>
/// The unload process has started, the Unloading event will be called
/// once the underlying LoaderAllocator has been finalized
/// </summary>
Unloading
}
private static readonly Dictionary<long, WeakReference<AssemblyLoadContext>> s_allContexts = new Dictionary<long, WeakReference<AssemblyLoadContext>>();
private static long s_nextId;
#region private data members
// If you modify any of these fields, you must also update the
// AssemblyLoadContextBaseObject structure in object.h
// synchronization primitive to protect against usage of this instance while unloading
private readonly object _unloadLock;
private event Func<Assembly, string, IntPtr>? _resolvingUnmanagedDll;
private event Func<AssemblyLoadContext, AssemblyName, Assembly>? _resolving;
private event Action<AssemblyLoadContext>? _unloading;
private readonly string? _name;
// Contains the reference to VM's representation of the AssemblyLoadContext
private readonly IntPtr _nativeAssemblyLoadContext;
// Id used by s_allContexts
private readonly long _id;
// Indicates the state of this ALC (Alive or in Unloading state)
private InternalState _state;
private readonly bool _isCollectible;
#endregion
protected AssemblyLoadContext() : this(false, false, null)
{
}
protected AssemblyLoadContext(bool isCollectible) : this(false, isCollectible, null)
{
}
public AssemblyLoadContext(string? name, bool isCollectible = false) : this(false, isCollectible, name)
{
}
private protected AssemblyLoadContext(bool representsTPALoadContext, bool isCollectible, string? name)
{
// Initialize the VM side of AssemblyLoadContext if not already done.
_isCollectible = isCollectible;
_name = name;
// The _unloadLock needs to be assigned after the IsCollectible to ensure proper behavior of the finalizer
// even in case the following allocation fails or the thread is aborted between these two lines.
_unloadLock = new object();
if (!isCollectible)
{
// For non collectible AssemblyLoadContext, the finalizer should never be called and thus the AssemblyLoadContext should not
// be on the finalizer queue.
GC.SuppressFinalize(this);
}
// If this is a collectible ALC, we are creating a weak handle tracking resurrection otherwise we use a strong handle
var thisHandle = GCHandle.Alloc(this, IsCollectible ? GCHandleType.WeakTrackResurrection : GCHandleType.Normal);
var thisHandlePtr = GCHandle.ToIntPtr(thisHandle);
_nativeAssemblyLoadContext = InitializeAssemblyLoadContext(thisHandlePtr, representsTPALoadContext, isCollectible);
// Add this instance to the list of alive ALC
lock (s_allContexts)
{
_id = s_nextId++;
s_allContexts.Add(_id, new WeakReference<AssemblyLoadContext>(this, true));
}
}
~AssemblyLoadContext()
{
// Use the _unloadLock as a guard to detect the corner case when the constructor of the AssemblyLoadContext was not executed
// e.g. due to the JIT failing to JIT it.
if (_unloadLock != null)
{
// Only valid for a Collectible ALC. Non-collectible ALCs have the finalizer suppressed.
Debug.Assert(IsCollectible);
// We get here only in case the explicit Unload was not initiated.
Debug.Assert(_state != InternalState.Unloading);
InitiateUnload();
}
}
private void RaiseUnloadEvent()
{
// Ensure that we raise the Unload event only once
Interlocked.Exchange(ref _unloading, null!)?.Invoke(this);
}
private void InitiateUnload()
{
RaiseUnloadEvent();
// When in Unloading state, we are not supposed to be called on the finalizer
// as the native side is holding a strong reference after calling Unload
lock (_unloadLock)
{
Debug.Assert(_state == InternalState.Alive);
var thisStrongHandle = GCHandle.Alloc(this, GCHandleType.Normal);
var thisStrongHandlePtr = GCHandle.ToIntPtr(thisStrongHandle);
// The underlying code will transform the original weak handle
// created by InitializeLoadContext to a strong handle
PrepareForAssemblyLoadContextRelease(_nativeAssemblyLoadContext, thisStrongHandlePtr);
_state = InternalState.Unloading;
}
lock (s_allContexts)
{
s_allContexts.Remove(_id);
}
}
public IEnumerable<Assembly> Assemblies
{
get
{
foreach (Assembly a in GetLoadedAssemblies())
{
AssemblyLoadContext? alc = GetLoadContext(a);
if (alc == this)
{
yield return a;
}
}
}
}
// Event handler for resolving native libraries.
// This event is raised if the native library could not be resolved via
// the default resolution logic [including AssemblyLoadContext.LoadUnmanagedDll()]
//
// Inputs: Invoking assembly, and library name to resolve
// Returns: A handle to the loaded native library
public event Func<Assembly, string, IntPtr>? ResolvingUnmanagedDll
{
add
{
_resolvingUnmanagedDll += value;
}
remove
{
_resolvingUnmanagedDll -= value;
}
}
// Event handler for resolving managed assemblies.
// This event is raised if the managed assembly could not be resolved via
// the default resolution logic [including AssemblyLoadContext.Load()]
//
// Inputs: The AssemblyLoadContext and AssemblyName to be loaded
// Returns: The Loaded assembly object.
public event Func<AssemblyLoadContext, AssemblyName, Assembly?>? Resolving
{
add
{
_resolving += value;
}
remove
{
_resolving -= value;
}
}
public event Action<AssemblyLoadContext>? Unloading
{
add
{
_unloading += value;
}
remove
{
_unloading -= value;
}
}
#region AppDomainEvents
// Occurs when an Assembly is loaded
internal static event AssemblyLoadEventHandler? AssemblyLoad;
// Occurs when resolution of type fails
internal static event ResolveEventHandler? TypeResolve;
// Occurs when resolution of resource fails
internal static event ResolveEventHandler? ResourceResolve;
// Occurs when resolution of assembly fails
// This event is fired after resolve events of AssemblyLoadContext fails
internal static event ResolveEventHandler? AssemblyResolve;
#endregion
public static AssemblyLoadContext Default => DefaultAssemblyLoadContext.s_loadContext;
public bool IsCollectible { get { return _isCollectible;} }
public string? Name { get { return _name;} }
public override string ToString() => "\"" + Name + "\" " + GetType().ToString() + " #" + _id;
public static IEnumerable<AssemblyLoadContext> All
{
get
{
_ = AssemblyLoadContext.Default; // Ensure default is initialized
List<WeakReference<AssemblyLoadContext>>? alcList = null;
lock (s_allContexts)
{
// To make this thread safe we need a quick snapshot while locked
alcList = new List<WeakReference<AssemblyLoadContext>>(s_allContexts.Values);
}
foreach (WeakReference<AssemblyLoadContext> weakAlc in alcList)
{
if (weakAlc.TryGetTarget(out AssemblyLoadContext? alc))
{
yield return alc;
}
}
}
}
// Helper to return AssemblyName corresponding to the path of an IL assembly
public static AssemblyName GetAssemblyName(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException(nameof(assemblyPath));
}
return AssemblyName.GetAssemblyName(assemblyPath);
}
// Custom AssemblyLoadContext implementations can override this
// method to perform custom processing and use one of the protected
// helpers above to load the assembly.
protected virtual Assembly? Load(AssemblyName assemblyName)
{
return null;
}
#if !CORERT
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public Assembly LoadFromAssemblyName(AssemblyName assemblyName)
{
if (assemblyName == null)
throw new ArgumentNullException(nameof(assemblyName));
// Attempt to load the assembly, using the same ordering as static load, in the current load context.
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Assembly.Load(assemblyName, ref stackMark, this);
}
#endif
// These methods load assemblies into the current AssemblyLoadContext
// They may be used in the implementation of an AssemblyLoadContext derivation
public Assembly LoadFromAssemblyPath(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException(nameof(assemblyPath));
}
if (PathInternal.IsPartiallyQualified(assemblyPath))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(assemblyPath));
}
lock (_unloadLock)
{
VerifyIsAlive();
return InternalLoadFromPath(assemblyPath, null);
}
}
public Assembly LoadFromNativeImagePath(string nativeImagePath, string? assemblyPath)
{
if (nativeImagePath == null)
{
throw new ArgumentNullException(nameof(nativeImagePath));
}
if (PathInternal.IsPartiallyQualified(nativeImagePath))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(nativeImagePath));
}
if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(assemblyPath));
}
lock (_unloadLock)
{
VerifyIsAlive();
return InternalLoadFromPath(assemblyPath, nativeImagePath);
}
}
public Assembly LoadFromStream(Stream assembly)
{
return LoadFromStream(assembly, null);
}
public Assembly LoadFromStream(Stream assembly, Stream? assemblySymbols)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
int iAssemblyStreamLength = (int)assembly.Length;
if (iAssemblyStreamLength <= 0)
{
throw new BadImageFormatException(SR.BadImageFormat_BadILFormat);
}
// Allocate the byte[] to hold the assembly
byte[] arrAssembly = new byte[iAssemblyStreamLength];
// Copy the assembly to the byte array
assembly.Read(arrAssembly, 0, iAssemblyStreamLength);
// Get the symbol stream in byte[] if provided
byte[]? arrSymbols = null;
if (assemblySymbols != null)
{
var iSymbolLength = (int)assemblySymbols.Length;
arrSymbols = new byte[iSymbolLength];
assemblySymbols.Read(arrSymbols, 0, iSymbolLength);
}
lock (_unloadLock)
{
VerifyIsAlive();
return InternalLoad(arrAssembly, arrSymbols);
}
}
// This method provides a way for overriders of LoadUnmanagedDll() to load an unmanaged DLL from a specific path in a
// platform-independent way. The DLL is loaded with default load flags.
protected IntPtr LoadUnmanagedDllFromPath(string unmanagedDllPath)
{
if (unmanagedDllPath == null)
{
throw new ArgumentNullException(nameof(unmanagedDllPath));
}
if (unmanagedDllPath.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(unmanagedDllPath));
}
if (PathInternal.IsPartiallyQualified(unmanagedDllPath))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(unmanagedDllPath));
}
return InternalLoadUnmanagedDllFromPath(unmanagedDllPath);
}
// Custom AssemblyLoadContext implementations can override this
// method to perform the load of unmanaged native dll
// This function needs to return the HMODULE of the dll it loads
protected virtual IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
//defer to default coreclr policy of loading unmanaged dll
return IntPtr.Zero;
}
public void Unload()
{
if (!IsCollectible)
{
throw new InvalidOperationException(SR.AssemblyLoadContext_Unload_CannotUnloadIfNotCollectible);
}
GC.SuppressFinalize(this);
InitiateUnload();
}
internal static void OnProcessExit()
{
lock (s_allContexts)
{
foreach (var alcAlive in s_allContexts)
{
if (alcAlive.Value.TryGetTarget(out AssemblyLoadContext? alc))
{
alc.RaiseUnloadEvent();
}
}
}
}
private void VerifyIsAlive()
{
if (_state != InternalState.Alive)
{
throw new InvalidOperationException(SR.AssemblyLoadContext_Verify_NotUnloading);
}
}
private static AsyncLocal<AssemblyLoadContext?>? s_asyncLocalCurrent;
/// <summary>Nullable current AssemblyLoadContext used for context sensitive reflection APIs</summary>
/// <remarks>
/// This is an advanced setting used in reflection assembly loading scenarios.
///
/// There are a set of contextual reflection APIs which load managed assemblies through an inferred AssemblyLoadContext.
/// * <see cref="System.Activator.CreateInstance" />
/// * <see cref="System.Reflection.Assembly.Load" />
/// * <see cref="System.Reflection.Assembly.GetType" />
/// * <see cref="System.Type.GetType" />
///
/// When CurrentContextualReflectionContext is null, the AssemblyLoadContext is inferred.
/// The inference logic is simple.
/// * For static methods, it is the AssemblyLoadContext which loaded the method caller's assembly.
/// * For instance methods, it is the AssemblyLoadContext which loaded the instance's assembly.
///
/// When this property is set, the CurrentContextualReflectionContext value is used by these contextual reflection APIs for loading.
///
/// This property is typically set in a using block by
/// <see cref="System.Runtime.Loader.AssemblyLoadContext.EnterContextualReflection"/>.
///
/// The property is stored in an AsyncLocal<AssemblyLoadContext>. This means the setting can be unique for every async or thread in the process.
///
/// For more details see https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/AssemblyLoadContext.ContextualReflection.md
/// </remarks>
public static AssemblyLoadContext? CurrentContextualReflectionContext
{
get { return s_asyncLocalCurrent?.Value; }
}
private static void SetCurrentContextualReflectionContext(AssemblyLoadContext? value)
{
if (s_asyncLocalCurrent == null)
{
Interlocked.CompareExchange<AsyncLocal<AssemblyLoadContext?>?>(ref s_asyncLocalCurrent, new AsyncLocal<AssemblyLoadContext?>(), null);
}
s_asyncLocalCurrent!.Value = value; // Remove ! when compiler specially-recognizes CompareExchange for nullability
}
/// <summary>Enter scope using this AssemblyLoadContext for ContextualReflection</summary>
/// <returns>A disposable ContextualReflectionScope for use in a using block</returns>
/// <remarks>
/// Sets CurrentContextualReflectionContext to this instance.
/// <see cref="System.Runtime.Loader.AssemblyLoadContext.CurrentContextualReflectionContext"/>
///
/// Returns a disposable ContextualReflectionScope for use in a using block. When the using calls the
/// Dispose() method, it restores the ContextualReflectionScope to its previous value.
/// </remarks>
public ContextualReflectionScope EnterContextualReflection()
{
return new ContextualReflectionScope(this);
}
/// <summary>Enter scope using this AssemblyLoadContext for ContextualReflection</summary>
/// <param name="activating">Set CurrentContextualReflectionContext to the AssemblyLoadContext which loaded activating.</param>
/// <returns>A disposable ContextualReflectionScope for use in a using block</returns>
/// <remarks>
/// Sets CurrentContextualReflectionContext to to the AssemblyLoadContext which loaded activating.
/// <see cref="System.Runtime.Loader.AssemblyLoadContext.CurrentContextualReflectionContext"/>
///
/// Returns a disposable ContextualReflectionScope for use in a using block. When the using calls the
/// Dispose() method, it restores the ContextualReflectionScope to its previous value.
/// </remarks>
public static ContextualReflectionScope EnterContextualReflection(Assembly? activating)
{
if (activating == null)
return new ContextualReflectionScope(null);
AssemblyLoadContext? assemblyLoadContext = GetLoadContext(activating);
if (assemblyLoadContext == null)
{
// All RuntimeAssemblies & Only RuntimeAssemblies have an AssemblyLoadContext
throw new ArgumentException(SR.Arg_MustBeRuntimeAssembly, nameof(activating));
}
return assemblyLoadContext.EnterContextualReflection();
}
/// <summary>Opaque disposable struct used to restore CurrentContextualReflectionContext</summary>
/// <remarks>
/// This is an implmentation detail of the AssemblyLoadContext.EnterContextualReflection APIs.
/// It is a struct, to avoid heap allocation.
/// It is required to be public to avoid boxing.
/// <see cref="System.Runtime.Loader.AssemblyLoadContext.EnterContextualReflection"/>
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct ContextualReflectionScope : IDisposable
{
private readonly AssemblyLoadContext? _activated;
private readonly AssemblyLoadContext? _predecessor;
private readonly bool _initialized;
internal ContextualReflectionScope(AssemblyLoadContext? activating)
{
_predecessor = AssemblyLoadContext.CurrentContextualReflectionContext;
AssemblyLoadContext.SetCurrentContextualReflectionContext(activating);
_activated = activating;
_initialized = true;
}
public void Dispose()
{
if (_initialized)
{
// Do not clear initialized. Always restore the _predecessor in Dispose()
// _initialized = false;
AssemblyLoadContext.SetCurrentContextualReflectionContext(_predecessor);
}
}
}
private Assembly? ResolveSatelliteAssembly(AssemblyName assemblyName)
{
// Called by native runtime when CultureName is not empty
Debug.Assert(assemblyName.CultureName?.Length > 0);
string satelliteSuffix = ".resources";
if (assemblyName.Name == null || !assemblyName.Name.EndsWith(satelliteSuffix, StringComparison.Ordinal))
return null;
string parentAssemblyName = assemblyName.Name.Substring(0, assemblyName.Name.Length - satelliteSuffix.Length);
Assembly parentAssembly = LoadFromAssemblyName(new AssemblyName(parentAssemblyName));
AssemblyLoadContext parentALC = GetLoadContext(parentAssembly)!;
string parentDirectory = Path.GetDirectoryName(parentAssembly.Location)!;
string assemblyPath = Path.Combine(parentDirectory, assemblyName.CultureName!, $"{assemblyName.Name}.dll");
if (Internal.IO.File.InternalExists(assemblyPath))
{
return parentALC.LoadFromAssemblyPath(assemblyPath);
}
else if (Path.IsCaseSensitive)
{
assemblyPath = Path.Combine(parentDirectory, assemblyName.CultureName!.ToLowerInvariant(), $"{assemblyName.Name}.dll");
if (Internal.IO.File.InternalExists(assemblyPath))
{
return parentALC.LoadFromAssemblyPath(assemblyPath);
}
}
return null;
}
}
internal sealed class DefaultAssemblyLoadContext : AssemblyLoadContext
{
internal static readonly AssemblyLoadContext s_loadContext = new DefaultAssemblyLoadContext();
internal DefaultAssemblyLoadContext() : base(true, false, "Default")
{
}
}
internal sealed class IndividualAssemblyLoadContext : AssemblyLoadContext
{
internal IndividualAssemblyLoadContext(string name) : base(false, false, name)
{
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// BulkSendBatchSummary
/// </summary>
[DataContract]
public partial class BulkSendBatchSummary : IEquatable<BulkSendBatchSummary>, IValidatableObject
{
public BulkSendBatchSummary()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="BulkSendBatchSummary" /> class.
/// </summary>
/// <param name="BatchId">BatchId.</param>
/// <param name="BatchName">BatchName.</param>
/// <param name="BatchSize">BatchSize.</param>
/// <param name="BatchUri">BatchUri.</param>
/// <param name="Failed">Failed.</param>
/// <param name="Queued">Queued.</param>
/// <param name="Sent">Sent.</param>
/// <param name="SubmittedDate">SubmittedDate.</param>
public BulkSendBatchSummary(string BatchId = default(string), string BatchName = default(string), string BatchSize = default(string), string BatchUri = default(string), string Failed = default(string), string Queued = default(string), string Sent = default(string), string SubmittedDate = default(string))
{
this.BatchId = BatchId;
this.BatchName = BatchName;
this.BatchSize = BatchSize;
this.BatchUri = BatchUri;
this.Failed = Failed;
this.Queued = Queued;
this.Sent = Sent;
this.SubmittedDate = SubmittedDate;
}
/// <summary>
/// Gets or Sets BatchId
/// </summary>
[DataMember(Name="batchId", EmitDefaultValue=false)]
public string BatchId { get; set; }
/// <summary>
/// Gets or Sets BatchName
/// </summary>
[DataMember(Name="batchName", EmitDefaultValue=false)]
public string BatchName { get; set; }
/// <summary>
/// Gets or Sets BatchSize
/// </summary>
[DataMember(Name="batchSize", EmitDefaultValue=false)]
public string BatchSize { get; set; }
/// <summary>
/// Gets or Sets BatchUri
/// </summary>
[DataMember(Name="batchUri", EmitDefaultValue=false)]
public string BatchUri { get; set; }
/// <summary>
/// Gets or Sets Failed
/// </summary>
[DataMember(Name="failed", EmitDefaultValue=false)]
public string Failed { get; set; }
/// <summary>
/// Gets or Sets Queued
/// </summary>
[DataMember(Name="queued", EmitDefaultValue=false)]
public string Queued { get; set; }
/// <summary>
/// Gets or Sets Sent
/// </summary>
[DataMember(Name="sent", EmitDefaultValue=false)]
public string Sent { get; set; }
/// <summary>
/// Gets or Sets SubmittedDate
/// </summary>
[DataMember(Name="submittedDate", EmitDefaultValue=false)]
public string SubmittedDate { 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 BulkSendBatchSummary {\n");
sb.Append(" BatchId: ").Append(BatchId).Append("\n");
sb.Append(" BatchName: ").Append(BatchName).Append("\n");
sb.Append(" BatchSize: ").Append(BatchSize).Append("\n");
sb.Append(" BatchUri: ").Append(BatchUri).Append("\n");
sb.Append(" Failed: ").Append(Failed).Append("\n");
sb.Append(" Queued: ").Append(Queued).Append("\n");
sb.Append(" Sent: ").Append(Sent).Append("\n");
sb.Append(" SubmittedDate: ").Append(SubmittedDate).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 BulkSendBatchSummary);
}
/// <summary>
/// Returns true if BulkSendBatchSummary instances are equal
/// </summary>
/// <param name="other">Instance of BulkSendBatchSummary to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BulkSendBatchSummary other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.BatchId == other.BatchId ||
this.BatchId != null &&
this.BatchId.Equals(other.BatchId)
) &&
(
this.BatchName == other.BatchName ||
this.BatchName != null &&
this.BatchName.Equals(other.BatchName)
) &&
(
this.BatchSize == other.BatchSize ||
this.BatchSize != null &&
this.BatchSize.Equals(other.BatchSize)
) &&
(
this.BatchUri == other.BatchUri ||
this.BatchUri != null &&
this.BatchUri.Equals(other.BatchUri)
) &&
(
this.Failed == other.Failed ||
this.Failed != null &&
this.Failed.Equals(other.Failed)
) &&
(
this.Queued == other.Queued ||
this.Queued != null &&
this.Queued.Equals(other.Queued)
) &&
(
this.Sent == other.Sent ||
this.Sent != null &&
this.Sent.Equals(other.Sent)
) &&
(
this.SubmittedDate == other.SubmittedDate ||
this.SubmittedDate != null &&
this.SubmittedDate.Equals(other.SubmittedDate)
);
}
/// <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.BatchId != null)
hash = hash * 59 + this.BatchId.GetHashCode();
if (this.BatchName != null)
hash = hash * 59 + this.BatchName.GetHashCode();
if (this.BatchSize != null)
hash = hash * 59 + this.BatchSize.GetHashCode();
if (this.BatchUri != null)
hash = hash * 59 + this.BatchUri.GetHashCode();
if (this.Failed != null)
hash = hash * 59 + this.Failed.GetHashCode();
if (this.Queued != null)
hash = hash * 59 + this.Queued.GetHashCode();
if (this.Sent != null)
hash = hash * 59 + this.Sent.GetHashCode();
if (this.SubmittedDate != null)
hash = hash * 59 + this.SubmittedDate.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
// AcceptSocket property variables.
internal Socket _acceptSocket;
private Socket _connectSocket;
// Buffer,Offset,Count property variables.
internal byte[] _buffer;
internal int _count;
internal int _offset;
// BufferList property variables.
internal IList<ArraySegment<byte>> _bufferList;
// BytesTransferred property variables.
private int _bytesTransferred;
// Completed event property variables.
private event EventHandler<SocketAsyncEventArgs> _completed;
private bool _completedChanged;
// LastOperation property variables.
private SocketAsyncOperation _completedOperation;
// ReceiveMessageFromPacketInfo property variables.
private IPPacketInformation _receiveMessageFromPacketInfo;
// RemoteEndPoint property variables.
private EndPoint _remoteEndPoint;
// SendPacketsSendSize property variable.
internal int _sendPacketsSendSize;
// SendPacketsElements property variables.
internal SendPacketsElement[] _sendPacketsElements;
// SocketError property variables.
private SocketError _socketError;
private Exception _connectByNameError;
// SocketFlags property variables.
internal SocketFlags _socketFlags;
// UserToken property variables.
private object _userToken;
// Internal buffer for AcceptEx when Buffer not supplied.
internal byte[] _acceptBuffer;
internal int _acceptAddressBufferCount;
// Internal SocketAddress buffer.
internal Internals.SocketAddress _socketAddress;
// Misc state variables.
private ExecutionContext _context;
private static readonly ContextCallback s_executionCallback = ExecutionCallback;
private Socket _currentSocket;
private bool _disposeCalled;
// Controls thread safety via Interlocked.
private const int Configuring = -1;
private const int Free = 0;
private const int InProgress = 1;
private const int Disposed = 2;
private int _operating;
private MultipleConnectAsync _multipleConnect;
private static bool s_loggingEnabled = SocketsEventSource.Log.IsEnabled();
public SocketAsyncEventArgs()
{
InitializeInternals();
}
public Socket AcceptSocket
{
get { return _acceptSocket; }
set { _acceptSocket = value; }
}
public Socket ConnectSocket
{
get { return _connectSocket; }
}
public byte[] Buffer
{
get { return _buffer; }
}
public int Offset
{
get { return _offset; }
}
public int Count
{
get { return _count; }
}
// NOTE: this property is mutually exclusive with Buffer.
// Setting this property with an existing non-null Buffer will throw.
public IList<ArraySegment<byte>> BufferList
{
get { return _bufferList; }
set
{
StartConfiguring();
try
{
if (value != null && _buffer != null)
{
throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, "Buffer"));
}
_bufferList = value;
SetupMultipleBuffers();
}
finally
{
Complete();
}
}
}
public int BytesTransferred
{
get { return _bytesTransferred; }
}
public event EventHandler<SocketAsyncEventArgs> Completed
{
add
{
_completed += value;
_completedChanged = true;
}
remove
{
_completed -= value;
_completedChanged = true;
}
}
protected virtual void OnCompleted(SocketAsyncEventArgs e)
{
EventHandler<SocketAsyncEventArgs> handler = _completed;
if (handler != null)
{
handler(e._currentSocket, e);
}
}
public SocketAsyncOperation LastOperation
{
get { return _completedOperation; }
}
public IPPacketInformation ReceiveMessageFromPacketInfo
{
get { return _receiveMessageFromPacketInfo; }
}
public EndPoint RemoteEndPoint
{
get { return _remoteEndPoint; }
set { _remoteEndPoint = value; }
}
public SendPacketsElement[] SendPacketsElements
{
get { return _sendPacketsElements; }
set
{
StartConfiguring();
try
{
_sendPacketsElements = value;
SetupSendPacketsElements();
}
finally
{
Complete();
}
}
}
public int SendPacketsSendSize
{
get { return _sendPacketsSendSize; }
set { _sendPacketsSendSize = value; }
}
public SocketError SocketError
{
get { return _socketError; }
set { _socketError = value; }
}
public Exception ConnectByNameError
{
get { return _connectByNameError; }
}
public SocketFlags SocketFlags
{
get { return _socketFlags; }
set { _socketFlags = value; }
}
public object UserToken
{
get { return _userToken; }
set { _userToken = value; }
}
public void SetBuffer(byte[] buffer, int offset, int count)
{
SetBufferInternal(buffer, offset, count);
}
public void SetBuffer(int offset, int count)
{
SetBufferInternal(_buffer, offset, count);
}
private void SetBufferInternal(byte[] buffer, int offset, int count)
{
StartConfiguring();
try
{
if (buffer == null)
{
// Clear out existing buffer.
_buffer = null;
_offset = 0;
_count = 0;
}
else
{
// Can't have both Buffer and BufferList.
if (_bufferList != null)
{
throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, "BufferList"));
}
// Offset and count can't be negative and the
// combination must be in bounds of the array.
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0 || count > (buffer.Length - offset))
{
throw new ArgumentOutOfRangeException("count");
}
_buffer = buffer;
_offset = offset;
_count = count;
}
// Pin new or unpin old buffer if necessary.
SetupSingleBuffer();
}
finally
{
Complete();
}
}
internal void SetResults(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
_socketError = socketError;
_connectByNameError = null;
_bytesTransferred = bytesTransferred;
_socketFlags = flags;
}
internal void SetResults(Exception exception, int bytesTransferred, SocketFlags flags)
{
_connectByNameError = exception;
_bytesTransferred = bytesTransferred;
_socketFlags = flags;
if (exception == null)
{
_socketError = SocketError.Success;
}
else
{
SocketException socketException = exception as SocketException;
if (socketException != null)
{
_socketError = socketException.SocketErrorCode;
}
else
{
_socketError = SocketError.SocketError;
}
}
}
private static void ExecutionCallback(object state)
{
var thisRef = (SocketAsyncEventArgs)state;
thisRef.OnCompleted(thisRef);
}
// Marks this object as no longer "in-use". Will also execute a Dispose deferred
// because I/O was in progress.
internal void Complete()
{
// Mark as not in-use.
_operating = Free;
InnerComplete();
// Check for deferred Dispose().
// The deferred Dispose is not guaranteed if Dispose is called while an operation is in progress.
// The _disposeCalled variable is not managed in a thread-safe manner on purpose for performance.
if (_disposeCalled)
{
Dispose();
}
}
// Dispose call to implement IDisposable.
public void Dispose()
{
// Remember that Dispose was called.
_disposeCalled = true;
// Check if this object is in-use for an async socket operation.
if (Interlocked.CompareExchange(ref _operating, Disposed, Free) != Free)
{
// Either already disposed or will be disposed when current operation completes.
return;
}
// OK to dispose now.
FreeInternals(false);
// Don't bother finalizing later.
GC.SuppressFinalize(this);
}
~SocketAsyncEventArgs()
{
FreeInternals(true);
}
// NOTE: Use a try/finally to make sure Complete is called when you're done
private void StartConfiguring()
{
int status = Interlocked.CompareExchange(ref _operating, Configuring, Free);
if (status == InProgress || status == Configuring)
{
throw new InvalidOperationException(SR.net_socketopinprogress);
}
else if (status == Disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
// Prepares for a native async socket call.
// This method performs the tasks common to all socket operations.
internal void StartOperationCommon(Socket socket)
{
// Change status to "in-use".
if (Interlocked.CompareExchange(ref _operating, InProgress, Free) != Free)
{
// If it was already "in-use" check if Dispose was called.
if (_disposeCalled)
{
// Dispose was called - throw ObjectDisposed.
throw new ObjectDisposedException(GetType().FullName);
}
// Only one at a time.
throw new InvalidOperationException(SR.net_socketopinprogress);
}
// Prepare execution context for callback.
// If event delegates have changed or socket has changed
// then discard any existing context.
if (_completedChanged || socket != _currentSocket)
{
_completedChanged = false;
_context = null;
}
// Capture execution context if none already.
if (_context == null)
{
_context = ExecutionContext.Capture();
}
// Remember current socket.
_currentSocket = socket;
}
internal void StartOperationAccept()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Accept;
// AcceptEx needs a single buffer with room for two special sockaddr data structures.
// It can also take additional buffer space in front of those special sockaddr
// structures that can be filled in with initial data coming in on a connection.
// First calculate the special AcceptEx address buffer size.
// It is the size of two native sockaddr buffers with 16 extra bytes each.
// The native sockaddr buffers vary by address family so must reference the current socket.
_acceptAddressBufferCount = 2 * (_currentSocket._rightEndPoint.Serialize().Size + 16);
// If our caller specified a buffer (willing to get received data with the Accept) then
// it needs to be large enough for the two special sockaddr buffers that AcceptEx requires.
// Throw if that buffer is not large enough.
bool userSuppliedBuffer = _buffer != null;
if (userSuppliedBuffer)
{
// Caller specified a buffer - see if it is large enough
if (_count < _acceptAddressBufferCount)
{
throw new ArgumentException(SR.Format(SR.net_buffercounttoosmall, "Count"));
}
// Buffer is already pinned if necessary.
}
else
{
// Caller didn't specify a buffer so use an internal one.
// See if current internal one is big enough, otherwise create a new one.
if (_acceptBuffer == null || _acceptBuffer.Length < _acceptAddressBufferCount)
{
_acceptBuffer = new byte[_acceptAddressBufferCount];
}
}
InnerStartOperationAccept(userSuppliedBuffer);
}
internal void StartOperationConnect()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Connect;
_multipleConnect = null;
_connectSocket = null;
InnerStartOperationConnect();
}
internal void StartOperationWrapperConnect(MultipleConnectAsync args)
{
_completedOperation = SocketAsyncOperation.Connect;
_multipleConnect = args;
_connectSocket = null;
}
internal void CancelConnectAsync()
{
if (_operating == InProgress && _completedOperation == SocketAsyncOperation.Connect)
{
if (_multipleConnect != null)
{
// If a multiple connect is in progress, abort it.
_multipleConnect.Cancel();
}
else
{
// Otherwise we're doing a normal ConnectAsync - cancel it by closing the socket.
// _currentSocket will only be null if _multipleConnect was set, so we don't have to check.
if (_currentSocket == null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SocketAsyncEventArgs::CancelConnectAsync - CurrentSocket and MultipleConnect both null!");
}
Debug.Fail("SocketAsyncEventArgs::CancelConnectAsync - CurrentSocket and MultipleConnect both null!");
}
_currentSocket.Dispose();
}
}
}
internal void StartOperationReceive()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Receive;
InnerStartOperationReceive();
}
internal void StartOperationReceiveFrom()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.ReceiveFrom;
InnerStartOperationReceiveFrom();
}
internal void StartOperationReceiveMessageFrom()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.ReceiveMessageFrom;
InnerStartOperationReceiveMessageFrom();
}
internal void StartOperationSend()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Send;
InnerStartOperationSend();
}
internal void StartOperationSendPackets()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.SendPackets;
InnerStartOperationSendPackets();
}
internal void StartOperationSendTo()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.SendTo;
InnerStartOperationSendTo();
}
internal void UpdatePerfCounters(int size, bool sendOp)
{
if (sendOp)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesSent, size);
if (_currentSocket.Transport == TransportType.Udp)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsSent);
}
}
else
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesReceived, size);
if (_currentSocket.Transport == TransportType.Udp)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsReceived);
}
}
}
internal void FinishOperationSyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
SetResults(socketError, bytesTransferred, flags);
// This will be null if we're doing a static ConnectAsync to a DnsEndPoint with AddressFamily.Unspecified;
// the attempt socket will be closed anyways, so not updating the state is OK.
if (_currentSocket != null)
{
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
Complete();
}
internal void FinishConnectByNameSyncFailure(Exception exception, int bytesTransferred, SocketFlags flags)
{
SetResults(exception, bytesTransferred, flags);
if (_currentSocket != null)
{
_currentSocket.UpdateStatusAfterSocketError(_socketError);
}
Complete();
}
internal void FinishOperationAsyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
SetResults(socketError, bytesTransferred, flags);
// This will be null if we're doing a static ConnectAsync to a DnsEndPoint with AddressFamily.Unspecified;
// the attempt socket will be closed anyways, so not updating the state is OK.
if (_currentSocket != null)
{
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_context, s_executionCallback, this);
}
}
internal void FinishOperationAsyncFailure(Exception exception, int bytesTransferred, SocketFlags flags)
{
SetResults(exception, bytesTransferred, flags);
if (_currentSocket != null)
{
_currentSocket.UpdateStatusAfterSocketError(_socketError);
}
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_context, s_executionCallback, this);
}
}
internal void FinishWrapperConnectSuccess(Socket connectSocket, int bytesTransferred, SocketFlags flags)
{
SetResults(SocketError.Success, bytesTransferred, flags);
_currentSocket = connectSocket;
_connectSocket = connectSocket;
// Complete the operation and raise the event.
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_context, s_executionCallback, this);
}
}
internal void FinishOperationSuccess(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
SetResults(socketError, bytesTransferred, flags);
switch (_completedOperation)
{
case SocketAsyncOperation.Accept:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
// Get the endpoint.
Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket._rightEndPoint);
socketError = FinishOperationAccept(remoteSocketAddress);
if (socketError == SocketError.Success)
{
_acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket, _currentSocket._rightEndPoint.Create(remoteSocketAddress));
if (s_loggingEnabled)
SocketsEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
}
else
{
SetResults(socketError, bytesTransferred, SocketFlags.None);
_acceptSocket = null;
}
break;
case SocketAsyncOperation.Connect:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
socketError = FinishOperationConnect();
// Mark socket connected.
if (socketError == SocketError.Success)
{
if (s_loggingEnabled)
SocketsEventSource.Connected(_currentSocket, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint);
_currentSocket.SetToConnected();
_connectSocket = _currentSocket;
}
break;
case SocketAsyncOperation.Disconnect:
_currentSocket.SetToDisconnected();
_currentSocket._remoteEndPoint = null;
break;
case SocketAsyncOperation.Receive:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
break;
case SocketAsyncOperation.ReceiveFrom:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
// Deal with incoming address.
_socketAddress.InternalSize = GetSocketAddressSize();
Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
if (!socketAddressOriginal.Equals(_socketAddress))
{
try
{
_remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
}
catch
{
}
}
break;
case SocketAsyncOperation.ReceiveMessageFrom:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
// Deal with incoming address.
_socketAddress.InternalSize = GetSocketAddressSize();
socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
if (!socketAddressOriginal.Equals(_socketAddress))
{
try
{
_remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
}
catch
{
}
}
FinishOperationReceiveMessageFrom();
break;
case SocketAsyncOperation.Send:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
break;
case SocketAsyncOperation.SendPackets:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogSendPacketsBuffers(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
FinishOperationSendPackets();
break;
case SocketAsyncOperation.SendTo:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
break;
}
if (socketError != SocketError.Success)
{
// Asynchronous failure or something went wrong after async success.
SetResults(socketError, bytesTransferred, flags);
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
// Complete the operation and raise completion event.
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_context, s_executionCallback, this);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using ApprovalTests;
using ApprovalTests.Reporters;
using ConsoleToolkit.ApplicationStyles.Internals;
using ConsoleToolkit.CommandLineInterpretation;
using ConsoleToolkit.CommandLineInterpretation.ConfigurationAttributes;
using ConsoleToolkit.ConsoleIO;
using ConsoleToolkit.ConsoleIO.Internal;
using ConsoleToolkit.Testing;
using ConsoleToolkitTests.TestingUtilities;
using NUnit.Framework;
using Description = ConsoleToolkit.CommandLineInterpretation.ConfigurationAttributes.DescriptionAttribute;
// ReSharper disable UnusedMember.Local
namespace ConsoleToolkitTests.CommandLineInterpretation.CommandInterpreterAcceptanceTests
{
/// <summary>
/// This test implements the arguments of the git add and clone commands, as a proof that relatively complex command options
/// can be specified. (i.e. its not just a made up example.)
/// </summary>
[TestFixture]
[UseReporter(typeof (CustomReporter))]
public class Config3AcceptanceTests
{
private CommandLineInterpreterConfiguration _posix;
private CommandLineInterpreterConfiguration _msDos;
private CommandLineInterpreterConfiguration _msStd;
private ConsoleInterfaceForTesting _consoleOutInterface;
private ConsoleAdapter _console;
private static readonly string _applicationName = "AcceptanceTest";
[Command]
[Description("Add file contents to the index.")]
class AddCommand
{
[Positional("filepattern")]
[Description("Files to add content from. Fileglobs (e.h. *.c) can be given to add all matching files. Also, a leading directory name (e.g. dir to add dir/file1 and dir/file2) can be given to all all files in the directory recursively.")]
public string FilePattern { get; set; }
[Option("dryrun", "n")]
[Description("Don't actually add the file(s), just show if they exist and/or will be ignored.")]
public bool DryRun { get; set; }
[Option("verbose", "v")]
[Description("Be verbose.")]
public bool Verbose { get; set; }
[Option("force", "f")]
[Description("Allow adding otherwise ignored files.")]
public bool Force { get; set; }
[Option("interactive", "i")]
[Description(@"Add modified contents in the working tree interactively to the index. Optional path arguments may be supplied to limit operation to a subset of the working tree. See ""Interactive mode"" for details.")]
public bool Interactive { get; set; }
[Option("patch", "p")]
[Description(@"Interactively choose hunks of patch between the index and the work tree and add them to the index. This gives the user a chance to review the difference before adding modified contents to the index.
This effectively runs add --interactive, but bypasses the initial command menu and directly jumps to the patch subcommand. See ""Interactive mode"" for details.")]
public bool Patch { get; set; }
[Option("edit", "e")]
[Description(@"Open the diff vs. the index in an editor and let the user edit it. After the editor was closed, adjust the hunk headers and apply the patch to the index.
The intent of this option is to pick and choose lines of the patch to apply, or even to modify the contents of lines to be staged. This can be quicker and more flexible than using the interactive hunk selector. However, it is easy to confuse oneself and create a patch that does not apply to the index.")]
public bool Edit { get; set; }
[Option("update", "u")]
[Description(@"Only match <filepattern> against already tracked files in the index rather than the working tree. That means that it will never stage new files, but that it will stage modified new contents of tracked files and that it will remove files from the index if the corresponding files in the working tree have been removed.
If no <filepattern> is given, default to "".""; in other words, update all tracked files in the current directory and its subdirectories.")]
public bool Update { get; set; }
[Option("all", "A")]
[Description(@"Like -u, but match <filepattern> against files in the working tree in addition to the index. That means that it will find new files as well as staging modified content and removing files that are no longer in the working tree.")]
public bool All { get; set; }
[Option("intent-to-add", "N")]
[Description(@"Record only the fact that the path will be added later. An entry for the path is placed in the index with no content. This is useful for, among other things, showing the unstaged content of such files with git diff and committing them with git commit -a.")]
public bool IntentToAdd { get; set; }
[Option]
[Description(@"Don't add the file(s), but only refresh their stat() information in the index.")]
public bool Refresh { get; set; }
[Option("ignore-errors")]
[Description(@"If some files could not be added because of errors indexing them, do not abort the operation, but continue adding the others. The command shall still exit with non-zero status. The configuration variable add.ignoreErrors can be set to true to make this the default behaviour.")]
public bool IgnoreErrors { get; set; }
[Option("ignore-missing")]
[Description(@"This option can only be used together with --dry-run. By using this option the user can check if any of the given files would be ignored, no matter if they are already present in the work tree or not.")]
public bool IgnoreMissing { get; set; }
}
[Command]
[Description("Clone a repository into a new directory")]
class CloneCommand
{
[Positional("repository")]
[Description("The (possibly remote) repository to clone from. See the URLS section below for more information on specifying repositories.")]
public string Repository { get; set; }
[Positional("directory", DefaultValue = null)]
[Description(@"The name of a new directory to clone into. The ""humanish"" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git). Cloning into an existing directory is only allowed if the directory is empty.")]
public string Directory { get; set; }
[Option("local", "l")]
[Description(@"When the repository to clone from is on a local machine, this flag bypasses the normal ""git aware"" transport mechanism and clones the repository by making a copy of HEAD and everything under objects and refs directories. The files under .git/objects/ directory are hardlinked to save space when possible.
If the repository is specified as a local path (e.g., /path/to/repo), this is the default, and --local is essentially a no-op. If the repository is specified as a URL, then this flag is ignored (and we never use the local optimizations). Specifying --no-local will override the default when /path/to/repo is given, using the regular git transport instead.
To force copying instead of hardlinking (which may be desirable if you are trying to make a back-up of your repository), but still avoid the usual ""git aware"" transport mechanism, --no-hardlinks can be used.")]
public bool Local { get; set; }
[Option("no-hard-links")]
[Description("Optimize the cloning process from a repository on a local filesystem by copying files under .git/objects directory.")]
public bool NoHardLinks { get; set; }
[Option("shared", "s")]
[Description(@"When the repository to clone is on the local machine, instead of using hard links, automatically setup .git/objects/info/alternates to share the objects with the source repository. The resulting repository starts out without any object of its own.
NOTE: this is a possibly dangerous operation; do not use it unless you understand what it does. If you clone your repository using this option and then delete branches (or use any other git command that makes any existing commit unreferenced) in the source repository, some objects may become unreferenced (or dangling). These objects may be removed by normal git operations (such as git commit) which automatically call git gc --auto. (See git-gc(1).) If these objects are removed and were referenced by the cloned repository, then the cloned repository will become corrupt.
Note that running git repack without the -l option in a repository cloned with -s will copy objects from the source repository into a pack in the cloned repository, removing the disk space savings of clone -s. It is safe, however, to run git gc, which uses the -l option by default.
If you want to break the dependency of a repository cloned with -s on its source repository, you can simply run git repack -a to copy all objects from the source repository into a pack in the cloned repository.")]
public bool Shared { get; set; }
[Option("reference")]
[Description(@"If the reference repository is on the local machine, automatically setup .git/objects/info/alternates to obtain objects from the reference repository. Using an already existing repository as an alternate will require fewer objects to be copied from the repository being cloned, reducing network and local storage costs.
NOTE: see the NOTE for the --shared option.")]
public string ReferenceRepository { get; set; }
[Option("quiet", "q")]
[Description("Operate quietly. Progress is not reported to the standard error stream. This flag is also passed to the 'rsync' command when given.")]
public bool Quiet { get; set; }
[Option("verbose", "v")]
[Description("Be verbose.")]
public bool Verbose { get; set; }
[Option("progress")]
[Description("Progress status is reported on the standard error stream by default when it is attached to a terminal, unless -q is specified. This flag forces progress status even if the standard error stream is not directed to a terminal.")]
public bool Progress { get; set; }
[Option("no-checkout", "n")]
[Description("No checkout of HEAD is performed after the clone is complete.")]
public bool NoCheckout { get; set; }
[Option("bare")]
[Description("Make a bare GIT repository. That is, instead of creating <directory> and placing the administrative files in <directory>/.git, make the <directory> itself the $GIT_DIR. This obviously implies the -n because there is nowhere to check out the working tree. Also the branch heads at the remote are copied directly to corresponding local branch heads, without mapping them to refs/remotes/origin/. When this option is used, neither remote-tracking branches nor the related configuration variables are created.")]
public bool Bare { get; set; }
[Option("mirror")]
[Description("Set up a mirror of the source repository. This implies --bare. Compared to --bare, --mirror not only maps local branches of the source to local branches of the target, it maps all refs (including remote-tracking branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a git remote update in the target repository.")]
public bool Mirror { get; set; }
[Option("origin", "o")]
[Description("Instead of using the remote name origin to keep track of the upstream repository, use <name>.")]
public string Origin { get; set; }
[Option("branch", "b")]
[Description(@"Instead of pointing the newly created HEAD to the branch pointed to by the cloned repository's HEAD, point to <name> branch instead. In a non-bare repository, this is the branch that will be checked out. --branch can also take tags and detaches the HEAD at that commit in the resulting repository.")]
public string Branch { get; set; }
[Option("upload-pack", "u")]
[Description(@"When given, and the repository to clone from is accessed via ssh, this specifies a non-default path for the command run on the other end.")]
public string UploadPack { get; set; }
[Option("template")]
[Description(@"Specify the directory from which templates will be used; (See the ""TEMPLATE DIRECTORY"" section of git-init(1).")]
public string Template { get; set; }
[Option("config", "c")]
[Description(@"Set a configuration variable in the newly-created repository; this takes effect immediately after the repository is initialized, but before the remote history is fetched or any files checked out. The key is in the same format as expected by git-config(1) (e.g., core.eol=true). If multiple values are given for the same key, each value will be written to the config file. This makes it safe, for example, to add additional fetch refspecs to the origin remote.")]
public List<string> Config { get; set; }
[Option("depth")]
[Description(@"Create a shallow clone with a history truncated to the specified number of revisions. A shallow repository has a number of limitations (you cannot clone or fetch from it, nor push from nor into it), but is adequate if you are only interested in the recent history of a large project with a long history, and would want to send in fixes as patches.")]
public int Depth { get; set; }
[Option("single-branch")]
[Description(@"Clone only the history leading to the tip of a single branch, either specified by the --branch option or the primary branch remote's HEAD points at. When creating a shallow clone with the --depth option, this is the default, unless --no-single-branch is given to fetch the histories near the tips of all branches. Further fetches into the resulting repository will only update the remote-tracking branch for the branch this option was used for the initial cloning. If the HEAD at the remote did not point at any branch when --single-branch clone was made, no remote-tracking branch is created.")]
public bool SingleBranch { get; set; }
[Option("recursive", "recursive-submodules")]
[Description(@"After the clone is created, initialize all submodules within, using their default settings. This is equivalent to running git submodule update --init --recursive immediately after the clone is finished. This option is ignored if the cloned repository does not have a worktree/checkout (i.e. if any of --no-checkout/-n, --bare, or --mirror is given)")]
public bool RecurseSubmodules { get; set; }
[Option("seperate-git-dir")]
[Description(@"Instead of placing the cloned repository where it is supposed to be, place the cloned repository at the specified directory, then make a filesytem-agnostic git symbolic link to there. The result is git repository can be separated from working tree.")]
public string SeperateGitDir { get; set; }
}
[SetUp]
public void SetUp()
{
_posix = new CommandLineInterpreterConfiguration(CommandLineParserConventions.PosixConventions);
_msDos = new CommandLineInterpreterConfiguration(CommandLineParserConventions.MsDosConventions);
_msStd = new CommandLineInterpreterConfiguration(CommandLineParserConventions.MicrosoftStandard);
Configure(_posix);
Configure(_msDos);
Configure(_msStd);
_consoleOutInterface = new ConsoleInterfaceForTesting();
_consoleOutInterface.WindowWidth = 80;
_consoleOutInterface.BufferWidth = 80;
_console = new ConsoleAdapter(_consoleOutInterface);
}
private void Configure(CommandLineInterpreterConfiguration config)
{
config.Load(typeof(AddCommand));
config.Load(typeof(CloneCommand));
}
[Test]
public void ConfigurationShouldBeDescribed()
{
CommandConfigDescriber.Describe(_posix, _console, "POSIX", CommandLineParserConventions.PosixConventions, CommandExecutionMode.CommandLine);
var description = _consoleOutInterface.GetBuffer();
Approvals.Verify(description);
}
[Test]
public void PosixStyle()
{
var commands = new[]
{
@"add *.c",
@"clone --reference my2.6 git://git.kernel.org/pub/scm/.../linux-2.7 my2.7",
@"clone git@github.com:whatever",
@"clone git@github.com:whatever folder-name",
@"clone --mirror https://github.com/exampleuser/repository-to-mirror.git",
@"clone --mirror -- https://github.com/exampleuser/repository-to-mirror.git"
};
Approvals.Verify(CommandExecutorUtil.Do(_posix, commands, 50, false));
}
[Test]
public void MsDosStyleCommand1()
{
var commands = new[]
{
@"add *.c",
@"clone /reference:my2.6 git://git.kernel.org/pub/scm/.../linux-2.7 my2.7",
@"clone git@github.com:whatever",
@"clone git@github.com:whatever folder-name",
@"clone /mirror https://github.com/exampleuser/repository-to-mirror.git"
};
Approvals.Verify(CommandExecutorUtil.Do(_msDos, commands, 50, false));
}
[Test]
public void MsStdStyleCommand1()
{
var commands = new[]
{
@"add *.c",
@"clone -reference my2.6 git://git.kernel.org/pub/scm/.../linux-2.7 my2.7",
@"clone git@github.com:whatever",
@"clone git@github.com:whatever folder-name",
@"clone -mirror https://github.com/exampleuser/repository-to-mirror.git",
@"clone git@github.com:whatever -c A -c B -c C",
@"clone -mirror:True https://github.com/exampleuser/repository-to-mirror.git"
};
Approvals.Verify(CommandExecutorUtil.Do(_msStd, commands, 50, false));
}
// ReSharper restore UnusedAutoPropertyAccessor.Local
// ReSharper restore UnusedMember.Local
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using RTApiInformation = Windows.Foundation.Metadata.ApiInformation;
using RTHttpBaseProtocolFilter = Windows.Web.Http.Filters.HttpBaseProtocolFilter;
using RTHttpCacheReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior;
using RTHttpCacheWriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior;
using RTHttpCookieUsageBehavior = Windows.Web.Http.Filters.HttpCookieUsageBehavior;
using RTPasswordCredential = Windows.Security.Credentials.PasswordCredential;
using RTCertificate = Windows.Security.Cryptography.Certificates.Certificate;
using RTCertificateQuery = Windows.Security.Cryptography.Certificates.CertificateQuery;
using RTCertificateStores = Windows.Security.Cryptography.Certificates.CertificateStores;
namespace System.Net.Http
{
public class HttpClientHandler : HttpMessageHandler
{
private const string clientAuthenticationOID = "1.3.6.1.5.5.7.3.2";
private static readonly Lazy<bool> s_RTCookieUsageBehaviorSupported =
new Lazy<bool>(InitRTCookieUsageBehaviorSupported);
#region Fields
private readonly RTHttpBaseProtocolFilter rtFilter;
private readonly HttpHandlerToFilter handlerToFilter;
private readonly HttpMessageHandler diagnosticsPipeline;
private volatile bool operationStarted;
private volatile bool disposed;
private ClientCertificateOption clientCertificateOptions;
private CookieContainer cookieContainer;
private bool useCookies;
private DecompressionMethods automaticDecompression;
private IWebProxy proxy;
private X509Certificate2Collection clientCertificates;
private IDictionary<String, Object> properties; // Only create dictionary when required.
#endregion Fields
#region Properties
public virtual bool SupportsAutomaticDecompression
{
get { return true; }
}
public virtual bool SupportsProxy
{
get { return false; }
}
public virtual bool SupportsRedirectConfiguration
{
get { return false; }
}
public bool UseCookies
{
get { return useCookies; }
set
{
CheckDisposedOrStarted();
useCookies = value;
}
}
public CookieContainer CookieContainer
{
get { return cookieContainer; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (!UseCookies)
{
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_invalid_enable_first, nameof(UseCookies), "true"));
}
CheckDisposedOrStarted();
cookieContainer = value;
}
}
public ClientCertificateOption ClientCertificateOptions
{
get { return clientCertificateOptions; }
set
{
if (value != ClientCertificateOption.Manual &&
value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
clientCertificateOptions = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get { return automaticDecompression; }
set
{
CheckDisposedOrStarted();
// Automatic decompression is implemented downstack.
// HBPF will decompress both gzip and deflate, we will set
// accept-encoding for one, the other, or both passed in here.
rtFilter.AutomaticDecompression = (value != DecompressionMethods.None);
automaticDecompression = value;
}
}
public bool UseProxy
{
get { return rtFilter.UseProxy; }
set
{
CheckDisposedOrStarted();
rtFilter.UseProxy = value;
}
}
public IWebProxy Proxy
{
// We don't actually support setting a different proxy because our Http stack in NETNative
// layers on top of the WinRT HttpClient which uses Wininet. And that API layer simply
// uses the proxy information in the registry (and the same that Internet Explorer uses).
// However, we can't throw PlatformNotSupportedException because the .NET Desktop stack
// does support this and doing so would break apps. So, we'll just let this get/set work
// even though we ignore it. The majority of apps actually use the default proxy anyways
// so setting it here would be a no-op.
get { return proxy; }
set
{
CheckDisposedOrStarted();
proxy = value;
SetProxyCredential(proxy);
}
}
public bool PreAuthenticate
{
get { return true; }
set
{
/*
TODO:#18104
if (value != PreAuthenticate)
{
throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(PreAuthenticate)));
}
*/
CheckDisposedOrStarted();
}
}
public bool UseDefaultCredentials
{
get { return Credentials == null; }
set
{
CheckDisposedOrStarted();
if (value)
{
// System managed
rtFilter.ServerCredential = null;
}
else if (rtFilter.ServerCredential == null)
{
// The only way to disable default credentials is to provide credentials.
// Do not overwrite credentials if they were already assigned.
rtFilter.ServerCredential = new RTPasswordCredential();
}
}
}
public ICredentials Credentials
{
get
{
RTPasswordCredential rtCreds = rtFilter.ServerCredential;
if (rtCreds == null)
{
return null;
}
NetworkCredential creds = new NetworkCredential(rtCreds.UserName, rtCreds.Password);
return creds;
}
set
{
if (value == null)
{
CheckDisposedOrStarted();
rtFilter.ServerCredential = null;
}
else if (value == CredentialCache.DefaultCredentials)
{
CheckDisposedOrStarted();
// System managed
rtFilter.ServerCredential = null;
}
else if (value is NetworkCredential)
{
CheckDisposedOrStarted();
rtFilter.ServerCredential = RTPasswordCredentialFromNetworkCredential((NetworkCredential)value);
}
else
{
throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(Credentials)));
}
}
}
public ICredentials DefaultProxyCredentials
{
get
{
RTPasswordCredential rtCreds = rtFilter.ProxyCredential;
if (rtCreds == null)
{
return null;
}
NetworkCredential creds = new NetworkCredential(rtCreds.UserName, rtCreds.Password);
return creds;
}
set
{
if (value == null)
{
CheckDisposedOrStarted();
rtFilter.ProxyCredential = null;
}
else if (value == CredentialCache.DefaultCredentials)
{
CheckDisposedOrStarted();
// System managed
rtFilter.ProxyCredential = null;
}
else if (value is NetworkCredential)
{
CheckDisposedOrStarted();
rtFilter.ProxyCredential = RTPasswordCredentialFromNetworkCredential((NetworkCredential)value);
}
else
{
throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(DefaultProxyCredentials)));
}
}
}
public bool AllowAutoRedirect
{
get { return rtFilter.AllowAutoRedirect; }
set
{
CheckDisposedOrStarted();
rtFilter.AllowAutoRedirect = value;
}
}
// WinINet limit
public int MaxAutomaticRedirections
{
get { return 10; }
set
{
/*
* TODO:#17812
if (value != MaxAutomaticRedirections)
{
throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(MaxAutomaticRedirections)));
}
*/
CheckDisposedOrStarted();
}
}
public int MaxConnectionsPerServer
{
get { return (int)rtFilter.MaxConnectionsPerServer; }
set
{
CheckDisposedOrStarted();
rtFilter.MaxConnectionsPerServer = (uint)value;
}
}
public long MaxRequestContentBufferSize
{
get { return HttpContent.MaxBufferSize; }
set
{
// .NET Native port note: We don't have an easy way to implement the MaxRequestContentBufferSize property. To maximize the chance of app compat,
// we will "succeed" as long as the requested buffer size doesn't exceed the max. However, no actual
// enforcement of the max buffer size occurs.
if (value > MaxRequestContentBufferSize)
{
throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(MaxRequestContentBufferSize)));
}
CheckDisposedOrStarted();
}
}
public int MaxResponseHeadersLength
{
// Windows.Web.Http is built on WinINet. There is no maximum limit (except for out of memory)
// for received response headers. So, returning -1 (indicating no limit) is appropriate.
get { return -1; }
set
{
/*
* TODO:#18036
throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(MaxResponseHeadersLength)));
*/
}
}
private bool RTCookieUsageBehaviorSupported
{
get
{
return s_RTCookieUsageBehaviorSupported.Value;
}
}
public X509CertificateCollection ClientCertificates
{
// TODO: Not yet implemented. Issue #7623.
get
{
if (clientCertificates == null)
{
clientCertificates = new X509Certificate2Collection();
}
return clientCertificates;
}
}
public static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> DangerousAcceptAnyServerCertificateValidator { get; } = delegate { return true; };
public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback
{
// TODO: Not yet implemented. Issue #7623.
get{ return null; }
set
{
CheckDisposedOrStarted();
if (value != null)
{
/*
throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(ServerCertificateCustomValidationCallback)));
*/
}
}
}
public bool CheckCertificateRevocationList
{
// We can't get this property to actually work yet since the current WinRT Windows.Web.Http APIs don't have a setting for this.
// FYI: The WinRT API always checks for certificate revocation. If the revocation status can't be determined completely, i.e.
// the revocation server is offline, then the request is still allowed.
get { return true; }
set
{
CheckDisposedOrStarted();
/*TODO#18116
if (!value)
{
throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(CheckCertificateRevocationList)));
}
*/
}
}
public SslProtocols SslProtocols
{
get { return SslProtocols.None; }
set
{
CheckDisposedOrStarted();
if (value != SslProtocols.None)
{
/*
TODO:#18116
throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(SslProtocols)));
*/
}
}
}
public IDictionary<String, Object> Properties
{
get
{
if (properties == null)
{
properties = new Dictionary<String, object>();
}
return properties;
}
}
#endregion Properties
#region De/Constructors
public HttpClientHandler()
{
this.rtFilter = new RTHttpBaseProtocolFilter();
this.handlerToFilter = new HttpHandlerToFilter(this.rtFilter);
this.diagnosticsPipeline = new DiagnosticsHandler(handlerToFilter);
this.clientCertificateOptions = ClientCertificateOption.Manual;
InitRTCookieUsageBehavior();
this.useCookies = true; // deal with cookies by default.
this.cookieContainer = new CookieContainer(); // default container used for dealing with auto-cookies.
// Managed at this layer for granularity, but uses the desktop default.
this.rtFilter.AutomaticDecompression = false;
this.automaticDecompression = DecompressionMethods.None;
// Set initial proxy credentials based on default system proxy.
SetProxyCredential(null);
// We don't support using the UI model in HttpBaseProtocolFilter() especially for auto-handling 401 responses.
this.rtFilter.AllowUI = false;
// The .NET Desktop System.Net Http APIs (based on HttpWebRequest/HttpClient) uses no caching by default.
// To preserve app-compat, we turn off caching (as much as possible) in the WinRT HttpClient APIs.
// TODO (#7877): use RTHttpCacheReadBehavior.NoCache when available in the next version of WinRT HttpClient API.
this.rtFilter.CacheControl.ReadBehavior = RTHttpCacheReadBehavior.MostRecent;
this.rtFilter.CacheControl.WriteBehavior = RTHttpCacheWriteBehavior.NoCache;
}
protected override void Dispose(bool disposing)
{
if (disposing && !disposed)
{
disposed = true;
try
{
rtFilter.Dispose();
}
catch (InvalidComObjectException)
{
// We'll ignore this error since it can happen when Dispose() is called from an object's finalizer
// and the WinRT object (rtFilter) has already been disposed by the .NET Native runtime.
}
}
base.Dispose(disposing);
}
#endregion De/Constructors
#region Request Setup
private async Task ConfigureRequest(HttpRequestMessage request)
{
ApplyRequestCookies(request);
ApplyDecompressionSettings(request);
await ApplyClientCertificateSettings().ConfigureAwait(false);
}
// Taken from System.Net.CookieModule.OnSendingHeaders
private void ApplyRequestCookies(HttpRequestMessage request)
{
if (UseCookies)
{
string cookieHeader = CookieContainer.GetCookieHeader(request.RequestUri);
if (!string.IsNullOrWhiteSpace(cookieHeader))
{
bool success = request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.Cookie, cookieHeader);
System.Diagnostics.Debug.Assert(success);
}
}
}
private void ApplyDecompressionSettings(HttpRequestMessage request)
{
// Decompression: Add the Gzip and Deflate headers if not already present.
ApplyDecompressionSetting(request, DecompressionMethods.GZip, "gzip");
ApplyDecompressionSetting(request, DecompressionMethods.Deflate, "deflate");
}
private void ApplyDecompressionSetting(HttpRequestMessage request, DecompressionMethods method, string methodName)
{
if ((AutomaticDecompression & method) == method)
{
bool found = false;
foreach (StringWithQualityHeaderValue encoding in request.Headers.AcceptEncoding)
{
if (methodName.Equals(encoding.Value, StringComparison.OrdinalIgnoreCase))
{
found = true;
break;
}
}
if (!found)
{
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue(methodName));
}
}
}
private async Task ApplyClientCertificateSettings()
{
if (ClientCertificateOptions == ClientCertificateOption.Manual)
{
return;
}
// Get the certs that can be used for Client Authentication.
var query = new RTCertificateQuery();
var ekus = query.EnhancedKeyUsages;
ekus.Add(clientAuthenticationOID);
var clientCertificates = await RTCertificateStores.FindAllAsync(query).AsTask().ConfigureAwait(false);
if (clientCertificates.Count > 0)
{
this.rtFilter.ClientCertificate = clientCertificates[0];
}
}
#endregion Request Setup
#region Request Execution
protected internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
CheckDisposed();
SetOperationStarted();
HttpResponseMessage response;
try
{
await ConfigureRequest(request).ConfigureAwait(false);
Task<HttpResponseMessage> responseTask = DiagnosticsHandler.IsEnabled() ?
this.diagnosticsPipeline.SendAsync(request, cancellationToken) :
this.handlerToFilter.SendAsync(request, cancellationToken);
response = await responseTask.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
// Convert back to the expected exception type
throw new HttpRequestException(SR.net_http_client_execution_error, ex);
}
ProcessResponse(response);
return response;
}
#endregion Request Execution
#region Response Processing
private void ProcessResponse(HttpResponseMessage response)
{
ProcessResponseCookies(response);
}
// Taken from System.Net.CookieModule.OnReceivedHeaders
private void ProcessResponseCookies(HttpResponseMessage response)
{
if (UseCookies)
{
IEnumerable<string> values;
if (response.Headers.TryGetValues(HttpKnownHeaderNames.SetCookie, out values))
{
foreach (string cookieString in values)
{
if (!string.IsNullOrWhiteSpace(cookieString))
{
try
{
// Parse the cookies so that we can filter some of them out
CookieContainer helper = new CookieContainer();
helper.SetCookies(response.RequestMessage.RequestUri, cookieString);
CookieCollection cookies = helper.GetCookies(response.RequestMessage.RequestUri);
foreach (Cookie cookie in cookies)
{
// We don't want to put HttpOnly cookies in the CookieContainer if the system
// doesn't support the RTHttpBaseProtocolFilter CookieUsageBehavior property.
// Prior to supporting that, the WinRT HttpClient could not turn off cookie
// processing. So, it would always be storing all cookies in its internal container.
// Putting HttpOnly cookies in the .NET CookieContainer would cause problems later
// when the .NET layer tried to add them on outgoing requests and conflicted with
// the WinRT internal cookie processing.
//
// With support for WinRT CookieUsageBehavior, cookie processing is turned off
// within the WinRT layer. This allows us to process cookies using only the .NET
// layer. So, we need to add all applicable cookies that are received to the
// CookieContainer.
if (RTCookieUsageBehaviorSupported || !cookie.HttpOnly)
{
CookieContainer.Add(response.RequestMessage.RequestUri, cookie);
}
}
}
catch (Exception)
{
}
}
}
}
}
}
#endregion Response Processing
#region Helpers
private void SetOperationStarted()
{
if (!operationStarted)
{
operationStarted = true;
}
}
private void CheckDisposed()
{
if (disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private RTPasswordCredential RTPasswordCredentialFromNetworkCredential(NetworkCredential creds)
{
// RTPasswordCredential doesn't allow assigning string.Empty values, but those are the default values.
RTPasswordCredential rtCreds = new RTPasswordCredential();
if (!string.IsNullOrEmpty(creds.UserName))
{
if (!string.IsNullOrEmpty(creds.Domain))
{
rtCreds.UserName = creds.Domain + "\\" + creds.UserName;
}
else
{
rtCreds.UserName = creds.UserName;
}
}
if (!string.IsNullOrEmpty(creds.Password))
{
rtCreds.Password = creds.Password;
}
return rtCreds;
}
private void SetProxyCredential(IWebProxy proxy)
{
// We don't support changing the proxy settings in the NETNative version of HttpClient since it's layered on
// WinRT HttpClient. But we do support passing in explicit proxy credentials, if specified, which we can
// get from the specified or default proxy.
ICredentials proxyCredentials = null;
if (proxy != null)
{
proxyCredentials = proxy.Credentials;
}
if (proxyCredentials != CredentialCache.DefaultCredentials && proxyCredentials is NetworkCredential)
{
this.rtFilter.ProxyCredential = RTPasswordCredentialFromNetworkCredential((NetworkCredential)proxyCredentials);
}
}
private static bool InitRTCookieUsageBehaviorSupported()
{
return RTApiInformation.IsPropertyPresent(
"Windows.Web.Http.Filters.HttpBaseProtocolFilter",
"CookieUsageBehavior");
}
// Regardless of whether we're running on a machine that supports this WinRT API, we still might not be able
// to call the API. This is due to the calling app being compiled against an older Windows 10 Tools SDK. Since
// this library was compiled against the newer SDK, having these new API calls in this class will cause JIT
// failures in CoreCLR which generate a MissingMethodException before the code actually runs. So, we need
// these helper methods and try/catch handling.
private void InitRTCookieUsageBehavior()
{
try
{
InitRTCookieUsageBehaviorHelper();
}
catch (MissingMethodException)
{
Debug.WriteLine("HttpClientHandler.InitRTCookieUsageBehavior: MissingMethodException");
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void InitRTCookieUsageBehaviorHelper()
{
// Always turn off WinRT cookie processing if the WinRT API supports turning it off.
// Use .NET CookieContainer handling only.
if (RTCookieUsageBehaviorSupported)
{
this.rtFilter.CookieUsageBehavior = RTHttpCookieUsageBehavior.NoCookies;
}
}
#endregion Helpers
}
}
| |
using System;
using System.Diagnostics;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
#if DLAB_UNROOT_COMMON_NAMESPACE
using DLaB.Common.Exceptions;
#else
using Source.DLaB.Common.Exceptions;
#endif
#if DLAB_UNROOT_NAMESPACE || DLAB_XRM
namespace DLaB.Xrm
#else
namespace Source.DLaB.Xrm
#endif
{
/// <summary>
/// Type of Active Attribute
/// </summary>
public enum ActiveAttributeType
{
/// <summary>
/// Entity does not support an Active Attribute
/// </summary>
None,
/// <summary>
/// Entity uses an IsDisabled Attribute
/// </summary>
IsDisabled,
/// <summary>
/// Entity uses a StateCode Attribute
/// </summary>
StateCode,
}
/// <summary>
/// Determines the Active Attribute for the Entity
/// </summary>
/// <typeparam name="T"></typeparam>
#if !DLAB_XRM_DEBUG
[DebuggerNonUserCode]
#endif
public class ActivePropertyInfo<T> where T : Entity
{
#region Properties
/// <summary>
/// Gets or sets the active attribute type.
/// </summary>
/// <value>
/// The active attribute type.
/// </value>
public ActiveAttributeType ActiveAttribute { get; set; }
/// <summary>
/// Gets or sets the name of the active attribute.
/// </summary>
/// <value>
/// The name of the active attribute.
/// </value>
public string AttributeName { get; set; }
/// <summary>
/// Gets or sets the state of the active.
/// </summary>
/// <value>
/// The state of the active.
/// </value>
public int? ActiveState { get; set; }
/// <summary>
/// Gets or sets the not active state code integer value of the entity.
/// </summary>
/// <value>
/// The state of the not active.
/// </value>
public int? NotActiveState { get; set; }
#endregion Properties
/// <summary>
/// Initializes a new instance of the <see cref="ActivePropertyInfo{T}"/> class.
/// </summary>
/// <exception cref="TypeArgumentException">'Entity' is an invalid type for T. Please use the LateBoundActivePropertyInfo.</exception>
public ActivePropertyInfo()
{
if (typeof(T) == typeof(Entity))
{
throw new TypeArgumentException("'Entity' is an invalid type for T. Please use the LateBoundActivePropertyInfo.");
}
SetAttributeNameAndType(EntityHelper.GetEntityLogicalName<T>());
}
/// <summary>
/// Initializes a new instance of the <see cref="ActivePropertyInfo{T}"/> class.
/// </summary>
/// <param name="logicalName">Name of the logical.</param>
/// <exception cref="System.ArgumentNullException">logicalName</exception>
protected ActivePropertyInfo(string logicalName)
{
if (logicalName == null)
{
throw new ArgumentNullException(nameof(logicalName));
}
SetAttributeNameAndType(logicalName);
}
private void SetAttributeNameAndType(string logicalName)
{
switch (logicalName)
{
case "businessunit":
case "equipment":
case "organization":
case "resource":
case "systemuser":
ActiveAttribute = ActiveAttributeType.IsDisabled;
AttributeName = "isdisabled";
break;
#region Default CRM Entites with no active flag
case "accountleads":
case "actioncard":
case "actioncardusersettings":
case "actioncarduserstate":
case "activitymimeattachment":
case "activityparty":
case "annotation":
case "annualfiscalcalendar":
case "appconfiginstance":
case "appconfigmaster":
case "appmodule":
case "appmodulecomponent":
case "appmoduleroles":
case "attributemap":
case "audit":
case "bookableresourcebookingexchangesyncidmapping":
case "bulkdeletefailure":
case "bulkoperationlog":
case "businessunitnewsarticle":
case "calendar":
case "calendarrule":
case "campaignactivityitem":
case "campaignitem":
case "canvasapp":
case "cardtype":
case "category":
case "channelaccessprofileentityaccesslevel":
case "channelaccessprofileruleitem":
case "competitor":
case "competitorproduct":
case "competitorsalesliterature":
case "connectionroleassociation":
case "connectionroleobjecttypecode":
case "constraintbasedgroup":
case "contactinvoices":
case "contactleads":
case "contactorders":
case "contactquotes":
case "contracttemplate":
case "convertruleitem":
case "customcontrol":
case "customcontroldefaultconfig":
case "customcontrolresource":
case "customeraddress":
case "customeropportunityrole":
case "customerrelationship":
case "dataperformance":
case "dependency":
case "discount":
case "displaystring":
case "documenttemplate":
case "duplicaterecord":
case "duplicaterulecondition":
case "dynamicpropertyassociation":
case "dynamicpropertyinstance":
case "dynamicpropertyoptionsetitem":
case "emailsignature":
case "entitlementchannel":
case "entitlementcontacts":
case "entitlementproducts":
case "entitlementtemplate":
case "entitlementtemplatechannel":
case "entitlementtemplateproducts":
case "entitydataprovider":
case "entitydatasource":
case "entitymap":
case "exchangesyncidmapping":
case "expanderevent":
case "fieldpermission":
case "fieldsecurityprofile":
case "fixedmonthlyfiscalcalendar":
case "hierarchyrule":
case "hierarchysecurityconfiguration":
case "importjob":
case "incidentknowledgebaserecord":
case "invaliddependency":
case "invoicedetail":
case "isvconfig":
case "kbarticlecomment":
case "kbarticletemplate":
case "knowledgearticlescategories":
case "knowledgebaserecord":
case "leadaddress":
case "leadcompetitors":
case "leadproduct":
case "license":
case "listmember":
case "mailboxstatistics":
case "mailboxtrackingcategory":
case "mailboxtrackingfolder":
case "mobileofflineprofile":
case "mobileofflineprofileitem":
case "mobileofflineprofileitemassociation":
case "monthlyfiscalcalendar":
case "msdyn_odatav4ds":
case "msdyn_solutioncomponentdatasource":
case "msdyn_solutioncomponentsummary":
case "navigationsetting":
case "officegraphdocument":
case "offlinecommanddefinition":
case "opportunitycompetitors":
case "opportunityproduct":
case "organizationui":
case "orginsightsmetric":
case "orginsightsnotification":
case "personaldocumenttemplate":
case "pluginassembly":
case "plugintracelog":
case "plugintype":
case "plugintypestatistic":
case "post":
case "postcomment":
case "postfollow":
case "postlike":
case "principalentitymap":
case "principalobjectattributeaccess":
case "privilege":
case "processstage":
case "processtrigger":
case "productassociation":
case "productpricelevel":
case "productsalesliterature":
case "productsubstitute":
case "publisher":
case "publisheraddress":
case "quarterlyfiscalcalendar":
case "queuemembership":
case "quotedetail":
case "recommendationcache":
case "recommendationmodelmapping":
case "recommendationmodelversion":
case "recommendationmodelversionhistory":
case "recommendeddocument":
case "recurrencerule":
case "relationshiprolemap":
case "report":
case "reportcategory":
case "reportentity":
case "reportlink":
case "reportvisibility":
case "resourcegroup":
case "resourcespec":
case "ribboncustomization":
case "role":
case "roleprivileges":
case "roletemplateprivileges":
case "rollupfield":
case "routingruleitem":
case "salesliterature":
case "salesliteratureitem":
case "salesorderdetail":
case "savedorginsightsconfiguration":
case "savedqueryvisualization":
case "sdkmessage":
case "sdkmessagefilter":
case "sdkmessagepair":
case "sdkmessageprocessingstepimage":
case "sdkmessageprocessingstepsecureconfig":
case "sdkmessagerequest":
case "sdkmessagerequestfield":
case "sdkmessageresponse":
case "sdkmessageresponsefield":
case "semiannualfiscalcalendar":
case "service":
case "servicecontractcontacts":
case "serviceendpoint":
case "sharepointdata":
case "sharepointdocument":
case "site":
case "sitemap":
case "slaitem":
case "slakpiinstance":
case "socialinsightsconfiguration":
case "solution":
case "solutioncomponent":
case "subject":
case "subscriptionmanuallytrackedobject":
case "subscriptiontrackingdeletedobject":
case "suggestioncardtemplate":
case "syncerror":
case "systemform":
case "systemuserlicenses":
case "systemuserprofiles":
case "systemuserroles":
case "systemusersyncmappingprofiles":
case "team":
case "teammembership":
case "teamprofiles":
case "teamroles":
case "teamsyncattributemappingprofiles":
case "teamtemplate":
case "template":
case "territory":
case "textanalyticsentitymapping":
case "timezonedefinition":
case "timezonelocalizedname":
case "timezonerule":
case "topic":
case "topichistory":
case "topicmodelconfiguration":
case "topicmodelexecutionhistory":
case "tracelog":
case "transformationparametermapping":
case "uom":
case "userentityinstancedata":
case "userentityuisettings":
case "userform":
case "usermapping":
case "userqueryvisualization":
case "usersettings":
case "webresource":
case "workflowdependency":
case "workflowlog":
#endregion Default CRM Entites with no active flag
ActiveAttribute = ActiveAttributeType.None;
break;
default:
if (logicalName.Length > 4 && logicalName[3] == '_')
{
var prefix = logicalName.ToLower().Substring(0, 3);
if (logicalName.ToLower().Split(new [] { prefix }, StringSplitOptions.None).Length >= 3 || logicalName.ToLower().EndsWith("_association"))
{
// N:N Joins or association entities do not contain active flags
ActiveAttribute = ActiveAttributeType.None;
break;
}
}
SetStateAttributesAndValue(logicalName);
break;
}
}
/// <summary>
/// Sets the state attributes and value.
/// </summary>
/// <param name="logicalName">Name of the logical.</param>
protected void SetStateAttributesAndValue(string logicalName)
{
ActiveAttribute = ActiveAttributeType.StateCode;
AttributeName = "statecode";
switch (logicalName)
{
// Entities with a Canceled State
case "activitypointer":
case "appointment":
case "bulkoperation":
case "campaignactivity":
case "contractdetail":
case "email":
case "fax":
case "letter":
case "orderclose":
case "phonecall":
case "quoteclose":
case "recurringappointmentmaster":
case "serviceappointment":
case "taskstate":
NotActiveState = 2;
break;
case "duplicaterule": // don't ask me why, but this one is flipped
ActiveState = 1;
NotActiveState = 0;
break;
// Entities with states that can't be grouped into separate all inclusive active and inactive states
case "asyncoperation":
case "bulkdeleteoperation":
case "contract":
case "lead":
case "opportunity":
case "processsession":
case "quote":
case "sdkmessageprocessingstep":
case "workflow":
ActiveAttribute = ActiveAttributeType.None;
break;
default:
if (IsJoinEntity(logicalName))
{
ActiveAttribute = ActiveAttributeType.None;
}
else
{
ActiveState = 0;
NotActiveState = 1;
}
break;
}
}
/// <summary>
/// Determines whether [is join entity] [the specified logical name].
/// </summary>
/// <param name="logicalName">Name of the logical.</param>
/// <returns></returns>
private bool IsJoinEntity(string logicalName)
{
// Entities of the type new_Foo_Bar are usually Join Entities that don't have a state
return logicalName.Split('_').Length >= 3;
}
/// <summary>
/// Determines whether the specified service is active.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="entityId">The entity identifier.</param>
/// <returns></returns>
public static bool? IsActive(IOrganizationService service, Guid entityId)
{
var info = new ActivePropertyInfo<T>();
var entity = service.GetEntity<T>(entityId, new ColumnSet(info.AttributeName));
return IsActive(info, entity);
}
/// <summary>
/// Determines whether the specified information is active.
/// </summary>
/// <param name="info">The information.</param>
/// <param name="entity">The entity.</param>
/// <returns></returns>
/// <exception cref="System.Exception">ActivePropertyInfo defines Attribute StateCode, but neither ActiveState or NotActiveState is popualted</exception>
/// <exception cref="EnumCaseUndefinedException{ActiveAttributeType}"></exception>
protected static bool? IsActive(ActivePropertyInfo<T> info, T entity)
{
bool? active;
switch (info.ActiveAttribute)
{
case ActiveAttributeType.None:
// Unable to determine
active = null;
break;
case ActiveAttributeType.IsDisabled:
active = !entity.GetAttributeValue<bool>(info.AttributeName);
break;
case ActiveAttributeType.StateCode:
var state = entity.GetAttributeValue<OptionSetValue>(info.AttributeName).Value;
if (info.ActiveState.HasValue)
{
active = state == info.ActiveState;
}
else if (info.NotActiveState.HasValue)
{
active = state != info.NotActiveState;
}
else
{
throw new Exception("ActivePropertyInfo defines Attribute StateCode, but neither ActiveState or NotActiveState is popualted");
}
break;
default:
throw new EnumCaseUndefinedException<ActiveAttributeType>(info.ActiveAttribute);
}
return active;
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 450157 $
* $LastChangedDate: 2006-10-30 20:09:11 +0100 (lun., 30 oct. 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System;
namespace IBatisNet.DataMapper.Configuration.ResultMapping
{
/// <summary>
/// Collection of <see cref="IResultMap"/>
/// </summary>
public class ResultMapCollection
{
private const int DEFAULT_CAPACITY = 2;
private const int CAPACITY_MULTIPLIER = 2;
private int _count = 0;
private IResultMap[] _innerList = null;
/// <summary>
/// Read-only property describing how many elements are in the Collection.
/// </summary>
public int Count
{
get { return _count; }
}
/// <summary>
/// Constructs a ResultMapCollection. The list is initially empty and has a capacity
/// of zero. Upon adding the first element to the list the capacity is
/// increased to 8, and then increased in multiples of two as required.
/// </summary>
public ResultMapCollection()
{
this.Clear();
}
/// <summary>
/// Removes all items from the collection.
/// </summary>
public void Clear()
{
_innerList = new IResultMap[DEFAULT_CAPACITY];
_count = 0;
}
/// <summary>
/// Constructs a ResultMapCollection with a given initial capacity.
/// The list is initially empty, but will have room for the given number of elements
/// before any reallocations are required.
/// </summary>
/// <param name="capacity">The initial capacity of the list</param>
public ResultMapCollection(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException("Capacity", "The size of the list must be >0.");
}
_innerList = new IResultMap[capacity];
}
/// <summary>
/// Length of the collection
/// </summary>
public int Length
{
get { return _innerList.Length; }
}
/// <summary>
/// Sets or Gets the ResultMap at the given index.
/// </summary>
public IResultMap this[int index]
{
get
{
if (index < 0 || index >= _count)
{
throw new ArgumentOutOfRangeException("index");
}
return _innerList[index];
}
set
{
if (index < 0 || index >= _count)
{
throw new ArgumentOutOfRangeException("index");
}
_innerList[index] = value;
}
}
/// <summary>
/// Add an ResultMap
/// </summary>
/// <param name="value"></param>
/// <returns>Index</returns>
public int Add(IResultMap value)
{
Resize(_count + 1);
int index = _count++;
_innerList[index] = value;
return index;
}
/// <summary>
/// Add a list of ResultMap to the collection
/// </summary>
/// <param name="value"></param>
public void AddRange(IResultMap[] value)
{
for (int i = 0; i < value.Length; i++)
{
Add(value[i]);
}
}
/// <summary>
/// Add a list of ResultMap to the collection
/// </summary>
/// <param name="value"></param>
public void AddRange(ResultMapCollection value)
{
for (int i = 0; i < value.Count; i++)
{
Add(value[i]);
}
}
/// <summary>
/// Indicate if a ResultMap is in the collection
/// </summary>
/// <param name="value">A ResultMap</param>
/// <returns>True fi is in</returns>
public bool Contains(IResultMap value)
{
for (int i = 0; i < _count; i++)
{
if (_innerList[i].Id == value.Id)
{
return true;
}
}
return false;
}
/// <summary>
/// Insert a ResultMap in the collection.
/// </summary>
/// <param name="index">Index where to insert.</param>
/// <param name="value">A ResultMap</param>
public void Insert(int index, IResultMap value)
{
if (index < 0 || index > _count)
{
throw new ArgumentOutOfRangeException("index");
}
Resize(_count + 1);
Array.Copy(_innerList, index, _innerList, index + 1, _count - index);
_innerList[index] = value;
_count++;
}
/// <summary>
/// Remove a ResultMap of the collection.
/// </summary>
public void Remove(IResultMap value)
{
for (int i = 0; i < _count; i++)
{
if (_innerList[i].Id == value.Id)
{
RemoveAt(i);
return;
}
}
}
/// <summary>
/// Removes a ResultMap at the given index. The size of the list is
/// decreased by one.
/// </summary>
/// <param name="index"></param>
public void RemoveAt(int index)
{
if (index < 0 || index >= _count)
{
throw new ArgumentOutOfRangeException("index");
}
int remaining = _count - index - 1;
if (remaining > 0)
{
Array.Copy(_innerList, index + 1, _innerList, index, remaining);
}
_count--;
_innerList[_count] = null;
}
/// <summary>
/// Ensures that the capacity of this collection is at least the given minimum
/// value. If the currect capacity of the list is less than min, the
/// capacity is increased to twice the current capacity.
/// </summary>
/// <param name="minSize"></param>
private void Resize(int minSize)
{
int oldSize = _innerList.Length;
if (minSize > oldSize)
{
IResultMap[] oldEntries = _innerList;
int newSize = oldEntries.Length * CAPACITY_MULTIPLIER;
if (newSize < minSize)
{
newSize = minSize;
}
_innerList = new IResultMap[newSize];
Array.Copy(oldEntries, 0, _innerList, 0, _count);
}
}
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.Collections.Generic;
using System.Globalization;
using Perspex;
using Perspex.Media;
using TheArtOfDev.HtmlRenderer.Adapters;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using TheArtOfDev.HtmlRenderer.Core.Utils;
using TheArtOfDev.HtmlRenderer.Perspex.Utilities;
namespace TheArtOfDev.HtmlRenderer.Perspex.Adapters
{
/// <summary>
/// Adapter for Perspex Graphics.
/// </summary>
internal sealed class GraphicsAdapter : RGraphics
{
#region Fields and Consts
/// <summary>
/// The wrapped Perspex graphics object
/// </summary>
private readonly IDrawingContext _g;
/// <summary>
/// if to release the graphics object on dispose
/// </summary>
private readonly bool _releaseGraphics;
#endregion
private Stack<IDisposable> _clipStack = new Stack<IDisposable>();
/// <summary>
/// Init.
/// </summary>
/// <param name="g">the Perspex graphics object to use</param>
/// <param name="initialClip">the initial clip of the graphics</param>
/// <param name="releaseGraphics">optional: if to release the graphics object on dispose (default - false)</param>
public GraphicsAdapter(IDrawingContext g, RRect initialClip, bool releaseGraphics = false)
: base(PerspexAdapter.Instance, initialClip)
{
ArgChecker.AssertArgNotNull(g, "g");
_g = g;
_releaseGraphics = releaseGraphics;
}
/// <summary>
/// Init.
/// </summary>
public GraphicsAdapter()
: base(PerspexAdapter.Instance, RRect.Empty)
{
_g = null;
_releaseGraphics = false;
}
public override void PopClip()
{
_clipStack.Pop()?.Dispose();
}
public override void PushClip(RRect rect)
{
_clipStack.Push(_g.PushClip(Util.Convert(rect)));
//_clipStack.Push(rect);
//_g.PushClip(new RectangleGeometry(Utils.Convert(rect)));
}
public override void PushClipExclude(RRect rect)
{
_clipStack.Push(null);
//TODO: Implement exclude rect, see #128
//var geometry = new CombinedGeometry();
//geometry.Geometry1 = new RectangleGeometry(Utils.Convert(_clipStack.Peek()));
//geometry.Geometry2 = new RectangleGeometry(Utils.Convert(rect));
//geometry.GeometryCombineMode = GeometryCombineMode.Exclude;
//_clipStack.Push(_clipStack.Peek());
//_g.PushClip(geometry);
}
public override Object SetAntiAliasSmoothingMode()
{
return null;
}
public override void ReturnPreviousSmoothingMode(Object prevMode)
{ }
public override RSize MeasureString(string str, RFont font)
{
var text = GetText(str, font);
var measure = text.Measure();
return new RSize(measure.Width, measure.Height);
}
FormattedText GetText(string str, RFont font)
{
var f = ((FontAdapter)font);
return new FormattedText(str, f.Name, font.Size, f.FontStyle, TextAlignment.Left, f.Weight);
}
public override void MeasureString(string str, RFont font, double maxWidth, out int charFit, out double charFitWidth)
{
var text = GetText(str, font);
var fullLength = text.Measure().Width;
if (fullLength < maxWidth)
{
charFitWidth = fullLength;
charFit = str.Length;
return;
}
int lastLen = 0;
double lastMeasure = 0;
BinarySearch(len =>
{
text = GetText(str.Substring(0, len), font);
var size = text.Measure().Width;
lastMeasure = size;
lastLen = len;
if (size <= maxWidth)
return -1;
return 1;
}, 0, str.Length);
if (lastMeasure > maxWidth)
{
lastLen--;
lastMeasure = GetText(str.Substring(0, lastLen), font).Measure().Width;
}
charFit = lastLen;
charFitWidth = lastMeasure;
}
private static int BinarySearch(Func<int, int> condition, int start, int end)
{
do
{
int ind = start + (end - start)/2;
int res = condition(ind);
if (res == 0)
return ind;
else if (res > 0)
{
if (start != ind)
start = ind;
else
start = ind + 1;
}
else
end = ind;
} while (end > start);
return -1;
}
public override void DrawString(string str, RFont font, RColor color, RPoint point, RSize size, bool rtl)
{
var text = GetText(str, font);
text.Constraint = Util.Convert(size);
_g.DrawText(new SolidColorBrush(Util.Convert(color)), Util.Convert(point), text);
}
public override RBrush GetTextureBrush(RImage image, RRect dstRect, RPoint translateTransformLocation)
{
//TODO: Implement texture brush
return PerspexAdapter.Instance.GetSolidBrush(Util.Convert(Colors.Magenta));
//var brush = new ImageBrush(((ImageAdapter)image).Image);
//brush.Stretch = Stretch.None;
//brush.TileMode = TileMode.Tile;
//brush.Viewport = Utils.Convert(dstRect);
//brush.ViewportUnits = BrushMappingMode.Absolute;
//brush.Transform = new TranslateTransform(translateTransformLocation.X, translateTransformLocation.Y);
//brush.Freeze();
//return new BrushAdapter(brush);
}
public override RGraphicsPath GetGraphicsPath()
{
return new GraphicsPathAdapter();
}
public override void Dispose()
{
while (_clipStack.Count != 0)
PopClip();
if (_releaseGraphics)
_g.Dispose();
}
#region Delegate graphics methods
public override void DrawLine(RPen pen, double x1, double y1, double x2, double y2)
{
x1 = (int)x1;
x2 = (int)x2;
y1 = (int)y1;
y2 = (int)y2;
var adj = pen.Width;
if (Math.Abs(x1 - x2) < .1 && Math.Abs(adj % 2 - 1) < .1)
{
x1 += .5;
x2 += .5;
}
if (Math.Abs(y1 - y2) < .1 && Math.Abs(adj % 2 - 1) < .1)
{
y1 += .5;
y2 += .5;
}
_g.DrawLine(((PenAdapter)pen).CreatePen(), new Point(x1, y1), new Point(x2, y2));
}
public override void DrawRectangle(RPen pen, double x, double y, double width, double height)
{
var adj = pen.Width;
if (Math.Abs(adj % 2 - 1) < .1)
{
x += .5;
y += .5;
}
_g.DrawRectange(((PenAdapter) pen).CreatePen(), new Rect(x, y, width, height));
}
public override void DrawRectangle(RBrush brush, double x, double y, double width, double height)
{
_g.FillRectange(((BrushAdapter) brush).Brush, new Rect(x, y, width, height));
}
public override void DrawImage(RImage image, RRect destRect, RRect srcRect)
{
_g.DrawImage(((ImageAdapter) image).Image, 1, Util.Convert(srcRect), Util.Convert(destRect));
}
public override void DrawImage(RImage image, RRect destRect)
{
_g.DrawImage(((ImageAdapter) image).Image, 1, new Rect(0, 0, image.Width, image.Height),
Util.Convert(destRect));
}
public override void DrawPath(RPen pen, RGraphicsPath path)
{
_g.DrawGeometry(null, ((PenAdapter)pen).CreatePen(), ((GraphicsPathAdapter)path).GetClosedGeometry());
}
public override void DrawPath(RBrush brush, RGraphicsPath path)
{
_g.DrawGeometry(((BrushAdapter)brush).Brush, null, ((GraphicsPathAdapter)path).GetClosedGeometry());
}
public override void DrawPolygon(RBrush brush, RPoint[] points)
{
if (points != null && points.Length > 0)
{
var g = new StreamGeometry();
using (var context = g.Open())
{
context.BeginFigure(Util.Convert(points[0]), true);
for (int i = 1; i < points.Length; i++)
context.LineTo(Util.Convert(points[i]));
context.EndFigure(false);
}
_g.DrawGeometry(((BrushAdapter)brush).Brush, null, g);
}
}
#endregion
}
}
| |
using NSubstitute;
using OpenKh.Engine;
using System;
using System.Numerics;
using Xunit;
namespace OpenKh.Tests.Engine
{
public class CameraTests
{
[Theory]
[InlineData(512f, 384f, 1.5f, 1.073426127f, 1.431234717f)]
[InlineData(512f, 384f, 1.047197461f, 1.7320510149002075f, 2.309401512f)]
[InlineData(512f, 288f, 1.5f, 0.805069625377655f, 1.431234717f)]
[InlineData(512f, 288f, 1.047197461f, 1.299038291f, 2.309401512f)]
[InlineData(640f, 480f, 1.5f, 1.073426127f, 1.431234717f)]
[InlineData(1920f, 1080f, 1.047197461f, 1.299038291f, 2.309401512f)]
public void SetProjectionMatrixTest(
float width, float height, float fov,
float expectedM11, float expectedM22)
{
var camera = new Camera();
camera.AspectRatio = width / height;
camera.FieldOfView = fov;
AssertMatrix(new Matrix4x4(
expectedM11, 0, 0, 0,
0, expectedM22, 0f, 0,
0, 0f, -1f, -1f,
0, 0, -1f, 0
), camera.Projection);
}
[Fact]
public void SetWorldMatrixTest()
{
var camera = new Camera();
camera.CameraPosition = new Vector3(0f, 251.1999969f, -920f);
camera.CameraLookAt = new Vector3(0f, 170f, -500f);
camera.CameraUp = new Vector3(0f, 1f, 0f);
AssertMatrix(new Matrix4x4(
-1, 0, 0, 0,
0, 0.9818192f, 0.189818367f, 0,
0, 0.189818367f, -0.9818192f, 0,
0, -72.00009f, -950.956f, 1
), camera.World);
}
[Theory]
[InlineData(0f, 0f, 0f, 520f, -500f)]
[InlineData(420f, 0f, 0f, 251.19999f, -920f)]
[InlineData(420f, 1f, -353.4177246f, 251.199997f, -726.927002f)]
public void TargetCameraSetsPositionTest(
float radius, float yRotation,
float expectedX, float expectedY, float expectedZ)
{
var entity = Substitute.For<IEntity>();
entity.Position.ReturnsForAnyArgs(new Vector3(0f, 0f, -500f));
var camera = new Camera();
var targetCamera = new TargetCamera(camera)
{
Type = 0,
Radius = radius,
YRotation = yRotation,
BackYRotation = yRotation,
Interpolate = false,
};
targetCamera.Update(entity, 0);
var expected = new Vector3(expectedX, expectedY, expectedZ);
AssertVector3(expected, camera.CameraPosition);
}
[Fact]
public void TargetCameraSetCorrectValuesToCamera()
{
var entity = Substitute.For<IEntity>();
entity.Position.ReturnsForAnyArgs(new Vector3(0f, 150f, 0f));
var camera = new Camera();
var targetCamera = new TargetCamera(camera)
{
Type = 0,
Radius = 420f,
YRotation = 0f,
BackYRotation = 0f,
Interpolate = false,
};
targetCamera.Update(entity, 0);
var expectedPosition = new Vector3(0f, 401.2f, -420);
var expectedLookAt = new Vector3(0f, 320f, 0f);
AssertVector3(expectedPosition, camera.CameraPosition);
AssertVector3(expectedLookAt, camera.CameraLookAt);
}
[Theory]
[InlineData(Math.PI, Math.PI)]
[InlineData(0, 0)]
[InlineData(-Math.PI, Math.PI)]
[InlineData(1, -1)]
[InlineData(4, 2.2831852436065674f)]
public void TargetCameraRotatesInstantlyOnEntity(
float entityRotation, float expected)
{
var entity = Substitute.For<IEntity>();
entity.Rotation.ReturnsForAnyArgs(new Vector3(0f, entityRotation, 0f));
var camera = new Camera();
var targetCamera = new TargetCamera(camera)
{
Type = 0,
Radius = 420f,
YRotation = 0f,
BackYRotation = 0f,
Interpolate = false
};
targetCamera.InstantlyRotateCameraToEntity(entity);
targetCamera.Update(entity, 0);
Assert.Equal(expected, targetCamera.YRotation, 4);
}
[Theory]
[InlineData(100f, 200f, 100f, 0)]
[InlineData(100f, 200f, 124.7499924f, 1)]
[InlineData(100f, 200f, 143.3124847f, 2)]
[InlineData(100f, 200f, 157.2343445f, 3)]
[InlineData(100f, 200f, 167.6757507f, 4)]
[InlineData(100f, 200f, 175.5068054f, 5)]
[InlineData(100f, 200f, 181.3800964f, 6)]
[InlineData(100f, 200f, 185.7850647f, 7)]
[InlineData(100f, 200f, 189.0887909f, 8)]
[InlineData(100f, 200f, 191.5665894f, 9)]
[InlineData(100f, 200f, 193.4249268f, 10)]
[InlineData(100f, 200f, 194.8186798f, 11)]
[InlineData(100f, 200f, 195.8639984f, 12)]
[InlineData(100f, 200f, 196.6479950f, 13)]
public void TargetCameraInterpolatesCorrectly(
float src, float dst, float expected, int frameIndex)
{
var entity = Substitute.For<IEntity>();
entity.Position.ReturnsForAnyArgs(new Vector3(dst, -170f, -500f));
var camera = new Camera();
var targetCamera = new TargetCamera(camera)
{
Type = 0,
Radius = 420f,
YRotation = 0f,
BackYRotation = 0f,
At = new Vector4(src, 0f, 500f, 1f),
AtTargetPrev = new Vector4(dst, 0f, 500f, 1f),
};
const double DeltaTime = 1.0 / 30.0;
while (frameIndex-- > 0)
targetCamera.Update(entity, DeltaTime);
Assert.Equal(expected, targetCamera.At.X, 3);
}
[Fact]
public void TargetCameraInterpolatesCorrectlyEdgeCase()
{
var entity = Substitute.For<IEntity>();
entity.Position.ReturnsForAnyArgs(new Vector3(200, 300f, -400f));
var camera = new Camera();
var targetCamera = new TargetCamera(camera)
{
Type = 0,
Radius = 420f,
YRotation = 0f,
BackYRotation = 0f,
At = new Vector4(100f, 300f, 500f, 1f),
AtTarget = new Vector4(200f, -470f, 500f, 1f),
AtTargetPrev = new Vector4(98f, -468f, 502f, 1f),
};
const int FrameCount = 10;
const double DeltaTime = 1.0 / 30.0;
for (var frame = 0; frame < FrameCount; frame++)
targetCamera.Update(entity, DeltaTime);
var expected = new Vector4(194.24677f, -425.70007f, 405.75323f, 1);
Assert.Equal(expected, targetCamera.At);
}
private void AssertVector3(Vector3 expected, Vector3 actual)
{
const int Precision = 3;
Assert.Equal(expected.X, actual.X, Precision);
Assert.Equal(expected.Y, actual.Y, Precision);
Assert.Equal(expected.Z, actual.Z, Precision);
}
private void AssertMatrix(Matrix4x4 expected, Matrix4x4 actual)
{
const int Precision = 3;
Assert.Equal(expected.M11, actual.M11, Precision);
Assert.Equal(expected.M12, actual.M12, Precision);
Assert.Equal(expected.M13, actual.M13, Precision);
Assert.Equal(expected.M14, actual.M14, Precision);
Assert.Equal(expected.M21, actual.M21, Precision);
Assert.Equal(expected.M22, actual.M22, Precision);
Assert.Equal(expected.M23, actual.M23, Precision);
Assert.Equal(expected.M24, actual.M24, Precision);
Assert.Equal(expected.M31, actual.M31, Precision);
Assert.Equal(expected.M32, actual.M32, Precision);
Assert.Equal(expected.M33, actual.M33, Precision);
Assert.Equal(expected.M34, actual.M34, Precision);
Assert.Equal(expected.M41, actual.M41, Precision);
Assert.Equal(expected.M42, actual.M42, Precision);
Assert.Equal(expected.M43, actual.M43, Precision);
Assert.Equal(expected.M44, actual.M44, Precision);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
namespace ProjectEuler
{
public struct Fraction : IEquatable<Fraction>, IComparable<Fraction>
{
long _numerator;
public long Numerator
{
get { return _numerator; }
private set { _numerator = value; }
}
long _denominator;
public long Denominator
{
get { return _denominator == 0 ? 1 : _denominator; }
private set
{
if (value == 0)
throw new InvalidOperationException("Denominator cannot be assigned a 0 Value.");
_denominator = value;
}
}
public Fraction(long value)
{
_numerator = value;
_denominator = 1;
Reduce();
}
public Fraction(long numerator, long denominator)
{
if (denominator == 0)
throw new InvalidOperationException("Denominator cannot be assigned a 0 Value.");
_numerator = numerator;
_denominator = denominator;
Reduce();
}
private void Reduce()
{
try
{
if (Numerator == 0)
{
Denominator = 1;
return;
}
long iGCD = GCD(Numerator, Denominator);
Numerator /= iGCD;
Denominator /= iGCD;
if (Denominator < 0)
{
Numerator *= -1;
Denominator *= -1;
}
}
catch (Exception exp)
{
throw new InvalidOperationException("Cannot reduce Fraction: " + exp.Message);
}
}
public bool Equals(Fraction other)
{
if (other == null)
return false;
return (Numerator == other.Numerator && Denominator == other.Denominator);
}
public override bool Equals(object obj)
{
if (obj == null || !(obj is Fraction))
return false;
return Equals((Fraction)obj);
}
public int CompareTo(Fraction other)
{
if (other == null)
return -1;
return this == other ? 0 : this > other ? 1 : -1;
}
public int CompareTo(object obj)
{
if (obj == null || !(obj is Fraction))
return -1;
return CompareTo((Fraction)obj);
}
public override int GetHashCode()
{
return Convert.ToInt32((Numerator ^ Denominator) & 0xFFFFFFFF);
}
public override string ToString()
{
if (this.Denominator == 1)
return this.Numerator.ToString();
var sb = new System.Text.StringBuilder();
sb.Append(this.Numerator);
sb.Append('/');
sb.Append(this.Denominator);
return sb.ToString();
}
public static Fraction Parse(string strValue)
{
int i = strValue.IndexOf('/');
if (i == -1)
return DecimalToFraction(Convert.ToDecimal(strValue));
long iNumerator = Convert.ToInt64(strValue.Substring(0, i));
long iDenominator = Convert.ToInt64(strValue.Substring(i + 1));
return new Fraction(iNumerator, iDenominator);
}
public static bool TryParse(string strValue, out Fraction fraction)
{
if (!string.IsNullOrWhiteSpace(strValue))
{
try
{
int i = strValue.IndexOf('/');
if (i == -1)
{
decimal dValue;
if (decimal.TryParse(strValue, out dValue))
{
fraction = DecimalToFraction(dValue);
return true;
}
}
else
{
long iNumerator, iDenominator;
if (long.TryParse(strValue.Substring(0, i), out iNumerator) && long.TryParse(strValue.Substring(i + 1), out iDenominator))
{
fraction = new Fraction(iNumerator, iDenominator);
return true;
}
}
}
catch { }
}
fraction = new Fraction();
return false;
}
private static Fraction DoubleToFraction(double dValue)
{
char separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
try
{
checked
{
Fraction frac;
if (dValue % 1 == 0) // if whole number
{
frac = new Fraction((long)dValue);
}
else
{
double dTemp = dValue;
long iMultiple = 1;
string strTemp = dValue.ToString();
while (strTemp.IndexOf("E") > 0) // if in the form like 12E-9
{
dTemp *= 10;
iMultiple *= 10;
strTemp = dTemp.ToString();
}
int i = 0;
while (strTemp[i] != separator)
i++;
int iDigitsAfterDecimal = strTemp.Length - i - 1;
while (iDigitsAfterDecimal > 0)
{
dTemp *= 10;
iMultiple *= 10;
iDigitsAfterDecimal--;
}
frac = new Fraction((int)Math.Round(dTemp), iMultiple);
}
return frac;
}
}
catch (OverflowException e)
{
throw new InvalidCastException("Conversion to Fraction in no possible due to overflow.", e);
}
catch (Exception e)
{
throw new InvalidCastException("Conversion to Fraction in not possible.", e);
}
}
private static Fraction DecimalToFraction(decimal dValue)
{
char separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
try
{
checked
{
Fraction frac;
if (dValue % 1 == 0) // if whole number
{
frac = new Fraction((long)dValue);
}
else
{
decimal dTemp = dValue;
long iMultiple = 1;
string strTemp = dValue.ToString();
while (strTemp.IndexOf("E") > 0) // if in the form like 12E-9
{
dTemp *= 10;
iMultiple *= 10;
strTemp = dTemp.ToString();
}
int i = 0;
while (strTemp[i] != separator)
i++;
int iDigitsAfterDecimal = strTemp.Length - i - 1;
while (iDigitsAfterDecimal > 0)
{
dTemp *= 10;
iMultiple *= 10;
iDigitsAfterDecimal--;
}
frac = new Fraction((int)Math.Round(dTemp), iMultiple);
}
return frac;
}
}
catch (OverflowException e)
{
throw new InvalidCastException("Conversion to Fraction in no possible due to overflow.", e);
}
catch (Exception e)
{
throw new InvalidCastException("Conversion to Fraction in not possible.", e);
}
}
private static Fraction Inverse(Fraction frac1)
{
if (frac1.Numerator == 0)
throw new InvalidOperationException("Operation not possible (Denominator cannot be assigned a ZERO Value)");
long iNumerator = frac1.Denominator;
long iDenominator = frac1.Numerator;
return new Fraction(iNumerator, iDenominator);
}
private static Fraction Negate(Fraction frac1)
{
long iNumerator = -frac1.Numerator;
long iDenominator = frac1.Denominator;
return new Fraction(iNumerator, iDenominator);
}
private static Fraction Add(Fraction frac1, Fraction frac2)
{
try
{
checked
{
long iNumerator = frac1.Numerator * frac2.Denominator + frac2.Numerator * frac1.Denominator;
long iDenominator = frac1.Denominator * frac2.Denominator;
return new Fraction(iNumerator, iDenominator);
}
}
catch (OverflowException e)
{
throw new OverflowException("Overflow occurred while performing arithemetic operation on Fraction.", e);
}
catch (Exception e)
{
throw new Exception("An error occurred while performing arithemetic operation on Fraction.", e);
}
}
private static Fraction Multiply(Fraction frac1, Fraction frac2)
{
try
{
checked
{
long iNumerator = frac1.Numerator * frac2.Numerator;
long iDenominator = frac1.Denominator * frac2.Denominator;
return new Fraction(iNumerator, iDenominator);
}
}
catch (OverflowException e)
{
throw new OverflowException("Overflow occurred while performing arithemetic operation on Fraction.", e);
}
catch (Exception e)
{
throw new Exception("An error occurred while performing arithemetic operation on Fraction.", e);
}
}
public static long GCD(long iNo1, long iNo2)
{
if (iNo1 < 0) iNo1 = -iNo1;
if (iNo2 < 0) iNo2 = -iNo2;
do
{
if (iNo1 < iNo2)
{
long tmp = iNo1;
iNo1 = iNo2;
iNo2 = tmp;
}
iNo1 = iNo1 % iNo2;
}
while (iNo1 != 0);
return iNo2;
}
public static Fraction operator -(Fraction frac1) { return (Negate(frac1)); }
public static Fraction operator +(Fraction frac1, Fraction frac2) { return (Add(frac1, frac2)); }
public static Fraction operator -(Fraction frac1, Fraction frac2) { return (Add(frac1, -frac2)); }
public static Fraction operator *(Fraction frac1, Fraction frac2) { return (Multiply(frac1, frac2)); }
public static Fraction operator /(Fraction frac1, Fraction frac2) { return (Multiply(frac1, Inverse(frac2))); }
public static bool operator ==(Fraction frac1, Fraction frac2) { return frac1.Equals(frac2); }
public static bool operator !=(Fraction frac1, Fraction frac2) { return (!frac1.Equals(frac2)); }
public static bool operator <(Fraction frac1, Fraction frac2) { return frac1.Numerator * frac2.Denominator < frac2.Numerator * frac1.Denominator; }
public static bool operator >(Fraction frac1, Fraction frac2) { return frac1.Numerator * frac2.Denominator > frac2.Numerator * frac1.Denominator; }
public static bool operator <=(Fraction frac1, Fraction frac2) { return frac1.Numerator * frac2.Denominator <= frac2.Numerator * frac1.Denominator; }
public static bool operator >=(Fraction frac1, Fraction frac2) { return frac1.Numerator * frac2.Denominator >= frac2.Numerator * frac1.Denominator; }
public static implicit operator Fraction(long value) { return new Fraction(value); }
public static implicit operator Fraction(double value) { return DoubleToFraction(value); }
public static implicit operator Fraction(decimal value) { return DecimalToFraction(value); }
public static explicit operator double(Fraction frac)
{
return (double)(frac.Numerator / frac.Denominator);
}
public static explicit operator decimal(Fraction frac)
{
return ((decimal)frac.Numerator / (decimal)frac.Denominator);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
public static partial class VirtualMachineScaleSetVMsOperationsExtensions
{
/// <summary>
/// The operation to re-image a virtual machine scale set instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static void Reimage(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).ReimageAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to re-image a virtual machine scale set instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ReimageAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.ReimageWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to re-image a virtual machine scale set instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static void BeginReimage(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).BeginReimageAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to re-image a virtual machine scale set instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginReimageAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginReimageWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to deallocate a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static void Deallocate(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).DeallocateAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to deallocate a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeallocateAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeallocateWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to deallocate a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static void BeginDeallocate(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).BeginDeallocateAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to deallocate a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeallocateAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeallocateWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to delete a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static void Delete(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).DeleteAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to delete a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to delete a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static void BeginDelete(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).BeginDeleteAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to delete a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to get a virtual machine scale set virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static VirtualMachineScaleSetVM Get(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
return Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).GetAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to get a virtual machine scale set virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachineScaleSetVM> GetAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// The operation to get a virtual machine scale set virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static VirtualMachineScaleSetVMInstanceView GetInstanceView(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
return Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).GetInstanceViewAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to get a virtual machine scale set virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachineScaleSetVMInstanceView> GetInstanceViewAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.GetInstanceViewWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// The operation to list virtual machine scale sets VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// The list parameters.
/// </param>
public static IPage<VirtualMachineScaleSetVM> List(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string virtualMachineScaleSetName, ODataQuery<VirtualMachineScaleSetVM> odataQuery = default(ODataQuery<VirtualMachineScaleSetVM>), string select = default(string))
{
return Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).ListAsync(resourceGroupName, virtualMachineScaleSetName, odataQuery, select), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to list virtual machine scale sets VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// The list parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachineScaleSetVM>> ListAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string virtualMachineScaleSetName, ODataQuery<VirtualMachineScaleSetVM> odataQuery = default(ODataQuery<VirtualMachineScaleSetVM>), string select = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, odataQuery, select, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// The operation to power off (stop) a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static void PowerOff(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).PowerOffAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to power off (stop) a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PowerOffAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PowerOffWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to power off (stop) a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static void BeginPowerOff(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).BeginPowerOffAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to power off (stop) a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginPowerOffAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginPowerOffWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to restart a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static void Restart(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).RestartAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to restart a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task RestartAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.RestartWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to restart a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static void BeginRestart(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).BeginRestartAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to restart a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginRestartAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginRestartWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to start a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static void Start(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).StartAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to start a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task StartAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.StartWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to start a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
public static void BeginStart(this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId)
{
Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).BeginStartAsync(resourceGroupName, vmScaleSetName, instanceId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to start a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='instanceId'>
/// The instance id of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginStartAsync( this IVirtualMachineScaleSetVMsOperations operations, string resourceGroupName, string vmScaleSetName, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginStartWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to list virtual machine scale sets VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<VirtualMachineScaleSetVM> ListNext(this IVirtualMachineScaleSetVMsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IVirtualMachineScaleSetVMsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to list virtual machine scale sets VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachineScaleSetVM>> ListNextAsync( this IVirtualMachineScaleSetVMsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Static;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using NUnit.Framework;
/// <summary>
/// Test utility methods.
/// </summary>
public static partial class TestUtils
{
/** Indicates long running and/or memory/cpu intensive test. */
public const string CategoryIntensive = "LONG_TEST";
/** Indicates examples tests. */
public const string CategoryExamples = "EXAMPLES_TEST";
/** */
private const int DfltBusywaitSleepInterval = 200;
/** Work dir. */
private static readonly string WorkDir =
// ReSharper disable once AssignNullToNotNullAttribute
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ignite_work");
/** */
private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess
? new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms1g",
"-Xmx4g",
"-ea",
"-DIGNITE_QUIET=true",
"-Duser.timezone=UTC"
}
: new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms64m",
"-Xmx99m",
"-ea",
"-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000",
"-DIGNITE_QUIET=true",
"-Duser.timezone=UTC"
};
/** */
private static readonly IList<string> JvmDebugOpts =
new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", "-DIGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP=false" };
/** */
public static bool JvmDebug = true;
/** */
[ThreadStatic]
private static Random _random;
/** */
private static int _seed = Environment.TickCount;
/// <summary>
///
/// </summary>
public static Random Random
{
get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IList<string> TestJavaOptions(bool? jvmDebug = null)
{
IList<string> ops = new List<string>(TestJvmOpts);
if (jvmDebug ?? JvmDebug)
{
foreach (string opt in JvmDebugOpts)
ops.Add(opt);
}
return ops;
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
public static void RunMultiThreaded(Action action, int threadNum)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
action();
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
/// <param name="duration">Duration of test execution in seconds</param>
public static void RunMultiThreaded(Action action, int threadNum, int duration)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
bool stop = false;
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
while (true)
{
Thread.MemoryBarrier();
// ReSharper disable once AccessToModifiedClosure
if (stop)
break;
action();
}
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
Thread.Sleep(duration * 1000);
stop = true;
Thread.MemoryBarrier();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
/// Wait for particular topology size.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="size">Size.</param>
/// <param name="timeout">Timeout.</param>
/// <returns>
/// <c>True</c> if topology took required size.
/// </returns>
public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000)
{
int left = timeout;
while (true)
{
if (grid.GetCluster().GetNodes().Count != size)
{
if (left > 0)
{
Thread.Sleep(100);
left -= 100;
}
else
break;
}
else
return true;
}
return false;
}
/// <summary>
/// Waits for condition, polling in busy wait loop.
/// </summary>
/// <param name="cond">Condition.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <returns>True if condition predicate returned true within interval; false otherwise.</returns>
public static bool WaitForCondition(Func<bool> cond, int timeout)
{
if (timeout <= 0)
return cond();
var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval);
while (DateTime.Now < maxTime)
{
if (cond())
return true;
Thread.Sleep(DfltBusywaitSleepInterval);
}
return false;
}
/// <summary>
/// Gets the static discovery.
/// </summary>
public static TcpDiscoverySpi GetStaticDiscovery()
{
return new TcpDiscoverySpi
{
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] { "127.0.0.1:47500" }
},
SocketTimeout = TimeSpan.FromSeconds(0.3)
};
}
/// <summary>
/// Gets the primary keys.
/// </summary>
public static IEnumerable<int> GetPrimaryKeys(IIgnite ignite, string cacheName,
IClusterNode node = null)
{
var aff = ignite.GetAffinity(cacheName);
node = node ?? ignite.GetCluster().GetLocalNode();
return Enumerable.Range(1, int.MaxValue).Where(x => aff.IsPrimary(node, x));
}
/// <summary>
/// Gets the primary key.
/// </summary>
public static int GetPrimaryKey(IIgnite ignite, string cacheName, IClusterNode node = null)
{
return GetPrimaryKeys(ignite, cacheName, node).First();
}
/// <summary>
/// Asserts that the handle registry is empty.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, 0, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, expectedCount, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="grid">The grid to check.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout)
{
var handleRegistry = ((Ignite)grid).HandleRegistry;
expectedCount++; // Skip default lifecycle bean
if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout))
return;
var items = handleRegistry.GetItems().Where(x => !(x.Value is LifecycleHandlerHolder)).ToList();
if (items.Any())
{
Assert.Fail("HandleRegistry is not empty in grid '{0}' (expected {1}, actual {2}):\n '{3}'",
grid.Name, expectedCount, handleRegistry.Count,
items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y));
}
}
/// <summary>
/// Serializes and deserializes back an object.
/// </summary>
public static T SerializeDeserialize<T>(T obj, bool raw = false)
{
var cfg = new BinaryConfiguration
{
Serializer = raw ? new BinaryReflectiveSerializer {RawMode = true} : null
};
var marsh = new Marshaller(cfg) { CompactFooter = false };
return marsh.Unmarshal<T>(marsh.Marshal(obj));
}
/// <summary>
/// Clears the work dir.
/// </summary>
public static void ClearWorkDir()
{
if (!Directory.Exists(WorkDir))
{
return;
}
// Delete everything we can. Some files may be locked.
foreach (var e in Directory.GetFileSystemEntries(WorkDir, "*", SearchOption.AllDirectories))
{
try
{
File.Delete(e);
}
catch (Exception)
{
// Ignore
}
try
{
Directory.Delete(e, true);
}
catch (Exception)
{
// Ignore
}
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
namespace _4PosBackOffice.NET
{
internal partial class frmPOSreport : System.Windows.Forms.Form
{
private void loadLanguage()
{
//Note: Form Caption has a spelling mistake!!!
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2347;
//Sale Transaction List|Checked
if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2348;
//Persons|Checked
if (modRecordSet.rsLang.RecordCount){_Label1_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_Label1_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//Label1(1) = No Code [Sale Channels]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label1(1).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(1).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label1(2) = No Code [POS Devices]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label1(2).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(2).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2351;
//Transaction Reference|Checked
if (modRecordSet.rsLang.RecordCount){_Label1_3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_Label1_3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2352;
//Only Show Transaction with revoked Lines|Checked
if (modRecordSet.rsLang.RecordCount){chkRevoke.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkRevoke.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2353;
//Only show transaction with one or more Reversals
if (modRecordSet.rsLang.RecordCount){chkReversal.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkReversal.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2354;
//Do not show Consignments|Checked
if (modRecordSet.rsLang.RecordCount){chkNoCon.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkNoCon.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2355;
//Only show transaction with foreign Currencies|Checked
if (modRecordSet.rsLang.RecordCount){chkFC.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkFC.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2356;
//Only show Summary|Checked
if (modRecordSet.rsLang.RecordCount){chkSum.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkSum.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2357;
//Only Show Outstanding Consignments|Checked
if (modRecordSet.rsLang.RecordCount){chkOutCon.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkOutCon.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1181;
//Show/Print Report|Checked
if (modRecordSet.rsLang.RecordCount){cmdLoad.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdLoad.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmPOSreport.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private string getSQL()
{
string sql = null;
bool gl = false;
string lWhere = null;
short x = 0;
string lString = null;
//If 1 = 1 Then lWhere = lWhere & " AND (Sale.Sale_SaleChk=False)"
if (chkOutCon.CheckState)
lWhere = lWhere + " AND (Consignment_CompleteSaleID Is Null)";
if (chkNoCon.CheckState)
lWhere = lWhere + " AND (ConsignmentID Is Null)";
if (chkRevoke.CheckState)
lWhere = lWhere + " AND (SaleItem_Revoke=True)";
if (chkReversal.CheckState)
lWhere = lWhere + " AND (SaleItem_Reversal=True)";
if (chkFC.CheckState)
lWhere = lWhere + " AND (Sale_PaymentType=8)";
lString = "";
for (x = 0; x <= this.lstChannel.Items.Count - 1; x++) {
if (this.lstChannel.GetItemChecked(x)) {
lString = lString + " OR Sale_ChannelID=" + GID.GetItemData(ref lstChannel, ref x);
}
}
if (!string.IsNullOrEmpty(lString)) {
lString = " AND (" + Strings.Mid(lString, 4) + ")";
lWhere = lWhere + lString;
}
lString = "";
for (x = 0; x <= this.lstPerson.Items.Count - 1; x++) {
if (this.lstPerson.GetItemChecked(x)) {
lString = lString + " OR Sale_PersonID=" + GID.GetItemData(ref lstPerson, ref x);
}
}
if (!string.IsNullOrEmpty(lString)) {
lString = " AND (" + Strings.Mid(lString, 4) + ")";
lWhere = lWhere + lString;
}
lString = "";
for (x = 0; x <= this.lstPOS.Items.Count - 1; x++) {
if (this.lstPOS.GetItemChecked(x)) {
lString = lString + " OR Sale_POSID=" + GID.GetItemData(ref lstPOS, ref x);
}
}
if (!string.IsNullOrEmpty(lString)) {
lString = " AND (" + Strings.Mid(lString, 4) + ")";
lWhere = lWhere + lString;
}
lString = "";
gl = false;
for (x = 0; x <= this.lstSaleref.Items.Count - 1; x++) {
if (this.lstSaleref.GetItemChecked(x)) {
if (x == 0) {
lString = lString + " Sale_CardRef <>''";
gl = true;
} else if (x == 1) {
if (gl == true) {
lString = lString + " OR Sale_OrderRef <>''";
} else {
lString = lString + " Sale_OrderRef <>''";
gl = true;
}
} else if (x == 2) {
if (gl == true) {
lString = lString + " OR Sale_SerialRef <>''";
} else {
lString = lString + " Sale_SerialRef <>''";
}
}
}
}
if (!string.IsNullOrEmpty(lString)) {
lString = " AND (" + Strings.Mid(lString, 2) + ")";
lWhere = lWhere + lString;
}
if (!string.IsNullOrEmpty(lWhere))
lWhere = " WHERE " + Strings.Mid(lWhere, 6);
//FROM OLD BO code sql = "SELECT DISTINCT Sale.*, aConsignment.*, aCustomer.Customer_InvoiceName, aChannel.Channel_Name, [Person_FirstName] & ' ' & [Person_LastName] AS PersonName,aPerson1.Person_Comm FROM SaleItem INNER JOIN ((aChannel INNER JOIN (aCustomer RIGHT JOIN (CustomerTransaction RIGHT JOIN (aConsignment RIGHT JOIN Sale ON aConsignment.Consignment_SaleID = Sale.SaleID) ON CustomerTransaction.CustomerTransaction_ReferenceID = Sale.SaleID) ON aCustomer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID) ON aChannel.ChannelID = Sale.Sale_ChannelID) INNER JOIN aPerson1 ON Sale.Sale_PersonID = aPerson1.PersonID) ON SaleItem.SaleItem_SaleID = Sale.SaleID "
//added new Mgr field below sql = "SELECT DISTINCT Sale.*, aConsignment.*, aCustomer.Customer_InvoiceName, aChannel.Channel_Name, [Person_FirstName] & ' ' & [Person_LastName] AS PersonName,aPerson.Person_Comm FROM SaleItem INNER JOIN ((aChannel INNER JOIN (aCustomer RIGHT JOIN (CustomerTransaction RIGHT JOIN (aConsignment RIGHT JOIN Sale ON aConsignment.Consignment_SaleID = Sale.SaleID) ON CustomerTransaction.CustomerTransaction_ReferenceID = Sale.SaleID) ON aCustomer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID) ON aChannel.ChannelID = Sale.Sale_ChannelID) INNER JOIN aPerson ON Sale.Sale_PersonID = aPerson.PersonID) ON SaleItem.SaleItem_SaleID = Sale.SaleID "
//query copy of report SELECT Sale.*, aConsignment.*, aCustomer.Customer_InvoiceName, aChannel.Channel_Name, [Person_FirstName] & ' ' & [Person_LastName] AS PersonName, aPerson.Person_Comm FROM SaleItem INNER JOIN ((aChannel INNER JOIN (aCustomer RIGHT JOIN (CustomerTransaction RIGHT JOIN (aConsignment RIGHT JOIN Sale ON aConsignment.Consignment_SaleID = Sale.SaleID) ON CustomerTransaction.CustomerTransaction_ReferenceID = Sale.SaleID) ON aCustomer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID) ON aChannel.ChannelID = Sale.Sale_ChannelID) INNER JOIN aPerson ON Sale.Sale_PersonID = aPerson.PersonID) ON SaleItem.SaleItem_SaleID = Sale.SaleID WHERE (((Sale.Sale_PosID)=12) AND ((SaleItem.SaleItem_Reversal)=True));
if (chkOutCon.CheckState) {
//sql = "SELECT DISTINCT Sale.*, aConsignment.*, aCustomer.Customer_InvoiceName, aChannel.Channel_Name, aPerson.Person_FirstName & ' ' & aPerson.Person_LastName AS PersonName, aPerson.Person_Comm, aPerson1.Person_FirstName & ' ' & aPerson1.Person_LastName AS MgrName FROM (SaleItem INNER JOIN ((aChannel INNER JOIN (aCustomer RIGHT JOIN (CustomerTransaction RIGHT JOIN (aConsignment INNER JOIN Sale ON aConsignment.Consignment_SaleID = Sale.SaleID) ON CustomerTransaction.CustomerTransaction_ReferenceID = Sale.SaleID) ON aCustomer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID) ON aChannel.ChannelID = Sale.Sale_ChannelID) INNER JOIN aPerson ON Sale.Sale_PersonID = aPerson.PersonID) ON SaleItem.SaleItem_SaleID = Sale.SaleID) LEFT JOIN aPerson1 ON Sale.Sale_ManagerID = aPerson1.PersonID "
sql = "SELECT DISTINCT Sale.*, aConsignment.*, aCustomer.Customer_InvoiceName, aChannel.Channel_Name, aPerson.Person_FirstName & ' ' & aPerson.Person_LastName AS PersonName, aPerson.Person_Comm, aPerson1.Person_FirstName & ' ' & aPerson1.Person_LastName AS MgrName, aPOS1.POS_Name FROM ((SaleItem INNER JOIN ((aChannel INNER JOIN (aCustomer RIGHT JOIN (CustomerTransaction RIGHT JOIN (aConsignment INNER JOIN Sale ON aConsignment.Consignment_SaleID = Sale.SaleID) ON CustomerTransaction.CustomerTransaction_ReferenceID = Sale.SaleID) ON aCustomer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID) ON aChannel.ChannelID = Sale.Sale_ChannelID) INNER JOIN aPerson ON Sale.Sale_PersonID = aPerson.PersonID) ON SaleItem.SaleItem_SaleID = Sale.SaleID) LEFT JOIN aPerson1 ON Sale.Sale_ManagerID = aPerson1.PersonID) INNER JOIN aPOS1 ON Sale.Sale_PosID = aPOS1.POSID ";
} else {
//sql = "SELECT DISTINCT Sale.*, aConsignment.*, aCustomer.Customer_InvoiceName, aChannel.Channel_Name, aPerson.Person_FirstName & ' ' & aPerson.Person_LastName AS PersonName, aPerson.Person_Comm, aPerson1.Person_FirstName & ' ' & aPerson1.Person_LastName AS MgrName FROM (SaleItem RIGHT JOIN ((aChannel INNER JOIN (aCustomer RIGHT JOIN (CustomerTransaction RIGHT JOIN (aConsignment RIGHT JOIN Sale ON aConsignment.Consignment_SaleID = Sale.SaleID) ON CustomerTransaction.CustomerTransaction_ReferenceID = Sale.SaleID) ON aCustomer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID) ON aChannel.ChannelID = Sale.Sale_ChannelID) INNER JOIN aPerson ON Sale.Sale_PersonID = aPerson.PersonID) ON SaleItem.SaleItem_SaleID = Sale.SaleID) LEFT JOIN aPerson1 ON Sale.Sale_ManagerID = aPerson1.PersonID "
sql = "SELECT DISTINCT Sale.*, aConsignment.*, aCustomer.Customer_InvoiceName, aChannel.Channel_Name, aPerson.Person_FirstName & ' ' & aPerson.Person_LastName AS PersonName, aPerson.Person_Comm, aPerson1.Person_FirstName & ' ' & aPerson1.Person_LastName AS MgrName, aPOS1.POS_Name FROM ((SaleItem RIGHT JOIN ((aChannel INNER JOIN (aCustomer RIGHT JOIN (CustomerTransaction RIGHT JOIN (aConsignment RIGHT JOIN Sale ON aConsignment.Consignment_SaleID = Sale.SaleID) ON CustomerTransaction.CustomerTransaction_ReferenceID = Sale.SaleID) ON aCustomer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID) ON aChannel.ChannelID = Sale.Sale_ChannelID) INNER JOIN aPerson ON Sale.Sale_PersonID = aPerson.PersonID) ON SaleItem.SaleItem_SaleID = Sale.SaleID) LEFT JOIN aPerson1 ON Sale.Sale_ManagerID = aPerson1.PersonID) INNER JOIN aPOS1 ON Sale.Sale_PosID = aPOS1.POSID ";
}
sql = sql + lWhere;
Debug.Print(sql);
return sql;
}
private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.Close();
}
private void cmdLoad_Click(System.Object eventSender, System.EventArgs eventArgs)
{
string sql = null;
decimal SumSales = default(decimal);
ADODB.Recordset rs = default(ADODB.Recordset);
ADODB.Recordset rsData = default(ADODB.Recordset);
CrystalDecisions.CrystalReports.Engine.ReportDocument Report = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
//As New cryPOSreport
ReportNone.Load("cryNoRecords.rpt");
Report.Load("cryPOSreport.rpt");
// ERROR: Not supported in C#: OnErrorStatement
if (chkSum.CheckState) {
Report.Load("cryPOSreportSum.rpt");
} else {
Report.Load("cryPOSreport.rpt");
//Set Report = New cryPOSreportRevoke
}
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
rs = modReport.getRSreport(ref "SELECT Report.Report_Heading, aCompany.Company_Name From aCompany, Report;");
Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name"));
Report.SetParameterValue("txtDayend", rs.Fields("Report_Heading"));
rs.Close();
rs = modReport.getRSreport(ref getSQL());
if (rs.BOF | rs.EOF) {
ReportNone.SetParameterValue("txtCompanyName.", Report.ParameterFields("txtCompanyName").ToString);
ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString);
My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone;
My.MyProject.Forms.frmReportShow.mReport = ReportNone;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
return;
}
sql = "SELECT SaleItem.*, IIf([SaleItem_DepositType]=1,[Deposit_Name]+'-bottle',IIf([SaleItem_DepositType]=2,[Deposit_Name]+'-Crate',[Deposit_Name]+'-Case')) AS StockItem_Name FROM SaleItem INNER JOIN aDeposit ON SaleItem.SaleItem_StockItemID = aDeposit.DepositID Where (((SaleItem.SaleItem_DepositType) <> 0)) Union ";
sql = sql + "SELECT SaleItem.*, aStockItem.StockItem_Name FROM SaleItem INNER JOIN aStockItem ON SaleItem.SaleItem_StockItemID = aStockItem.StockItemID Where (((SaleItem.SaleItem_DepositType) = 0) And ((SaleItem.SaleItem_Recipe) = 0)) Union ";
sql = sql + "SELECT SaleItem.*, aRecipe.Recipe_Name AS StockItem_Name FROM SaleItem INNER JOIN aRecipe ON SaleItem.SaleItem_StockItemID = aRecipe.RecipeID WHERE (((SaleItem.SaleItem_DepositType)=0) AND ((SaleItem.SaleItem_Recipe)<>0));";
//sql = "SELECT SaleItem.*, IIf([SaleItem_DepositType]=1,[Deposit_Name]+'-bottle',IIf([SaleItem_DepositType]=2,[Deposit_Name]+'-Crate',[Deposit_Name]+'-Case')) AS StockItem_Name FROM SaleItem INNER JOIN aDeposit ON SaleItem.SaleItem_StockItemID = aDeposit.DepositID Where (((SaleItem.SaleItem_DepositType) <> 0) AND ((SaleItem.SaleItem_Revoke) <> 0)) Union SELECT SaleItem.*, aStockItem.StockItem_Name FROM SaleItem INNER JOIN aStockItem ON SaleItem.SaleItem_StockItemID = aStockItem.StockItemID Where (((SaleItem.SaleItem_DepositType) = 0) AND ((SaleItem.SaleItem_Revoke) <> 0))"
sql = "SELECT SaleItem.*, IIf([SaleItem_DepositType]=1,[Deposit_Name]+'-bottle',IIf([SaleItem_DepositType]=2,[Deposit_Name]+'-Crate',[Deposit_Name]+'-Case')) AS StockItem_Name FROM SaleItem INNER JOIN aDeposit ON SaleItem.SaleItem_StockItemID = aDeposit.DepositID Where (((SaleItem.SaleItem_DepositType) <> 0)) Union SELECT SaleItem.*, aStockItem.StockItem_Name FROM SaleItem INNER JOIN aStockItem ON SaleItem.SaleItem_StockItemID = aStockItem.StockItemID Where (((SaleItem.SaleItem_DepositType) = 0))";
rsData = modReport.getRSreport(ref sql);
if (rsData.BOF | rsData.EOF) {
ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString);
ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString);
My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone;
My.MyProject.Forms.frmReportShow.mReport = ReportNone;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
return;
}
if (emp_Clicked() == true) {
SumSales = 0;
while (rs.EOF == false) {
SumSales = SumSales + rs.Fields("Sale_Total").Value;
rs.moveNext();
}
//Resise to excluding vat
SumSales = SumSales - (SumSales * 0.14);
rs.MoveFirst();
Report.SetParameterValue("txtComm", (Information.IsDBNull(rs.Fields("Person_Comm").Value) ? 0 : rs.Fields("Person_Comm").Value));
Report.SetParameterValue("txtTotalCommision", Strings.FormatNumber((SumSales * rs.Fields("Person_Comm").Value) / 100, 2));
}
if (chkOutCon.CheckState)
Report.SetParameterValue("txtTitle", "Point Of Sale Outstanding Consignments for Device");
Report.Database.Tables(1).SetDataSource(rs);
Report.Database.Tables(2).SetDataSource(rsData);
//Report.VerifyOnEveryPrint = True
My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtComm").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report;
My.MyProject.Forms.frmReportShow.mReport = Report;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
}
private bool emp_Clicked()
{
bool functionReturnValue = false;
short intj = 0;
short j = 0;
short inClick = 0;
inClick = lstPerson.Items.Count - 1;
intj = 0;
for (j = 0; j <= inClick; j++) {
if (lstPerson.GetItemChecked(j) == true) {
intj = intj + 1;
functionReturnValue = true;
return functionReturnValue;
}
}
functionReturnValue = false;
return functionReturnValue;
}
private short emp_Clicked1()
{
short intj = 0;
short j = 0;
short inClick = 0;
inClick = lstPerson.Items.Count - 1;
intj = 0;
for (j = 0; j <= inClick; j++) {
if (lstPerson.GetItemChecked(j) == true) {
intj = intj + 1;
}
}
}
private void frmPOSreport_Load(System.Object eventSender, System.EventArgs eventArgs)
{
ADODB.Recordset rs = default(ADODB.Recordset);
lstPerson.Items.Clear();
rs = modReport.getRSreport(ref "SELECT aPerson.PersonID, [Person_FirstName] & ' ' & [Person_Position] AS personName From aPerson Where (((aPerson.PersonID) <> 1) And ((aPerson.Person_Disabled) = False)) ORDER BY [Person_FirstName] & ' ' & [Person_Position];");
int m = 0;
while (!(rs.EOF)) {
m = this.lstPerson.Items.Add(rs.Fields("PersonName").Value);
//lstPerson = New SetItemData(m, rs.Fields("PersonID").Value)
rs.MoveNext();
}
lstChannel.Items.Clear();
rs = modReport.getRSreport(ref "SELECT aChannel.ChannelID, aChannel.Channel_Name From aChannel Where (((aChannel.Channel_Disabled) = False)) ORDER BY aChannel.ChannelID;");
//Dim m As Integer
while (!(rs.EOF)) {
m = this.lstChannel.Items.Add(rs.Fields("Channel_Name").Value);
//lstChannel = New SetItemData(m, rs.Fields("ChannelID").Value)
rs.moveNext();
}
lstPOS.Items.Clear();
rs = modReport.getRSreport(ref "SELECT aPOS.POSID, aPOS.POS_Name From aPOS ORDER BY aPOS.POSID;");
while (!(rs.EOF)) {
m = this.lstPOS.Items.Add(rs.Fields("POS_Name").Value);
//lstPOS = New SetItemData(m, rs.Fields("POSID").Value)
rs.moveNext();
}
loadLanguage();
}
}
}
| |
// 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 SubtractScalarSingle()
{
var test = new SimpleBinaryOpTest__SubtractScalarSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// 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();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// 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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
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 SimpleBinaryOpTest__SubtractScalarSingle
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[ElementCount];
private static Single[] _data2 = new Single[ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single> _dataTable;
static SimpleBinaryOpTest__SubtractScalarSingle()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__SubtractScalarSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse.SubtractScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse.SubtractScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse.SubtractScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse).GetMethod(nameof(Sse.SubtractScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse).GetMethod(nameof(Sse.SubtractScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse).GetMethod(nameof(Sse.SubtractScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse.SubtractScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.SubtractScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.SubtractScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.SubtractScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__SubtractScalarSingle();
var result = Sse.SubtractScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse.SubtractScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(left[0] - right[0]) != BitConverter.SingleToInt32Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.SubtractScalar)}<Single>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Media;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using MetroFramework.Forms;
using MetroFramework.Interfaces;
namespace MetroFramework
{
/// <summary>
/// Metro-styled message notification.
/// </summary>
public static class MetroMessageBox
{
/// <summary>
/// Shows a metro-styles message notification into the specified owner window.
/// </summary>
/// <param name="owner"></param>
/// <param name="message"></param>
/// <param name="height" optional=211></param>
/// <returns></returns>
public static DialogResult Show(IWin32Window owner, String message)
{ return Show(owner, message, "Notification", 211); }
/// <summary>
/// Shows a metro-styles message notification into the specified owner window.
/// </summary>
/// <param name="owner"></param>
/// <param name="message"></param>
/// <param name="height" optional=211></param>
/// <returns></returns>
public static DialogResult Show(IWin32Window owner, String message,int height)
{ return Show(owner, message, "Notification", height); }
/// <summary>
/// Shows a metro-styles message notification into the specified owner window.
/// </summary>
/// <param name="owner"></param>
/// <param name="message"></param>
/// <param name="title"></param>
/// <param name="height" optional=211></param>
/// <returns></returns>
public static DialogResult Show(IWin32Window owner, String message, String title)
{ return Show(owner, message, title, MessageBoxButtons.OK, 211); }
/// <summary>
/// Shows a metro-styles message notification into the specified owner window.
/// </summary>
/// <param name="owner"></param>
/// <param name="message"></param>
/// <param name="title"></param>
/// <param name="height" optional=211></param>
/// <returns></returns>
public static DialogResult Show(IWin32Window owner, String message, String title, int height)
{ return Show(owner, message, title, MessageBoxButtons.OK, height); }
/// <summary>
/// Shows a metro-styles message notification into the specified owner window.
/// </summary>
/// <param name="owner"></param>
/// <param name="message"></param>
/// <param name="title"></param>
/// <param name="buttons"></param>
/// <param name="height" optional=211></param>
/// <returns></returns>
public static DialogResult Show(IWin32Window owner, String message, String title, MessageBoxButtons buttons)
{ return Show(owner, message, title, buttons, MessageBoxIcon.None, 211); }
/// <summary>
/// Shows a metro-styles message notification into the specified owner window.
/// </summary>
/// <param name="owner"></param>
/// <param name="message"></param>
/// <param name="title"></param>
/// <param name="buttons"></param>
/// <param name="height" optional=211></param>
/// <returns></returns>
public static DialogResult Show(IWin32Window owner, String message, String title, MessageBoxButtons buttons, int height)
{ return Show(owner, message, title, buttons, MessageBoxIcon.None, height); }
/// <summary>
/// Shows a metro-styles message notification into the specified owner window.
/// </summary>
/// <param name="owner"></param>
/// <param name="message"></param>
/// <param name="title"></param>
/// <param name="buttons"></param>
/// <param name="icon"></param>
/// <param name="height" optional=211></param>
/// <returns></returns>
public static DialogResult Show(IWin32Window owner, String message, String title, MessageBoxButtons buttons, MessageBoxIcon icon)
{ return Show(owner, message, title, buttons, icon, MessageBoxDefaultButton.Button1, 211); }
/// <summary>
/// Shows a metro-styles message notification into the specified owner window.
/// </summary>
/// <param name="owner"></param>
/// <param name="message"></param>
/// <param name="title"></param>
/// <param name="buttons"></param>
/// <param name="icon"></param>
/// <param name="height" optional=211></param>
/// <returns></returns>
public static DialogResult Show(IWin32Window owner, String message, String title, MessageBoxButtons buttons, MessageBoxIcon icon, int height)
{ return Show(owner, message, title, buttons, icon, MessageBoxDefaultButton.Button1, height); }
/// <summary>
/// Shows a metro-styles message notification into the specified owner window.
/// </summary>
/// <param name="owner"></param>
/// <param name="message"></param>
/// <param name="title"></param>
/// <param name="buttons"></param>
/// <param name="icon"></param>
/// <param name="defaultbutton"></param>
/// <param name="height" optional=211></param>
/// <returns></returns>
public static DialogResult Show(IWin32Window owner, String message, String title, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultbutton)
{
return Show(owner, message, title, buttons, icon, defaultbutton, 211);
}
/// <summary>
/// Shows a metro-styles message notification into the specified owner window.
/// </summary>
/// <param name="owner"></param>
/// <param name="message"></param>
/// <param name="title"></param>
/// <param name="buttons"></param>
/// <param name="icon"></param>
/// <param name="defaultbutton"></param>
/// <param name="height" optional=211></param>
/// <returns></returns>
public static DialogResult Show(IWin32Window owner, String message, String title, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultbutton, int height)
{
DialogResult _result = DialogResult.None;
if (owner != null)
{
Form _owner = (owner as Form == null) ? ((UserControl)owner).ParentForm : (Form)owner;
//int _minWidth = 500;
//int _minHeight = 350;
//if (_owner.Size.Width < _minWidth ||
// _owner.Size.Height < _minHeight)
//{
// if (_owner.Size.Width < _minWidth && _owner.Size.Height < _minHeight) {
// _owner.Size = new Size(_minWidth, _minHeight);
// }
// else
// {
// if (_owner.Size.Width < _minWidth) _owner.Size = new Size(_minWidth, _owner.Size.Height);
// else _owner.Size = new Size(_owner.Size.Width, _minHeight);
// }
// int x = Convert.ToInt32(Math.Ceiling((decimal)(Screen.PrimaryScreen.WorkingArea.Size.Width / 2) - (_owner.Size.Width / 2)));
// int y = Convert.ToInt32(Math.Ceiling((decimal)(Screen.PrimaryScreen.WorkingArea.Size.Height / 2) - (_owner.Size.Height / 2)));
// _owner.Location = new Point(x, y);
//}
switch (icon)
{
case MessageBoxIcon.Error:
SystemSounds.Hand.Play(); break;
case MessageBoxIcon.Exclamation:
SystemSounds.Exclamation.Play(); break;
case MessageBoxIcon.Question:
SystemSounds.Beep.Play(); break;
default:
SystemSounds.Asterisk.Play(); break;
}
MetroMessageBoxControl _control = new MetroMessageBoxControl();
_control.BackColor = _owner.BackColor;
_control.Properties.Buttons = buttons;
_control.Properties.DefaultButton = defaultbutton;
_control.Properties.Icon = icon;
_control.Properties.Message = message;
_control.Properties.Title = title;
_control.Padding = new Padding(0, 0, 0, 0);
_control.ControlBox = false;
_control.ShowInTaskbar = false;
_control.TopMost = true;
//_owner.Controls.Add(_control);
//if (_owner is IMetroForm)
//{
// //if (((MetroForm)_owner).DisplayHeader)
// //{
// // _offset += 30;
// //}
// _control.Theme = ((MetroForm)_owner).Theme;
// _control.Style = ((MetroForm)_owner).Style;
//}
_control.Size = new Size(_owner.Size.Width, height);
_control.Location = new Point(_owner.Location.X, _owner.Location.Y + (_owner.Height - _control.Height) / 2);
_control.ArrangeApperance();
int _overlaySizes = Convert.ToInt32(Math.Floor(_control.Size.Height * 0.28));
//_control.OverlayPanelTop.Size = new Size(_control.Size.Width, _overlaySizes - 30);
//_control.OverlayPanelBottom.Size = new Size(_control.Size.Width, _overlaySizes);
_control.ShowDialog();
_control.BringToFront();
_control.SetDefaultButton();
Action<MetroMessageBoxControl> _delegate = new Action<MetroMessageBoxControl>(ModalState);
IAsyncResult _asyncresult = _delegate.BeginInvoke(_control, null, _delegate);
bool _cancelled = false;
try
{
while (!_asyncresult.IsCompleted)
{ Thread.Sleep(1); Application.DoEvents(); }
}
catch
{
_cancelled = true;
if (!_asyncresult.IsCompleted)
{
try { _asyncresult = null; }
catch { }
}
_delegate = null;
}
if (!_cancelled)
{
_result = _control.Result;
//_owner.Controls.Remove(_control);
_control.Dispose(); _control = null;
}
}
return _result;
}
private static void ModalState(MetroMessageBoxControl control)
{
while (control.Visible)
{ }
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ServersOperations.
/// </summary>
public static partial class ServersOperationsExtensions
{
/// <summary>
/// Creates or updates a firewall rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating a firewall rule.
/// </param>
public static ServerFirewallRule CreateOrUpdateFirewallRule(this IServersOperations operations, string resourceGroupName, string serverName, string firewallRuleName, ServerFirewallRule parameters)
{
return operations.CreateOrUpdateFirewallRuleAsync(resourceGroupName, serverName, firewallRuleName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a firewall rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating a firewall rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ServerFirewallRule> CreateOrUpdateFirewallRuleAsync(this IServersOperations operations, string resourceGroupName, string serverName, string firewallRuleName, ServerFirewallRule parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateFirewallRuleWithHttpMessagesAsync(resourceGroupName, serverName, firewallRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a firewall rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule.
/// </param>
public static void DeleteFirewallRule(this IServersOperations operations, string resourceGroupName, string serverName, string firewallRuleName)
{
operations.DeleteFirewallRuleAsync(resourceGroupName, serverName, firewallRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a firewall rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteFirewallRuleAsync(this IServersOperations operations, string resourceGroupName, string serverName, string firewallRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteFirewallRuleWithHttpMessagesAsync(resourceGroupName, serverName, firewallRuleName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a firewall rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule.
/// </param>
public static ServerFirewallRule GetFirewallRule(this IServersOperations operations, string resourceGroupName, string serverName, string firewallRuleName)
{
return operations.GetFirewallRuleAsync(resourceGroupName, serverName, firewallRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a firewall rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ServerFirewallRule> GetFirewallRuleAsync(this IServersOperations operations, string resourceGroupName, string serverName, string firewallRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetFirewallRuleWithHttpMessagesAsync(resourceGroupName, serverName, firewallRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns a list of firewall rules.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
public static IEnumerable<ServerFirewallRule> ListFirewallRules(this IServersOperations operations, string resourceGroupName, string serverName)
{
return operations.ListFirewallRulesAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a list of firewall rules.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<ServerFirewallRule>> ListFirewallRulesAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListFirewallRulesWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns a list of servers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IEnumerable<Server> List(this IServersOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Returns a list of servers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<Server>> ListAsync(this IServersOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a new server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating a server.
/// </param>
public static Server CreateOrUpdate(this IServersOperations operations, string resourceGroupName, string serverName, Server parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serverName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a new server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating a server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Server> CreateOrUpdateAsync(this IServersOperations operations, string resourceGroupName, string serverName, Server parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a SQL server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
public static void Delete(this IServersOperations operations, string resourceGroupName, string serverName)
{
operations.DeleteAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a SQL server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
public static Server GetByResourceGroup(this IServersOperations operations, string resourceGroupName, string serverName)
{
return operations.GetByResourceGroupAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Server> GetByResourceGroupAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetByResourceGroupWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns a server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
public static IEnumerable<Server> ListByResourceGroup(this IServersOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a server.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<Server>> ListByResourceGroupAsync(this IServersOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns server usages.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
public static IEnumerable<ServerMetric> ListUsages(this IServersOperations operations, string resourceGroupName, string serverName)
{
return operations.ListUsagesAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns server usages.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<ServerMetric>> ListUsagesAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListUsagesWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a database service objective.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='serviceObjectiveName'>
/// The name of the service objective to retrieve.
/// </param>
public static ServiceObjective GetServiceObjective(this IServersOperations operations, string resourceGroupName, string serverName, string serviceObjectiveName)
{
return operations.GetServiceObjectiveAsync(resourceGroupName, serverName, serviceObjectiveName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a database service objective.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='serviceObjectiveName'>
/// The name of the service objective to retrieve.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ServiceObjective> GetServiceObjectiveAsync(this IServersOperations operations, string resourceGroupName, string serverName, string serviceObjectiveName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetServiceObjectiveWithHttpMessagesAsync(resourceGroupName, serverName, serviceObjectiveName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns database service objectives.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
public static IEnumerable<ServiceObjective> ListServiceObjectives(this IServersOperations operations, string resourceGroupName, string serverName)
{
return operations.ListServiceObjectivesAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns database service objectives.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<ServiceObjective>> ListServiceObjectivesAsync(this IServersOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListServiceObjectivesWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.