context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Data; using System.Diagnostics.Eventing.Reader; using System.Dynamic; using System.Linq; using System.Reflection; using System.Text; using Its.Log.Instrumentation.Extensions; using NUnit.Framework; using Assert = NUnit.Framework.Assert; using StringAssert = NUnit.Framework.StringAssert; namespace Its.Log.Instrumentation.UnitTests { [TestFixture] public class FormatterSetTests { [SetUp] public void SetUp() { Log.Formatters.Clear(); Extension.EnableAll(); } [TearDown] public void TearDown() { Log.Formatters.Clear(); } [Test] public void CreatePropertiesFormatter_creates_a_function_that_emits_the_property_names_and_values_for_a_specific_type() { var func = Log.Formatters.CreatePropertiesFormatter<Widget>(); var s = func(new Widget { Name = "Bob" }); Assert.That(s, Contains.Substring("Name = Bob")); } [Test] public void CreateFormatter_creates_a_function_that_emits_the_specified_property_names_and_values_for_a_specific_type() { var func = Log.Formatters.CreateFormatterFor<SomethingWithLotsOfProperties>( o => o.DateProperty, o => o.StringProperty); var s = func(new SomethingWithLotsOfProperties { DateProperty = DateTime.MinValue, StringProperty = "howdy" }); Assert.That(s, Contains.Substring("DateProperty = 0001-01-01 00:00:00Z")); Assert.That(s, Contains.Substring("StringProperty = howdy")); Assert.That(s, !Contains.Substring("IntProperty")); Assert.That(s, !Contains.Substring("BoolProperty")); Assert.That(s, !Contains.Substring("UriProperty")); } [Test] public void CreateFormatter_throws_when_an_expression_is_not_a_MemberExpression() { var formatter = new FormatterSet(); var ex = Assert.Throws<ArgumentException>(() => formatter.CreateFormatterFor<SomethingWithLotsOfProperties>( o => o.DateProperty.ToShortDateString(), o => o.StringProperty)); Assert.That(ex.Message, Contains.Substring("o => o.DateProperty.ToShortDateString()")); } [Test] public void RegisterFormatter_creates_a_function_that_emits_the_specified_property_names_and_values_for_a_specific_type() { Log.Formatters.RegisterPropertiesFormatter<SomethingWithLotsOfProperties>( o => o.DateProperty, o => o.StringProperty); var s = new SomethingWithLotsOfProperties { DateProperty = DateTime.MinValue, StringProperty = "howdy" }.ToLogString(); Assert.That(s, Contains.Substring("DateProperty = 0001-01-01 00:00:00Z")); Assert.That(s, Contains.Substring("StringProperty = howdy")); Assert.That(s, !Contains.Substring("IntProperty")); Assert.That(s, !Contains.Substring("BoolProperty")); Assert.That(s, !Contains.Substring("UriProperty")); } [Test] public void RegisterFormatter_throws_when_an_expression_is_not_a_MemberExpression() { var formatter = new FormatterSet(); var ex = Assert.Throws<ArgumentException>(() => formatter.RegisterPropertiesFormatter<SomethingWithLotsOfProperties>( o => o.DateProperty.ToShortDateString(), o => o.StringProperty)); Assert.That(ex.Message, Contains.Substring("o => o.DateProperty.ToShortDateString()")); } [Test] public void RegisterPropertiesFormatter_for_string_does_nothing() { var formatter = new FormatterSet(); formatter.RegisterPropertiesFormatter<string>(); Assert.That(formatter.Format("hello"), Is.EqualTo("hello")); } [Test] public void CreatePropertiesFormatter_LogEntry() { var func = Log.Formatters.CreatePropertiesFormatter<LogEntry>(); var s = func(new LogEntry("message") { Category = "category" }); Console.WriteLine(s); Assert.IsTrue(s.Contains("TimeStamp")); Assert.IsTrue(s.Contains("Category")); Assert.IsTrue(s.Contains("Message")); } [Test] public void Recursive_formatter_calls_do_not_cause_exceptions() { var widget = new Widget(); widget.Parts = new List<Part> { new Part { Widget = widget } }; Log.Formatters.RegisterPropertiesFormatter<Widget>(); Log.Formatters.RegisterPropertiesFormatter<Part>(); // this should not throw var s = widget.ToLogString(); Console.WriteLine(s); } [Test] public void FormatterSet_expands_IEnumerable() { var list = new List<string> { "this", "that", "the other thing" }; var formatted = new FormatterSet().Format(list); Assert.That(formatted, Is.EqualTo("{ this, that, the other thing }")); } [Test] public void FormatterSet_expands_properties_of_ExpandoObjects() { dynamic expando = new ExpandoObject(); expando.Name = "socks"; expando.Parts = null; Log.Formatters.RegisterPropertiesFormatter<Widget>(); dynamic expandoString = Log.ToLogString(expando); Assert.That(expandoString, Is.EqualTo("{ Name = socks | Parts = [null] }")); } [Test] public void FormatterSet_does_not_expand_string() { var widget = new Widget(); widget.Parts = new List<Part> { new Part { Widget = widget } }; Log.Formatters.RegisterPropertiesFormatter<Widget>(); Log.Formatters.RegisterPropertiesFormatter<Part>(); // this should not throw var s = widget.ToLogString(); Console.WriteLine(s); Assert.IsFalse(s.Contains("Name = { D },{ e }")); } [Test] public void Default_formatter_for_Type_displays_only_the_name() { var formatter = new FormatterSet(); Assert.That(formatter.Format(GetType()), Is.EqualTo(GetType().Name)); Assert.That(formatter.Format(typeof (FormatterSetTests)), Is.EqualTo(typeof (FormatterSetTests).Name)); } [Test] public void Custom_formatter_for_Type_can_be_registered() { var formatter = new FormatterSet(); formatter.RegisterFormatter<Type>(t => t.GUID.ToString()); Assert.That(formatter.Format(GetType()), Is.EqualTo(GetType().GUID.ToString())); } [Test] public void Default_formatter_for_null_Nullable_indicates_null() { var formatter = new FormatterSet(); int? nullable = null; var output = formatter.Format(nullable); Assert.That(output, Is.EqualTo(formatter.Format<object>(null))); } [Test] public void FormatterSet_recursively_formats_types_within_IEnumerable() { var list = new List<Widget> { new Widget { Name = "widget x" }, new Widget { Name = "widget y" }, new Widget { Name = "widget z" } }; var formatted = new FormatterSet() .RegisterFormatter<Widget>( w => w.Name + ", Parts: " + (w.Parts == null ? "0" : w.Parts.Count.ToString())) .Format(list); Console.WriteLine(formatted); Assert.That(formatted, Is.EqualTo("{ widget x, Parts: 0, widget y, Parts: 0, widget z, Parts: 0 }")); } [Test] public void FormatterSet_truncates_expansion_of_long_IEnumerable() { var list = new List<string>(); for (var i = 1; i < 11; i++) { list.Add("number " + i); } var formatterSet = new FormatterSet { ListExpansionLimit = 4 }; var formatted = formatterSet.Format(list); Console.WriteLine(formatted); Assert.IsTrue(formatted.Contains("number 1")); Assert.IsTrue(formatted.Contains("number 4")); Assert.IsFalse(formatted.Contains("number 5")); Assert.IsTrue(formatted.Contains("6 more")); } [Test] public void Formatter_iterates_IEnumerable_property_when_its_actual_type_is_an_array_of_structs() { Assert.That( new[] { 1, 2, 3, 4, 5 }.ToLogString(), Is.EqualTo("{ 1, 2, 3, 4, 5 }")); } [Test] public void Formatter_iterates_IEnumerable_property_when_its_actual_type_is_an_array_of_objects() { Log.Formatters.RegisterPropertiesFormatter<Node>(); var node = new Node { Id = "1", Nodes = new[] { new Node { Id = "1.1" }, new Node { Id = "1.2" }, new Node { Id = "1.3" }, } }; var output = node.ToLogString(); StringAssert.Contains("1.1", output); StringAssert.Contains("1.2", output); StringAssert.Contains("1.3", output); } [Test] public void Formatter_iterates_IEnumerable_property_when_its_reflected_type_is_array() { Log.Formatters.RegisterPropertiesFormatter<Node>(); var node = new Node { Id = "1", NodesArray = new[] { new Node { Id = "1.1" }, new Node { Id = "1.2" }, new Node { Id = "1.3" }, } }; var output = node.ToLogString(); StringAssert.Contains("1.1", output); StringAssert.Contains("1.2", output); StringAssert.Contains("1.3", output); } [Test] public void Default_LogEntry_formatter_can_be_set() { var log = ""; Log.Formatters.RegisterFormatter<LogEntry>(e => string.Format("Here's a log entry!")); using (Log.Events().Subscribe(e => log += e.ToLogString())) { Log.Write("hello"); } Assert.That(log, Contains.Substring("Here's a log entry!")); } [Test] public void When_default_LogEntry_formatter_is_changed_it_controls_formatting_of_newly_registered_LogEntry_generic_types() { var log = ""; Log.Formatters.RegisterFormatter<LogEntry>(e => "Here's a log entry!"); using (Log.Events().Subscribe(e => log += e.ToLogString())) { Log.Write(() => new { hello = "hello" }); } Assert.That(log, Contains.Substring("Here's a log entry!")); Assert.That(log, !Contains.Substring("hello")); } [Test] public void Previously_registered_formatters_for_generic_LogEntry_types_use_updated_non_generic_LogEntry_formatter() { var log = ""; using (Log.Events().Subscribe(e => log += e.ToLogString())) { Log.Write(() => new { msg = "one" }); Log.Formatters.RegisterFormatter<LogEntry>(e => "Here's a log entry!"); Log.Write(() => new { msg = "two" }); } Assert.That(log, Contains.Substring("one")); Assert.That(log, Contains.Substring("Here's a log entry!")); Assert.That(log, !Contains.Substring("two")); } [Test] public void CreatePropertiesFormatter_expands_properties_of_structs() { var func = new FormatterSet().CreatePropertiesFormatter<EntityId>(); var id = new EntityId("the typename", "the id"); var value = func(id); Console.WriteLine(value); Assert.That(value, Contains.Substring("TypeName = the typename")); Assert.That(value, Contains.Substring("Id = the id")); } [Test] public void Static_fields_are_not_written() { var formatter = new FormatterSet(); formatter.RegisterPropertiesFormatter<BoundaryTests.NestedWidget>(); Assert.That(formatter.Format(new Widget()), !Contains.Substring("StaticField")); } [Test] public void Static_properties_are_not_written() { var formatter = new FormatterSet(); formatter.RegisterPropertiesFormatter<BoundaryTests.NestedWidget>(); Assert.That(formatter.Format(new Widget()), !Contains.Substring("StaticProperty")); } [Test] public void CreatePropertiesFormatter_expands_fields_of_objects() { var func = new FormatterSet().CreatePropertiesFormatter<SomeStruct>(); var today = DateTime.Today; var tomorrow = DateTime.Today.AddDays(1); var id = new SomeStruct { DateField = today, DateProperty = tomorrow }; var value = func(id); Console.WriteLine(value); Assert.That(value, Contains.Substring("DateField = ")); Assert.That(value, Contains.Substring("DateProperty = ")); } [Test] public void Exceptions_always_get_properties_formatters() { var exception = new ReflectionTypeLoadException( new[] { typeof (FileStyleUriParser), typeof (AssemblyKeyFileAttribute) }, new Exception[] { new EventLogInvalidDataException() }); var formatter = new FormatterSet(); var message = formatter.Format(exception); Assert.That(message, Contains.Substring("ReflectionTypeLoadException")); Assert.That(message, Contains.Substring("FileStyleUriParser")); Assert.That(message, Contains.Substring("AssemblyKeyFileAttribute")); Assert.That(message, Contains.Substring("EventLogInvalidDataException")); } [Test] public void Exception_Data_is_included_by_default() { var ex = new InvalidOperationException("oh noes!", new NullReferenceException()); var key = "a very important int"; ex.Data[key] = 123456; var msg = ex.ToLogString(); Assert.That(msg, Contains.Substring(key)); Assert.That(msg, Contains.Substring("123456")); } [Test] public void Exception_StackTrace_is_included_by_default() { string msg; var ex = new InvalidOperationException("oh noes!", new NullReferenceException()); try { throw ex; } catch (Exception thrownException) { msg = thrownException.ToLogString(); } Assert.That(msg, Contains.Substring("StackTrace = at Its.Log.Instrumentation.UnitTests.FormatterSetTests.Exception_StackTrace_is_included_by_default() ")); } [Test] public void Exception_Type_is_included_by_default() { var ex = new InvalidOperationException("oh noes!", new NullReferenceException()); var msg = ex.ToLogString(); Assert.That(msg, Contains.Substring("InvalidOperationException")); } [Test] public void Exception_Message_is_included_by_default() { var ex = new InvalidOperationException("oh noes!", new NullReferenceException()); var msg = ex.ToLogString(); Assert.That(msg, Contains.Substring("oh noes!")); } [Test] public void Exception_InnerExceptions_are_included_by_default() { var ex = new InvalidOperationException("oh noes!", new NullReferenceException("oh my.", new DataException("oops!"))); Assert.That(ex.ToLogString(), Contains.Substring("NullReferenceException")); Assert.That(ex.ToLogString(), Contains.Substring("DataException")); } [Test] public void When_a_property_throws_it_does_not_prevent_other_properties_from_being_written() { var log = new StringBuilder(); Log.Formatters.RegisterPropertiesFormatter<SomePropertyThrows>(); using (Log.Events().Subscribe(e => log.AppendLine(e.ToLogString()))) using (TestHelper.LogToConsole()) { Log.Write(() => new SomePropertyThrows()); } Assert.That(log.ToString(), Contains.Substring("Ok =")); Assert.That(log.ToString(), Contains.Substring("Fine =")); Assert.That(log.ToString(), Contains.Substring("PerfectlyFine =")); } [Test] public void Clearing_formatters_reregisters_Params_formatters() { var log = ""; using (Log.Events().Subscribe(e => log += e.ToLogString())) { Log.WithParams(() => new { ints = new[] { 1, 2, 3 } }).Write("1"); Log.Formatters.Clear(); Log.WithParams(() => new { ints = new[] { 4, 5, 6 } }).Write("1"); } Assert.That(log, Contains.Substring("ints = { 1, 2, 3 }")); Assert.That(log, Contains.Substring("ints = { 4, 5, 6 }")); } [Test] public void Clearing_formatters_reregisters_LogEntry_formatters() { var log = ""; using (Log.Events().Subscribe(e => log += e.ToLogString())) { Log.Write(() => new { ints = new[] { 1, 2, 3 } }); Log.Formatters.Clear(); Log.Write(() => new { ints = new[] { 4, 5, 6 } }); } Assert.That(log, Contains.Substring("ints = { 1, 2, 3 }")); Assert.That(log, Contains.Substring("ints = { 4, 5, 6 }")); } [Test] public void CreatePropertiesFormatter_can_include_internal_fields() { var formatter = new FormatterSet().CreatePropertiesFormatter<Node>(true); var output = formatter(new Node { Id = "5" }); Assert.That(output, Contains.Substring("_id = 5")); } [Test] public void CreatePropertiesFormatter_does_not_include_autoproperty_backing_fields() { var formatter = new FormatterSet().CreatePropertiesFormatter<Node>(true); var output = formatter(new Node()); Assert.That(output, !Contains.Substring("<Nodes>k__BackingField")); Assert.That(output, !Contains.Substring("<NodesArray>k__BackingField")); } [Test] public void CreatePropertiesFormatter_can_include_internal_properties() { var formatter = new FormatterSet().CreatePropertiesFormatter<Node>(true); var output = formatter(new Node { Id = "6" }); Assert.That(output, Contains.Substring("InternalId = 6")); } [Test] public void When_Clear_is_called_then_default_formatters_are_immediately_reregistered() { var formatterSet = new FormatterSet(); var logEntry = new LogEntry("hola!"); var before = formatterSet.Format(logEntry); formatterSet.RegisterFormatter<LogEntry>(e => "hello!"); Assert.That(formatterSet.Format(logEntry), Is.Not.EqualTo(before)); formatterSet.Clear(); Assert.That(formatterSet.Format(logEntry), Is.EqualTo(before)); } [Test] public void Anonymous_types_are_automatically_fully_formatted() { var formatter = new FormatterSet(); var ints = new[] { 3, 2, 1 }; var output = formatter.Format(new { ints, count = ints.Count() }); Assert.That(output, Is.EqualTo("{ ints = { 3, 2, 1 } | count = 3 }")); } [NUnit.Framework.Ignore("Perf test")] [Test] public void Perf_experiment_comparing_methods_of_tracking_recursion_depth() { var threadStaticCounter = new RecursionCounter(); int iterations = 100000; Timer.TimeOperation(i => { using (threadStaticCounter.Enter()) using (threadStaticCounter.Enter()) using (threadStaticCounter.Enter()) { Assert.That(threadStaticCounter.Depth, Is.EqualTo(3)); } }, iterations, "simple counter"); } [NUnit.Framework.Ignore("Perf test")] [Test] public void Perf_experiment_comparing_methods_of_tracking_recursion_depth_across_multiple_threads() { var simpleCounter = new RecursionCounter(); int iterations = 1000000; Timer.TimeOperation(i => { using (simpleCounter.Enter()) using (simpleCounter.Enter()) using (simpleCounter.Enter()) { Assert.That(simpleCounter.Depth, Is.EqualTo(3)); } }, iterations, "simple counter", true); } } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ReactNative.Bridge; using ReactNative.Collections; using System; using System.Collections.Generic; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Windows.Foundation; using Windows.Networking.Sockets; using Windows.Storage.Streams; namespace ReactNative.DevSupport { class WebSocketJavaScriptExecutor : IJavaScriptExecutor { private const int ConnectTimeoutMilliseconds = 5000; private const int ConnectRetryCount = 3; private readonly object _gate = new object(); private readonly MessageWebSocket _webSocket; private readonly JObject _injectedObjects; private readonly IDictionary<int, TaskCompletionSource<JToken>> _callbacks; private bool _connected; private DataWriter _messageWriter; private int _requestId; private bool _isDisposed; public WebSocketJavaScriptExecutor() { _webSocket = new MessageWebSocket(); _webSocket.Control.MessageType = SocketMessageType.Utf8; _webSocket.MessageReceived += OnMessageReceived; _webSocket.Closed += OnClosed; _injectedObjects = new JObject(); _callbacks = new Dictionary<int, TaskCompletionSource<JToken>>(); } public async Task ConnectAsync(string webSocketServerUrl, CancellationToken token) { var uri = default(Uri); if (!Uri.TryCreate(webSocketServerUrl, UriKind.Absolute, out uri)) { throw new ArgumentOutOfRangeException(nameof(webSocketServerUrl), "Expected valid URI argument."); } var retryCount = ConnectRetryCount; while (true) { var timeoutSource = new CancellationTokenSource(ConnectTimeoutMilliseconds); using (token.Register(timeoutSource.Cancel)) { try { await ConnectCoreAsync(uri, timeoutSource.Token).ConfigureAwait(false); return; } catch (OperationCanceledException ex) when (ex.CancellationToken == timeoutSource.Token) { token.ThrowIfCancellationRequested(); } catch { if (--retryCount <= 0) { throw; } } } } } public JToken CallFunctionReturnFlushedQueue(string moduleName, string methodName, JArray arguments) { return Call("callFunctionReturnFlushedQueue", new JArray { moduleName, methodName, arguments, }); } public JToken InvokeCallbackAndReturnFlushedQueue(int callbackId, JArray arguments) { return Call("invokeCallbackAndReturnFlushedQueue", new JArray { callbackId, arguments, }); } public JToken FlushedQueue() { return Call("flushedQueue", new JArray()); } public void RunScript(string script, string sourceUrl) { var requestId = Interlocked.Increment(ref _requestId); var callback = new TaskCompletionSource<JToken>(); lock (_gate) { _callbacks.Add(requestId, callback); } try { var request = new JObject { { "id", requestId }, { "method", "executeApplicationScript" }, { "url", script }, { "inject", _injectedObjects }, }; SendMessageAsync(requestId, request.ToString(Formatting.None)).Wait(); callback.Task.Wait(); } catch (AggregateException ex) when (ex.InnerExceptions.Count == 1) { throw ex.InnerException; } finally { lock (_gate) { _callbacks.Remove(requestId); } } } public void SetGlobalVariable(string propertyName, JToken value) { _injectedObjects.Add(propertyName, value.ToString(Formatting.None)); } public void Dispose() { _isDisposed = true; _messageWriter.Dispose(); _webSocket.Dispose(); lock (_gate) { foreach (var callback in _callbacks) { // Set null rather than cancelling to prevent exception callback.Value.TrySetResult(null); } } } private JToken Call(string methodName, JArray arguments) { var requestId = Interlocked.Increment(ref _requestId); var callback = new TaskCompletionSource<JToken>(); lock (_gate) { _callbacks.Add(requestId, callback); } try { var request = new JObject { { "id", requestId }, { "method", methodName }, { "arguments", arguments }, }; SendMessageAsync(requestId, request.ToString(Formatting.None)).Wait(); return callback.Task.Result; } catch (AggregateException ex) when (ex.InnerExceptions.Count == 1) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); /* Should not */ throw; } finally { lock (_gate) { _callbacks.Remove(requestId); } } } private async Task ConnectCoreAsync(Uri uri, CancellationToken token) { var asyncAction = default(IAsyncAction); using (token.Register(() => asyncAction?.Cancel())) { if (!_connected) { asyncAction = _webSocket.ConnectAsync(uri); await asyncAction; _messageWriter = new DataWriter(_webSocket.OutputStream); _connected = true; } } await PrepareJavaScriptRuntimeAsync(token); } private async Task<JToken> PrepareJavaScriptRuntimeAsync(CancellationToken token) { var cancellationSource = new TaskCompletionSource<bool>(); using (token.Register(() => cancellationSource.SetResult(false))) { var requestId = Interlocked.Increment(ref _requestId); var callback = new TaskCompletionSource<JToken>(); lock (_gate) { _callbacks.Add(requestId, callback); } try { var request = new JObject { { "id", requestId }, { "method", "prepareJSRuntime" }, }; await SendMessageAsync(requestId, request.ToString(Formatting.None)); await Task.WhenAny(callback.Task, cancellationSource.Task); token.ThrowIfCancellationRequested(); return await callback.Task; } finally { lock (_gate) { _callbacks.Remove(requestId); } } } } private async Task SendMessageAsync(int requestId, string message) { if (!_isDisposed) { _messageWriter.WriteString(message); await _messageWriter.StoreAsync(); // TODO: check result of `StoreAsync()` } else { var callback = default(TaskCompletionSource<JToken>); if (_callbacks.TryGetValue(requestId, out callback)) { callback.TrySetResult(JValue.CreateNull()); } } } private void OnMessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { using (var reader = args.GetDataReader()) { reader.UnicodeEncoding = UnicodeEncoding.Utf8; var response = reader.ReadString(reader.UnconsumedBufferLength); var json = JObject.Parse(response); if (json.ContainsKey("replyID")) { var replyId = json.Value<int>("replyID"); var callback = default(TaskCompletionSource<JToken>); if (_callbacks.TryGetValue(replyId, out callback)) { var result = default(JToken); if (json != null && json.TryGetValue("result", out result)) { if (result.Type == JTokenType.String) { callback.TrySetResult(JToken.Parse(result.Value<string>())); } else { callback.TrySetResult(result); } } else { callback.TrySetResult(null); } } } } } private void OnClosed(IWebSocket sender, WebSocketClosedEventArgs args) { Dispose(); } } }
/* This file is licensed 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 NUnit.Framework; namespace Org.XmlUnit.Diff { public abstract class AbstractDifferenceEngineTest { protected abstract AbstractDifferenceEngine DifferenceEngine { get; } private ComparisonResult outcome = ComparisonResult.SIMILAR; private ComparisonResult ResultGrabber(Comparison comparison, ComparisonResult outcome) { this.outcome = outcome; return outcome; } [Test] public void CompareTwoNulls() { AbstractDifferenceEngine d = DifferenceEngine; d.DifferenceEvaluator = ResultGrabber; Assert.AreEqual(Wrap(ComparisonResult.EQUAL), d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, null, null, null, null, null, null, null, null))); Assert.AreEqual(ComparisonResult.EQUAL, outcome); } [Test] public void CompareControlNullTestNonNull() { AbstractDifferenceEngine d = DifferenceEngine; d.DifferenceEvaluator = ResultGrabber; Assert.AreEqual(Wrap(ComparisonResult.DIFFERENT), d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, null, null, null, null, null, null, "", null))); Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); } [Test] public void CompareControlNonNullTestNull() { AbstractDifferenceEngine d = DifferenceEngine; d.DifferenceEvaluator = ResultGrabber; Assert.AreEqual(Wrap(ComparisonResult.DIFFERENT), d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, null, null, "", null, null, null, null, null))); Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); } [Test] public void CompareTwoDifferentNonNulls() { AbstractDifferenceEngine d = DifferenceEngine; d.DifferenceEvaluator = ResultGrabber; Assert.AreEqual(Wrap(ComparisonResult.DIFFERENT), d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, null, null, Convert.ToInt16("1"), null, null, null, Convert.ToInt16("2"), null))); Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); } [Test] public void CompareTwoEqualNonNulls() { AbstractDifferenceEngine d = DifferenceEngine; d.DifferenceEvaluator = ResultGrabber; Assert.AreEqual(Wrap(ComparisonResult.EQUAL), d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, null, null, Convert.ToInt16("2"), null, null, null, Convert.ToInt16("2"), null))); Assert.AreEqual(ComparisonResult.EQUAL, outcome); } [Test] public void CompareNotifiesComparisonListener() { AbstractDifferenceEngine d = DifferenceEngine; int invocations = 0; d.ComparisonListener += delegate(Comparison comp, ComparisonResult r) { invocations++; Assert.AreEqual(ComparisonResult.EQUAL, r); }; Assert.AreEqual(Wrap(ComparisonResult.EQUAL), d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, null, null, Convert.ToInt16("2"), null, null, null, Convert.ToInt16("2"), null))); Assert.AreEqual(1, invocations); } [Test] public void CompareNotifiesMatchListener() { AbstractDifferenceEngine d = DifferenceEngine; int invocations = 0; d.MatchListener += delegate(Comparison comp, ComparisonResult r) { invocations++; Assert.AreEqual(ComparisonResult.EQUAL, r); }; Assert.AreEqual(Wrap(ComparisonResult.EQUAL), d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, null, null, Convert.ToInt16("2"), null, null, null, Convert.ToInt16("2"), null))); Assert.AreEqual(1, invocations); } [Test] public void CompareNotifiesDifferenceListener() { AbstractDifferenceEngine d = DifferenceEngine; int invocations = 0; d.DifferenceListener += delegate(Comparison comp, ComparisonResult r) { invocations++; Assert.AreEqual(ComparisonResult.SIMILAR, r); }; Assert.AreEqual(Wrap(ComparisonResult.SIMILAR), d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, null, null, Convert.ToInt16("2"), null, null, null, Convert.ToInt16("3"), null))); Assert.AreEqual(1, invocations); } [Test] public void CompareUsesResultOfEvaluator() { AbstractDifferenceEngine d = DifferenceEngine; int invocations = 0; d.ComparisonListener += delegate(Comparison comp, ComparisonResult r) { invocations++; Assert.AreEqual(ComparisonResult.SIMILAR, r); }; d.DifferenceEvaluator = delegate(Comparison comparison, ComparisonResult outcome) { return ComparisonResult.SIMILAR; }; Assert.AreEqual(Wrap(ComparisonResult.SIMILAR), d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, null, null, Convert.ToInt16("2"), null, null, null, Convert.ToInt16("2"), null))); Assert.AreEqual(1, invocations); } [Test] public void CompareUsesResultOfController() { AbstractDifferenceEngine d = DifferenceEngine; int invocations = 0; d.ComparisonListener += delegate(Comparison comp, ComparisonResult r) { invocations++; Assert.AreEqual(ComparisonResult.SIMILAR, r); }; d.ComparisonController = _ => true; Assert.AreEqual(WrapAndStop(ComparisonResult.SIMILAR), d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, null, null, Convert.ToInt16("1"), null, null, null, Convert.ToInt16("2"), null))); Assert.AreEqual(1, invocations); } [Test] public void OngoingComparisonStateBasics() { AbstractDifferenceEngine.ComparisonState cs = Wrap(ComparisonResult.EQUAL); Assert.AreEqual(cs, new AbstractDifferenceEngine.OngoingComparisonState(null)); } [Test] public void AndThenUsesCurrentFinishedFlag() { AbstractDifferenceEngine.ComparisonState cs = WrapAndStop(ComparisonResult.SIMILAR); Assert.AreEqual(WrapAndStop(ComparisonResult.SIMILAR), cs.AndThen(() => Wrap(ComparisonResult.EQUAL))); cs = Wrap(ComparisonResult.SIMILAR); Assert.AreEqual(Wrap(ComparisonResult.EQUAL), cs.AndThen(() => Wrap(ComparisonResult.EQUAL))); } [Test] public void AndIfTrueThenUsesCurrentFinishedFlag() { AbstractDifferenceEngine.ComparisonState cs = WrapAndStop(ComparisonResult.SIMILAR); Assert.AreEqual(WrapAndStop(ComparisonResult.SIMILAR), cs.AndIfTrueThen(true, () => Wrap(ComparisonResult.EQUAL))); cs = Wrap(ComparisonResult.SIMILAR); Assert.AreEqual(Wrap(ComparisonResult.EQUAL), cs.AndIfTrueThen(true, () => Wrap(ComparisonResult.EQUAL))); } [Test] public void AndIfTrueThenIsNoopIfFirstArgIsFalse() { AbstractDifferenceEngine.ComparisonState cs = WrapAndStop(ComparisonResult.SIMILAR); Assert.AreEqual(WrapAndStop(ComparisonResult.SIMILAR), cs.AndIfTrueThen(false, () => Wrap(ComparisonResult.EQUAL))); cs = Wrap(ComparisonResult.SIMILAR); Assert.AreEqual(Wrap(ComparisonResult.SIMILAR), cs.AndIfTrueThen(false, () => Wrap(ComparisonResult.EQUAL))); } [Test] public void CantSetNullNodeMatcher() { Assert.Throws<ArgumentNullException>(() => DifferenceEngine.NodeMatcher = null); } [Test] public void CantSetNullComparisonController() { Assert.Throws<ArgumentNullException>(() => DifferenceEngine.ComparisonController = null); } [Test] public void CantSetNullDifferenceEvaluator() { Assert.Throws<ArgumentNullException>(() => DifferenceEngine.DifferenceEvaluator = null); } [Test] public void CantSetNullAttributeFilter() { Assert.Throws<ArgumentNullException>(() => DifferenceEngine.AttributeFilter = null); } [Test] public void CantSetNullNodeFilter() { Assert.Throws<ArgumentNullException>(() => DifferenceEngine.NodeFilter = null); } [Test] public void ComparisonStateEqualsLooksAtType() { Assert.AreNotEqual(Wrap(ComparisonResult.SIMILAR), new MyOngoing()); } [Test] public void ComparisonStateEqualsLooksAtResult() { Assert.AreNotEqual(Wrap(ComparisonResult.SIMILAR), Wrap(ComparisonResult.DIFFERENT)); } [Test] public void HashCodeLooksAtFinished() { Assert.AreNotEqual(Wrap(ComparisonResult.SIMILAR).GetHashCode(), WrapAndStop(ComparisonResult.SIMILAR).GetHashCode()); } [Test] public void TrivialComparisonStateToString() { string s = Wrap(ComparisonResult.SIMILAR).ToString(); Assert.That(s, Does.Contain("OngoingComparisonState")); Assert.That(s, Does.Contain("SIMILAR")); } protected static AbstractDifferenceEngine.ComparisonState Wrap(ComparisonResult c) { return new AbstractDifferenceEngine.OngoingComparisonState(null, c); } protected static AbstractDifferenceEngine.ComparisonState WrapAndStop(ComparisonResult c) { return new AbstractDifferenceEngine.FinishedComparisonState(null, c); } internal class MyOngoing : AbstractDifferenceEngine.ComparisonState { internal MyOngoing() : base(null, false, ComparisonResult.SIMILAR) { } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for dsc nodes. (see /// http://aka.ms/azureautomationsdk/dscnodeoperations for more /// information) /// </summary> internal partial class DscNodeOperations : IServiceOperations<AutomationManagementClient>, IDscNodeOperations { /// <summary> /// Initializes a new instance of the DscNodeOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DscNodeOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Delete the dsc node identified by node id. (see /// http://aka.ms/azureautomationsdk/dscnodeoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. Automation account name. /// </param> /// <param name='nodeId'> /// Required. The node id. /// </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 automationAccount, Guid nodeId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // 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("automationAccount", automationAccount); tracingParameters.Add("nodeId", nodeId); 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/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodes/"; url = url + Uri.EscapeDataString(nodeId.ToString()); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); 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.Add("x-ms-version", "2014-06-01"); // 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 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> /// Retrieve the dsc node identified by node id. (see /// http://aka.ms/azureautomationsdk/dscnodeoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='nodeId'> /// Required. The node id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get dsc node operation. /// </returns> public async Task<DscNodeGetResponse> GetAsync(string resourceGroupName, string automationAccount, Guid nodeId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // 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("automationAccount", automationAccount); tracingParameters.Add("nodeId", nodeId); 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/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodes/"; url = url + Uri.EscapeDataString(nodeId.ToString()); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); 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", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // 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 DscNodeGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DscNode nodeInstance = new DscNode(); result.Node = nodeInstance; JToken lastSeenValue = responseDoc["lastSeen"]; if (lastSeenValue != null && lastSeenValue.Type != JTokenType.Null) { DateTimeOffset lastSeenInstance = ((DateTimeOffset)lastSeenValue); nodeInstance.LastSeen = lastSeenInstance; } JToken registrationTimeValue = responseDoc["registrationTime"]; if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null) { DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue); nodeInstance.RegistrationTime = registrationTimeInstance; } JToken ipValue = responseDoc["ip"]; if (ipValue != null && ipValue.Type != JTokenType.Null) { string ipInstance = ((string)ipValue); nodeInstance.Ip = ipInstance; } JToken accountIdValue = responseDoc["accountId"]; if (accountIdValue != null && accountIdValue.Type != JTokenType.Null) { Guid accountIdInstance = Guid.Parse(((string)accountIdValue)); nodeInstance.AccountId = accountIdInstance; } JToken nodeConfigurationValue = responseDoc["nodeConfiguration"]; if (nodeConfigurationValue != null && nodeConfigurationValue.Type != JTokenType.Null) { DscNodeConfigurationAssociationProperty nodeConfigurationInstance = new DscNodeConfigurationAssociationProperty(); nodeInstance.NodeConfiguration = nodeConfigurationInstance; JToken nameValue = nodeConfigurationValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); nodeConfigurationInstance.Name = nameInstance; } } JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); nodeInstance.Status = statusInstance; } JToken nodeIdValue = responseDoc["nodeId"]; if (nodeIdValue != null && nodeIdValue.Type != JTokenType.Null) { Guid nodeIdInstance = Guid.Parse(((string)nodeIdValue)); nodeInstance.NodeId = nodeIdInstance; } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); nodeInstance.Id = idInstance; } JToken nameValue2 = responseDoc["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); nodeInstance.Name = nameInstance2; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); nodeInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); nodeInstance.Tags.Add(tagsKey, tagsValue); } } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); nodeInstance.Type = typeInstance; } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); nodeInstance.Etag = etagInstance; } } } 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> /// Retrieve a list of dsc nodes. (see /// http://aka.ms/azureautomationsdk/dscnodeoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Optional. The parameters supplied to the list operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list dsc nodes operation. /// </returns> public async Task<DscNodeListResponse> ListAsync(string resourceGroupName, string automationAccount, DscNodeListParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // 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("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodes"; List<string> queryParameters = new List<string>(); List<string> odataFilter = new List<string>(); if (parameters != null && parameters.Status != null) { odataFilter.Add("status eq '" + Uri.EscapeDataString(parameters.Status) + "'"); } if (parameters != null && parameters.NodeConfigurationName != null) { odataFilter.Add("nodeConfiguration/name eq '" + Uri.EscapeDataString(parameters.NodeConfigurationName) + "'"); } if (parameters != null && parameters.Name != null) { odataFilter.Add("name eq '" + Uri.EscapeDataString(parameters.Name) + "'"); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(" and ", odataFilter)); } queryParameters.Add("api-version=2015-10-31"); 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", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // 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 DscNodeListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DscNode dscNodeInstance = new DscNode(); result.Nodes.Add(dscNodeInstance); JToken lastSeenValue = valueValue["lastSeen"]; if (lastSeenValue != null && lastSeenValue.Type != JTokenType.Null) { DateTimeOffset lastSeenInstance = ((DateTimeOffset)lastSeenValue); dscNodeInstance.LastSeen = lastSeenInstance; } JToken registrationTimeValue = valueValue["registrationTime"]; if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null) { DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue); dscNodeInstance.RegistrationTime = registrationTimeInstance; } JToken ipValue = valueValue["ip"]; if (ipValue != null && ipValue.Type != JTokenType.Null) { string ipInstance = ((string)ipValue); dscNodeInstance.Ip = ipInstance; } JToken accountIdValue = valueValue["accountId"]; if (accountIdValue != null && accountIdValue.Type != JTokenType.Null) { Guid accountIdInstance = Guid.Parse(((string)accountIdValue)); dscNodeInstance.AccountId = accountIdInstance; } JToken nodeConfigurationValue = valueValue["nodeConfiguration"]; if (nodeConfigurationValue != null && nodeConfigurationValue.Type != JTokenType.Null) { DscNodeConfigurationAssociationProperty nodeConfigurationInstance = new DscNodeConfigurationAssociationProperty(); dscNodeInstance.NodeConfiguration = nodeConfigurationInstance; JToken nameValue = nodeConfigurationValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); nodeConfigurationInstance.Name = nameInstance; } } JToken statusValue = valueValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); dscNodeInstance.Status = statusInstance; } JToken nodeIdValue = valueValue["nodeId"]; if (nodeIdValue != null && nodeIdValue.Type != JTokenType.Null) { Guid nodeIdInstance = Guid.Parse(((string)nodeIdValue)); dscNodeInstance.NodeId = nodeIdInstance; } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dscNodeInstance.Id = idInstance; } JToken nameValue2 = valueValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); dscNodeInstance.Name = nameInstance2; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dscNodeInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dscNodeInstance.Tags.Add(tagsKey, tagsValue); } } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); dscNodeInstance.Type = typeInstance; } JToken etagValue = valueValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); dscNodeInstance.Etag = etagInstance; } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve next list of configurations. (see /// http://aka.ms/azureautomationsdk/dscnodeoperations for more /// information) /// </summary> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list dsc nodes operation. /// </returns> public async Task<DscNodeListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // 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 DscNodeListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DscNode dscNodeInstance = new DscNode(); result.Nodes.Add(dscNodeInstance); JToken lastSeenValue = valueValue["lastSeen"]; if (lastSeenValue != null && lastSeenValue.Type != JTokenType.Null) { DateTimeOffset lastSeenInstance = ((DateTimeOffset)lastSeenValue); dscNodeInstance.LastSeen = lastSeenInstance; } JToken registrationTimeValue = valueValue["registrationTime"]; if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null) { DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue); dscNodeInstance.RegistrationTime = registrationTimeInstance; } JToken ipValue = valueValue["ip"]; if (ipValue != null && ipValue.Type != JTokenType.Null) { string ipInstance = ((string)ipValue); dscNodeInstance.Ip = ipInstance; } JToken accountIdValue = valueValue["accountId"]; if (accountIdValue != null && accountIdValue.Type != JTokenType.Null) { Guid accountIdInstance = Guid.Parse(((string)accountIdValue)); dscNodeInstance.AccountId = accountIdInstance; } JToken nodeConfigurationValue = valueValue["nodeConfiguration"]; if (nodeConfigurationValue != null && nodeConfigurationValue.Type != JTokenType.Null) { DscNodeConfigurationAssociationProperty nodeConfigurationInstance = new DscNodeConfigurationAssociationProperty(); dscNodeInstance.NodeConfiguration = nodeConfigurationInstance; JToken nameValue = nodeConfigurationValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); nodeConfigurationInstance.Name = nameInstance; } } JToken statusValue = valueValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); dscNodeInstance.Status = statusInstance; } JToken nodeIdValue = valueValue["nodeId"]; if (nodeIdValue != null && nodeIdValue.Type != JTokenType.Null) { Guid nodeIdInstance = Guid.Parse(((string)nodeIdValue)); dscNodeInstance.NodeId = nodeIdInstance; } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dscNodeInstance.Id = idInstance; } JToken nameValue2 = valueValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); dscNodeInstance.Name = nameInstance2; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dscNodeInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dscNodeInstance.Tags.Add(tagsKey, tagsValue); } } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); dscNodeInstance.Type = typeInstance; } JToken etagValue = valueValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); dscNodeInstance.Etag = etagInstance; } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Update the dsc node. (see /// http://aka.ms/azureautomationsdk/dscnodeoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the patch dsc node. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the patch dsc node operation. /// </returns> public async Task<DscNodePatchResponse> PatchAsync(string resourceGroupName, string automationAccount, DscNodePatchParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // 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("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "PatchAsync", 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/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodes/"; if (parameters.NodeId != null) { url = url + Uri.EscapeDataString(parameters.NodeId.ToString()); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject dscNodePatchParametersValue = new JObject(); requestDoc = dscNodePatchParametersValue; dscNodePatchParametersValue["nodeId"] = parameters.NodeId.ToString(); if (parameters.NodeConfiguration != null) { JObject nodeConfigurationValue = new JObject(); dscNodePatchParametersValue["nodeConfiguration"] = nodeConfigurationValue; if (parameters.NodeConfiguration.Name != null) { nodeConfigurationValue["name"] = parameters.NodeConfiguration.Name; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DscNodePatchResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodePatchResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DscNode nodeInstance = new DscNode(); result.Node = nodeInstance; JToken lastSeenValue = responseDoc["lastSeen"]; if (lastSeenValue != null && lastSeenValue.Type != JTokenType.Null) { DateTimeOffset lastSeenInstance = ((DateTimeOffset)lastSeenValue); nodeInstance.LastSeen = lastSeenInstance; } JToken registrationTimeValue = responseDoc["registrationTime"]; if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null) { DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue); nodeInstance.RegistrationTime = registrationTimeInstance; } JToken ipValue = responseDoc["ip"]; if (ipValue != null && ipValue.Type != JTokenType.Null) { string ipInstance = ((string)ipValue); nodeInstance.Ip = ipInstance; } JToken accountIdValue = responseDoc["accountId"]; if (accountIdValue != null && accountIdValue.Type != JTokenType.Null) { Guid accountIdInstance = Guid.Parse(((string)accountIdValue)); nodeInstance.AccountId = accountIdInstance; } JToken nodeConfigurationValue2 = responseDoc["nodeConfiguration"]; if (nodeConfigurationValue2 != null && nodeConfigurationValue2.Type != JTokenType.Null) { DscNodeConfigurationAssociationProperty nodeConfigurationInstance = new DscNodeConfigurationAssociationProperty(); nodeInstance.NodeConfiguration = nodeConfigurationInstance; JToken nameValue = nodeConfigurationValue2["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); nodeConfigurationInstance.Name = nameInstance; } } JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); nodeInstance.Status = statusInstance; } JToken nodeIdValue = responseDoc["nodeId"]; if (nodeIdValue != null && nodeIdValue.Type != JTokenType.Null) { Guid nodeIdInstance = Guid.Parse(((string)nodeIdValue)); nodeInstance.NodeId = nodeIdInstance; } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); nodeInstance.Id = idInstance; } JToken nameValue2 = responseDoc["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); nodeInstance.Name = nameInstance2; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); nodeInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); nodeInstance.Tags.Add(tagsKey, tagsValue); } } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); nodeInstance.Type = typeInstance; } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); nodeInstance.Etag = etagInstance; } } } 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.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 webapiskeleton.Areas.HelpPage.ModelDescriptions; using webapiskeleton.Areas.HelpPage.Models; namespace webapiskeleton.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); } } } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> using System; using UnityEngine; using UnityEditor; namespace AmplifyShaderEditor { [Serializable] public sealed class InputPort : WirePort { private const string InputDefaultNameStr = "Input"; [SerializeField] private bool m_typeLocked; [SerializeField] private string m_internalData = string.Empty; [SerializeField] private string m_internalDataWrapper = string.Empty; [SerializeField] private string m_dataName = string.Empty; [SerializeField] private string m_internalDataPropertyLabel = string.Empty; // this will only is important on master node [SerializeField] private MasterNodePortCategory m_category = MasterNodePortCategory.Fragment; private string m_propertyName = string.Empty; private int m_cachedPropertyId = -1; private int m_cachedFloatShaderID = -1; private int m_cachedVectorShaderID = -1; private int m_cachedColorShaderID = -1; //[SerializeField] //private RenderTexture m_inputPreview = null; //[SerializeField] private RenderTexture m_inputPreviewTexture = null; private Material m_inputPreviewMaterial = null; private Shader m_inputPreviewShader = null; public InputPort() : base( -1, -1, WirePortDataType.FLOAT, string.Empty ) { m_typeLocked = true; UpdateInternalData(); } public InputPort( int nodeId, int portId, WirePortDataType dataType, string name, bool typeLocked, int orderId = -1, MasterNodePortCategory category = MasterNodePortCategory.Fragment ) : base( nodeId, portId, dataType, name, orderId ) { m_dataName = name; m_internalDataPropertyLabel = ( string.IsNullOrEmpty( name ) || name.Equals( Constants.EmptyPortValue ) ) ? InputDefaultNameStr : name; m_typeLocked = typeLocked; m_category = category; UpdateInternalData(); } public InputPort( int nodeId, int portId, WirePortDataType dataType, string name, string dataName, bool typeLocked, int orderId = -1, MasterNodePortCategory category = MasterNodePortCategory.Fragment ) : base( nodeId, portId, dataType, name, orderId ) { m_dataName = dataName; m_internalDataPropertyLabel = ( string.IsNullOrEmpty( name ) || name.Equals( Constants.EmptyPortValue ) ) ? InputDefaultNameStr : name; m_typeLocked = typeLocked; m_category = category; UpdateInternalData(); } public override void FullDeleteConnections() { UIUtils.DeleteConnection( true, m_nodeId, m_portId, true, true ); } public override void NotifyExternalRefencesOnChange() { for ( int i = 0; i < m_externalReferences.Count; i++ ) { ParentNode node = UIUtils.GetNode( m_externalReferences[ i ].NodeId ); if ( node ) { OutputPort port = node.GetOutputPortByUniqueId( m_externalReferences[ i ].PortId ); port.UpdateInfoOnExternalConn( m_nodeId, m_portId, m_dataType ); node.OnConnectedInputNodeChanges( m_externalReferences[ i ].PortId, m_nodeId, m_portId, m_name, m_dataType ); } } } public void UpdateInternalData() { string[] data = String.IsNullOrEmpty( m_internalData ) ? null : m_internalData.Split( IOUtils.VECTOR_SEPARATOR ); switch ( m_dataType ) { case WirePortDataType.OBJECT: case WirePortDataType.FLOAT: { m_internalData = ( data == null ) ? "0.0" : data[ 0 ]; m_internalDataWrapper = string.Empty; } break; case WirePortDataType.INT: { if ( data == null ) { m_internalData = "0"; } else { string[] intData = data[ 0 ].Split( IOUtils.FLOAT_SEPARATOR ); m_internalData = ( intData.Length == 0 ) ? "0" : intData[ 0 ]; } m_internalDataWrapper = string.Empty; } break; case WirePortDataType.FLOAT2: { if ( data == null ) { m_internalData = "0" + IOUtils.VECTOR_SEPARATOR + "0"; } else { m_internalData = ( data.Length < 2 ) ? ( data[ 0 ] + IOUtils.VECTOR_SEPARATOR + "0" ) : ( data[ 0 ] + IOUtils.VECTOR_SEPARATOR + data[ 1 ] ); } m_internalDataWrapper = "float2( {0} )"; } break; case WirePortDataType.FLOAT3: { if ( data == null ) { m_internalData = "0" + IOUtils.VECTOR_SEPARATOR + "0" + IOUtils.VECTOR_SEPARATOR + "0"; } else { if ( data.Length < 3 ) { if ( data.Length == 1 ) { m_internalData = data[ 0 ] + IOUtils.VECTOR_SEPARATOR + "0" + IOUtils.VECTOR_SEPARATOR + "0"; } else { m_internalData = data[ 0 ] + IOUtils.VECTOR_SEPARATOR + data[ 1 ] + IOUtils.VECTOR_SEPARATOR + "0"; } } else if ( data.Length > 3 ) { m_internalData = data[ 0 ] + IOUtils.VECTOR_SEPARATOR + data[ 1 ] + IOUtils.VECTOR_SEPARATOR + data[ 2 ]; } } m_internalDataWrapper = "float3( {0} )"; } break; case WirePortDataType.FLOAT4: case WirePortDataType.COLOR: { if ( data == null ) { m_internalData = "0" + IOUtils.VECTOR_SEPARATOR + "0" + IOUtils.VECTOR_SEPARATOR + "0" + IOUtils.VECTOR_SEPARATOR + "0"; } else { if ( data.Length > 4 ) { m_internalData = string.Empty; for ( int i = 0; i < 3; i++ ) { m_internalData += data[ i ] + IOUtils.VECTOR_SEPARATOR; } m_internalData += data[ 3 ]; } else if ( data.Length < 4 ) { m_internalData = string.Empty; int i; for ( i = 0; i < data.Length; i++ ) { m_internalData += data[ i ] + IOUtils.VECTOR_SEPARATOR; } for ( ; i < 3; i++ ) { m_internalData += "0" + IOUtils.VECTOR_SEPARATOR; } m_internalData += "0"; } } m_internalDataWrapper = "float4( {0} )"; } break; case WirePortDataType.FLOAT3x3: case WirePortDataType.FLOAT4x4: { if ( data == null ) { for ( int i = 0; i < 15; i++ ) { m_internalData += "0" + IOUtils.VECTOR_SEPARATOR; } m_internalData += "0"; } else { if ( data.Length < 16 ) { m_internalData = string.Empty; int i; for ( i = 0; i < data.Length; i++ ) { m_internalData += data[ i ] + IOUtils.VECTOR_SEPARATOR; } for ( ; i < 15; i++ ) { m_internalData += "0" + IOUtils.VECTOR_SEPARATOR; } m_internalData += "0"; } } m_internalDataWrapper = "float4x4( {0} )"; } break; } } //TODO: Replace GenerateShaderForOutput(...) calls to this one // This is a new similar method to GenerateShaderForOutput(...) which always autocasts public string GeneratePortInstructions( ref MasterNodeDataCollector dataCollector ) { string result = string.Empty; if ( m_externalReferences.Count > 0 && !m_locked ) { result = UIUtils.GetNode( m_externalReferences[ 0 ].NodeId ).GenerateShaderForOutput( m_externalReferences[ 0 ].PortId, ref dataCollector, false ); if ( m_externalReferences[ 0 ].DataType != m_dataType ) { result = UIUtils.CastPortType( ref dataCollector, UIUtils.GetNode( m_nodeId ).CurrentPrecisionType, new NodeCastInfo( m_externalReferences[ 0 ].NodeId, m_externalReferences[ 0 ].PortId ), null, m_externalReferences[ 0 ].DataType, m_dataType, result ); } } else { result = !String.IsNullOrEmpty( m_internalDataWrapper ) ? String.Format( m_internalDataWrapper, m_internalData ) : m_internalData; } return result; } public string GenerateShaderForOutput( ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar ) { string result = string.Empty; if ( m_externalReferences.Count > 0 && !m_locked ) { result = UIUtils.GetNode( m_externalReferences[ 0 ].NodeId ).GenerateShaderForOutput( m_externalReferences[ 0 ].PortId, ref dataCollector, ignoreLocalVar ); } else { if ( !String.IsNullOrEmpty( m_internalDataWrapper ) ) { result = String.Format( m_internalDataWrapper, m_internalData ); } else { result = m_internalData; } } return result; } public string GenerateShaderForOutput( ref MasterNodeDataCollector dataCollector, WirePortDataType inputPortType, bool ignoreLocalVar, bool autoCast = false ) { string result = string.Empty; if ( m_externalReferences.Count > 0 && !m_locked ) { result = UIUtils.GetNode( m_externalReferences[ 0 ].NodeId ).GenerateShaderForOutput( m_externalReferences[ 0 ].PortId, ref dataCollector, ignoreLocalVar ); if ( autoCast && m_externalReferences[ 0 ].DataType != inputPortType ) { result = UIUtils.CastPortType( ref dataCollector, UIUtils.GetNode( m_nodeId ).CurrentPrecisionType, new NodeCastInfo( m_externalReferences[ 0 ].NodeId, m_externalReferences[ 0 ].PortId ), null, m_externalReferences[ 0 ].DataType, inputPortType, result ); } } else { if ( !String.IsNullOrEmpty( m_internalDataWrapper ) ) { result = String.Format( m_internalDataWrapper, m_internalData ); } else { result = m_internalData; } } return result; } public OutputPort GetOutputConnection( int connID = 0 ) { if ( connID < m_externalReferences.Count ) { return UIUtils.GetNode( m_externalReferences[ connID ].NodeId ).OutputPorts[ m_externalReferences[ connID ].PortId ]; } return null; } public ParentNode GetOutputNode( int connID = 0 ) { if ( connID < m_externalReferences.Count ) { return UIUtils.GetNode( m_externalReferences[ connID ].NodeId ); } return null; } public bool TypeLocked { get { return m_typeLocked; } } public void WriteToString( ref string myString ) { if ( m_externalReferences.Count != 1 ) { return; } IOUtils.AddTypeToString( ref myString, IOUtils.WireConnectionParam ); IOUtils.AddFieldValueToString( ref myString, m_nodeId ); IOUtils.AddFieldValueToString( ref myString, m_portId ); IOUtils.AddFieldValueToString( ref myString, m_externalReferences[ 0 ].NodeId ); IOUtils.AddFieldValueToString( ref myString, m_externalReferences[ 0 ].PortId ); IOUtils.AddLineTerminator( ref myString ); } public void ShowInternalData( UndoParentNode owner, bool useCustomLabel = false, string customLabel = null ) { string label = ( useCustomLabel == true && customLabel != null ) ? customLabel : m_internalDataPropertyLabel; switch ( m_dataType ) { case WirePortDataType.OBJECT: case WirePortDataType.FLOAT: { FloatInternalData = owner.EditorGUILayoutFloatField( label, FloatInternalData ); } break; case WirePortDataType.FLOAT2: { Vector2InternalData = owner.EditorGUILayoutVector2Field( label, Vector2InternalData ); } break; case WirePortDataType.FLOAT3: { Vector3InternalData = owner.EditorGUILayoutVector3Field( label, Vector3InternalData ); } break; case WirePortDataType.FLOAT4: { Vector4InternalData = owner.EditorGUILayoutVector4Field( label, Vector4InternalData ); } break; case WirePortDataType.FLOAT3x3: case WirePortDataType.FLOAT4x4: { Matrix4x4 matrix = Matrix4x4InternalData; for ( int i = 0; i < 4; i++ ) { Vector4 currVec = matrix.GetRow( i ); EditorGUI.BeginChangeCheck(); currVec = owner.EditorGUILayoutVector4Field( label + "[ " + i + " ]", currVec ); if ( EditorGUI.EndChangeCheck() ) { matrix.SetRow( i, currVec ); } } Matrix4x4InternalData = matrix; } break; case WirePortDataType.COLOR: { ColorInternalData = owner.EditorGUILayoutColorField( label, ColorInternalData ); } break; case WirePortDataType.INT: { IntInternalData = owner.EditorGUILayoutIntField( label, IntInternalData ); } break; } } public float FloatInternalData { set { InternalData = value.ToString(); if ( value % 1 == 0 ) { m_internalData += ".0"; } } get { float data = 0f; try { data = Convert.ToSingle( m_internalData ); } catch ( Exception e ) { data = 0f; FloatInternalData = data; if ( DebugConsoleWindow.DeveloperMode ) Debug.LogException( e ); } return data; } } public int IntInternalData { set { InternalData = value.ToString(); } get { int data = 0; try { data = Convert.ToInt32( m_internalData ); } catch ( Exception e) { data = 0; IntInternalData = data; if ( DebugConsoleWindow.DeveloperMode ) Debug.LogException( e ); } return data; } } public Vector2 Vector2InternalData { set { InternalData = value.x.ToString() + IOUtils.VECTOR_SEPARATOR + value.y.ToString(); } get { Vector2 data = new Vector2(); string[] components = m_internalData.Split( IOUtils.VECTOR_SEPARATOR ); if ( components.Length >= 2 ) { try { data.x = Convert.ToSingle( components[ 0 ] ); data.y = Convert.ToSingle( components[ 1 ] ); } catch ( Exception e ) { data = Vector2.zero; Vector2InternalData = data; if ( DebugConsoleWindow.DeveloperMode ) Debug.LogException( e ); } } else { Vector2InternalData = data; if ( DebugConsoleWindow.DeveloperMode ) Debug.LogError( "Length smaller than 2" ); } return data; } } public Vector3 Vector3InternalData { set { InternalData = value.x.ToString() + IOUtils.VECTOR_SEPARATOR + value.y.ToString() + IOUtils.VECTOR_SEPARATOR + value.z.ToString(); } get { Vector3 data = new Vector3(); string[] components = m_internalData.Split( IOUtils.VECTOR_SEPARATOR ); if ( components.Length >= 3 ) { try { data.x = Convert.ToSingle( components[ 0 ] ); data.y = Convert.ToSingle( components[ 1 ] ); data.z = Convert.ToSingle( components[ 2 ] ); } catch ( Exception e) { data = Vector3.zero; Vector3InternalData = data; if ( DebugConsoleWindow.DeveloperMode ) Debug.LogException( e ); } } else { Vector3InternalData = data; if ( DebugConsoleWindow.DeveloperMode ) Debug.LogError( "Length smaller than 3" ); } return data; } } public Vector4 Vector4InternalData { set { InternalData = value.x.ToString() + IOUtils.VECTOR_SEPARATOR + value.y.ToString() + IOUtils.VECTOR_SEPARATOR + value.z.ToString() + IOUtils.VECTOR_SEPARATOR + value.w.ToString(); } get { Vector4 data = new Vector4(); string[] components = m_internalData.Split( IOUtils.VECTOR_SEPARATOR ); if ( components.Length >= 4 ) { try { data.x = Convert.ToSingle( components[ 0 ] ); data.y = Convert.ToSingle( components[ 1 ] ); data.z = Convert.ToSingle( components[ 2 ] ); data.w = Convert.ToSingle( components[ 3 ] ); } catch ( Exception e) { data = Vector4.zero; Vector4InternalData = data; if ( DebugConsoleWindow.DeveloperMode ) Debug.LogException( e ); } } else { Vector4InternalData = data; if ( DebugConsoleWindow.DeveloperMode ) Debug.LogError( "Length smaller than 4" ); } return data; } } public Color ColorInternalData { set { InternalData = value.r.ToString() + IOUtils.VECTOR_SEPARATOR + value.g.ToString() + IOUtils.VECTOR_SEPARATOR + value.b.ToString() + IOUtils.VECTOR_SEPARATOR + value.a.ToString(); } get { Color data = new Color(); string[] components = m_internalData.Split( IOUtils.VECTOR_SEPARATOR ); if ( components.Length >= 4 ) { try { data.r = Convert.ToSingle( components[ 0 ] ); data.g = Convert.ToSingle( components[ 1 ] ); data.b = Convert.ToSingle( components[ 2 ] ); data.a = Convert.ToSingle( components[ 3 ] ); } catch ( Exception e ) { data = Color.clear; ColorInternalData = data; if ( DebugConsoleWindow.DeveloperMode ) Debug.LogException( e ); } } else { ColorInternalData = data; if ( DebugConsoleWindow.DeveloperMode ) Debug.LogError( "Length smaller than 4" ); } return data; } } public Matrix4x4 Matrix4x4InternalData { set { InternalData = value[ 0, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 0, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 0, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 0, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 1, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 1, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 1, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 1, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 2, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 2, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 2, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 2, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 3, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 3, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 3, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + value[ 3, 3 ].ToString(); } get { Matrix4x4 data = new Matrix4x4(); string[] components = m_internalData.Split( IOUtils.VECTOR_SEPARATOR ); if ( components.Length >= 16 ) { try { data[ 0, 0 ] = Convert.ToSingle( components[ 0 ] ); data[ 0, 1 ] = Convert.ToSingle( components[ 1 ] ); data[ 0, 2 ] = Convert.ToSingle( components[ 2 ] ); data[ 0, 3 ] = Convert.ToSingle( components[ 3 ] ); data[ 1, 0 ] = Convert.ToSingle( components[ 4 ] ); data[ 1, 1 ] = Convert.ToSingle( components[ 5 ] ); data[ 1, 2 ] = Convert.ToSingle( components[ 6 ] ); data[ 1, 3 ] = Convert.ToSingle( components[ 7 ] ); data[ 2, 0 ] = Convert.ToSingle( components[ 8 ] ); data[ 2, 1 ] = Convert.ToSingle( components[ 9 ] ); data[ 2, 2 ] = Convert.ToSingle( components[ 10 ] ); data[ 2, 3 ] = Convert.ToSingle( components[ 11 ] ); data[ 3, 0 ] = Convert.ToSingle( components[ 12 ] ); data[ 3, 1 ] = Convert.ToSingle( components[ 13 ] ); data[ 3, 2 ] = Convert.ToSingle( components[ 14 ] ); data[ 3, 3 ] = Convert.ToSingle( components[ 15 ] ); } catch ( Exception e ) { Matrix4x4InternalData = data; if ( DebugConsoleWindow.DeveloperMode ) Debug.LogException( e ); } } else { Matrix4x4InternalData = data; if ( DebugConsoleWindow.DeveloperMode ) Debug.LogError( "Length smaller than 16" ); } return data; } } public override void ForceClearConnection() { UIUtils.DeleteConnection( true, m_nodeId, m_portId, false, true ); } public string InternalData { get { return m_internalData; } set { if ( !value.Equals( m_internalData ) ) { m_internalData = value; } } } public string WrappedInternalData { get { return string.IsNullOrEmpty( m_internalDataWrapper ) ? m_internalData : String.Format( m_internalDataWrapper, m_internalData ); } } public override WirePortDataType DataType { get { return base.DataType; } // must be set to update internal data. do not delete set { if ( base.DataType != value ) { base.DataType = value; if ( m_externalReferences.Count == 0 ) UpdateInternalData(); } } } public string DataName { get { return m_dataName; } set { m_dataName = value; } } public MasterNodePortCategory Category { set { m_category = value; } get { return m_category; } } private int CachedFloatPropertyID { get { if ( m_cachedFloatShaderID == -1 ) m_cachedFloatShaderID = Shader.PropertyToID( "_InputFloat" ); return m_cachedFloatShaderID; } } private int CachedVectorPropertyID { get { if ( m_cachedVectorShaderID == -1 ) m_cachedVectorShaderID = Shader.PropertyToID( "_InputVector" ); return m_cachedVectorShaderID; } } private int CachedColorPropertyID { get { if ( m_cachedColorShaderID == -1 ) m_cachedColorShaderID = Shader.PropertyToID( "_InputColor" ); return m_cachedColorShaderID; } } public bool InputNodeHasPreview() { return GetOutputNode( 0 ).HasPreviewShader; } public void SetPreviewInputTexture() { if( string.IsNullOrEmpty( m_propertyName) ) m_propertyName = "_" + Convert.ToChar( PortId + 65 ); if ( m_cachedPropertyId == -1 ) m_cachedPropertyId = Shader.PropertyToID( m_propertyName ); UIUtils.GetNode( NodeId ).PreviewMaterial.SetTexture( m_cachedPropertyId, GetOutputConnection( 0 ).OutputPreviewTexture ); } public void SetPreviewInputValue() { if ( m_inputPreviewTexture == null ) m_inputPreviewTexture = new RenderTexture( 128, 128, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear ); switch ( DataType ) { case WirePortDataType.FLOAT: { if( m_inputPreviewShader != UIUtils.FloatShader ) { m_inputPreviewShader = UIUtils.FloatShader; InputPreviewMaterial.shader = m_inputPreviewShader; } float f = FloatInternalData; InputPreviewMaterial.SetFloat( CachedFloatPropertyID, f ); } break; case WirePortDataType.FLOAT2: { if ( m_inputPreviewShader != UIUtils.Vector2Shader ) { m_inputPreviewShader = UIUtils.Vector2Shader; InputPreviewMaterial.shader = m_inputPreviewShader; } Vector2 v2 = Vector2InternalData; InputPreviewMaterial.SetVector( CachedVectorPropertyID, new Vector4( v2.x, v2.y, 0, 0 ) ); } break; case WirePortDataType.FLOAT3: { if ( m_inputPreviewShader != UIUtils.Vector3Shader ) { m_inputPreviewShader = UIUtils.Vector3Shader; InputPreviewMaterial.shader = m_inputPreviewShader; } Vector3 v3 = Vector3InternalData; InputPreviewMaterial.SetVector( CachedVectorPropertyID, new Vector4( v3.x, v3.y, v3.z, 0 ) ); } break; case WirePortDataType.FLOAT4: { if ( m_inputPreviewShader != UIUtils.Vector4Shader ) { m_inputPreviewShader = UIUtils.Vector4Shader; InputPreviewMaterial.shader = m_inputPreviewShader; } InputPreviewMaterial.SetVector( CachedVectorPropertyID, Vector4InternalData ); } break; case WirePortDataType.COLOR: { if ( m_inputPreviewShader != UIUtils.ColorShader ) { m_inputPreviewShader = UIUtils.ColorShader; InputPreviewMaterial.shader = m_inputPreviewShader; } InputPreviewMaterial.SetColor( CachedColorPropertyID, ColorInternalData ); } break; case WirePortDataType.FLOAT3x3: case WirePortDataType.FLOAT4x4: { if ( m_inputPreviewShader != UIUtils.FloatShader ) { m_inputPreviewShader = UIUtils.FloatShader; InputPreviewMaterial.shader = m_inputPreviewShader; } InputPreviewMaterial.SetFloat( CachedFloatPropertyID, 1 ); } break; default: { if ( m_inputPreviewShader != UIUtils.FloatShader ) { m_inputPreviewShader = UIUtils.FloatShader; InputPreviewMaterial.shader = m_inputPreviewShader; } InputPreviewMaterial.SetFloat( CachedFloatPropertyID, 0 ); } break; } RenderTexture temp = RenderTexture.active; RenderTexture.active = m_inputPreviewTexture; Graphics.Blit( null, m_inputPreviewTexture, InputPreviewMaterial ); RenderTexture.active = temp; if ( string.IsNullOrEmpty( m_propertyName ) ) m_propertyName = "_" + Convert.ToChar( PortId + 65 ); if ( m_cachedPropertyId == -1 ) m_cachedPropertyId = Shader.PropertyToID( m_propertyName ); UIUtils.GetNode( NodeId ).PreviewMaterial.SetTexture( m_propertyName, m_inputPreviewTexture ); } public override void Destroy() { base.Destroy(); //if ( m_inputPreview != null ) // UnityEngine.ScriptableObject.DestroyImmediate( m_inputPreview ); //m_inputPreview = null; if ( m_inputPreviewTexture != null ) UnityEngine.ScriptableObject.DestroyImmediate( m_inputPreviewTexture ); m_inputPreviewTexture = null; if ( m_inputPreviewMaterial != null ) UnityEngine.ScriptableObject.DestroyImmediate( m_inputPreviewMaterial ); m_inputPreviewMaterial = null; m_inputPreviewShader = null; } public Shader InputPreviewShader { get { if ( m_inputPreviewShader == null ) m_inputPreviewShader = AssetDatabase.LoadAssetAtPath<Shader>( AssetDatabase.GUIDToAssetPath( "d9ca47581ac157145bff6f72ac5dd73e" ) ); //ranged float if ( m_inputPreviewShader == null ) m_inputPreviewShader = Shader.Find( "Unlit/Colored Transparent" ); return m_inputPreviewShader; } set { m_inputPreviewShader = value; } } public Material InputPreviewMaterial { get { if ( m_inputPreviewMaterial == null ) m_inputPreviewMaterial = new Material( InputPreviewShader ); return m_inputPreviewMaterial; } //set //{ // m_inputPreviewMaterial = value; //} } public override string Name { get { return m_name; } set { m_name = value; m_internalDataPropertyLabel = ( string.IsNullOrEmpty( value ) || value.Equals( Constants.EmptyPortValue ) ) ? InputDefaultNameStr : value; m_dirtyLabelSize = true; } } public string InternalDataName { get { return m_internalDataPropertyLabel; } set { m_internalDataPropertyLabel = value; } } public bool ValidInternalData { get { switch ( m_dataType ) { case WirePortDataType.FLOAT: case WirePortDataType.FLOAT2: case WirePortDataType.FLOAT3: case WirePortDataType.FLOAT4: case WirePortDataType.FLOAT3x3: case WirePortDataType.FLOAT4x4: case WirePortDataType.COLOR: case WirePortDataType.INT:return true; case WirePortDataType.OBJECT: case WirePortDataType.SAMPLER1D: case WirePortDataType.SAMPLER2D: case WirePortDataType.SAMPLER3D: case WirePortDataType.SAMPLERCUBE: default:return false; } } } public RenderTexture InputPreviewTexture { get { if ( IsConnected ) return GetOutputConnection( 0 ).OutputPreviewTexture; else return m_inputPreviewTexture; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using OLEDB.Test.ModuleCore; namespace System.Xml.Tests { ///////////////////////////////////////////////////////////////////////// // TestCase ReadOuterXml // ///////////////////////////////////////////////////////////////////////// [InheritRequired()] public abstract partial class TCReadOuterXml : TCXMLReaderBaseGeneral { // Element names to test ReadOuterXml on private static string s_EMP1 = "EMPTY1"; private static string s_EMP2 = "EMPTY2"; private static string s_EMP3 = "EMPTY3"; private static string s_EMP4 = "EMPTY4"; private static string s_ENT1 = "ENTITY1"; private static string s_NEMP0 = "NONEMPTY0"; private static string s_NEMP1 = "NONEMPTY1"; private static string s_NEMP2 = "NONEMPTY2"; private static string s_ELEM1 = "CHARS2"; private static string s_ELEM2 = "SKIP3"; private static string s_ELEM3 = "CONTENT"; private static string s_ELEM4 = "COMPLEX"; // Element names after the ReadOuterXml call private static string s_NEXT1 = "COMPLEX"; private static string s_NEXT2 = "ACT2"; private static string s_NEXT3 = "CHARS_ELEM1"; private static string s_NEXT4 = "AFTERSKIP3"; private static string s_NEXT5 = "TITLE"; private static string s_NEXT6 = "ENTITY2"; private static string s_NEXT7 = "DUMMY"; // Expected strings returned by ReadOuterXml private static string s_EXP_EMP1 = "<EMPTY1 />"; private static string s_EXP_EMP2 = "<EMPTY2 val=\"abc\" />"; private static string s_EXP_EMP3 = "<EMPTY3></EMPTY3>"; private static string s_EXP_EMP4 = "<EMPTY4 val=\"abc\"></EMPTY4>"; private static string s_EXP_NEMP1 = "<NONEMPTY1>ABCDE</NONEMPTY1>"; private static string s_EXP_NEMP2 = "<NONEMPTY2 val=\"abc\">1234</NONEMPTY2>"; private static string s_EXP_ELEM1 = "<CHARS2>xxx<MARKUP />yyy</CHARS2>"; private static string s_EXP_ELEM2 = "<SKIP3><ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 /></SKIP3>"; private static string s_EXP_ELEM3 = "<CONTENT><e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1></CONTENT>"; private static string s_EXP_ELEM4 = "<COMPLEX>Text<!-- comment --><![CDATA[cdata]]></COMPLEX>"; private static string s_EXP_ELEM4_XSLT = "<COMPLEX>Text<!-- comment -->cdata</COMPLEX>"; private static string s_EXP_ENT1_EXPAND_ALL = "<ENTITY1 att1=\"xxx&lt;xxxAxxxCxxxNO_REFERENCEe1;xxx\">xxx&gt;xxxBxxxDxxxNO_REFERENCEe1;xxx</ENTITY1>"; private static string s_EXP_ENT1_EXPAND_CHAR = "<ENTITY1 att1=\"xxx&lt;xxxAxxxCxxx&e1;xxx\">xxx&gt;xxxBxxxDxxx&e1;xxx</ENTITY1>"; private int TestOuterOnElement(string strElem, string strOuterXml, string strNextElemName, bool bWhitespace) { ReloadSource(); DataReader.PositionOnElement(strElem); CError.Compare(DataReader.ReadOuterXml(), strOuterXml, "outer"); if (bWhitespace) { if (!(IsXsltReader() || IsXPathNavigatorReader()))// xslt doesn't return whitespace { if (IsCoreReader()) { CError.Compare(DataReader.VerifyNode(XmlNodeType.Whitespace, String.Empty, "\n"), true, "vn"); } else { CError.Compare(DataReader.VerifyNode(XmlNodeType.Whitespace, String.Empty, "\r\n"), true, "vn"); } DataReader.Read(); } } CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, strNextElemName, String.Empty), true, "vn2"); return TEST_PASS; } private int TestOuterOnAttribute(string strElem, string strName, string strValue) { ReloadSource(); DataReader.PositionOnElement(strElem); DataReader.MoveToAttribute(DataReader.AttributeCount / 2); string strExpected = String.Format("{0}=\"{1}\"", strName, strValue); CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer"); CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, strName, strValue), true, "vn"); return TEST_PASS; } private int TestOuterOnNodeType(XmlNodeType nt) { ReloadSource(); PositionOnNodeType(nt); DataReader.Read(); XmlNodeType expNt = DataReader.NodeType; string expName = DataReader.Name; string expValue = DataReader.Value; ReloadSource(); PositionOnNodeType(nt); CError.Compare(DataReader.ReadOuterXml(), String.Empty, "outer"); CError.Compare(DataReader.VerifyNode(expNt, expName, expValue), true, "vn"); return TEST_PASS; } //////////////////////////////////////////////////////////////// // Variations //////////////////////////////////////////////////////////////// [Variation("ReadOuterXml on empty element w/o attributes", Pri = 0)] public int ReadOuterXml1() { if (IsBinaryReader()) { return TEST_SKIPPED; } return TestOuterOnElement(s_EMP1, s_EXP_EMP1, s_EMP2, true); } [Variation("ReadOuterXml on empty element w/ attributes", Pri = 0)] public int ReadOuterXml2() { if (IsBinaryReader()) { return TEST_SKIPPED; } return TestOuterOnElement(s_EMP2, s_EXP_EMP2, s_EMP3, true); } [Variation("ReadOuterXml on full empty element w/o attributes")] public int ReadOuterXml3() { return TestOuterOnElement(s_EMP3, s_EXP_EMP3, s_NEMP0, true); } [Variation("ReadOuterXml on full empty element w/ attributes")] public int ReadOuterXml4() { return TestOuterOnElement(s_EMP4, s_EXP_EMP4, s_NEXT1, true); } [Variation("ReadOuterXml on element with text content", Pri = 0)] public int ReadOuterXml5() { return TestOuterOnElement(s_NEMP1, s_EXP_NEMP1, s_NEMP2, true); } [Variation("ReadOuterXml on element with attributes", Pri = 0)] public int ReadOuterXml6() { return TestOuterOnElement(s_NEMP2, s_EXP_NEMP2, s_NEXT2, true); } [Variation("ReadOuterXml on element with text and markup content")] public int ReadOuterXml7() { if (IsBinaryReader()) { return TEST_SKIPPED; } return TestOuterOnElement(s_ELEM1, s_EXP_ELEM1, s_NEXT3, true); } [Variation("ReadOuterXml with multiple level of elements")] public int ReadOuterXml8() { if (IsBinaryReader()) { return TEST_SKIPPED; } return TestOuterOnElement(s_ELEM2, s_EXP_ELEM2, s_NEXT4, false); } [Variation("ReadOuterXml with multiple level of elements, text and attributes", Pri = 0)] public int ReadOuterXml9() { string strExpected = s_EXP_ELEM3; strExpected = strExpected.Replace('\'', '"'); return TestOuterOnElement(s_ELEM3, strExpected, s_NEXT5, true); } [Variation("ReadOuterXml on element with complex content (CDATA, PIs, Comments)", Pri = 0)] public int ReadOuterXml10() { if (IsXsltReader() || IsXPathNavigatorReader()) return TestOuterOnElement(s_ELEM4, s_EXP_ELEM4_XSLT, s_NEXT7, true); else return TestOuterOnElement(s_ELEM4, s_EXP_ELEM4, s_NEXT7, true); } [Variation("ReadOuterXml on element with entities, EntityHandling = ExpandEntities")] public int ReadOuterXml11() { string strExpected; if (IsXsltReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsCoreReader() || IsXPathNavigatorReader()) { strExpected = s_EXP_ENT1_EXPAND_ALL; } else { strExpected = s_EXP_ENT1_EXPAND_CHAR; } return TestOuterOnElement(s_ENT1, strExpected, s_NEXT6, false); } [Variation("ReadOuterXml on attribute node of empty element")] public int ReadOuterXml12() { return TestOuterOnAttribute(s_EMP2, "val", "abc"); } [Variation("ReadOuterXml on attribute node of full empty element")] public int ReadOuterXml13() { return TestOuterOnAttribute(s_EMP4, "val", "abc"); } [Variation("ReadOuterXml on attribute node", Pri = 0)] public int ReadOuterXml14() { return TestOuterOnAttribute(s_NEMP2, "val", "abc"); } [Variation("ReadOuterXml on attribute with entities, EntityHandling = ExpandEntities", Pri = 0)] public int ReadOuterXml15() { ReloadSource(); DataReader.PositionOnElement(s_ENT1); DataReader.MoveToAttribute(DataReader.AttributeCount / 2); string strExpected; if (IsXsltReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsCoreReader() || IsXPathNavigatorReader()) strExpected = "att1=\"xxx&lt;xxxAxxxCxxxNO_REFERENCEe1;xxx\""; else { strExpected = "att1=\"xxx&lt;xxxAxxxCxxx&e1;xxx\""; } CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer"); if (IsXmlTextReader()) CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_CHAR_ENTITIES), true, "vn"); else CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_ENTITIES), true, "vn"); return TEST_PASS; } [Variation("ReadOuterXml on Comment")] public int ReadOuterXml16() { return TestOuterOnNodeType(XmlNodeType.Comment); } [Variation("ReadOuterXml on ProcessingInstruction")] public int ReadOuterXml17() { return TestOuterOnNodeType(XmlNodeType.ProcessingInstruction); } [Variation("ReadOuterXml on DocumentType")] public int ReadOuterXml18() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; return TestOuterOnNodeType(XmlNodeType.DocumentType); } [Variation("ReadOuterXml on XmlDeclaration")] public int ReadOuterXml19() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; return TestOuterOnNodeType(XmlNodeType.XmlDeclaration); } [Variation("ReadOuterXml on EndElement")] public int ReadOuterXml20() { return TestOuterOnNodeType(XmlNodeType.EndElement); } [Variation("ReadOuterXml on Text")] public int ReadOuterXml21() { return TestOuterOnNodeType(XmlNodeType.Text); } [Variation("ReadOuterXml on EntityReference")] public int ReadOuterXml22() { if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; return TestOuterOnNodeType(XmlNodeType.EntityReference); } [Variation("ReadOuterXml on EndEntity")] public int ReadOuterXml23() { if (IsXmlTextReader() || IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; return TestOuterOnNodeType(XmlNodeType.EndEntity); } [Variation("ReadOuterXml on CDATA")] public int ReadOuterXml24() { if (IsXsltReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; return TestOuterOnNodeType(XmlNodeType.CDATA); } [Variation("ReadOuterXml on XmlDeclaration attributes")] public int ReadOuterXml25() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; ReloadSource(); DataReader.PositionOnNodeType(XmlNodeType.XmlDeclaration); DataReader.MoveToAttribute(DataReader.AttributeCount / 2); CError.Compare(DataReader.ReadOuterXml().ToLower(), "encoding=\"utf-8\"", "outer"); if (IsBinaryReader()) CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "encoding", "utf-8"), true, "vn"); else CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "encoding", "UTF-8"), true, "vn"); return TEST_PASS; } [Variation("ReadOuterXml on DocumentType attributes")] public int ReadOuterXml26() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; ReloadSource(); DataReader.PositionOnNodeType(XmlNodeType.DocumentType); DataReader.MoveToAttribute(DataReader.AttributeCount / 2); CError.Compare(DataReader.ReadOuterXml(), "SYSTEM=\"AllNodeTypes.dtd\"", "outer"); CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "SYSTEM", "AllNodeTypes.dtd"), true, "vn"); return TEST_PASS; } [Variation("ReadOuterXml on element with entities, EntityHandling = ExpandCharEntities")] public int TRReadOuterXml27() { string strExpected; if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) strExpected = s_EXP_ENT1_EXPAND_ALL; else { if (IsXmlNodeReader()) { strExpected = s_EXP_ENT1_EXPAND_CHAR; } else { strExpected = s_EXP_ENT1_EXPAND_CHAR; } } ReloadSource(); DataReader.PositionOnElement(s_ENT1); CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer"); CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, s_NEXT6, String.Empty), true, "vn"); return TEST_PASS; } [Variation("ReadOuterXml on attribute with entities, EntityHandling = ExpandCharEntites")] public int TRReadOuterXml28() { string strExpected; if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) strExpected = "att1=\"xxx&lt;xxxAxxxCxxxNO_REFERENCEe1;xxx\""; else { if (IsXmlNodeReader()) { strExpected = "att1=\"xxx&lt;xxxAxxxCxxxNO_REFERENCEe1;xxx\""; } else { strExpected = "att1=\"xxx&lt;xxxAxxxCxxxNO_REFERENCEe1;xxx\""; } } ReloadSource(); DataReader.PositionOnElement(s_ENT1); DataReader.MoveToAttribute(DataReader.AttributeCount / 2); CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer"); if (IsXmlTextReader()) CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_CHAR_ENTITIES), true, "vn"); else CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_ENTITIES), true, "vn"); return TEST_PASS; } [Variation("One large element")] public int TestTextReadOuterXml29() { String strp = "a "; strp += strp; strp += strp; strp += strp; strp += strp; strp += strp; strp += strp; strp += strp; string strxml = "<Name a=\"b\">" + strp + " </Name>"; ReloadSourceStr(strxml); DataReader.Read(); CError.Compare(DataReader.ReadOuterXml(), strxml, "rox"); return TEST_PASS; } [Variation("Read OuterXml when Namespaces=false and has an attribute xmlns")] public int ReadOuterXmlWhenNamespacesIgnoredWorksWithXmlns() { ReloadSourceStr("<?xml version='1.0' encoding='utf-8' ?> <foo xmlns='testing'><bar id='1'/></foo>"); if (IsXmlTextReader() || IsXmlValidatingReader()) DataReader.Namespaces = false; DataReader.MoveToContent(); CError.WriteLine(DataReader.ReadOuterXml()); return TEST_PASS; } [Variation("XmlReader.ReadOuterXml outputs multiple namespace declarations if called within multiple XmlReader.ReadSubtree() calls")] public int SubtreeXmlReaderOutputsSingleNamespaceDeclaration() { string xml = @"<root xmlns = ""http://www.test.com/""> <device> <thing>1</thing> </device></root>"; ReloadSourceStr(xml); DataReader.ReadToFollowing("device"); Foo(DataReader.ReadSubtree()); return TEST_PASS; } private void Foo(XmlReader reader) { reader.Read(); Bar(reader.ReadSubtree()); } private void Bar(XmlReader reader) { reader.Read(); string foo = reader.ReadOuterXml(); CError.Compare(foo, "<device xmlns=\"http://www.test.com/\"> <thing>1</thing> </device>", "<device xmlns=\"http://www.test.com/\"><thing>1</thing></device>", "mismatch"); } } }
namespace LL.MDE.Components.Qvt.Transformation.EA2FMEA { using System; using System.Collections.Generic; using System.Linq; using LL.MDE.Components.Qvt.Common; using LL.MDE.DataModels.EnAr; using LL.MDE.DataModels.XML; public class RelationAddStructureRoot { private readonly IMetaModelInterface editor; private readonly TransformationEA2FMEA transformation; private Dictionary<CheckOnlyDomains, EnforceDomains> traceabilityMap = new Dictionary<CheckOnlyDomains, EnforceDomains>(); public RelationAddStructureRoot(IMetaModelInterface editor , TransformationEA2FMEA transformation ) { this.editor = editor;this.transformation = transformation; } public EnforceDomains FindPreviousResult(LL.MDE.DataModels.EnAr.Package abstractionLevelP,LL.MDE.DataModels.XML.Tag structure) { CheckOnlyDomains input = new CheckOnlyDomains(abstractionLevelP,structure); return traceabilityMap.ContainsKey(input) ? traceabilityMap[input] : null; } internal static ISet<CheckResultAddStructureRoot> Check( LL.MDE.DataModels.EnAr.Package abstractionLevelP,LL.MDE.DataModels.XML.Tag structure ) { ISet<CheckResultAddStructureRoot> result = new HashSet<CheckResultAddStructureRoot>();ISet<MatchDomainAbstractionLevelP> matchDomainAbstractionLevelPs = CheckDomainAbstractionLevelP(abstractionLevelP);ISet<MatchDomainStructure> matchDomainStructures = CheckDomainStructure(structure);foreach (MatchDomainAbstractionLevelP matchDomainAbstractionLevelP in matchDomainAbstractionLevelPs ) {foreach (MatchDomainStructure matchDomainStructure in matchDomainStructures ) {string alpName = matchDomainAbstractionLevelP.alpName; LL.MDE.DataModels.EnAr.Package fctsysP = matchDomainAbstractionLevelP.fctsysP; string fctsysName = matchDomainAbstractionLevelP.fctsysName; CheckResultAddStructureRoot checkonlysMatch = new CheckResultAddStructureRoot () {matchDomainAbstractionLevelP = matchDomainAbstractionLevelP,matchDomainStructure = matchDomainStructure,}; result.Add(checkonlysMatch); } // End foreach } // End foreach return result; } internal static ISet<MatchDomainAbstractionLevelP> CheckDomainAbstractionLevelP(LL.MDE.DataModels.EnAr.Package abstractionLevelP) { ISet<MatchDomainAbstractionLevelP> result = new HashSet<MatchDomainAbstractionLevelP>(); string alpName = abstractionLevelP.Name; LL.MDE.DataModels.EnAr.Package fctsysP = abstractionLevelP.ParentPackage(); string fctsysName = fctsysP.Name; MatchDomainAbstractionLevelP match = new MatchDomainAbstractionLevelP() { abstractionLevelP = abstractionLevelP, alpName = alpName, fctsysP = fctsysP, fctsysName = fctsysName, }; result.Add(match); return result; } internal static ISet<MatchDomainStructure> CheckDomainStructure(LL.MDE.DataModels.XML.Tag structure) { ISet<MatchDomainStructure> result = new HashSet<MatchDomainStructure>(); MatchDomainStructure match = new MatchDomainStructure() { structure = structure, }; result.Add(match); return result; } internal void CheckAndEnforce(LL.MDE.DataModels.EnAr.Package abstractionLevelP,LL.MDE.DataModels.XML.Tag structure,LL.MDE.DataModels.XML.Tag structureElements ) { CheckOnlyDomains input = new CheckOnlyDomains(abstractionLevelP,structure); EnforceDomains output = new EnforceDomains(structureElements); if (traceabilityMap.ContainsKey(input) && !traceabilityMap[input].Equals(output)) { throw new Exception("This relation has already been used with different enforced parameters!"); } if (!traceabilityMap.ContainsKey(input)) { ISet<CheckResultAddStructureRoot> result = Check (abstractionLevelP,structure); Enforce(result, structureElements); traceabilityMap[input] = output; } } internal void Enforce(ISet<CheckResultAddStructureRoot> result, LL.MDE.DataModels.XML.Tag structureElements ) { foreach (CheckResultAddStructureRoot match in result) { // Extracting variables binded in source domains LL.MDE.DataModels.EnAr.Package abstractionLevelP = match.matchDomainAbstractionLevelP.abstractionLevelP; string alpName = match.matchDomainAbstractionLevelP.alpName; LL.MDE.DataModels.EnAr.Package fctsysP = match.matchDomainAbstractionLevelP.fctsysP; string fctsysName = match.matchDomainAbstractionLevelP.fctsysName; LL.MDE.DataModels.XML.Tag structure = match.matchDomainStructure.structure; // Assigning variables binded in the where clause string elementName=fctsysName + ' ' + alpName; // Enforcing each enforced domain MatchDomainStructureElements targetMatchDomainStructureElements = EnforceStructureElements(elementName, structureElements ); // Retrieving variables binded in the enforced domains LL.MDE.DataModels.XML.Tag fmStructureelement = targetMatchDomainStructureElements.fmStructureelement; LL.MDE.DataModels.XML.Tag longName1 = targetMatchDomainStructureElements.longName1; LL.MDE.DataModels.XML.Tag l41 = targetMatchDomainStructureElements.l41; LL.MDE.DataModels.XML.Attribute lAttr1 = targetMatchDomainStructureElements.lAttr1; LL.MDE.DataModels.XML.Tag fmSeDecomposition = targetMatchDomainStructureElements.fmSeDecomposition; LL.MDE.DataModels.XML.Attribute structureId = targetMatchDomainStructureElements.structureId; // Calling other relations as defined in the where clause new RelationCreateStructureRootLink(editor,transformation).CheckAndEnforce(structureId,structure);new RelationRootProperty2StructureElement(editor,transformation).CheckAndEnforce(abstractionLevelP,fmSeDecomposition,structure,structureElements);} } internal MatchDomainStructureElements EnforceStructureElements(string elementName, LL.MDE.DataModels.XML.Tag structureElements) { MatchDomainStructureElements match = new MatchDomainStructureElements(); // Contructing structureElements LL.MDE.DataModels.XML.Tag fmStructureelement = null; fmStructureelement = (LL.MDE.DataModels.XML.Tag) editor.CreateNewObjectInField(structureElements, "childTags"); // Contructing fmStructureelement editor.AddOrSetInField(fmStructureelement, "tagname", "FM-STRUCTURE-ELEMENT" ); LL.MDE.DataModels.XML.Tag longName1 = null; longName1 = (LL.MDE.DataModels.XML.Tag) editor.CreateNewObjectInField(fmStructureelement, "childTags"); LL.MDE.DataModels.XML.Tag fmSeDecomposition = null; fmSeDecomposition = (LL.MDE.DataModels.XML.Tag) editor.CreateNewObjectInField(fmStructureelement, "childTags"); LL.MDE.DataModels.XML.Attribute structureId = null; structureId = (LL.MDE.DataModels.XML.Attribute) editor.CreateNewObjectInField(fmStructureelement, "attributes"); // Contructing longName1 editor.AddOrSetInField(longName1, "tagname", "LONG-NAME" ); LL.MDE.DataModels.XML.Tag l41 = null; l41 = (LL.MDE.DataModels.XML.Tag) editor.CreateNewObjectInField(longName1, "childTags"); // Contructing l41 editor.AddOrSetInField(l41, "tagname", "L-4" ); editor.AddOrSetInField(l41, "value", elementName ); LL.MDE.DataModels.XML.Attribute lAttr1 = null; lAttr1 = (LL.MDE.DataModels.XML.Attribute) editor.CreateNewObjectInField(l41, "attributes"); // Contructing lAttr1 editor.AddOrSetInField(lAttr1, "name", "L" ); // Contructing fmSeDecomposition editor.AddOrSetInField(fmSeDecomposition, "tagname", "FM-SE-DECOMPOSITION" ); // Contructing structureId editor.AddOrSetInField(structureId, "name", "ID" ); editor.AddOrSetInField(structureId, "value", "root" ); // Return newly binded variables match.structureElements = structureElements; match.fmStructureelement = fmStructureelement; match.longName1 = longName1; match.l41 = l41; match.lAttr1 = lAttr1; match.fmSeDecomposition = fmSeDecomposition; match.structureId = structureId; return match; } public class CheckOnlyDomains : Tuple<Package,Tag> { public CheckOnlyDomains(Package abstractionLevelP,Tag structure) : base(abstractionLevelP,structure) { } public Package abstractionLevelP { get { return Item1; } } public Tag structure { get { return Item2; } } } public class EnforceDomains : Tuple<Tag> { public EnforceDomains(Tag structureElements) : base(structureElements) { } public Tag structureElements { get { return Item1; } } } internal class CheckResultAddStructureRoot { public MatchDomainAbstractionLevelP matchDomainAbstractionLevelP; public MatchDomainStructure matchDomainStructure; } internal class MatchDomainAbstractionLevelP { public LL.MDE.DataModels.EnAr.Package abstractionLevelP; public string alpName; public string fctsysName; public LL.MDE.DataModels.EnAr.Package fctsysP; } internal class MatchDomainStructure { public LL.MDE.DataModels.XML.Tag structure; } internal class MatchDomainStructureElements { public LL.MDE.DataModels.XML.Tag fmSeDecomposition; public LL.MDE.DataModels.XML.Tag fmStructureelement; public LL.MDE.DataModels.XML.Tag l41; public LL.MDE.DataModels.XML.Attribute lAttr1; public LL.MDE.DataModels.XML.Tag longName1; public LL.MDE.DataModels.XML.Tag structureElements; public LL.MDE.DataModels.XML.Attribute structureId; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; #endregion /// <summary> /// Common utility methods. /// </summary> public class Net_Utils { #region Methods /// <summary> /// Gets local host name or argument <b>hostName</b> value if it's specified. /// </summary> /// <param name="hostName">Host name or null.</param> /// <returns>Returns local host name or argument <b>hostName</b> value if it's specified.</returns> public static string GetLocalHostName(string hostName) { if (string.IsNullOrEmpty(hostName)) { return System.Net.Dns.GetHostName(); } else { return hostName; } } /// <summary> /// Compares if specified array itmes equals. /// </summary> /// <param name="array1">Array 1.</param> /// <param name="array2">Array 2</param> /// <returns>Returns true if both arrays are equal.</returns> public static bool CompareArray(Array array1, Array array2) { return CompareArray(array1, array2, array2.Length); } /// <summary> /// Compares if specified array itmes equals. /// </summary> /// <param name="array1">Array 1.</param> /// <param name="array2">Array 2</param> /// <param name="array2Count">Number of bytes in array 2 used for compare.</param> /// <returns>Returns true if both arrays are equal.</returns> public static bool CompareArray(Array array1, Array array2, int array2Count) { if (array1 == null && array2 == null) { return true; } if (array1 == null && array2 != null) { return false; } if (array1 != null && array2 == null) { return false; } if (array1.Length != array2Count) { return false; } else { for (int i = 0; i < array1.Length; i++) { if (!array1.GetValue(i).Equals(array2.GetValue(i))) { return false; } } } return true; } /// <summary> /// Copies <b>source</b> stream data to <b>target</b> stream. /// </summary> /// <param name="source">Source stream. Reading starts from stream current position.</param> /// <param name="target">Target stream. Writing starts from stream current position.</param> /// <param name="blockSize">Specifies transfer block size in bytes.</param> /// <returns>Returns number of bytes copied.</returns> public static long StreamCopy(Stream source, Stream target, int blockSize) { if (source == null) { throw new ArgumentNullException("source"); } if (target == null) { throw new ArgumentNullException("target"); } if (blockSize < 1024) { throw new ArgumentException("Argument 'blockSize' value must be >= 1024."); } byte[] buffer = new byte[blockSize]; long totalReaded = 0; while (true) { int readedCount = source.Read(buffer, 0, buffer.Length); // We reached end of stream, we readed all data sucessfully. if (readedCount == 0) { return totalReaded; } else { target.Write(buffer, 0, readedCount); totalReaded += readedCount; } } } /// <summary> /// Gets if the specified string value is IP address. /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if specified value is IP address.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public static bool IsIPAddress(string value) { if (value == null) { throw new ArgumentNullException("value"); } IPAddress ip = null; return IPAddress.TryParse(value, out ip); } /// <summary> /// Gets if the specified IP address is multicast address. /// </summary> /// <param name="ip">IP address.</param> /// <returns>Returns true if <b>ip</b> is muticast address, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> s null reference.</exception> public static bool IsMulticastAddress(IPAddress ip) { if (ip == null) { throw new ArgumentNullException("ip"); } // IPv4 multicast 224.0.0.0 to 239.255.255.255 if (ip.IsIPv6Multicast) { return true; } else if (ip.AddressFamily == AddressFamily.InterNetwork) { byte[] bytes = ip.GetAddressBytes(); if (bytes[0] >= 224 && bytes[0] <= 239) { return true; } } return false; } /// <summary> /// Parses IPEndPoint from the specified string value. /// </summary> /// <param name="value">IPEndPoint string value.</param> /// <returns>Returns parsed IPEndPoint.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static IPEndPoint ParseIPEndPoint(string value) { if (value == null) { throw new ArgumentNullException("value"); } try { string[] ip_port = value.Split(':'); return new IPEndPoint(IPAddress.Parse(ip_port[0]), Convert.ToInt32(ip_port[1])); } catch (Exception x) { throw new ArgumentException("Invalid IPEndPoint value.", "value", x); } } /// <summary> /// Gets if IO completion ports supported by OS. /// </summary> /// <returns></returns> public static bool IsIoCompletionPortsSupported() { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.SetBuffer(new byte[0], 0, 0); e.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 111); s.SendToAsync(e); return true; } catch (NotSupportedException nX) { string dummy = nX.Message; return false; } finally { s.Close(); } } /// <summary> /// Converts specified string to HEX string. /// </summary> /// <param name="text">String to convert.</param> /// <returns>Returns hex string.</returns> public static string Hex(string text) { return BitConverter.ToString(Encoding.Default.GetBytes(text)).ToLower().Replace("-", ""); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MusicStore.Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; 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 J2N.Collections.Generic.Extensions; using J2N.Threading; using Lucene.Net.Documents; using NUnit.Framework; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Threading; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using FieldType = FieldType; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using TestUtil = Lucene.Net.Util.TestUtil; /// <summary> /// Simple test that adds numeric terms, where each term has the /// totalTermFreq of its integer value, and checks that the totalTermFreq is correct. /// </summary> // TODO: somehow factor this with BagOfPostings? its almost the same [SuppressCodecs("Direct", "Memory", "Lucene3x")] // at night this makes like 200k/300k docs and will make Direct's heart beat! // Lucene3x doesnt have totalTermFreq, so the test isn't interesting there. [TestFixture] public class TestBagOfPositions : LuceneTestCase { [Test] [Slow] public virtual void Test() { IList<string> postingsList = new List<string>(); int numTerms = AtLeast(300); int maxTermsPerDoc = TestUtil.NextInt32(Random, 10, 20); bool isSimpleText = "SimpleText".Equals(TestUtil.GetPostingsFormat("field"), StringComparison.Ordinal); IndexWriterConfig iwc = NewIndexWriterConfig(Random, TEST_VERSION_CURRENT, new MockAnalyzer(Random)); if ((isSimpleText || iwc.MergePolicy is MockRandomMergePolicy) && (TestNightly || RandomMultiplier > 1)) { // Otherwise test can take way too long (> 2 hours) numTerms /= 2; } if (Verbose) { Console.WriteLine("maxTermsPerDoc=" + maxTermsPerDoc); Console.WriteLine("numTerms=" + numTerms); } for (int i = 0; i < numTerms; i++) { string term = Convert.ToString(i, CultureInfo.InvariantCulture); for (int j = 0; j < i; j++) { postingsList.Add(term); } } postingsList.Shuffle(Random); ConcurrentQueue<string> postings = new ConcurrentQueue<string>(postingsList); Directory dir = NewFSDirectory(CreateTempDir(GetFullMethodName())); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); int threadCount = TestUtil.NextInt32(Random, 1, 5); if (Verbose) { Console.WriteLine("config: " + iw.IndexWriter.Config); Console.WriteLine("threadCount=" + threadCount); } Field prototype = NewTextField("field", "", Field.Store.NO); FieldType fieldType = new FieldType(prototype.FieldType); if (Random.NextBoolean()) { fieldType.OmitNorms = true; } int options = Random.Next(3); if (options == 0) { fieldType.IndexOptions = IndexOptions.DOCS_AND_FREQS; // we dont actually need positions fieldType.StoreTermVectors = true; // but enforce term vectors when we do this so we check SOMETHING } else if (options == 1 && !DoesntSupportOffsets.Contains(TestUtil.GetPostingsFormat("field"))) { fieldType.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; } // else just positions ThreadJob[] threads = new ThreadJob[threadCount]; CountdownEvent startingGun = new CountdownEvent(1); for (int threadID = 0; threadID < threadCount; threadID++) { Random threadRandom = new Random(Random.Next()); Document document = new Document(); Field field = new Field("field", "", fieldType); document.Add(field); threads[threadID] = new ThreadAnonymousInnerClassHelper(this, numTerms, maxTermsPerDoc, postings, iw, startingGun, threadRandom, document, field); threads[threadID].Start(); } startingGun.Signal(); foreach (ThreadJob t in threads) { t.Join(); } iw.ForceMerge(1); DirectoryReader ir = iw.GetReader(); Assert.AreEqual(1, ir.Leaves.Count); AtomicReader air = (AtomicReader)ir.Leaves[0].Reader; Terms terms = air.GetTerms("field"); // numTerms-1 because there cannot be a term 0 with 0 postings: Assert.AreEqual(numTerms - 1, terms.Count); TermsEnum termsEnum = terms.GetEnumerator(); while (termsEnum.MoveNext()) { int value = Convert.ToInt32(termsEnum.Term.Utf8ToString(), CultureInfo.InvariantCulture); Assert.AreEqual(value, termsEnum.TotalTermFreq); // don't really need to check more than this, as CheckIndex // will verify that totalTermFreq == total number of positions seen // from a docsAndPositionsEnum. } ir.Dispose(); iw.Dispose(); dir.Dispose(); } private class ThreadAnonymousInnerClassHelper : ThreadJob { private readonly TestBagOfPositions outerInstance; private readonly int numTerms; private readonly int maxTermsPerDoc; private readonly ConcurrentQueue<string> postings; private readonly RandomIndexWriter iw; private readonly CountdownEvent startingGun; private readonly Random threadRandom; private readonly Document document; private readonly Field field; public ThreadAnonymousInnerClassHelper(TestBagOfPositions outerInstance, int numTerms, int maxTermsPerDoc, ConcurrentQueue<string> postings, RandomIndexWriter iw, CountdownEvent startingGun, Random threadRandom, Document document, Field field) { this.outerInstance = outerInstance; this.numTerms = numTerms; this.maxTermsPerDoc = maxTermsPerDoc; this.postings = postings; this.iw = iw; this.startingGun = startingGun; this.threadRandom = threadRandom; this.document = document; this.field = field; } public override void Run() { try { startingGun.Wait(); while (!(postings.Count == 0)) { StringBuilder text = new StringBuilder(); int numTerms = threadRandom.Next(maxTermsPerDoc); for (int i = 0; i < numTerms; i++) { string token; if (!postings.TryDequeue(out token)) { break; } text.Append(' '); text.Append(token); } field.SetStringValue(text.ToString()); iw.AddDocument(document); } } catch (Exception e) { throw new Exception(e.Message, e); } } } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.ElasticMapReduce.Model { /// <summary> /// <para>Describes the status of the job flow.</para> /// </summary> public class JobFlowExecutionStatusDetail { private string state; private DateTime? creationDateTime; private DateTime? startDateTime; private DateTime? readyDateTime; private DateTime? endDateTime; private string lastStateChangeReason; /// <summary> /// The state of the job flow. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>COMPLETED, FAILED, TERMINATED, RUNNING, SHUTTING_DOWN, STARTING, WAITING, BOOTSTRAPPING</description> /// </item> /// </list> /// </para> /// </summary> public string State { get { return this.state; } set { this.state = value; } } /// <summary> /// Sets the State property /// </summary> /// <param name="state">The value to set for the State property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public JobFlowExecutionStatusDetail WithState(string state) { this.state = state; return this; } // Check to see if State property is set internal bool IsSetState() { return this.state != null; } /// <summary> /// The creation date and time of the job flow. /// /// </summary> public DateTime CreationDateTime { get { return this.creationDateTime ?? default(DateTime); } set { this.creationDateTime = value; } } /// <summary> /// Sets the CreationDateTime property /// </summary> /// <param name="creationDateTime">The value to set for the CreationDateTime property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public JobFlowExecutionStatusDetail WithCreationDateTime(DateTime creationDateTime) { this.creationDateTime = creationDateTime; return this; } // Check to see if CreationDateTime property is set internal bool IsSetCreationDateTime() { return this.creationDateTime.HasValue; } /// <summary> /// The start date and time of the job flow. /// /// </summary> public DateTime StartDateTime { get { return this.startDateTime ?? default(DateTime); } set { this.startDateTime = value; } } /// <summary> /// Sets the StartDateTime property /// </summary> /// <param name="startDateTime">The value to set for the StartDateTime property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public JobFlowExecutionStatusDetail WithStartDateTime(DateTime startDateTime) { this.startDateTime = startDateTime; return this; } // Check to see if StartDateTime property is set internal bool IsSetStartDateTime() { return this.startDateTime.HasValue; } /// <summary> /// The date and time when the job flow was ready to start running bootstrap actions. /// /// </summary> public DateTime ReadyDateTime { get { return this.readyDateTime ?? default(DateTime); } set { this.readyDateTime = value; } } /// <summary> /// Sets the ReadyDateTime property /// </summary> /// <param name="readyDateTime">The value to set for the ReadyDateTime property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public JobFlowExecutionStatusDetail WithReadyDateTime(DateTime readyDateTime) { this.readyDateTime = readyDateTime; return this; } // Check to see if ReadyDateTime property is set internal bool IsSetReadyDateTime() { return this.readyDateTime.HasValue; } /// <summary> /// The completion date and time of the job flow. /// /// </summary> public DateTime EndDateTime { get { return this.endDateTime ?? default(DateTime); } set { this.endDateTime = value; } } /// <summary> /// Sets the EndDateTime property /// </summary> /// <param name="endDateTime">The value to set for the EndDateTime property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public JobFlowExecutionStatusDetail WithEndDateTime(DateTime endDateTime) { this.endDateTime = endDateTime; return this; } // Check to see if EndDateTime property is set internal bool IsSetEndDateTime() { return this.endDateTime.HasValue; } /// <summary> /// Description of the job flow last changed state. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 10280</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string LastStateChangeReason { get { return this.lastStateChangeReason; } set { this.lastStateChangeReason = value; } } /// <summary> /// Sets the LastStateChangeReason property /// </summary> /// <param name="lastStateChangeReason">The value to set for the LastStateChangeReason property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public JobFlowExecutionStatusDetail WithLastStateChangeReason(string lastStateChangeReason) { this.lastStateChangeReason = lastStateChangeReason; return this; } // Check to see if LastStateChangeReason property is set internal bool IsSetLastStateChangeReason() { return this.lastStateChangeReason != null; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Xna.Framework; namespace CocosSharp { public enum CCMenuState { Waiting, TrackingTouch, Focused }; enum Alignment { None, Vertical, Horizontal, Column, Row } struct AlignmentState { public Alignment Alignment { get; set; } public float Padding { get; set; } public uint[] NumberOfItemsPer { get; set; } public AlignmentState (Alignment alignment, float padding, uint[] numberOfItems) : this() { Alignment = alignment; Padding = padding; NumberOfItemsPer = numberOfItems; } public AlignmentState (Alignment alignment, float padding) : this(alignment, padding, null) { } public AlignmentState (Alignment alignment, uint[] numberOfItems) : this(alignment, 0, numberOfItems) { } } /// <summary> /// A CCMenu /// Features and Limitation: /// You can add MenuItem objects in runtime using addChild: /// But the only accecpted children are MenuItem objects /// </summary> public class CCMenu : CCNode { public const float DefaultPadding = 5; public const int DefaultMenuHandlerPriority = -128; List<CCMenuItem> menuItems = new List<CCMenuItem>(); #region Properties public bool Enabled { get; set; } protected CCMenuState MenuState { get; set; } protected CCMenuItem SelectedMenuItem { get; set; } AlignmentState alignmentState; // Note that this only has a value if the GamePad or Keyboard is enabled. // Touch devices do not have a "focus" concept. public CCMenuItem FocusedItem { get { CCMenuItem focusedItem = null; foreach (CCMenuItem item in menuItems) { if (item.HasFocus) { focusedItem = item; break; } } return focusedItem; } } public override bool HasFocus { set { base.HasFocus = value; // Set the first menu item to have the focus if (FocusedItem == null && menuItems.Count > 0) { menuItems[0].HasFocus = true; } } } public override CCScene Scene { get { return base.Scene; } internal set { if (Scene != value) { base.Scene = value; foreach (CCMenuItem item in menuItems) { item.Scene = value; } } } } #endregion Properties #region Constructors public CCMenu(params CCMenuItem[] items) : base() { alignmentState = new AlignmentState(Alignment.None, DefaultPadding); Enabled = true; SelectedMenuItem = null; MenuState = CCMenuState.Waiting; IsColorCascaded = true; IsOpacityCascaded = true; AnchorPoint = new CCPoint(0.5f, 0.5f); IgnoreAnchorPointForPosition = true; if (items != null) { int z = 0; foreach (CCMenuItem item in items) { AddChild(item, z); z++; } } // We will set the position as being not set Position = CCPoint.NegativeInfinity; } #endregion Constructors #region Setup content protected override void AddedToScene() { base.AddedToScene(); if (Scene != null) { var touchListener = new CCEventListenerTouchOneByOne(); touchListener.IsSwallowTouches = true; touchListener.OnTouchBegan = TouchBegan; touchListener.OnTouchMoved = TouchMoved; touchListener.OnTouchEnded = TouchEnded; touchListener.OnTouchCancelled = TouchCancelled; AddEventListener(touchListener); switch(alignmentState.Alignment) { case Alignment.Vertical: AlignItemsVertically(alignmentState.Padding); break; case Alignment.Horizontal: AlignItemsHorizontally(alignmentState.Padding); break; case Alignment.Column: AlignItemsInColumns(alignmentState.NumberOfItemsPer); break; case Alignment.Row: AlignItemsInRows(alignmentState.NumberOfItemsPer); break; } } } protected override void VisibleBoundsChanged() { base.VisibleBoundsChanged(); if (Camera != null) { CCRect visibleBounds = Layer.VisibleBoundsWorldspace; // If the position has already been set then we need to respect // that position if (Position == CCPoint.NegativeInfinity) Position = visibleBounds.Center; if(ContentSize == CCSize.Zero) ContentSize = visibleBounds.Size; } } #endregion Setup content public void AddChild(CCMenuItem menuItem) { this.AddChild(menuItem, menuItem.ZOrder); } public void AddChild(CCMenuItem menuItem, int zOrder, int tag=0) { base.AddChild(menuItem, zOrder); menuItems.Add(menuItem); } public void RemoveChild(CCMenuItem menuItem, bool cleanup) { if (SelectedMenuItem == menuItem) { SelectedMenuItem = null; } base.RemoveChild(menuItem, cleanup); menuItems.Remove(menuItem); } public override void OnEnter() { base.OnEnter(); CCFocusManager.Instance.Add(menuItems.ToArray()); } public override void OnExit() { if (MenuState == CCMenuState.TrackingTouch) { if (SelectedMenuItem != null) { SelectedMenuItem.Selected = false; SelectedMenuItem = null; } MenuState = CCMenuState.Waiting; } CCFocusManager.Instance.Remove(menuItems.ToArray()); base.OnExit(); } #region Touch events protected virtual CCMenuItem ItemForTouch(CCTouch touch) { CCMenuItem touchedMenuItem = null; CCPoint touchLocation = touch.Location; if (menuItems != null && menuItems.Count > 0) { foreach (CCMenuItem menuItem in menuItems) { if (menuItem != null && menuItem.Visible && menuItem.Enabled) { CCRect r = menuItem.BoundingBoxTransformedToWorld; if (r.ContainsPoint(touchLocation)) { touchedMenuItem = menuItem; break; } } } } return touchedMenuItem; } bool TouchBegan(CCTouch touch, CCEvent touchEvent) { if (MenuState != CCMenuState.Waiting || !Visible || !Enabled) { return false; } for (CCNode c = Parent; c != null; c = c.Parent) { if (c.Visible == false) { return false; } } SelectedMenuItem = ItemForTouch(touch); if (SelectedMenuItem != null) { MenuState = CCMenuState.TrackingTouch; SelectedMenuItem.Selected = true; return true; } return false; } void TouchEnded(CCTouch touch, CCEvent touchEvent) { Debug.Assert(MenuState == CCMenuState.TrackingTouch, "[Menu TouchEnded] -- invalid state"); if (SelectedMenuItem != null) { SelectedMenuItem.Selected = false; SelectedMenuItem.Activate(); } MenuState = CCMenuState.Waiting; } void TouchCancelled(CCTouch touch, CCEvent touchEvent) { Debug.Assert(MenuState == CCMenuState.TrackingTouch, "[Menu ccTouchCancelled] -- invalid state"); if (SelectedMenuItem != null) { SelectedMenuItem.Selected = false; } MenuState = CCMenuState.Waiting; } void TouchMoved(CCTouch touch, CCEvent touchEvent) { Debug.Assert(MenuState == CCMenuState.TrackingTouch, "[Menu TouchMoved] -- invalid state"); CCMenuItem currentItem = ItemForTouch(touch); if (currentItem != SelectedMenuItem) { if(SelectedMenuItem != null) { SelectedMenuItem.Selected = false; } if(currentItem != null) { currentItem.Selected = true; } SelectedMenuItem = currentItem; } } #endregion Touch events #region Alignment public void AlignItemsVertically(float padding = DefaultPadding) { alignmentState.Alignment = Alignment.Vertical; alignmentState.Padding = padding; float width = 0f; float height = -padding; if (menuItems != null && menuItems.Count > 0) { // First pass to get width and height foreach (CCMenuItem menuItem in menuItems) { if (menuItem.Visible) { height += menuItem.ContentSize.Height * menuItem.ScaleY + padding; width = Math.Max(width, menuItem.ContentSize.Width); } } float y = height / 2.0f; foreach (CCMenuItem menuItem in menuItems) { if (menuItem.Visible) { menuItem.Position = new CCPoint(0, y - menuItem.ContentSize.Height * menuItem.ScaleY / 2.0f); y -= menuItem.ContentSize.Height * menuItem.ScaleY + padding; width = Math.Max(width, menuItem.ContentSize.Width); } } } ContentSize = new CCSize(width, height); } public void AlignItemsHorizontally(float padding = DefaultPadding) { alignmentState.Alignment = Alignment.Horizontal; alignmentState.Padding = padding; float height = 0f; float width = -padding; if (menuItems != null && menuItems.Count > 0) { // First pass to get width and height foreach (CCMenuItem menuItem in menuItems) { if (menuItem.Visible) { width += menuItem.ContentSize.Width * menuItem.ScaleX + padding; height = Math.Max(height, menuItem.ContentSize.Height); } } float x = -width / 2.0f; foreach (CCMenuItem menuItem in menuItems) { if (menuItem.Visible) { menuItem.Position = new CCPoint(x + menuItem.ContentSize.Width * menuItem.ScaleX / 2.0f, 0); x += menuItem.ContentSize.Width * menuItem.ScaleX + padding; height = Math.Max(height, menuItem.ContentSize.Height); } } } ContentSize = new CCSize(width, height); } public void AlignItemsInColumns(params uint[] numOfItemsPerRow) { alignmentState.Alignment = Alignment.Column; alignmentState.NumberOfItemsPer = numOfItemsPerRow; float height = -DefaultPadding; int row = 0; int rowHeight = 0; int columnsOccupied = 0; uint rowColumns; if (menuItems != null && menuItems.Count > 0) { foreach (CCMenuItem item in menuItems) { if (item.Visible) { Debug.Assert (row < numOfItemsPerRow.Length); rowColumns = numOfItemsPerRow[row]; // can not have zero columns on a row Debug.Assert (rowColumns > 0, ""); float tmp = item.ContentSize.Height; rowHeight = (int)((rowHeight >= tmp || float.IsNaN (tmp)) ? rowHeight : tmp); ++columnsOccupied; if (columnsOccupied >= rowColumns) { height += rowHeight + (int)DefaultPadding; columnsOccupied = 0; rowHeight = 0; ++row; } } } // check if too many rows/columns for available menu items Debug.Assert(columnsOccupied == 0, ""); CCSize menuSize = ContentSize; row = 0; rowHeight = 0; rowColumns = 0; float w = 0.0f; float x = 0.0f; float y = (height / 2f); foreach (CCMenuItem item in menuItems) { if (item.Visible) { if (rowColumns == 0) { rowColumns = numOfItemsPerRow[row]; if (rowColumns == 0) { throw (new ArgumentException ("Can not have a zero column size for a row.")); } w = (menuSize.Width - 2 * DefaultPadding) / rowColumns; // 1 + rowColumns x = w / 2f; // center of column } float tmp = item.ContentSize.Height * item.ScaleY; rowHeight = (int)((rowHeight >= tmp || float.IsNaN (tmp)) ? rowHeight : tmp); item.Position = new CCPoint(DefaultPadding + x - (menuSize.Width - 2 * DefaultPadding) / 2, y - item.ContentSize.Height * item.ScaleY / 2); x += w; ++columnsOccupied; if (columnsOccupied >= rowColumns) { y -= rowHeight + DefaultPadding; columnsOccupied = 0; rowColumns = 0; rowHeight = 0; ++row; } } } } } public void AlignItemsInRows(params uint[] numOfItemsPerColumn) { alignmentState.Alignment = Alignment.Row; alignmentState.NumberOfItemsPer = numOfItemsPerColumn; List<float> columnWidths = new List<float>(); List<float> columnHeights = new List<float>(); float width = -DefaultPadding * 2.0f; float columnHeight = -DefaultPadding; int column = 0; int columnWidth = 0; int rowsOccupied = 0; uint columnRows; if (menuItems != null && menuItems.Count > 0) { foreach (CCMenuItem item in menuItems) { if(item.Visible) { // check if too many menu items for the amount of rows/columns Debug.Assert (column < numOfItemsPerColumn.Length, ""); columnRows = numOfItemsPerColumn[column]; // can't have zero rows on a column Debug.Assert (columnRows > 0, ""); float tmp = item.ContentSize.Width * item.ScaleX; columnWidth = (int)((columnWidth >= tmp || float.IsNaN (tmp)) ? columnWidth : tmp); columnHeight += (int)(item.ContentSize.Height * item.ScaleY + DefaultPadding); ++rowsOccupied; if (rowsOccupied >= columnRows) { columnWidths.Add(columnWidth); columnHeights.Add(columnHeight); width += columnWidth + DefaultPadding * 2.0f; rowsOccupied = 0; columnWidth = 0; columnHeight = -DefaultPadding; ++column; } } } // check if too many rows/columns for available menu items. Debug.Assert(rowsOccupied == 0, ""); CCSize menuSize = ContentSize; column = 0; columnWidth = 0; columnRows = 0; float x = (-width / 2f); float y = 0.0f; foreach(CCMenuItem item in menuItems) { if (item.Visible) { if (columnRows == 0) { columnRows = numOfItemsPerColumn[column]; y = columnHeights [column]; } // columnWidth = fmaxf(columnWidth, [item contentSize].width); float tmp = item.ContentSize.Width * item.ScaleX; columnWidth = (int)((columnWidth >= tmp || float.IsNaN (tmp)) ? columnWidth : tmp); item.Position = new CCPoint (x + columnWidths [column] / 2, y - menuSize.Height / 2); y -= item.ContentSize.Height * item.ScaleY + 10; ++rowsOccupied; if (rowsOccupied >= columnRows) { x += columnWidth + 5; rowsOccupied = 0; columnRows = 0; columnWidth = 0; ++column; } } } } } #endregion Alignment } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; using Moq; using Xunit; namespace Microsoft.AspNetCore.StaticFiles { public class StaticFileMiddlewareTests { [Fact] public async Task ReturnsNotFoundWithoutWwwroot() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => app.UseStaticFiles()); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/ranges.txt"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Null(response.Headers.ETag); } [ConditionalFact] [OSSkipCondition(OperatingSystems.Windows, SkipReason = "Symlinks not supported on Windows")] public async Task ReturnsNotFoundForBrokenSymlink() { var badLink = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName() + ".txt"); Process.Start("ln", $"-s \"/tmp/{Path.GetRandomFileName()}\" \"{badLink}\"").WaitForExit(); Assert.True(File.Exists(badLink), "Should have created a symlink"); try { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true })) .UseWebRoot(AppContext.BaseDirectory); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(Path.GetFileName(badLink)); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Null(response.Headers.ETag); } finally { File.Delete(badLink); } } [Fact] public async Task ReturnsNotFoundIfSendFileThrows() { var mockSendFile = new Mock<IHttpResponseBodyFeature>(); mockSendFile.Setup(m => m.SendFileAsync(It.IsAny<string>(), It.IsAny<long>(), It.IsAny<long?>(), It.IsAny<CancellationToken>())) .ThrowsAsync(new FileNotFoundException()); mockSendFile.Setup(m => m.Stream).Returns(Stream.Null); using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.Use(async (ctx, next) => { ctx.Features.Set(mockSendFile.Object); await next(ctx); }); app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true }); }) .UseWebRoot(AppContext.BaseDirectory); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("TestDocument.txt"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Null(response.Headers.ETag); } [Fact] public async Task FoundFile_LastModifiedTrimsSeconds() { using (var fileProvider = new PhysicalFileProvider(AppContext.BaseDirectory)) { using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { FileProvider = fileProvider })); using var server = host.GetTestServer(); var fileInfo = fileProvider.GetFileInfo("TestDocument.txt"); var response = await server.CreateRequest("TestDocument.txt").GetAsync(); var last = fileInfo.LastModified; var trimmed = new DateTimeOffset(last.Year, last.Month, last.Day, last.Hour, last.Minute, last.Second, last.Offset).ToUniversalTime(); Assert.Equal(response.Content.Headers.LastModified.Value, trimmed); } } [Fact] public async Task NullArguments() { // No exception, default provided using (await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = null }))) { } // No exception, default provided using (await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { FileProvider = null }))) { } // PathString(null) is OK. using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles((string)null)); using var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } [Theory] [MemberData(nameof(ExistingFiles))] public async Task FoundFile_Served_All(string baseUrl, string baseDir, string requestUrl) { await FoundFile_Served(baseUrl, baseDir, requestUrl); } [ConditionalTheory] [OSSkipCondition(OperatingSystems.Linux)] [OSSkipCondition(OperatingSystems.MacOSX)] [InlineData("", @".", "/testDocument.Txt")] [InlineData("/somedir", @".", "/somedir/Testdocument.TXT")] [InlineData("/SomeDir", @".", "/soMediR/testdocument.txT")] [InlineData("/somedir", @"SubFolder", "/somedir/Ranges.tXt")] public async Task FoundFile_Served_Windows(string baseUrl, string baseDir, string requestUrl) { await FoundFile_Served(baseUrl, baseDir, requestUrl); } private async Task FoundFile_Served(string baseUrl, string baseDir, string requestUrl) { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider })); using var server = host.GetTestServer(); var fileInfo = fileProvider.GetFileInfo(Path.GetFileName(requestUrl)); var response = await server.CreateRequest(requestUrl).GetAsync(); var responseContent = await response.Content.ReadAsByteArrayAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.True(response.Content.Headers.ContentLength == fileInfo.Length); Assert.Equal(response.Content.Headers.ContentLength, responseContent.Length); Assert.NotNull(response.Headers.ETag); using (var stream = fileInfo.CreateReadStream()) { var fileContents = new byte[stream.Length]; stream.Read(fileContents, 0, (int)stream.Length); Assert.True(responseContent.SequenceEqual(fileContents)); } } } [Theory] [MemberData(nameof(ExistingFiles))] public async Task HeadFile_HeadersButNotBodyServed(string baseUrl, string baseDir, string requestUrl) { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider })); using var server = host.GetTestServer(); var fileInfo = fileProvider.GetFileInfo(Path.GetFileName(requestUrl)); var response = await server.CreateRequest(requestUrl).SendAsync("HEAD"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.True(response.Content.Headers.ContentLength == fileInfo.Length); Assert.Empty((await response.Content.ReadAsByteArrayAsync())); } } [Theory] [MemberData(nameof(MissingFiles))] public async Task Get_NoMatch_PassesThrough(string baseUrl, string baseDir, string requestUrl) => await PassesThrough("GET", baseUrl, baseDir, requestUrl); [Theory] [MemberData(nameof(MissingFiles))] public async Task Head_NoMatch_PassesThrough(string baseUrl, string baseDir, string requestUrl) => await PassesThrough("HEAD", baseUrl, baseDir, requestUrl); [Theory] [MemberData(nameof(MissingFiles))] public async Task Unknown_NoMatch_PassesThrough(string baseUrl, string baseDir, string requestUrl) => await PassesThrough("VERB", baseUrl, baseDir, requestUrl); [Theory] [MemberData(nameof(ExistingFiles))] public async Task Options_Match_PassesThrough(string baseUrl, string baseDir, string requestUrl) => await PassesThrough("OPTIONS", baseUrl, baseDir, requestUrl); [Theory] [MemberData(nameof(ExistingFiles))] public async Task Trace_Match_PassesThrough(string baseUrl, string baseDir, string requestUrl) => await PassesThrough("TRACE", baseUrl, baseDir, requestUrl); [Theory] [MemberData(nameof(ExistingFiles))] public async Task Post_Match_PassesThrough(string baseUrl, string baseDir, string requestUrl) => await PassesThrough("POST", baseUrl, baseDir, requestUrl); [Theory] [MemberData(nameof(ExistingFiles))] public async Task Put_Match_PassesThrough(string baseUrl, string baseDir, string requestUrl) => await PassesThrough("PUT", baseUrl, baseDir, requestUrl); [Theory] [MemberData(nameof(ExistingFiles))] public async Task Unknown_Match_PassesThrough(string baseUrl, string baseDir, string requestUrl) => await PassesThrough("VERB", baseUrl, baseDir, requestUrl); private async Task PassesThrough(string method, string baseUrl, string baseDir, string requestUrl) { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider })); using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).SendAsync(method); Assert.Null(response.Content.Headers.LastModified); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } } public static IEnumerable<object[]> MissingFiles => new[] { new[] {"", @".", "/missing.file"}, new[] {"/subdir", @".", "/subdir/missing.file"}, new[] {"/missing.file", @"./", "/missing.file"}, new[] {"", @"./", "/xunit.xml"} }; public static IEnumerable<object[]> ExistingFiles => new[] { new[] {"", @".", "/TestDocument.txt"}, new[] {"/somedir", @".", "/somedir/TestDocument.txt"}, new[] {"/SomeDir", @".", "/soMediR/TestDocument.txt"}, new[] {"", @"SubFolder", "/ranges.txt"}, new[] {"/somedir", @"SubFolder", "/somedir/ranges.txt"}, new[] {"", @"SubFolder", "/Empty.txt"} }; } }
using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.ClientObservers; using Orleans.CodeGeneration; using Orleans.Configuration; using Orleans.Messaging; using Orleans.Providers; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; namespace Orleans { internal class OutsideRuntimeClient : IRuntimeClient, IDisposable, IClusterConnectionStatusListener { internal static bool TestOnlyThrowExceptionDuringInit { get; set; } private readonly ILogger logger; private readonly ClientMessagingOptions clientMessagingOptions; private readonly ConcurrentDictionary<CorrelationId, CallbackData> callbacks; private InvokableObjectManager localObjects; private bool disposing; private ClientProviderRuntime clientProviderRuntime; internal readonly ClientStatisticsManager ClientStatistics; private readonly MessagingTrace messagingTrace; private readonly ClientGrainId clientId; private ThreadTrackingStatistic incomingMessagesThreadTimeTracking; private static readonly TimeSpan ResetTimeout = TimeSpan.FromMinutes(1); private const string BARS = "----------"; public IInternalGrainFactory InternalGrainFactory { get; private set; } private MessageFactory messageFactory; private IPAddress localAddress; private readonly ILoggerFactory loggerFactory; private readonly IOptions<StatisticsOptions> statisticsOptions; private readonly ApplicationRequestsStatisticsGroup appRequestStatistics; private readonly StageAnalysisStatisticsGroup schedulerStageStatistics; private readonly SharedCallbackData sharedCallbackData; private SafeTimer callbackTimer; public ActivationAddress CurrentActivationAddress { get; private set; } public ClientGatewayObserver gatewayObserver { get; private set; } public string CurrentActivationIdentity { get { return CurrentActivationAddress.ToString(); } } public IGrainReferenceRuntime GrainReferenceRuntime { get; private set; } internal ClientMessageCenter MessageCenter { get; private set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "MessageCenter is IDisposable but cannot call Dispose yet as it lives past the end of this method call.")] public OutsideRuntimeClient( ILoggerFactory loggerFactory, IOptions<ClientMessagingOptions> clientMessagingOptions, IOptions<StatisticsOptions> statisticsOptions, ApplicationRequestsStatisticsGroup appRequestStatistics, StageAnalysisStatisticsGroup schedulerStageStatistics, ClientStatisticsManager clientStatisticsManager, MessagingTrace messagingTrace) { this.loggerFactory = loggerFactory; this.statisticsOptions = statisticsOptions; this.appRequestStatistics = appRequestStatistics; this.schedulerStageStatistics = schedulerStageStatistics; this.ClientStatistics = clientStatisticsManager; this.messagingTrace = messagingTrace; this.logger = loggerFactory.CreateLogger<OutsideRuntimeClient>(); this.clientId = ClientGrainId.Create(); callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>(); this.clientMessagingOptions = clientMessagingOptions.Value; this.sharedCallbackData = new SharedCallbackData( msg => this.UnregisterCallback(msg.Id), this.loggerFactory.CreateLogger<CallbackData>(), this.clientMessagingOptions, this.appRequestStatistics, this.clientMessagingOptions.ResponseTimeout); } internal void ConsumeServices(IServiceProvider services) { try { this.ServiceProvider = services; var connectionLostHandlers = this.ServiceProvider.GetServices<ConnectionToClusterLostHandler>(); foreach (var handler in connectionLostHandlers) { this.ClusterConnectionLost += handler; } var gatewayCountChangedHandlers = this.ServiceProvider.GetServices<GatewayCountChangedHandler>(); foreach (var handler in gatewayCountChangedHandlers) { this.GatewayCountChanged += handler; } this.InternalGrainFactory = this.ServiceProvider.GetRequiredService<IInternalGrainFactory>(); this.messageFactory = this.ServiceProvider.GetService<MessageFactory>(); var serializationManager = this.ServiceProvider.GetRequiredService<SerializationManager>(); this.localObjects = new InvokableObjectManager( services.GetRequiredService<ClientGrainContext>(), this, serializationManager, this.messagingTrace, this.loggerFactory.CreateLogger<ClientGrainContext>()); var timerLogger = this.loggerFactory.CreateLogger<SafeTimer>(); var minTicks = Math.Min(this.clientMessagingOptions.ResponseTimeout.Ticks, TimeSpan.FromSeconds(1).Ticks); var period = TimeSpan.FromTicks(minTicks); this.callbackTimer = new SafeTimer(timerLogger, this.OnCallbackExpiryTick, null, period, period); this.GrainReferenceRuntime = this.ServiceProvider.GetRequiredService<IGrainReferenceRuntime>(); BufferPool.InitGlobalBufferPool(this.clientMessagingOptions); this.clientProviderRuntime = this.ServiceProvider.GetRequiredService<ClientProviderRuntime>(); this.localAddress = this.clientMessagingOptions.LocalAddress ?? ConfigUtilities.GetLocalIPAddress(this.clientMessagingOptions.PreferredFamily, this.clientMessagingOptions.NetworkInterfaceName); // Client init / sign-on message logger.Info(ErrorCode.ClientInitializing, string.Format( "{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}", BARS, Dns.GetHostName(), localAddress, clientId)); string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}", BARS, RuntimeVersion.Current, PrintAppDomainDetails()); logger.Info(ErrorCode.ClientStarting, startMsg); if (TestOnlyThrowExceptionDuringInit) { throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit"); } var statisticsLevel = statisticsOptions.Value.CollectionLevel; if (statisticsLevel.CollectThreadTimeTrackingStats()) { incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver", this.loggerFactory, this.statisticsOptions, this.schedulerStageStatistics); } } catch (Exception exc) { if (logger != null) logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc); ConstructorReset(); throw; } } public IServiceProvider ServiceProvider { get; private set; } public async Task Start(Func<Exception, Task<bool>> retryFilter = null) { // Deliberately avoid capturing the current synchronization context during startup and execute on the default scheduler. // This helps to avoid any issues (such as deadlocks) caused by executing with the client's synchronization context/scheduler. await Task.Run(() => this.StartInternal(retryFilter)).ConfigureAwait(false); logger.Info(ErrorCode.ProxyClient_StartDone, "{0} Started OutsideRuntimeClient with Global Client ID: {1}", BARS, CurrentActivationAddress.ToString() + ", client ID: " + clientId); } // used for testing to (carefully!) allow two clients in the same process private async Task StartInternal(Func<Exception, Task<bool>> retryFilter) { var gatewayManager = this.ServiceProvider.GetRequiredService<GatewayManager>(); await ExecuteWithRetries(async () => await gatewayManager.StartAsync(CancellationToken.None), retryFilter); var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative MessageCenter = ActivatorUtilities.CreateInstance<ClientMessageCenter>(this.ServiceProvider, localAddress, generation, clientId); MessageCenter.RegisterLocalMessageHandler(this.HandleMessage); MessageCenter.Start(); CurrentActivationAddress = ActivationAddress.NewActivationAddress(MessageCenter.MyAddress, clientId.GrainId); this.gatewayObserver = new ClientGatewayObserver(gatewayManager); this.InternalGrainFactory.CreateObjectReference<IClientGatewayObserver>(this.gatewayObserver); await ExecuteWithRetries( async () => await this.ServiceProvider.GetRequiredService<ClientClusterManifestProvider>().StartAsync(), retryFilter); ClientStatistics.Start(MessageCenter, clientId.GrainId); async Task ExecuteWithRetries(Func<Task> task, Func<Exception, Task<bool>> shouldRetry) { while (true) { try { await task(); return; } catch (Exception exception) when (shouldRetry != null) { var retry = await shouldRetry(exception); if (!retry) throw; } } } } private void HandleMessage(Message message) { switch (message.Direction) { case Message.Directions.Response: { ReceiveResponse(message); break; } case Message.Directions.OneWay: case Message.Directions.Request: { this.localObjects.Dispatch(message); break; } default: logger.Error(ErrorCode.Runtime_Error_100327, $"Message not supported: {message}."); break; } } public void SendResponse(Message request, Response response) { var message = this.messageFactory.CreateResponseMessage(request); OrleansOutsideRuntimeClientEvent.Log.SendResponse(message); message.BodyObject = response; MessageCenter.SendMessage(message); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "CallbackData is IDisposable but instances exist beyond lifetime of this method so cannot Dispose yet.")] public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, InvokeMethodOptions options) { var message = this.messageFactory.CreateMessage(request, options); OrleansOutsideRuntimeClientEvent.Log.SendRequest(message); SendRequestMessage(target, message, context, options); } private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource<object> context, InvokeMethodOptions options) { message.InterfaceType = target.InterfaceType; message.InterfaceVersion = target.InterfaceVersion; var targetGrainId = target.GrainId; var oneWay = (options & InvokeMethodOptions.OneWay) != 0; message.SendingGrain = CurrentActivationAddress.Grain; message.SendingActivation = CurrentActivationAddress.Activation; message.TargetGrain = targetGrainId; if (SystemTargetGrainId.TryParse(targetGrainId, out var systemTargetGrainId)) { // If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo message.TargetSilo = systemTargetGrainId.GetSiloAddress(); message.TargetActivation = ActivationId.GetDeterministic(targetGrainId); } if (message.IsExpirableMessage(this.clientMessagingOptions.DropExpiredMessages)) { // don't set expiration for system target messages. message.TimeToLive = this.clientMessagingOptions.ResponseTimeout; } if (!oneWay) { var callbackData = new CallbackData(this.sharedCallbackData, context, message); callbacks.TryAdd(message.Id, callbackData); } if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Send {0}", message); MessageCenter.SendMessage(message); } public void ReceiveResponse(Message response) { OrleansOutsideRuntimeClientEvent.Log.ReceiveResponse(response); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Received {0}", response); // ignore duplicate requests if (response.Result == Message.ResponseTypes.Rejection && (response.RejectionType == Message.RejectionTypes.DuplicateRequest || response.RejectionType == Message.RejectionTypes.CacheInvalidation)) { return; } else if (response.Result == Message.ResponseTypes.Status) { var status = (StatusResponse)response.BodyObject; callbacks.TryGetValue(response.Id, out var callback); var request = callback?.Message; if (!(request is null)) { callback.OnStatusUpdate(status); if (status.Diagnostics != null && status.Diagnostics.Count > 0 && logger.IsEnabled(LogLevel.Information)) { var diagnosticsString = string.Join("\n", status.Diagnostics); using (request.SetThreadActivityId()) { this.logger.LogInformation("Received status update for pending request, Request: {RequestMessage}. Status: {Diagnostics}", request, diagnosticsString); } } } else { if (status.Diagnostics != null && status.Diagnostics.Count > 0 && logger.IsEnabled(LogLevel.Information)) { var diagnosticsString = string.Join("\n", status.Diagnostics); using (response.SetThreadActivityId()) { this.logger.LogInformation("Received status update for unknown request. Message: {StatusMessage}. Status: {Diagnostics}", response, diagnosticsString); } } } return; } CallbackData callbackData; var found = callbacks.TryRemove(response.Id, out callbackData); if (found) { // We need to import the RequestContext here as well. // Unfortunately, it is not enough, since CallContext.LogicalGetData will not flow "up" from task completion source into the resolved task. // RequestContextExtensions.Import(response.RequestContextData); callbackData.DoCallback(response); } else { logger.Warn(ErrorCode.Runtime_Error_100011, "No callback for response message: " + response); } } private void UnregisterCallback(CorrelationId id) { callbacks.TryRemove(id, out _); } public void Reset(bool cleanup) { Utils.SafeExecute(() => { if (logger != null) { logger.Info("OutsideRuntimeClient.Reset(): client Id " + clientId); } }, this.logger); Utils.SafeExecute(() => { incomingMessagesThreadTimeTracking?.OnStopExecution(); }, logger, "Client.incomingMessagesThreadTimeTracking.OnStopExecution"); Utils.SafeExecute(() => { if (MessageCenter != null) { MessageCenter.Stop(); } }, logger, "Client.Stop-Transport"); Utils.SafeExecute(() => { if (ClientStatistics != null) { ClientStatistics.Stop(); } }, logger, "Client.Stop-ClientStatistics"); ConstructorReset(); } private void ConstructorReset() { Utils.SafeExecute(() => { if (logger != null) { logger.Info("OutsideRuntimeClient.ConstructorReset(): client Id " + clientId); } }); Utils.SafeExecute(() => this.Dispose()); } /// <inheritdoc /> public TimeSpan GetResponseTimeout() => this.sharedCallbackData.ResponseTimeout; /// <inheritdoc /> public void SetResponseTimeout(TimeSpan timeout) => this.sharedCallbackData.ResponseTimeout = timeout; public IAddressable CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker) { if (obj is GrainReference) throw new ArgumentException("Argument obj is already a grain reference.", nameof(obj)); if (obj is Grain) throw new ArgumentException("Argument must not be a grain class.", nameof(obj)); var observerId = obj is ClientObserver clientObserver ? clientObserver.GetObserverGrainId(this.clientId) : ObserverGrainId.Create(this.clientId); var reference = this.InternalGrainFactory.GetGrain(observerId.GrainId); if (!localObjects.TryRegister(obj, observerId, invoker)) { throw new ArgumentException($"Failed to add new observer {reference} to localObjects collection.", "reference"); } return reference; } public void DeleteObjectReference(IAddressable obj) { if (!(obj is GrainReference reference)) { throw new ArgumentException("Argument reference is not a grain reference."); } if (!ObserverGrainId.TryParse(reference.GrainId, out var observerId)) { throw new ArgumentException($"Reference {reference.GrainId} is not an observer reference"); } if (!localObjects.TryDeregister(observerId)) { throw new ArgumentException("Reference is not associated with a local object.", "reference"); } } private string PrintAppDomainDetails() { return string.Format("<AppDomain.Id={0}, AppDomain.FriendlyName={1}>", AppDomain.CurrentDomain.Id, AppDomain.CurrentDomain.FriendlyName); } public void Dispose() { if (this.disposing) return; this.disposing = true; Utils.SafeExecute(() => this.callbackTimer?.Dispose()); Utils.SafeExecute(() => MessageCenter?.Dispose()); this.ClusterConnectionLost = null; this.GatewayCountChanged = null; GC.SuppressFinalize(this); } public void BreakOutstandingMessagesToDeadSilo(SiloAddress deadSilo) { foreach (var callback in callbacks) { if (deadSilo.Equals(callback.Value.Message.TargetSilo)) { callback.Value.OnTargetSiloFail(); } } } /// <inheritdoc /> public event ConnectionToClusterLostHandler ClusterConnectionLost; /// <inheritdoc /> public event GatewayCountChangedHandler GatewayCountChanged; /// <inheritdoc /> public void NotifyClusterConnectionLost() { try { this.ClusterConnectionLost?.Invoke(this, EventArgs.Empty); } catch (Exception ex) { this.logger.Error(ErrorCode.ClientError, "Error when sending cluster disconnection notification", ex); } } /// <inheritdoc /> public void NotifyGatewayCountChanged(int currentNumberOfGateways, int previousNumberOfGateways) { try { this.GatewayCountChanged?.Invoke(this, new GatewayCountChangedEventArgs(currentNumberOfGateways, previousNumberOfGateways)); } catch (Exception ex) { this.logger.Error(ErrorCode.ClientError, "Error when sending gateway count changed notification", ex); } } private void OnCallbackExpiryTick(object state) { var currentStopwatchTicks = Stopwatch.GetTimestamp(); foreach (var pair in callbacks) { var callback = pair.Value; if (callback.IsCompleted) continue; if (callback.IsExpired(currentStopwatchTicks)) callback.OnTimeout(this.clientMessagingOptions.ResponseTimeout); } } } }
// Copyright (c) Ugo Lattanzi. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using StackExchange.Redis.Extensions.Core.Helpers; using StackExchange.Redis.Extensions.Tests.Helpers; using Xunit; namespace StackExchange.Redis.Extensions.Core.Tests; public abstract partial class CacheClientTestBase { [Fact] [Trait("Category", "Tags")] public async Task AddAsync_WithTags_ShouldAdd() { const string testKey = "test_key"; const string testValue = "test_value"; var testClass = new TestClass<string>(testKey, testValue); var testTags = new HashSet<string> { "test_tag" }; var addResult = await Sut.GetDefaultDatabase().AddAsync(testKey, testClass, tags: testTags).ConfigureAwait(false); Assert.True(addResult); } [Fact] [Trait("Category", "Tags")] public async Task AddAsync_WithTags_TagExists() { const string testKey = "test_key"; const string testValue = "test_value"; var testClass = new TestClass<string>(testKey, testValue); const string testTag = "test_tag"; await Sut.GetDefaultDatabase().AddAsync(testKey, testClass, tags: new() { testTag }).ConfigureAwait(false); var tagExists = await db.KeyExistsAsync(TagHelper.GenerateTagKey(testTag)).ConfigureAwait(false); Assert.True(tagExists); } [Fact] [Trait("Category", "Tags")] public async Task AddAsync_WithTags_CorrectTaggedKey() { const string testKey = "test_key"; const string testValue = "test_value"; var testClass = new TestClass<string>(testKey, testValue); const string testTag = "test_tag"; await Sut.GetDefaultDatabase().AddAsync(testKey, testClass, tags: new() { testTag }).ConfigureAwait(false); var tags = await db.SetMembersAsync(TagHelper.GenerateTagKey(testTag)).ConfigureAwait(false); var deserialized = tags?.Length > 0 ? serializer.Deserialize<string>(tags[0]) : string.Empty; Assert.Equal(testKey, deserialized); } [Fact] [Trait("Category", "Tags")] public async Task AddAsyncTimeSpan_WithTags_ShouldAdd() { const string testKey = "test_key"; const string testValue = "test_value"; var testClass = new TestClass<string>(testKey, testValue); var testTags = new HashSet<string> { "test_tag" }; var addResult = await Sut.GetDefaultDatabase().AddAsync(testKey, testClass, TimeSpan.FromSeconds(1), tags: testTags).ConfigureAwait(false); Assert.True(addResult); } [Fact] [Trait("Category", "Tags")] public async Task AddAsyncTimeSpan_WithTags_TagExists() { const string testKey = "test_key"; const string testValue = "test_value"; var testClass = new TestClass<string>(testKey, testValue); const string testTag = "test_tag"; await Sut.GetDefaultDatabase().AddAsync(testKey, testClass, TimeSpan.FromSeconds(1), tags: new() { testTag }).ConfigureAwait(false); var tagExists = await db.KeyExistsAsync(TagHelper.GenerateTagKey(testTag)).ConfigureAwait(false); Assert.True(tagExists); } [Fact] [Trait("Category", "Tags")] public async Task AddAsyncTimeSpan_WithTags_CorrectTaggedKey() { const string testKey = "test_key"; const string testValue = "test_value"; var testClass = new TestClass<string>(testKey, testValue); const string testTag = "test_tag"; await Sut.GetDefaultDatabase().AddAsync(testKey, testClass, TimeSpan.FromSeconds(1), tags: new() { testTag }).ConfigureAwait(false); var tags = await db.SetMembersAsync(TagHelper.GenerateTagKey(testTag)).ConfigureAwait(false); var deserialized = serializer.Deserialize<string>(tags[0]); Assert.Equal(testKey, deserialized); } [Fact] [Trait("Category", "Tags")] public async Task AddAsyncDateTimeOffset_WithTags_ShouldAdd() { const string testKey = "test_key"; const string testValue = "test_value"; var testClass = new TestClass<string>(testKey, testValue); var testTags = new HashSet<string> { "test_tag" }; var addResult = await Sut.GetDefaultDatabase().AddAsync(testKey, testClass, DateTimeOffset.UtcNow, tags: testTags).ConfigureAwait(false); Assert.True(addResult); } [Fact] [Trait("Category", "Tags")] public async Task AddAsyncDateTimeOffset_WithTags_TagExists() { const string testKey = "test_key"; const string testValue = "test_value"; var testClass = new TestClass<string>(testKey, testValue); const string testTag = "test_tag"; await Sut.GetDefaultDatabase().AddAsync(testKey, testClass, DateTimeOffset.UtcNow, tags: new() { testTag }).ConfigureAwait(false); var tagExists = await db.KeyExistsAsync(TagHelper.GenerateTagKey(testTag)).ConfigureAwait(false); Assert.True(tagExists); } [Fact] [Trait("Category", "Tags")] public async Task AddAsyncDateTimeOffset_WithTags_CorrectTaggedKey() { const string testKey = "test_key"; const string testValue = "test_value"; var testClass = new TestClass<string>(testKey, testValue); const string testTag = "test_tag"; await Sut.GetDefaultDatabase().AddAsync(testKey, testClass, DateTimeOffset.UtcNow, tags: new() { testTag }).ConfigureAwait(false); var tags = await db.SetMembersAsync(TagHelper.GenerateTagKey(testTag)).ConfigureAwait(false); var deserialized = serializer.Deserialize<string>(tags[0]); Assert.Equal(testKey, deserialized); } [Fact] [Trait("Category", "Tags")] public async Task GetByTagAsync_ShouldReturnSomeValues() { const string testKey = "test_key"; const string testValue = "test_value"; var testClass = new TestClass<string>(testKey, testValue); const string testTag = "test_tag"; await Sut.GetDefaultDatabase().AddAsync(testKey, testClass, tags: new() { testTag }).ConfigureAwait(false); var result = await Sut.GetDefaultDatabase().GetByTagAsync<TestClass<string>>(testTag).ConfigureAwait(false); Assert.Equal(1, result?.Count()); } [Fact] [Trait("Category", "Tags")] public async Task GetByTagAsync_ShouldReturnCorrectValue() { const string testKey = "test_key"; const string testValue = "test_value"; var testClass = new TestClass<string>(testKey, testValue); const string testTag = "test_tag"; await Sut.GetDefaultDatabase().AddAsync(testKey, testClass, tags: new() { testTag }).ConfigureAwait(false); var result = await Sut.GetDefaultDatabase().GetByTagAsync<TestClass<string>>(testTag).ConfigureAwait(false); Assert.Equal(testClass, result.First()); } [Fact] [Trait("Category", "Tags")] public async Task RemoveByTagAsync_ShouldReturnZero() { const string testTag = "test_tag"; var result = await Sut.GetDefaultDatabase().RemoveByTagAsync(testTag).ConfigureAwait(false); Assert.Equal(0, result); } [Fact] [Trait("Category", "Tags")] public async Task RemoveByTagAsync_ShouldReturnOneDeletedValue() { const string testKey = "test_key"; const string testValue = "test_value"; var testClass = new TestClass<string>(testKey, testValue); const string testTag = "test_tag"; await Sut.GetDefaultDatabase().AddAsync(testKey, testClass, tags: new() { testTag }).ConfigureAwait(false); var result = await Sut.GetDefaultDatabase().RemoveByTagAsync(testTag).ConfigureAwait(false); Assert.Equal(1, result); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using V2.PaidTimeOffDAL.Framework; using V2.PaidTimeOffDAL; using V2.PaidTimeOffBLL.Framework; namespace V2.PaidTimeOffBLL { #region PTORequestEO [Serializable()] public class PTORequestEO : ENTBaseWorkflowEO { #region Properties public int ENTUserAccountId { get; set; } public DateTime RequestDate { get; set; } public PTODayTypeBO.PTODayTypeEnum PTODayTypeId { get; set; } public PTORequestTypeBO.PTORequestTypeEnum PTORequestTypeId { get; set; } public string RequestDateString { get { return RequestDate.ToStandardDateFormat(); } } public string RequestTypeString { get { string text; switch (PTORequestTypeId) { case PTORequestTypeBO.PTORequestTypeEnum.Personal: text = "Personal"; break; case PTORequestTypeBO.PTORequestTypeEnum.Vacation: text = "Vacation"; break; case PTORequestTypeBO.PTORequestTypeEnum.Unpaid: text = "Unpaid"; break; default: throw new Exception("PTO Request Type unkown."); } switch (PTODayTypeId) { case PTODayTypeBO.PTODayTypeEnum.AM: text += "-AM"; break; case PTODayTypeBO.PTODayTypeEnum.PM: text += "-PM"; break; case PTODayTypeBO.PTODayTypeEnum.Full: break; default: throw new Exception("PTO Day Tyep unknown."); } return text; } } #endregion Properties #region Overrides public override bool Load(int id) { //Get the entity object from the DAL. PTORequest pTORequest = new PTORequestData().Select(id); MapEntityToProperties(pTORequest); return true; } protected override void MapEntityToCustomProperties(IENTBaseEntity entity) { PTORequest pTORequest = (PTORequest)entity; ID = pTORequest.PTORequestId; ENTUserAccountId = pTORequest.ENTUserAccountId; RequestDate = pTORequest.RequestDate; PTODayTypeId = (PTODayTypeBO.PTODayTypeEnum)pTORequest.PTODayTypeId; PTORequestTypeId = (PTORequestTypeBO.PTORequestTypeEnum)pTORequest.PTORequestTypeId; base.LoadWorkflow(this.GetType().AssemblyQualifiedName, ID); } public override bool Save(HRPaidTimeOffDataContext db, ref ENTValidationErrors validationErrors, int userAccountId) { if (DBAction == DBActionEnum.Save) { //Validate the object Validate(db, ref validationErrors); //Check if there were any validation errors if (validationErrors.Count == 0) { bool isNewRecord = IsNewRecord(); if (isNewRecord) { //Add ID = new PTORequestData().Insert(db, ENTUserAccountId, RequestDate, Convert.ToInt32(PTODayTypeId), Convert.ToInt32(PTORequestTypeId), userAccountId); } else { //Update if (!new PTORequestData().Update(db, ID, ENTUserAccountId, RequestDate, Convert.ToInt32(PTODayTypeId), Convert.ToInt32(PTORequestTypeId), userAccountId, Version)) { UpdateFailed(ref validationErrors); if (isNewRecord) ID = 0; return false; } } if (base.SaveWorkflow(db, ref validationErrors, this, userAccountId)) { return true; } else { if (isNewRecord) ID = 0; return false; } } else { //Didn't pass validation. ID = 0; return false; } } else { throw new Exception("DBAction not Save."); } } protected override void Validate(HRPaidTimeOffDataContext db, ref ENTValidationErrors validationErrors) { //Check if this was already selected as a request. } protected override void DeleteForReal(HRPaidTimeOffDataContext db) { if (DBAction == DBActionEnum.Delete) { new PTORequestData().Delete(db, ID); } else { throw new Exception("DBAction not delete."); } } protected override void ValidateDelete(HRPaidTimeOffDataContext db, ref ENTValidationErrors validationErrors) { } public override void Init() { PTODayTypeId = PTODayTypeBO.PTODayTypeEnum.Full; PTORequestTypeId = PTORequestTypeBO.PTORequestTypeEnum.Vacation; } protected override string GetDisplayText() { return RequestDate.ToStandardDateFormat(); } #endregion Overrides public void SetRequestToCancelled(HRPaidTimeOffDataContext db) { new PTORequestData().UpdateCancelled(db, ID, true); } public static void GetUsed(ref double usedPersonalDays, ref double usedVacationDays, ref double unpaid, int ptoRequestId, int userAccountId, short year) { PTORequestSelectByENTUserAccountIdYearResult result = new PTORequestData().SelectByENTUserAccountIdYear(ptoRequestId, userAccountId, year); if (result != null) { usedVacationDays = Convert.ToDouble(result.CountOfFullVacation + result.CountOfHalfVacation); usedPersonalDays = Convert.ToDouble(result.CountOfFullPersonal + result.CountOfHalfPersonal); unpaid = Convert.ToDouble(result.CountOfFullUnpaid + result.CountOfHalfUnPaid); } else { usedPersonalDays = 0; usedVacationDays = 0; unpaid = 0; } } } #endregion PTORequestEO #region PTORequestEOList [Serializable()] public class PTORequestEOList : ENTBaseEOList<PTORequestEO> { #region Overrides public override void Load() { LoadFromList(new PTORequestData().Select()); } #endregion Overrides #region Private Methods private void LoadFromList(List<PTORequest> pTORequests) { if (pTORequests.Count > 0) { foreach (PTORequest pTORequest in pTORequests) { PTORequestEO newPTORequestEO = new PTORequestEO(); newPTORequestEO.MapEntityToProperties(pTORequest); this.Add(newPTORequestEO); } } } #endregion Private Methods #region Internal Methods #endregion Internal Methods public void LoadPreviousByENTUserAccountId(int ptoRequestId, int entUserAccountId) { LoadFromList(new PTORequestData().SelectPreviousByENTUserAccountId(ptoRequestId, entUserAccountId)); } public void LoadByENTUserAccountId(int entUserAccountId) { LoadFromList(new PTORequestData().SelectByENTUserAccountId(entUserAccountId)); } public List<PTORequestEO> GetByRequestDate(DateTime requestDate) { var ret = from r in this where r.RequestDate == requestDate select r; return ret.ToList(); } public void LoadByCurrentOwnerId(int entUserAccountId) { LoadFromList(new PTORequestData().SelectByCurrentOwnerId(entUserAccountId, typeof(PTORequestEO).AssemblyQualifiedName)); } } #endregion PTORequestEOList }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using MongoDB.Util; namespace MongoDB.Configuration.Mapping.Util { /// <summary> /// </summary> public static class MemberReflectionOptimizer { private static readonly Dictionary<string, Func<object, object>> GetterCache = new Dictionary<string, Func<object, object>>(); private static readonly Dictionary<string, Action<object, object>> SetterCache = new Dictionary<string, Action<object, object>>(); private static readonly Dictionary<RuntimeTypeHandle, Func<object>> CreatorCache = new Dictionary<RuntimeTypeHandle, Func<object>>(); private static readonly object SyncObject = new object(); /// <summary> /// Gets the getter. /// </summary> /// <param name = "memberInfo">The member info.</param> /// <returns></returns> public static Func<object, object> GetGetter(MemberInfo memberInfo) { if(memberInfo == null) throw new ArgumentNullException("memberInfo"); if(memberInfo.MemberType != MemberTypes.Field && memberInfo.MemberType != MemberTypes.Property) throw new ArgumentException("Only fields and properties are supported.", "memberInfo"); if(memberInfo.MemberType == MemberTypes.Field) return GetFieldGetter(memberInfo as FieldInfo); if(memberInfo.MemberType == MemberTypes.Property) return GetPropertyGetter(memberInfo as PropertyInfo); throw new InvalidOperationException("Can only create getters for fields or properties."); } /// <summary> /// Gets the field getter. /// </summary> /// <param name = "fieldInfo">The field info.</param> /// <returns></returns> public static Func<object, object> GetFieldGetter(FieldInfo fieldInfo) { if(fieldInfo == null) throw new ArgumentNullException("fieldInfo"); var key = CreateKey(fieldInfo); Func<object, object> getter; lock (SyncObject) { if (GetterCache.TryGetValue(key, out getter)) return getter; } //We release the lock here, so the relatively time consuming compiling //does not imply contention. The price to pay is potential multiple compilations //of the same expression... var instanceParameter = Expression.Parameter(typeof (object), "target"); var member = Expression.Field(Expression.Convert(instanceParameter, fieldInfo.DeclaringType), fieldInfo); var lambda = Expression.Lambda<Func<object, object>>( Expression.Convert(member, typeof (object)), instanceParameter); getter = lambda.Compile(); lock(SyncObject) { GetterCache[key] = getter; } return getter; } /// <summary> /// Gets the property getter. /// </summary> /// <param name = "propertyInfo">The property info.</param> /// <returns></returns> public static Func<object, object> GetPropertyGetter(PropertyInfo propertyInfo) { if(propertyInfo == null) throw new ArgumentNullException("propertyInfo"); var key = CreateKey(propertyInfo); Func<object, object> getter; lock (SyncObject) { if (GetterCache.TryGetValue(key, out getter)) return getter; } if(!propertyInfo.CanRead) throw new InvalidOperationException("Cannot create a getter for a writeonly property."); var instanceParameter = Expression.Parameter(typeof(object), "target"); var member = Expression.Property(Expression.Convert(instanceParameter, propertyInfo.DeclaringType), propertyInfo); var lambda = Expression.Lambda<Func<object, object>>( Expression.Convert(member, typeof(object)), instanceParameter); getter = lambda.Compile(); lock (SyncObject) { GetterCache[key] = getter; } return getter; } /// <summary> /// Gets the setter. /// </summary> /// <param name = "memberInfo">The member info.</param> /// <returns></returns> public static Action<object, object> GetSetter(MemberInfo memberInfo) { if(memberInfo == null) throw new ArgumentNullException("memberInfo"); if(memberInfo.MemberType != MemberTypes.Field && memberInfo.MemberType != MemberTypes.Property) throw new ArgumentException("Only fields and properties are supported.", "memberInfo"); if(memberInfo.MemberType == MemberTypes.Field) return GetFieldSetter(memberInfo as FieldInfo); if(memberInfo.MemberType == MemberTypes.Property) return GetPropertySetter(memberInfo as PropertyInfo); throw new InvalidOperationException("Can only create setters for fields or properties."); } /// <summary> /// Gets the field setter. /// </summary> /// <param name = "fieldInfo">The field info.</param> /// <returns></returns> public static Action<object, object> GetFieldSetter(FieldInfo fieldInfo) { if(fieldInfo == null) throw new ArgumentNullException("fieldInfo"); var key = CreateKey(fieldInfo); Action<object, object> setter; lock (SyncObject) { if (SetterCache.TryGetValue(key, out setter)) return setter; } if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral) throw new InvalidOperationException("Cannot create a setter for a readonly field."); var sourceType = fieldInfo.DeclaringType; var method = new DynamicMethod("Set" + fieldInfo.Name, null, new[] {typeof (object), typeof (object)}, true); var gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Castclass, sourceType); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Unbox_Any, fieldInfo.FieldType); gen.Emit(OpCodes.Stfld, fieldInfo); gen.Emit(OpCodes.Ret); setter = (Action<object, object>) method.CreateDelegate(typeof (Action<object, object>)); lock (SyncObject) { SetterCache[key] = setter; } return setter; } /// <summary> /// Gets the property setter. /// </summary> /// <param name = "propertyInfo">The property info.</param> /// <returns></returns> public static Action<object, object> GetPropertySetter(PropertyInfo propertyInfo) { if(propertyInfo == null) throw new ArgumentNullException("propertyInfo"); var key = CreateKey(propertyInfo); Action<object, object> setter; lock (SyncObject) { if (SetterCache.TryGetValue(key, out setter)) return setter; } if (!propertyInfo.CanWrite) throw new InvalidOperationException("Cannot create a setter for a readonly property."); var instanceParameter = Expression.Parameter(typeof (object), "target"); var valueParameter = Expression.Parameter(typeof (object), "value"); var lambda = Expression.Lambda<Action<object, object>>( Expression.Call( Expression.Convert(instanceParameter, propertyInfo.DeclaringType), propertyInfo.GetSetMethod(true), Expression.Convert(valueParameter, propertyInfo.PropertyType)), instanceParameter, valueParameter); setter = lambda.Compile(); lock (SyncObject) { SetterCache[key] = setter; } return setter; } /// <summary> /// Gets an instance creator /// </summary> /// <param name="type">Type to instantiate</param> /// <returns>A delegate to create an object of the given type</returns> public static Func<object> GetCreator(Type type) { Func<object> creator; RuntimeTypeHandle runtimeTypeHandle = type.TypeHandle; lock (SyncObject) { if (CreatorCache.TryGetValue(runtimeTypeHandle, out creator)) return creator; } ConstructorInfo defaultConstructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], new ParameterModifier[0]); creator = Expression.Lambda<Func<object>>(Expression.New(defaultConstructor)).Compile(); lock (SyncObject) { CreatorCache[runtimeTypeHandle] = creator; } return creator; } /// <summary> /// Creates the key. /// </summary> /// <param name = "memberInfo">The member info.</param> /// <returns></returns> private static string CreateKey(MemberInfo memberInfo) { return string.Format("{0}_{1}_{2}_{3}", memberInfo.DeclaringType.FullName, memberInfo.MemberType, memberInfo.GetReturnType(), memberInfo.Name); } } }
using Tibia.Addresses; namespace Tibia { public partial class Version { public static void SetVersion822() { BattleList.StepCreatures = 0xA0; BattleList.MaxCreatures = 150; BattleList.Start = Player.Experience + 108; BattleList.End = BattleList.Start + (BattleList.StepCreatures * BattleList.MaxCreatures); Client.StartTime = 0x781258; Client.XTeaKey = 0x77BDB4; Client.SocketStruct = 0x77BD88; Client.SendPointer = 0x5A7600; Client.FrameRatePointer = 0x77FF3C; Client.FrameRateCurrentOffset = 0x0; Client.FrameRateLimitOffset = 0x58; Client.MultiClient = 0x502B94;//not verified Client.Status = 0x77F3F8; Client.SafeMode = 0x77C1D0; Client.FollowMode = Client.SafeMode + 4; Client.AttackMode = Client.FollowMode + 4; Client.ActionState = 0x77F458; Client.LastMSGText = 0x7814C0; //8.1, 8.0 = 0x7686A8 Client.LastMSGAuthor = Client.LastMSGText - 0x28; //8.1, 8.0 = 0x768680 Client.StatusbarText = 0x781270; Client.StatusbarTime = Client.StatusbarText - 4; Client.ClickId = 0x77F494; Client.ClickCount = Client.ClickId + 4; Client.ClickZ = Client.ClickId - 0x68; Client.SeeText = Client.ClickId + 12; Client.LoginServerStart = 0x776CF0; Client.StepLoginServer = 112; Client.DistancePort = 100; Client.MaxLoginServers = 10; Client.RSA = 0x5A7610; Client.LoginCharList = 0x77F3BC; Client.LoginSelectedChar = 0x77F3B8; Client.GameWindowRectPointer = 0x62E754; Client.GameWindowBar = 0x631AC0; Client.DatPointer = 0x77BDD4; Client.DialogPointer = 0x631ABC; Client.DialogLeft = 0x14; Client.DialogTop = 0x18; Client.DialogWidth = 0x1C; Client.DialogHeight = 0x20; Client.DialogCaption = 0x50; Client.LoginPassword = 0x77F3E4; Client.LoginAccount = Client.LoginPassword + 32; Client.LoginAccountNum = Client.LoginAccount + 12; Client.Nop = 0x90; Client.LoginPatchOrig = new byte[] { 0xE8, 0x0D, 0x1D, 0x09, 0x00 }; Client.LoginPatchOrig2 = new byte[] { 0xE8, 0xC8, 0x15, 0x09, 0x00 }; Container.Start = 0x62F208; Container.End = Container.Start + (Container.MaxContainers * Container.StepContainer); Container.StepContainer = 492; Container.StepSlot = 12; Container.MaxContainers = 16; Container.MaxStack = 100; Container.DistanceIsOpen = 0; Container.DistanceId = 4; Container.DistanceName = 16; Container.DistanceVolume = 48; Container.DistanceAmount = 56; Container.DistanceItemId = 60; Container.DistanceItemCount = 64; Creature.DistanceId = 0; Creature.DistanceType = 3; Creature.DistanceName = 4; Creature.DistanceX = 36; Creature.DistanceY = 40; Creature.DistanceZ = 44; Creature.DistanceScreenOffsetHoriz = 48; Creature.DistanceScreenOffsetVert = 52; Creature.DistanceIsWalking = 76; Creature.DistanceWalkSpeed = 140; Creature.DistanceDirection = 80; Creature.DistanceIsVisible = 144; Creature.DistanceBlackSquare = 128; Creature.DistanceLight = 120; Creature.DistanceLightColor = 124; Creature.DistanceHPBar = 136; Creature.DistanceSkull = 148; Creature.DistanceParty = 152; Creature.DistanceOutfit = 96; Creature.DistanceColorHead = 100; Creature.DistanceColorBody = 104; Creature.DistanceColorLegs = 108; Creature.DistanceColorFeet = 112; Creature.DistanceAddon = 116; DatItem.StepItems = 0x4C; DatItem.Width = 0; DatItem.Height = 4; DatItem.MaxSizeInPixels = 8; DatItem.Layers = 12; DatItem.PatternX = 16; DatItem.PatternY = 20; DatItem.PatternDepth = 24; DatItem.Phase = 28; DatItem.Sprite = 32; DatItem.Flags = 36; DatItem.CanLookAt = 0; DatItem.WalkSpeed = 40; DatItem.TextLimit = 44; DatItem.LightRadius = 48; DatItem.LightColor = 52; DatItem.ShiftX = 56; DatItem.ShiftY = 60; DatItem.WalkHeight = 64; DatItem.Automap = 68; DatItem.LensHelp = 72; Hotkey.SendAutomaticallyStart = 0x77C3C8; Hotkey.SendAutomaticallyStep = 0x1; Hotkey.TextStart = 0x77C3F0; Hotkey.TextStep = 0x100; Hotkey.ObjectStart = 0x77C2A8; Hotkey.ObjectStep = 0x4; Hotkey.ObjectUseTypeStart = 0x77C218; Hotkey.ObjectUseTypeStep = 0x4; Hotkey.MaxHotkeys = 36; Map.MapPointer = 0x636610; Map.StepTile = 172; Map.StepTileObject = 12; Map.DistanceTileObjectCount = 0; Map.DistanceTileObjects = 4; Map.DistanceObjectId = 0; Map.DistanceObjectData = 4; Map.DistanceObjectDataEx = 8; Map.MaxTileObjects = 13; Map.MaxX = 18; Map.MaxY = 14; Map.MaxZ = 8; Map.MaxTiles = 2016; Map.ZAxisDefault = 7; Map.PlayerTile = 0x3E3A08; Map.NameSpy1 = 0x4E95F9; Map.NameSpy2 = 0x4E9603; Map.NameSpy1Default = 19061; Map.NameSpy2Default = 16501; Map.LevelSpy1 = 0x4EB4AA; Map.LevelSpy2 = 0x4EB5AF; Map.LevelSpy3 = 0x4EB630; Map.LevelSpyPtr = 0x62E754; Map.LevelSpyAdd2 = 0x25D8; Map.LevelSpyDefault = new byte[] { 0x89, 0x86, 0xD8, 0x25, 0x00, 0x00 }; Map.RevealInvisible1 = 0x45BF63; Map.RevealInvisible2 = 0x4E88C5; Player.Experience = 0x626C64; Player.GoToX = Player.Experience + 80; Player.GoToY = Player.Experience + 76; Player.GoToZ = Player.Experience + 72; Player.Id = Player.Experience + 12; Player.Health = Player.Experience + 8; Player.HealthMax = Player.Experience + 4; Player.Level = Player.Experience - 4; Player.MagicLevel = Player.Experience - 8; Player.LevelPercent = Player.Experience - 12; Player.MagicLevelPercent = Player.Experience - 16; Player.Mana = Player.Experience - 20; Player.ManaMax = Player.Experience - 24; Player.Soul = Player.Experience - 28; Player.Stamina = Player.Experience - 32; Player.Capacity = Player.Experience - 36; Player.Fishing = Player.Experience - 52; Player.Shielding = Player.Experience - 56; Player.Distance = Player.Experience - 60; Player.Axe = Player.Experience - 64; Player.Sword = Player.Experience - 68; Player.Club = Player.Experience - 72; Player.Fist = Player.Experience - 76; Player.FishingPercent = Player.Experience - 80; Player.ShieldingPercent = Player.Experience - 84; Player.DistancePercent = Player.Experience - 88; Player.AxePercent = Player.Experience - 92; Player.SwordPercent = Player.Experience - 96; Player.ClubPercent = Player.Experience - 100; Player.FistPercent = Player.Experience - 104; Player.Flags = Player.Experience - 108; Player.MaxSlots = 10; Player.SlotHead = 0x62D190; Player.SlotNeck = Player.SlotHead + 12; Player.SlotBackpack = Player.SlotHead + 24; Player.SlotArmor = Player.SlotHead + 36; Player.SlotRight = Player.SlotHead + 48; Player.SlotLeft = Player.SlotHead + 60; Player.SlotLegs = Player.SlotHead + 72; Player.SlotFeet = Player.SlotHead + 84; Player.SlotRing = Player.SlotHead + 96; Player.SlotAmmo = Player.SlotHead + 108; Player.DistanceSlotCount = 4; Player.CurrentTileToGo = 0x626C78; Player.TilesToGo = 0x626C7C; Player.RedSquare = 0x626C3C; Player.GreenSquare = Player.RedSquare - 4; Player.WhiteSquare = Player.GreenSquare - 8; Player.AccessN = 0x766DF4; Player.AccessS = 0x766DC4; Player.TargetId = Player.RedSquare; Player.TargetBattlelistId = Player.TargetId - 8; Player.TargetBattlelistType = Player.TargetId - 5; Player.TargetType = Player.TargetId + 3; TextDisplay.PrintName = 0x4EC5E1; TextDisplay.PrintFPS = 0x4563C8; TextDisplay.ShowFPS = 0x624974; TextDisplay.PrintTextFunc = 0x4AC490; TextDisplay.NopFPS = 0x456304; Vip.Start = 0x624990; Vip.End = 0x625228; Vip.StepPlayers = 0x2C; Vip.MaxPlayers = 100; Vip.DistanceId = 0; Vip.DistanceName = 4; Vip.DistanceStatus = 34; Vip.DistanceIcon = 40; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.IO; using System.Windows.Forms; using Microsoft.WindowsAPICodePack.Shell; using Microsoft.WindowsAPICodePack.Taskbar; using System.Reflection; namespace TaskbarDemo { public partial class ChildDocument : Form { // Keep a reference to the Taskbar instance private TaskbarManager windowsTaskbar = TaskbarManager.Instance; private JumpList childWindowJumpList; private string childWindowAppId; public ChildDocument(int count) { childWindowAppId = "TaskbarDemo.ChildWindow" + count; InitializeComponent(); // Progress Bar foreach (string state in Enum.GetNames(typeof(TaskbarProgressBarState))) comboBoxProgressBarStates.Items.Add(state); // comboBoxProgressBarStates.SelectedItem = "NoProgress"; this.Shown += new EventHandler(ChildDocument_Shown); HighlightOverlaySelection(labelNoIconOverlay); } void ChildDocument_Shown(object sender, EventArgs e) { // Set our default windowsTaskbar.SetProgressState(TaskbarProgressBarState.NoProgress, this.Handle); } #region Progress Bar private void trackBar1_Scroll(object sender, EventArgs e) { // When the user changes the trackBar value, // update the progress bar in our UI as well as Taskbar progressBar1.Value = trackBar1.Value; windowsTaskbar.SetProgressValue(trackBar1.Value, 100, this.Handle); } private void comboBoxProgressBarStates_SelectedIndexChanged(object sender, EventArgs e) { // Update the status of the taskbar progress bar TaskbarProgressBarState state = (TaskbarProgressBarState)(Enum.Parse(typeof(TaskbarProgressBarState), (string)comboBoxProgressBarStates.SelectedItem)); windowsTaskbar.SetProgressState(state, this.Handle); // Update the application progress bar, // as well disable the trackbar in some cases switch (state) { case TaskbarProgressBarState.Normal: if (trackBar1.Value == 0) { trackBar1.Value = 20; progressBar1.Value = trackBar1.Value; } progressBar1.Style = ProgressBarStyle.Continuous; windowsTaskbar.SetProgressValue(trackBar1.Value, 100, this.Handle); trackBar1.Enabled = true; break; case TaskbarProgressBarState.Paused: if (trackBar1.Value == 0) { trackBar1.Value = 20; progressBar1.Value = trackBar1.Value; } progressBar1.Style = ProgressBarStyle.Continuous; windowsTaskbar.SetProgressValue(trackBar1.Value, 100, this.Handle); trackBar1.Enabled = true; break; case TaskbarProgressBarState.Error: if (trackBar1.Value == 0) { trackBar1.Value = 20; progressBar1.Value = trackBar1.Value; } progressBar1.Style = ProgressBarStyle.Continuous; windowsTaskbar.SetProgressValue(trackBar1.Value, 100, this.Handle); trackBar1.Enabled = true; break; case TaskbarProgressBarState.Indeterminate: progressBar1.Style = ProgressBarStyle.Marquee; progressBar1.MarqueeAnimationSpeed = 30; trackBar1.Enabled = false; break; case TaskbarProgressBarState.NoProgress: progressBar1.Value = 0; trackBar1.Value = 0; progressBar1.Style = ProgressBarStyle.Continuous; trackBar1.Enabled = false; break; } } #endregion #region Icon Overlay private void HighlightOverlaySelection(Control ctlOverlay) { TaskbarDemoMainForm.CheckOverlaySelection(ctlOverlay, labelNoIconOverlay); TaskbarDemoMainForm.CheckOverlaySelection(ctlOverlay, pictureIconOverlay1); TaskbarDemoMainForm.CheckOverlaySelection(ctlOverlay, pictureIconOverlay2); TaskbarDemoMainForm.CheckOverlaySelection(ctlOverlay, pictureIconOverlay3); } private void labelNoIconOverlay_Click(object sender, EventArgs e) { windowsTaskbar.SetOverlayIcon(this.Handle, null, null); HighlightOverlaySelection(labelNoIconOverlay); } private void pictureIconOverlay1_Click(object sender, EventArgs e) { windowsTaskbar.SetOverlayIcon(this.Handle, TaskbarDemo.Properties.Resources.Green, "Green"); HighlightOverlaySelection(pictureIconOverlay1); } private void pictureIconOverlay2_Click(object sender, EventArgs e) { windowsTaskbar.SetOverlayIcon(this.Handle, TaskbarDemo.Properties.Resources.Yellow, "Yellow"); HighlightOverlaySelection(pictureIconOverlay2); } private void pictureIconOverlay3_Click(object sender, EventArgs e) { windowsTaskbar.SetOverlayIcon(this.Handle, TaskbarDemo.Properties.Resources.Red, "Red"); HighlightOverlaySelection(pictureIconOverlay3); } #endregion private void buttonRefreshTaskbarList_Click(object sender, EventArgs e) { // Start from an empty list for user tasks childWindowJumpList.ClearAllUserTasks(); // Path to Windows system folder string systemFolder = Environment.GetFolderPath(Environment.SpecialFolder.System); // Path to the Program Files folder string programFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Path to Windows folder (if targeting .NET 4.0, can use Environment.SpecialFolder.Windows instead) string windowsFolder = Environment.GetEnvironmentVariable("windir"); foreach (object item in listBox1.SelectedItems) { switch (item.ToString()) { case "Notepad": childWindowJumpList.AddUserTasks(new JumpListLink(Path.Combine(systemFolder, "notepad.exe"), "Open Notepad") { IconReference = new IconReference(Path.Combine(systemFolder, "notepad.exe"), 0) }); break; case "Calculator": childWindowJumpList.AddUserTasks(new JumpListLink(Path.Combine(systemFolder, "calc.exe"), "Open Calculator") { IconReference = new IconReference(Path.Combine(systemFolder, "calc.exe"), 0) }); break; case "Paint": childWindowJumpList.AddUserTasks(new JumpListLink(Path.Combine(systemFolder, "mspaint.exe"), "Open Paint") { IconReference = new IconReference(Path.Combine(systemFolder, "mspaint.exe"), 0) }); break; case "WordPad": childWindowJumpList.AddUserTasks(new JumpListLink(Path.Combine(programFilesFolder, "Windows NT\\Accessories\\wordpad.exe"), "Open WordPad") { IconReference = new IconReference(Path.Combine(programFilesFolder, "Windows NT\\Accessories\\wordpad.exe"), 0) }); break; case "Windows Explorer": childWindowJumpList.AddUserTasks(new JumpListLink(Path.Combine(windowsFolder, "explorer.exe"), "Open Windows Explorer") { IconReference = new IconReference(Path.Combine(windowsFolder, "explorer.exe"), 0) }); break; case "Internet Explorer": childWindowJumpList.AddUserTasks(new JumpListLink(Path.Combine(programFilesFolder, "Internet Explorer\\iexplore.exe"), "Open Internet Explorer") { IconReference = new IconReference(Path.Combine(programFilesFolder, "Internet Explorer\\iexplore.exe"), 0) }); break; case "Control Panel": childWindowJumpList.AddUserTasks(new JumpListLink(((ShellObject)KnownFolders.ControlPanel).ParsingName, "Open Control Panel") { IconReference = new IconReference(Path.Combine(windowsFolder, "explorer.exe"), 0) }); break; case "Documents Library": if (ShellLibrary.IsPlatformSupported) { childWindowJumpList.AddUserTasks(new JumpListLink(KnownFolders.DocumentsLibrary.Path, "Open Documents Library") { IconReference = new IconReference(Path.Combine(windowsFolder, "explorer.exe"), 0) }); } break; } } childWindowJumpList.Refresh(); } private void button1_Click(object sender, EventArgs e) { childWindowJumpList = JumpList.CreateJumpListForIndividualWindow(childWindowAppId, this.Handle); ((Button)sender).Enabled = false; groupBoxCustomCategories.Enabled = true; buttonRefreshTaskbarList.Enabled = true; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using 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 Groups. /// </summary> internal partial class GroupsOperations : IServiceOperations<ApiManagementClient>, IGroupsOperations { /// <summary> /// Initializes a new instance of the GroupsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal GroupsOperations(ApiManagementClient client) { this._client = client; } private ApiManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.ApiManagement.ApiManagementClient. /// </summary> public ApiManagementClient Client { get { return this._client; } } /// <summary> /// Creates new group. /// </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='gid'> /// Required. Identifier of the group. /// </param> /// <param name='parameters'> /// Required. Create parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateAsync(string resourceGroupName, string serviceName, string gid, GroupCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (gid == null) { throw new ArgumentNullException("gid"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.Name.Length > 300) { throw new ArgumentOutOfRangeException("parameters.Name"); } // 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("gid", gid); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/groups/"; url = url + Uri.EscapeDataString(gid); 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 // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject groupCreateParametersValue = new JObject(); requestDoc = groupCreateParametersValue; groupCreateParametersValue["name"] = parameters.Name; if (parameters.Description != null) { groupCreateParametersValue["description"] = parameters.Description; } if (parameters.Type != null) { groupCreateParametersValue["type"] = parameters.Type.Value.ToString(); } if (parameters.ExternalId != null) { groupCreateParametersValue["externalId"] = parameters.ExternalId; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Deletes specific group 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='gid'> /// Required. Identifier of the group. /// </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 gid, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (gid == null) { throw new ArgumentNullException("gid"); } 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("gid", gid); 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 + "/groups/"; url = url + Uri.EscapeDataString(gid); 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 group. /// </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='gid'> /// Required. Identifier of the group. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Get Group operation response details. /// </returns> public async Task<GroupGetResponse> GetAsync(string resourceGroupName, string serviceName, string gid, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (gid == null) { throw new ArgumentNullException("gid"); } // 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("gid", gid); 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 + "/groups/"; url = url + Uri.EscapeDataString(gid); 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 // 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 GroupGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GroupGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { GroupContract valueInstance = new GroupContract(); result.Value = valueInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); valueInstance.IdPath = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); valueInstance.Name = nameInstance; } JToken descriptionValue = responseDoc["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); valueInstance.Description = descriptionInstance; } JToken builtInValue = responseDoc["builtIn"]; if (builtInValue != null && builtInValue.Type != JTokenType.Null) { bool builtInInstance = ((bool)builtInValue); valueInstance.System = builtInInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true)); valueInstance.Type = typeInstance; } JToken externalIdValue = responseDoc["externalId"]; if (externalIdValue != null && externalIdValue.Type != JTokenType.Null) { string externalIdInstance = ((string)externalIdValue); valueInstance.ExternalId = externalIdInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ETag")) { result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// List all groups. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='query'> /// Optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List Groups operation response details. /// </returns> public async Task<GroupListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("query", query); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/groups"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-10-10"); List<string> odataFilter = new List<string>(); if (query != null && query.Filter != null) { odataFilter.Add(Uri.EscapeDataString(query.Filter)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (query != null && query.Top != null) { queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString())); } if (query != null && query.Skip != null) { queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString())); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GroupListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GroupListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { GroupPaged resultInstance = new GroupPaged(); result.Result = resultInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { GroupContract groupContractInstance = new GroupContract(); resultInstance.Values.Add(groupContractInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); groupContractInstance.IdPath = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); groupContractInstance.Name = nameInstance; } JToken descriptionValue = valueValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); groupContractInstance.Description = descriptionInstance; } JToken builtInValue = valueValue["builtIn"]; if (builtInValue != null && builtInValue.Type != JTokenType.Null) { bool builtInInstance = ((bool)builtInValue); groupContractInstance.System = builtInInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true)); groupContractInstance.Type = typeInstance; } JToken externalIdValue = valueValue["externalId"]; if (externalIdValue != null && externalIdValue.Type != JTokenType.Null) { string externalIdInstance = ((string)externalIdValue); groupContractInstance.ExternalId = externalIdInstance; } } } JToken countValue = responseDoc["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); resultInstance.TotalCount = countInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); resultInstance.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// List next groups page. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List Groups operation response details. /// </returns> public async Task<GroupListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GroupListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GroupListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { GroupPaged resultInstance = new GroupPaged(); result.Result = resultInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { GroupContract groupContractInstance = new GroupContract(); resultInstance.Values.Add(groupContractInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); groupContractInstance.IdPath = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); groupContractInstance.Name = nameInstance; } JToken descriptionValue = valueValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); groupContractInstance.Description = descriptionInstance; } JToken builtInValue = valueValue["builtIn"]; if (builtInValue != null && builtInValue.Type != JTokenType.Null) { bool builtInInstance = ((bool)builtInValue); groupContractInstance.System = builtInInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true)); groupContractInstance.Type = typeInstance; } JToken externalIdValue = valueValue["externalId"]; if (externalIdValue != null && externalIdValue.Type != JTokenType.Null) { string externalIdInstance = ((string)externalIdValue); groupContractInstance.ExternalId = externalIdInstance; } } } JToken countValue = responseDoc["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); resultInstance.TotalCount = countInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); resultInstance.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Patches specific group. /// </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='gid'> /// Required. Identifier of the group. /// </param> /// <param name='parameters'> /// Required. Update parameters. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> UpdateAsync(string resourceGroupName, string serviceName, string gid, GroupUpdateParameters parameters, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (gid == null) { throw new ArgumentNullException("gid"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name != null && parameters.Name.Length > 300) { throw new ArgumentOutOfRangeException("parameters.Name"); } 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("gid", gid); tracingParameters.Add("parameters", parameters); tracingParameters.Add("etag", etag); TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/groups/"; url = url + Uri.EscapeDataString(gid); 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 = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", etag); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject groupUpdateParametersValue = new JObject(); requestDoc = groupUpdateParametersValue; if (parameters.Name != null) { groupUpdateParametersValue["name"] = parameters.Name; } if (parameters.Description != null) { groupUpdateParametersValue["description"] = parameters.Description; } if (parameters.Type != null) { groupUpdateParametersValue["type"] = parameters.Type.Value.ToString(); } if (parameters.ExternalId != null) { groupUpdateParametersValue["externalId"] = parameters.ExternalId; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.IO; using System.Collections; using System.Collections.Generic; using Server; using Server.Network; using Server.Engines.Craft; namespace Server.Items { [Flipable( 0x14EB, 0x14EC )] public class MapItem : Item, ICraftable { private Rectangle2D m_Bounds; private int m_Width, m_Height; private bool m_Protected; private bool m_Editable; private List<Point2D> m_Pins = new List<Point2D>(); private const int MaxUserPins = 50; [CommandProperty( AccessLevel.GameMaster )] public bool Protected { get { return m_Protected; } set { m_Protected = value; } } [CommandProperty( AccessLevel.GameMaster )] public Rectangle2D Bounds { get { return m_Bounds; } set { m_Bounds = value; } } [CommandProperty( AccessLevel.GameMaster )] public int Width { get { return m_Width; } set { m_Width = value; } } [CommandProperty( AccessLevel.GameMaster )] public int Height { get { return m_Height; } set { m_Height = value; } } public List<Point2D> Pins { get { return m_Pins; } } [Constructable] public MapItem() : base( 0x14EC ) { Weight = 1.0; m_Width = 200; m_Height = 200; } public virtual void CraftInit( Mobile from ) { } public void SetDisplay( int x1, int y1, int x2, int y2, int w, int h ) { Width = w; Height = h; if ( x1 < 0 ) x1 = 0; if ( y1 < 0 ) y1 = 0; if ( x2 >= 5120 ) x2 = 5119; if ( y2 >= 4096 ) y2 = 4095; Bounds = new Rectangle2D( x1, y1, x2-x1, y2-y1 ); } public MapItem( Serial serial ) : base( serial ) { } public override void OnDoubleClick( Mobile from ) { if ( from.InRange( GetWorldLocation(), 2 ) ) DisplayTo( from ); else from.SendLocalizedMessage( 500446 ); // That is too far away. } public virtual void DisplayTo( Mobile from ) { from.Send( new NewMapDetails( this ) ); from.Send( new MapDisplay( this ) ); for ( int i = 0; i < m_Pins.Count; ++i ) from.Send( new MapAddPin( this, m_Pins[i] ) ); from.Send( new MapSetEditable( this, ValidateEdit( from ) ) ); } public virtual void OnAddPin( Mobile from, int x, int y ) { if ( !ValidateEdit( from ) ) return; else if ( m_Pins.Count >= MaxUserPins ) return; Validate( ref x, ref y ); AddPin( x, y ); } public virtual void OnRemovePin( Mobile from, int number ) { if ( !ValidateEdit( from ) ) return; RemovePin( number ); } public virtual void OnChangePin( Mobile from, int number, int x, int y ) { if ( !ValidateEdit( from ) ) return; Validate( ref x, ref y ); ChangePin( number, x, y ); } public virtual void OnInsertPin( Mobile from, int number, int x, int y ) { if ( !ValidateEdit( from ) ) return; else if ( m_Pins.Count >= MaxUserPins ) return; Validate( ref x, ref y ); InsertPin( number, x, y ); } public virtual void OnClearPins( Mobile from ) { if ( !ValidateEdit( from ) ) return; ClearPins(); } public virtual void OnToggleEditable( Mobile from ) { if ( Validate( from ) ) m_Editable = !m_Editable; from.Send( new MapSetEditable( this, Validate( from ) && m_Editable ) ); } public virtual void Validate( ref int x, ref int y ) { if ( x < 0 ) x = 0; else if ( x >= m_Width ) x = m_Width - 1; if ( y < 0 ) y = 0; else if ( y >= m_Height ) y = m_Height - 1; } public virtual bool ValidateEdit( Mobile from ) { return m_Editable && Validate( from ); } public virtual bool Validate( Mobile from ) { if ( !from.CanSee( this ) || from.Map != this.Map || !from.Alive || InSecureTrade ) return false; else if ( from.AccessLevel >= AccessLevel.GameMaster ) return true; else if ( !Movable || m_Protected || !from.InRange( GetWorldLocation(), 2 ) ) return false; object root = RootParent; if ( root is Mobile && root != from ) return false; return true; } public void ConvertToWorld( int x, int y, out int worldX, out int worldY ) { worldX = ( ( m_Bounds.Width * x ) / Width ) + m_Bounds.X; worldY = ( ( m_Bounds.Height * y ) / Height ) + m_Bounds.Y; } public void ConvertToMap( int x, int y, out int mapX, out int mapY ) { mapX = ( ( x - m_Bounds.X ) * Width ) / m_Bounds.Width; mapY = ( ( y - m_Bounds.Y ) * Width ) / m_Bounds.Height; } public virtual void AddWorldPin( int x, int y ) { int mapX, mapY; ConvertToMap( x, y, out mapX, out mapY ); AddPin( mapX, mapY ); } public virtual void AddPin( int x, int y ) { m_Pins.Add( new Point2D( x, y ) ); } public virtual void RemovePin( int index ) { if ( index > 0 && index < m_Pins.Count ) m_Pins.RemoveAt( index ); } public virtual void InsertPin( int index, int x, int y ) { if ( index < 0 || index >= m_Pins.Count ) m_Pins.Add( new Point2D( x, y ) ); else m_Pins.Insert( index, new Point2D( x, y ) ); } public virtual void ChangePin( int index, int x, int y ) { if ( index >= 0 && index < m_Pins.Count ) m_Pins[index] = new Point2D( x, y ); } public virtual void ClearPins() { m_Pins.Clear(); } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); writer.Write( m_Bounds ); writer.Write( m_Width ); writer.Write( m_Height ); writer.Write( m_Protected ); writer.Write( m_Pins.Count ); for ( int i = 0; i < m_Pins.Count; ++i ) writer.Write( m_Pins[i] ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 0: { m_Bounds = reader.ReadRect2D(); m_Width = reader.ReadInt(); m_Height = reader.ReadInt(); m_Protected = reader.ReadBool(); int count = reader.ReadInt(); for ( int i = 0; i < count; i++ ) m_Pins.Add( reader.ReadPoint2D() ); break; } } } public static void Initialize() { PacketHandlers.Register( 0x56, 11, true, new OnPacketReceive( OnMapCommand ) ); } private static void OnMapCommand( NetState state, PacketReader pvSrc ) { Mobile from = state.Mobile; MapItem map = World.FindItem( pvSrc.ReadInt32() ) as MapItem; if ( map == null ) return; int command = pvSrc.ReadByte(); int number = pvSrc.ReadByte(); int x = pvSrc.ReadInt16(); int y = pvSrc.ReadInt16(); switch ( command ) { case 1: map.OnAddPin( from, x, y ); break; case 2: map.OnInsertPin( from, number, x, y ); break; case 3: map.OnChangePin( from, number, x, y ); break; case 4: map.OnRemovePin( from, number ); break; case 5: map.OnClearPins( from ); break; case 6: map.OnToggleEditable( from ); break; } } private sealed class MapDetails : Packet { public MapDetails( MapItem map ) : base ( 0x90, 19 ) { m_Stream.Write( (int) map.Serial ); m_Stream.Write( (short) 0x139D ); m_Stream.Write( (short) map.Bounds.Start.X ); m_Stream.Write( (short) map.Bounds.Start.Y ); m_Stream.Write( (short) map.Bounds.End.X ); m_Stream.Write( (short) map.Bounds.End.Y ); m_Stream.Write( (short) map.Width ); m_Stream.Write( (short) map.Height ); } } private sealed class NewMapDetails : Packet { public NewMapDetails(MapItem map) : base(0xF5, 21) { Map newmap = map.Map; if (newmap != Map.Trammel) newmap = Map.Trammel; m_Stream.Write((int)map.Serial); m_Stream.Write((short)0x139D); m_Stream.Write((short)map.Bounds.Start.X); m_Stream.Write((short)map.Bounds.Start.Y); m_Stream.Write((short)map.Bounds.End.X); m_Stream.Write((short)map.Bounds.End.Y); m_Stream.Write((short)map.Width); m_Stream.Write((short)map.Height); m_Stream.Write((short) /*( map.Facet == null ? 0 :*/ newmap.MapID); } } private abstract class MapCommand : Packet { public MapCommand( MapItem map, int command, int number, int x, int y ) : base ( 0x56, 11 ) { m_Stream.Write( (int) map.Serial ); m_Stream.Write( (byte) command ); m_Stream.Write( (byte) number ); m_Stream.Write( (short) x ); m_Stream.Write( (short) y ); } } private sealed class MapDisplay : MapCommand { public MapDisplay( MapItem map ) : base( map, 5, 0, 0, 0 ) { } } private sealed class MapAddPin : MapCommand { public MapAddPin( MapItem map, Point2D point ) : base( map, 1, 0, point.X, point.Y ) { } } private sealed class MapSetEditable : MapCommand { public MapSetEditable( MapItem map, bool editable ) : base( map, 7, editable ? 1 : 0, 0, 0 ) { } } #region ICraftable Members public int OnCraft( int quality, bool makersMark, Mobile from, CraftSystem craftSystem, Type typeRes, BaseTool tool, CraftItem craftItem, int resHue ) { CraftInit( from ); return 1; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Versioning; #if BIT64 using nint = System.Int64; using nuint = System.UInt64; #else using nint = System.Int32; using nuint = System.UInt32; #endif namespace System.Runtime.CompilerServices { // // Subsetted clone of System.Runtime.CompilerServices.Unsafe for internal runtime use. // Keep in sync with https://github.com/dotnet/corefx/tree/master/src/System.Runtime.CompilerServices.Unsafe. // /// <summary> /// Contains generic, low-level functionality for manipulating pointers. /// </summary> [CLSCompliant(false)] public static class Unsafe { /// <summary> /// Reads a value of type <typeparamref name="T"/> from the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe T Read<T>(void* source) { return Unsafe.As<byte, T>(ref *(byte*)source); } /// <summary> /// Reads a value of type <typeparamref name="T"/> from the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe T Read<T>(ref byte source) { return Unsafe.As<byte, T>(ref source); } /// <summary> /// Reads a value of type <typeparamref name="T"/> from the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe T ReadUnaligned<T>(void* source) { return Unsafe.As<byte, T>(ref *(byte*)source); } /// <summary> /// Reads a value of type <typeparamref name="T"/> from the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe T ReadUnaligned<T>(ref byte source) { return Unsafe.As<byte, T>(ref source); } /// <summary> /// Writes a value of type <typeparamref name="T"/> to the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void Write<T>(void* source, T value) { Unsafe.As<byte, T>(ref *(byte*)source) = value; } /// <summary> /// Writes a value of type <typeparamref name="T"/> to the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void Write<T>(ref byte source, T value) { Unsafe.As<byte, T>(ref source) = value; } /// <summary> /// Writes a value of type <typeparamref name="T"/> to the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void WriteUnaligned<T>(void* source, T value) { Unsafe.As<byte, T>(ref *(byte*)source) = value; } /// <summary> /// Writes a value of type <typeparamref name="T"/> to the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void WriteUnaligned<T>(ref byte source, T value) { Unsafe.As<byte, T>(ref source) = value; } /// <summary> /// Returns a pointer to the given by-ref parameter. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void* AsPointer<T>(ref T source) { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // ldarg.0 // conv.u // ret } /// <summary> /// Returns the size of an object of the given type parameter. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SizeOf<T>() { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // sizeof !!0 // ret } /// <summary> /// Casts the given object to the specified type, performs no dynamic type checking. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T As<T>(Object value) where T : class { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // ldarg.0 // ret } /// <summary> /// Reinterprets the given reference as a reference to a value of type <typeparamref name="TTo"/>. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref TTo As<TFrom, TTo>(ref TFrom source) { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // ldarg.0 // ret } [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static unsafe ref T AddByteOffset<T>(ref T source, nuint byteOffset) { return ref AddByteOffset(ref source, (IntPtr)(void*)byteOffset); } [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset) { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // ldarg.0 // ldarg.1 // add // ret } /// <summary> /// Adds an element offset to the given reference. /// </summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Add<T>(ref T source, int elementOffset) { return ref AddByteOffset(ref source, (IntPtr)(elementOffset * (nint)SizeOf<T>())); } /// <summary> /// Determines whether the specified references point to the same location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool AreSame<T>(ref T left, ref T right) { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // ldarg.0 // ldarg.1 // ceq // ret } /// <summary> /// Initializes a block of memory at the given location with a given initial value /// without assuming architecture dependent alignment of the address. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { for (uint i = 0; i < byteCount; i++) AddByteOffset(ref startAddress, i) = value; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands.Internal.Format { internal sealed class ListViewGenerator : ViewGenerator { // tableBody to use for this instance of the ViewGenerator; private ListControlBody _listBody; internal override void Initialize(TerminatingErrorContext terminatingErrorContext, PSPropertyExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters) { base.Initialize(terminatingErrorContext, mshExpressionFactory, db, view, formatParameters); if ((this.dataBaseInfo != null) && (this.dataBaseInfo.view != null)) { _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl; } } internal override void Initialize(TerminatingErrorContext errorContext, PSPropertyExpressionFactory expressionFactory, PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { base.Initialize(errorContext, expressionFactory, so, db, parameters); if ((this.dataBaseInfo != null) && (this.dataBaseInfo.view != null)) { _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl; } this.inputParameters = parameters; SetUpActiveProperties(so); } /// <summary> /// Let the view prepare itself for RemoteObjects. This will add "ComputerName" to the /// table columns. /// </summary> /// <param name="so"></param> internal override void PrepareForRemoteObjects(PSObject so) { Diagnostics.Assert(so != null, "so cannot be null"); // make sure computername property exists. Diagnostics.Assert(so.Properties[RemotingConstants.ComputerNameNoteProperty] != null, "PrepareForRemoteObjects cannot be called when the object does not contain ComputerName property."); if ((dataBaseInfo != null) && (dataBaseInfo.view != null) && (dataBaseInfo.view.mainControl != null)) { _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl.Copy(); // build up the definition for computer name. ListControlItemDefinition cnListItemDefinition = new ListControlItemDefinition(); cnListItemDefinition.label = new TextToken(); cnListItemDefinition.label.text = RemotingConstants.ComputerNameNoteProperty; FieldPropertyToken fpt = new FieldPropertyToken(); fpt.expression = new ExpressionToken(RemotingConstants.ComputerNameNoteProperty, false); cnListItemDefinition.formatTokenList.Add(fpt); _listBody.defaultEntryDefinition.itemDefinitionList.Add(cnListItemDefinition); } } internal override FormatStartData GenerateStartData(PSObject so) { FormatStartData startFormat = base.GenerateStartData(so); startFormat.shapeInfo = new ListViewHeaderInfo(); return startFormat; } internal override FormatEntryData GeneratePayload(PSObject so, int enumerationLimit) { FormatEntryData fed = new FormatEntryData(); if (this.dataBaseInfo.view != null) fed.formatEntryInfo = GenerateListViewEntryFromDataBaseInfo(so, enumerationLimit); else fed.formatEntryInfo = GenerateListViewEntryFromProperties(so, enumerationLimit); return fed; } private ListViewEntry GenerateListViewEntryFromDataBaseInfo(PSObject so, int enumerationLimit) { ListViewEntry lve = new ListViewEntry(); ListControlEntryDefinition activeListControlEntryDefinition = GetActiveListControlEntryDefinition(_listBody, so); foreach (ListControlItemDefinition listItem in activeListControlEntryDefinition.itemDefinitionList) { if (!EvaluateDisplayCondition(so, listItem.conditionToken)) continue; ListViewField lvf = new ListViewField(); PSPropertyExpressionResult result; lvf.formatPropertyField = GenerateFormatPropertyField(listItem.formatTokenList, so, enumerationLimit, out result); // we need now to provide a label if (listItem.label != null) { // if the directive provides one, we use it lvf.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(listItem.label); } else if (result != null) { // if we got a valid match from the Mshexpression, use it as a label lvf.label = result.ResolvedExpression.ToString(); } else { // we did fail getting a result (i.e. property does not exist on the object) // we try to fall back and see if we have an un-resolved PSPropertyExpression FormatToken token = listItem.formatTokenList[0]; FieldPropertyToken fpt = token as FieldPropertyToken; if (fpt != null) { PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo); // use the un-resolved PSPropertyExpression string as a label lvf.label = ex.ToString(); } else { TextToken tt = token as TextToken; if (tt != null) // we had a text token, use it as a label (last resort...) lvf.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } } lve.listViewFieldList.Add(lvf); } return lve; } private ListControlEntryDefinition GetActiveListControlEntryDefinition(ListControlBody listBody, PSObject so) { // see if we have an override that matches var typeNames = so.InternalTypeNames; TypeMatch match = new TypeMatch(expressionFactory, this.dataBaseInfo.db, typeNames); foreach (ListControlEntryDefinition x in listBody.optionalEntryList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo, so))) { return x; } } if (match.BestMatch != null) { return match.BestMatch as ListControlEntryDefinition; } else { Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typesWithoutPrefix != null) { match = new TypeMatch(expressionFactory, this.dataBaseInfo.db, typesWithoutPrefix); foreach (ListControlEntryDefinition x in listBody.optionalEntryList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { return x; } } if (match.BestMatch != null) { return match.BestMatch as ListControlEntryDefinition; } } // we do not have any override, use default return listBody.defaultEntryDefinition; } } private ListViewEntry GenerateListViewEntryFromProperties(PSObject so, int enumerationLimit) { // compute active properties every time if (this.activeAssociationList == null) { SetUpActiveProperties(so); } ListViewEntry lve = new ListViewEntry(); for (int k = 0; k < this.activeAssociationList.Count; k++) { MshResolvedExpressionParameterAssociation a = this.activeAssociationList[k]; ListViewField lvf = new ListViewField(); if (a.OriginatingParameter != null) { object key = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey); if (key != AutomationNull.Value) { lvf.propertyName = (string)key; } else { lvf.propertyName = a.ResolvedExpression.ToString(); } } else { lvf.propertyName = a.ResolvedExpression.ToString(); } FieldFormattingDirective directive = null; if (a.OriginatingParameter != null) { directive = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.FormatStringEntryKey) as FieldFormattingDirective; } lvf.formatPropertyField.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, a.ResolvedExpression, directive); lve.listViewFieldList.Add(lvf); } this.activeAssociationList = null; return lve; } private void SetUpActiveProperties(PSObject so) { List<MshParameter> mshParameterList = null; if (this.inputParameters != null) mshParameterList = this.inputParameters.mshParameterList; this.activeAssociationList = AssociationManager.SetupActiveProperties(mshParameterList, so, this.expressionFactory); } } }
//Author: Reza Nourbakhsh - rezanoorbakhsh@ymail.com using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Collections; namespace Marketing_Solution { class Program { static void Main(string[] args) { //Data from promotion sites Address address = new Address(); address.Street = "22 Balmaringa"; address.Suburb = "Gordon!"; address.Postcode = "2072"; address.Latitude = +40.689060m; address.Longitude = -74.044636m; OnlinePromotion onlinepromotion = new OnlinePromotion(); onlinepromotion.Name = "Nike*-40% Off Storewide!"; onlinepromotion.Address = address; onlinepromotion.PromotionCode = "124REZ"; onlinepromotion.ProviderKey = "1"; //Getting data from database Address situation = new Address(); situation.Street = "22 Balmaringa!"; situation.Suburb = "Gordon!"; situation.Postcode = "2072"; situation.Latitude = +40.689060m; situation.Longitude = -74.044636m; Promotion promotion = new Promotion(); promotion.Address = situation; promotion.Name = "Nike 40% Off Storewide"; promotion.PromotionCode = "124ZER"; //Test case 1 IPromotionMatcher objOzSite; objOzSite = PromotionCollection.getPromotionObj("Oz Winner"); Console.Write(objOzSite.IsMatch(onlinepromotion, promotion)); //Test case 2 IPromotionMatcher objSpSite; objSpSite = PromotionCollection.getPromotionObj("Surface Promotion"); Console.Write(objSpSite.IsMatch(onlinepromotion, promotion)); //Test case 3 IPromotionMatcher objHopSite; objHopSite = PromotionCollection.getPromotionObj("Hopeless Online Promotion"); Console.Write(objHopSite.IsMatch(onlinepromotion, promotion)); //To view Console.ReadLine(); } } public class Address { //To match the example I added street property public string Street { get; set; } public string Suburb { get; set; } public string Postcode { get; set; } public decimal Latitude { get; set; } public decimal Longitude { get; set; } } public class Promotion { public Address Address { get; set; } public string PromotionCode { get; set; } public string Name { get; set; } } public class OnlinePromotion { public Address Address { get; set; } public string PromotionCode { get; set; } public string ProviderKey { get; set; } public string Name { get; set; } } public interface IPromotionMatcher { bool IsMatch(OnlinePromotion onlinePromotion, Promotion promotion); } //Here I implemented the interface based on the factory design pattern //The purpose is providing a flexible code for adding more promotion site in the future //FACTORY class public class PromotionCollection { //Called by the client / tester static public IPromotionMatcher getPromotionObj(string site) { IPromotionMatcher objPromotion = null; //------------------------------------------------------------------------------------------------------------- //NOT: A Collection(array, link list, hashtable) can be added to store the list of the online promotion sites //-------------------------------------------------------------------------------------------------------------- switch (site) { case "Oz Winner": objPromotion = new OzWinner(); break; case "Surface Promotion": objPromotion = new SurfacePromotion(); break; case "Hopeless Online Promotion": objPromotion = new HopelessOnlinePromotion(); break; default: return objPromotion; } return objPromotion; } } //Oz Winner checker/handler //Oz Winner class public class OzWinner : IPromotionMatcher { //The specific distance - business rule const int DISTANCE = 500; #region IpromotionMatcher Members //Here IsMatch calls the distance method to calculate the distance and compare than with DISTANCE=500m public bool IsMatch(OnlinePromotion onlinePromotion, Promotion promotion) { bool IsMatchFlag = false; try { //Check the promotion code and the distance if (promotion.PromotionCode == onlinePromotion.PromotionCode && DISTANCE > distance(Convert.ToDouble(onlinePromotion.Address.Latitude), Convert.ToDouble(onlinePromotion.Address.Longitude), Convert.ToDouble(promotion.Address.Latitude), Convert.ToDouble(promotion.Address.Longitude))) { IsMatchFlag = true; } } catch (Exception ex) { Console.Write("An error occurred:" + ex.Message); } return IsMatchFlag; } #endregion //This method calculates the distance between two point based on the Lat and Long private double distance(double lat1, double lon1, double lat2, double lon2) { double theta = lon1 - lon2; double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta)); dist = Math.Acos(dist); dist = rad2deg(dist); dist = dist * 60 * 1.1515; dist = dist * 1.609344; return (dist); } //This method converts decimal degrees to radians private double deg2rad(double deg) { return (deg * Math.PI / 180.0); } //This method converts radians to decimal degrees private double rad2deg(double rad) { return (rad / Math.PI * 180.0); } } //Surface Promotion checker/handler //Surface Promotion class public class SurfacePromotion : IPromotionMatcher { //The regular expression that should match base on the business rules //All punctuation except % and $ const string REGEXP = @"[\p{P}-[%$]]"; #region IpromotionMatcher Members //Here IsMatch remove all the punctuation in both promotion, onlinepromotion name and address and compare them //Note that the punctuation except % and $ is replaced by null to make it easy for comparing and this must be done in both promotion and online promotion to enhance the accuracy public bool IsMatch(OnlinePromotion onlinePromotion, Promotion promotion) { bool IsMatchFlag = false; try { //Apply the filtering Regex regex = new Regex(REGEXP, RegexOptions.IgnoreCase); //Remove all punctuation except $ and % from onlinepromotion name and adderss string onlinePromotionNamePunctuationless = regex.Replace(onlinePromotion.Name, string.Empty); string promotionNamePunctuationless = regex.Replace(promotion.Name, string.Empty); //Remove all punctuation except $ and % from promotion name and adderss string onlinePromotionAddressPunctuationless = regex.Replace(onlinePromotion.Address.Street+","+onlinePromotion.Address.Suburb+","+onlinePromotion.Address.Postcode, " "); string promotionAddressPunctuationless = regex.Replace(promotion.Address.Street+","+ promotion.Address.Suburb+","+promotion.Address.Postcode, " "); //Campare the name and address of onlinepromotion and promotion if (String.Compare(onlinePromotionNamePunctuationless, promotionNamePunctuationless, true) == 1 && String.Compare(onlinePromotionAddressPunctuationless, promotionAddressPunctuationless, true) == 1) { IsMatchFlag = true; } } catch(Exception ex) { Console.Write("An error occurred:" + ex.Message); } return IsMatchFlag; } #endregion } //Hopeless online promotion checker/handler //Hopeless online promotion class public class HopelessOnlinePromotion : IPromotionMatcher { //Based on the business rules const int BACKWARDLENGTH = 3; #region IpromotionMatcher Members //Here the IsMatch calls promotionCodeCorrection which reverses the last three charachter of the onlinepromotion code public bool IsMatch(OnlinePromotion onlinePromotion, Promotion promotion) { bool IsMatchFlag = false; try { //IsMatchFlag = promotion.PromotionCode == promotionCodeCorrection(onlinePromotion.PromotionCode) ? true : false ; if (promotion.PromotionCode == promotionCodeCorrection(onlinePromotion.PromotionCode)) { IsMatchFlag = true; } } catch (Exception ex) { Console.Write("An error occurred:" + ex.Message); } return IsMatchFlag; } #endregion //This method reversed the last three charachter of the promotion code private string promotionCodeCorrection(string promotionCode) { string correctedPromotionCode = ""; try { char[] arr = promotionCode.ToCharArray(); char temp; temp = arr[promotionCode.Length - 1]; arr[promotionCode.Length - 1] = arr[promotionCode.Length - BACKWARDLENGTH]; arr[promotionCode.Length - BACKWARDLENGTH] = temp; correctedPromotionCode = new string(arr); } catch (Exception ex) { Console.Write("An error occurred:" + ex.Message); } return correctedPromotionCode; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text.RegularExpressions; namespace Arduino_Temperature_Retrofit { public enum eSQLStatus { Running, Idle, Stopped, NoSQLConnectionCreated, Error } class SQLStatusEventArgs : EventArgs { private eSQLStatus oldStatus; public eSQLStatus GetOldStatus() { return oldStatus; } public void SetOldStatus(eSQLStatus value) { oldStatus = value; } private eSQLStatus newStatus; public eSQLStatus GetNewStatus() { return newStatus; } public void SetNewStatus(eSQLStatus value) { newStatus = value; } public SQLStatusEventArgs(eSQLStatus oldState, eSQLStatus newState) { this.SetOldStatus(oldState); this.SetNewStatus(newState); } } class SQL { //will be returned in case of any (generic) error public const int SQL_EXIT_FAILURE = -1; #region Declaration for accessing the database public string User { get; set; } public string Password { get; set; } public string Server { get; set; } public string Scheme { get; set; } public eSQLStatus Status { get; private set; } private SqlConnection _connection = null; private int _connectionTimeout = 30; // default #endregion public event EventHandler StatusChanged; private void StatusChange(eSQLStatus eStatus) { StatusChanged?.Invoke(this, new SQLStatusEventArgs(Status, eStatus)); this.Status = eStatus; } public SQL() { Status = eSQLStatus.NoSQLConnectionCreated; StatusChange(eSQLStatus.NoSQLConnectionCreated); } #region Create Database Connection public SqlConnection CreateSQLConnection(string p_user, string p_password, string p_server, string p_scheme, int p_connectionTimeout) { User = p_user; Password = p_password; Server = p_server; Scheme = p_scheme; _connectionTimeout = p_connectionTimeout; return CreateSQLConnection(); } public SqlConnection CreateSQLConnection(int p_connectionTimeout) { _connectionTimeout = p_connectionTimeout; return CreateSQLConnection(); } public SqlConnection CreateSQLConnection(string p_user, string p_password, string p_server, string p_scheme) { User = p_user; Password = p_password; Server = p_server; Scheme = p_scheme; return CreateSQLConnection(); } public SqlConnection CreateSQLConnection() { try { string ConnectionString = "Data Source=" + Server + "; " + "Initial Catalog=" + Scheme + ";" + "User id=" + User + ";" + "Password=" + Password + ";" + "Connection Timeout=" + _connectionTimeout.ToString() + ";"; bool isValid = Regex.IsMatch(ConnectionString, @"^([^=;]+=[^=;]*)(;[^=;]+=[^=;]*)*;?$"); if (!isValid) { return null; } _connection = new SqlConnection(ConnectionString); StatusChange(eSQLStatus.Idle); return _connection; } catch (Exception) { StatusChange(eSQLStatus.Error); return null; } } public SqlConnection GetSqlConnection { get { return _connection; } } #endregion #region Database operations: Insert Row public int InsertRow(DataObject dObj) { StatusChange(eSQLStatus.Running); if (null == _connection) { if (null == CreateSQLConnection()) { Status = eSQLStatus.Error; return SQL_EXIT_FAILURE; } } if (_connection.State != ConnectionState.Open) { _connection.Open(); } if (_connection.State == ConnectionState.Open) { SqlCommand command = new SqlCommand { Connection = _connection, CommandType = CommandType.Text, CommandText = "insert into Datalog (SensorID, SensorName, Temperature, HeatIndex, Humidity, Pressure, LUX, LogTime) VALUES (@id, @name, @temp, @head, @hum, @press, @lux, getdate())" }; //@id, @name, @temp, @head, @hum, @press, @lux, getdate())"; command.Parameters.AddWithValue("@id", dObj.UniqueID); command.Parameters.AddWithValue("@name", dObj.Name); if (DataObjectCategory.HasTemperature(dObj.Protocol)) command.Parameters.AddWithValue("@temp", dObj.GetItem(DataObjectCategory.Temperatur)); else command.Parameters.AddWithValue("@temp", ""); if (DataObjectCategory.HasHeatIndex(dObj.Protocol)) command.Parameters.AddWithValue("@head", dObj.GetItem(DataObjectCategory.HeatIndex)); else command.Parameters.AddWithValue("@head", ""); if (DataObjectCategory.HasHumidity(dObj.Protocol)) command.Parameters.AddWithValue("@hum", dObj.GetItem(DataObjectCategory.Luftfeuchtigkeit)); else command.Parameters.AddWithValue("@hum", ""); if (DataObjectCategory.HasAirPressure(dObj.Protocol)) command.Parameters.AddWithValue("@press", dObj.GetItem(DataObjectCategory.Luftdruck)); else command.Parameters.AddWithValue("@press", ""); if (DataObjectCategory.HasLUX(dObj.Protocol)) command.Parameters.AddWithValue("@lux", dObj.GetItem(DataObjectCategory.Lichtwert)); else command.Parameters.AddWithValue("@lux", ""); int rowsAffacted = command.ExecuteNonQuery(); StatusChange(eSQLStatus.Idle); return rowsAffacted; } else { StatusChange(eSQLStatus.Error); return SQL_EXIT_FAILURE; } } public void InsertDBAll(Dictionary<string, DataObject> dataObjs) { foreach (KeyValuePair<string, DataObject> kvp in dataObjs) { DataObject dObj = (DataObject)kvp.Value; if (null == dObj || !dObj.DataAvailable || !dObj.Active || !dObj.WriteToDatabase) { continue; } if (dObj.DataInterfaceType == XMLProtocol.HTTP && dObj.HTTPException != null) { continue; } InsertRow(dObj); if (Status == eSQLStatus.Error) { return; } } } #endregion } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections; using System.Collections.Generic; using NLog.Common; /// <summary> /// Provides helpers to sort log events and associated continuations. /// </summary> internal static class SortHelpers { /// <summary> /// Key selector delegate. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="value">Value to extract key information from.</param> /// <returns>Key selected from log event.</returns> internal delegate TKey KeySelector<TValue, TKey>(TValue value); /// <summary> /// Performs bucket sort (group by) on an array of items and returns a dictionary for easy traversal of the result set. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="inputs">The inputs.</param> /// <param name="keySelector">The key selector function.</param> /// <returns> /// Dictionary where keys are unique input keys, and values are lists of <see cref="AsyncLogEventInfo"/>. /// </returns> public static Dictionary<TKey, List<TValue>> BucketSort<TValue, TKey>(this IEnumerable<TValue> inputs, KeySelector<TValue, TKey> keySelector) { var buckets = new Dictionary<TKey, List<TValue>>(); foreach (var input in inputs) { var keyValue = keySelector(input); List<TValue> eventsInBucket; if (!buckets.TryGetValue(keyValue, out eventsInBucket)) { eventsInBucket = new List<TValue>(); buckets.Add(keyValue, eventsInBucket); } eventsInBucket.Add(input); } return buckets; } /// <summary> /// Performs bucket sort (group by) on an array of items and returns a dictionary for easy traversal of the result set. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="inputs">The inputs.</param> /// <param name="keySelector">The key selector function.</param> /// <returns> /// Dictionary where keys are unique input keys, and values are lists of <see cref="AsyncLogEventInfo"/>. /// </returns> public static ReadOnlySingleBucketDictionary<TKey, IList<TValue>> BucketSort<TValue, TKey>(this IList<TValue> inputs, KeySelector<TValue, TKey> keySelector) { Dictionary<TKey, IList<TValue>> buckets = null; bool singleBucketFirstKey = false; TKey singleBucketKey = default(TKey); EqualityComparer<TKey> c = EqualityComparer<TKey>.Default; for (int i = 0; i < inputs.Count; i++) { TKey keyValue = keySelector(inputs[i]); if (!singleBucketFirstKey) { singleBucketFirstKey = true; singleBucketKey = keyValue; } else if (buckets == null) { if (!c.Equals(singleBucketKey, keyValue)) { // Multiple buckets needed, allocate full dictionary buckets = new Dictionary<TKey, IList<TValue>>(); var bucket = new List<TValue>(i); for (int j = 0; j < i; j++) { bucket.Add(inputs[j]); } buckets[singleBucketKey] = bucket; bucket = new List<TValue>(); bucket.Add(inputs[i]); buckets[keyValue] = bucket; } } else { IList<TValue> eventsInBucket; if (!buckets.TryGetValue(keyValue, out eventsInBucket)) { eventsInBucket = new List<TValue>(); buckets.Add(keyValue, eventsInBucket); } eventsInBucket.Add(inputs[i]); } } if (buckets != null) { return new ReadOnlySingleBucketDictionary<TKey, IList<TValue>>(buckets); } else { return new ReadOnlySingleBucketDictionary<TKey, IList<TValue>>(new KeyValuePair<TKey, IList<TValue>>(singleBucketKey, inputs)); } } /// <summary> /// Single-Bucket optimized readonly dictionary. Uses normal internally Dictionary if multiple buckets are needed. /// /// Avoids allocating a new dictionary, when all items are using the same bucket /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> public struct ReadOnlySingleBucketDictionary<TKey, TValue> : IDictionary<TKey, TValue> { readonly KeyValuePair<TKey, TValue>? _singleBucket; readonly Dictionary<TKey, TValue> _multiBucket; readonly IEqualityComparer<TKey> _comparer; public IEqualityComparer<TKey> Comparer { get { return _comparer; } } public ReadOnlySingleBucketDictionary(KeyValuePair<TKey, TValue> singleBucket) : this(singleBucket, EqualityComparer<TKey>.Default) { } public ReadOnlySingleBucketDictionary(Dictionary<TKey, TValue> multiBucket) : this(multiBucket, EqualityComparer<TKey>.Default) { } public ReadOnlySingleBucketDictionary(KeyValuePair<TKey, TValue> singleBucket, IEqualityComparer<TKey> comparer) { _comparer = comparer; _multiBucket = null; _singleBucket = singleBucket; } public ReadOnlySingleBucketDictionary(Dictionary<TKey, TValue> multiBucket, IEqualityComparer<TKey> comparer) { _comparer = comparer; _multiBucket = multiBucket; _singleBucket = default(KeyValuePair<TKey, TValue>); } /// <inheritDoc/> public int Count { get { if (_multiBucket != null) return _multiBucket.Count; else if (_singleBucket.HasValue) return 1; else return 0; } } /// <inheritDoc/> public ICollection<TKey> Keys { get { if (_multiBucket != null) return _multiBucket.Keys; else if (_singleBucket.HasValue) return new[] { _singleBucket.Value.Key }; else return ArrayHelper.Empty<TKey>(); } } /// <inheritDoc/> public ICollection<TValue> Values { get { if (_multiBucket != null) return _multiBucket.Values; else if (_singleBucket.HasValue) return new TValue[] { _singleBucket.Value.Value }; else return ArrayHelper.Empty<TValue>(); } } /// <inheritDoc/> public bool IsReadOnly { get { return true; } } /// <summary> /// Allows direct lookup of existing keys. If trying to access non-existing key exeption is thrown. /// Consider to use <see cref="TryGetValue(TKey, out TValue)"/> instead for better safety. /// </summary> /// <param name="key">Key value for lookup</param> /// <returns>Mapped value found</returns> public TValue this[TKey key] { get { if (_multiBucket != null) return _multiBucket[key]; else if (_singleBucket.HasValue && _comparer.Equals(_singleBucket.Value.Key, key)) return _singleBucket.Value.Value; else throw new System.Collections.Generic.KeyNotFoundException(); } set { throw new NotSupportedException("Readonly"); } } /// <summary> /// Non-Allocating struct-enumerator /// </summary> public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>> { bool _singleBucketFirstRead; readonly KeyValuePair<TKey, TValue> _singleBucket; readonly IEnumerator<KeyValuePair<TKey, TValue>> _multiBuckets; internal Enumerator(Dictionary<TKey, TValue> multiBucket) { _singleBucketFirstRead = false; _singleBucket = default(KeyValuePair<TKey, TValue>); _multiBuckets = multiBucket.GetEnumerator(); } internal Enumerator(KeyValuePair<TKey, TValue> singleBucket) { _singleBucketFirstRead = false; _singleBucket = singleBucket; _multiBuckets = null; } public KeyValuePair<TKey, TValue> Current { get { if (_multiBuckets != null) return new KeyValuePair<TKey, TValue>(_multiBuckets.Current.Key, _multiBuckets.Current.Value); else return new KeyValuePair<TKey, TValue>(_singleBucket.Key, _singleBucket.Value); } } object IEnumerator.Current { get { return Current; } } public void Dispose() { if (_multiBuckets != null) _multiBuckets.Dispose(); } public bool MoveNext() { if (_multiBuckets != null) return _multiBuckets.MoveNext(); else if (_singleBucketFirstRead) return false; else return _singleBucketFirstRead = true; } public void Reset() { if (_multiBuckets != null) _multiBuckets.Reset(); else _singleBucketFirstRead = false; } } public Enumerator GetEnumerator() { if (_multiBucket != null) return new Enumerator(_multiBucket); else if (_singleBucket.HasValue) return new Enumerator(_singleBucket.Value); else return new Enumerator(new Dictionary<TKey, TValue>()); } /// <inheritDoc/> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return GetEnumerator(); } /// <inheritDoc/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <inheritDoc/> public bool ContainsKey(TKey key) { if (_multiBucket != null) return _multiBucket.ContainsKey(key); else if (_singleBucket.HasValue) return _comparer.Equals(_singleBucket.Value.Key, key); else return false; } /// <summary>Will always throw, as dictionary is readonly</summary> public void Add(TKey key, TValue value) { throw new NotSupportedException(); // Readonly } /// <summary>Will always throw, as dictionary is readonly</summary> public bool Remove(TKey key) { throw new NotSupportedException(); // Readonly } /// <inheritDoc/> public bool TryGetValue(TKey key, out TValue value) { if (_multiBucket != null) { return _multiBucket.TryGetValue(key, out value); } else if (_singleBucket.HasValue && _comparer.Equals(_singleBucket.Value.Key, key)) { value = _singleBucket.Value.Value; return true; } else { value = default(TValue); return false; } } /// <summary>Will always throw, as dictionary is readonly</summary> public void Add(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); // Readonly } /// <summary>Will always throw, as dictionary is readonly</summary> public void Clear() { throw new NotSupportedException(); // Readonly } /// <inheritDoc/> public bool Contains(KeyValuePair<TKey, TValue> item) { if (_multiBucket != null) return ((IDictionary<TKey, TValue>)_multiBucket).Contains(item); else if (_singleBucket.HasValue) return _comparer.Equals(_singleBucket.Value.Key, item.Key) && EqualityComparer<TValue>.Default.Equals(_singleBucket.Value.Value, item.Value); else return false; } /// <inheritDoc/> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { if (_multiBucket != null) ((IDictionary<TKey, TValue>)_multiBucket).CopyTo(array, arrayIndex); else if (_singleBucket.HasValue) array[arrayIndex] = _singleBucket.Value; } /// <summary>Will always throw, as dictionary is readonly</summary> public bool Remove(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); // Readonly } } } }
using System; using System.Diagnostics; using i64 = System.Int64; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the sqlite3_get_table() and //sqlite3_free_table() ** interface routines. These are just wrappers around the main ** interface routine of sqlite3_exec(). ** ** These routines are in a separate files so that they will not be linked ** if they are not used. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" //#include <stdlib.h> //#include <string.h> #if !SQLITE_OMIT_GET_TABLE /* ** This structure is used to pass data from sqlite3_get_table() through ** to the callback function is uses to build the result. */ class TabResult { public string[] azResult; public string zErrMsg; public int nResult; public int nAlloc; public int nRow; public int nColumn; public int nData; public int rc; }; /* ** This routine is called once for each row in the result table. Its job ** is to fill in the TabResult structure appropriately, allocating new ** memory as necessary. */ static public int sqlite3_get_table_cb( object pArg, i64 nCol, object Oargv, object Ocolv ) { string[] argv = (string[])Oargv; string[]colv = (string[])Ocolv; TabResult p = (TabResult)pArg; int need; int i; string z; /* Make sure there is enough space in p.azResult to hold everything ** we need to remember from this invocation of the callback. */ if( p.nRow==0 && argv!=null ){ need = (int)nCol*2; }else{ need = (int)nCol; } if( p.nData + need >= p.nAlloc ){ string[] azNew; p.nAlloc = p.nAlloc*2 + need + 1; azNew = new string[p.nAlloc];//sqlite3_realloc( p.azResult, sizeof(char*)*p.nAlloc ); if( azNew==null ) goto malloc_failed; p.azResult = azNew; } /* If this is the first row, then generate an extra row containing ** the names of all columns. */ if( p.nRow==0 ){ p.nColumn = (int)nCol; for(i=0; i<nCol; i++){ z = sqlite3_mprintf("%s", colv[i]); if( z==null ) goto malloc_failed; p.azResult[p.nData++ -1] = z; } }else if( p.nColumn!=nCol ){ //sqlite3_free(ref p.zErrMsg); p.zErrMsg = sqlite3_mprintf( "sqlite3_get_table() called with two or more incompatible queries" ); p.rc = SQLITE_ERROR; return 1; } /* Copy over the row data */ if( argv!=null ){ for(i=0; i<nCol; i++){ if( argv[i]==null ){ z = null; }else{ int n = sqlite3Strlen30(argv[i])+1; //z = sqlite3_malloc( n ); //if( z==0 ) goto malloc_failed; z= argv[i];//memcpy(z, argv[i], n); } p.azResult[p.nData++ -1] = z; } p.nRow++; } return 0; malloc_failed: p.rc = SQLITE_NOMEM; return 1; } /* ** Query the database. But instead of invoking a callback for each row, ** malloc() for space to hold the result and return the entire results ** at the conclusion of the call. ** ** The result that is written to ***pazResult is held in memory obtained ** from malloc(). But the caller cannot free this memory directly. ** Instead, the entire table should be passed to //sqlite3_free_table() when ** the calling procedure is finished using it. */ static public int sqlite3_get_table( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ ref string[] pazResult, /* Write the result table here */ ref int pnRow, /* Write the number of rows in the result here */ ref int pnColumn, /* Write the number of columns of result here */ ref string pzErrMsg /* Write error messages here */ ){ int rc; TabResult res = new TabResult(); pazResult = null; pnColumn = 0; pnRow = 0; pzErrMsg = ""; res.zErrMsg = ""; res.nResult = 0; res.nRow = 0; res.nColumn = 0; res.nData = 1; res.nAlloc = 20; res.rc = SQLITE_OK; res.azResult = new string[res.nAlloc];// sqlite3_malloc( sizeof( char* ) * res.nAlloc ); if( res.azResult==null ){ db.errCode = SQLITE_NOMEM; return SQLITE_NOMEM; } res.azResult[0] = null; rc = sqlite3_exec(db, zSql, (dxCallback) sqlite3_get_table_cb, res, ref pzErrMsg); //Debug.Assert( sizeof(res.azResult[0])>= sizeof(res.nData) ); //res.azResult = SQLITE_INT_TO_PTR( res.nData ); if( (rc&0xff)==SQLITE_ABORT ){ //sqlite3_free_table(ref res.azResult[1] ); if( res.zErrMsg !=""){ if( pzErrMsg !=null ){ //sqlite3_free(ref pzErrMsg); pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg); } //sqlite3_free(ref res.zErrMsg); } db.errCode = res.rc; /* Assume 32-bit assignment is atomic */ return res.rc; } //sqlite3_free(ref res.zErrMsg); if( rc!=SQLITE_OK ){ //sqlite3_free_table(ref res.azResult[1]); return rc; } if( res.nAlloc>res.nData ){ string[] azNew; Array.Resize(ref res.azResult, res.nData-1);//sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) ); //if( azNew==null ){ // //sqlite3_free_table(ref res.azResult[1]); // db.errCode = SQLITE_NOMEM; // return SQLITE_NOMEM; //} res.nAlloc = res.nData+1; //res.azResult = azNew; } pazResult = res.azResult; pnColumn = res.nColumn; pnRow = res.nRow; return rc; } /* ** This routine frees the space the sqlite3_get_table() malloced. */ static void //sqlite3_free_table( ref string azResult /* Result returned from from sqlite3_get_table() */ ){ if( azResult !=null){ int i, n; //azResult--; //Debug.Assert( azResult!=0 ); //n = SQLITE_PTR_TO_INT(azResult[0]); //for(i=1; i<n; i++){ if( azResult[i] ) //sqlite3_free(azResult[i]); } //sqlite3_free(ref azResult); } } #endif //* SQLITE_OMIT_GET_TABLE */ } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlServerCe; using DowUtils; namespace Factotum{ class ChgComponent : ChangeFinder { public ChgComponent(SqlCeConnection cnnOrig, SqlCeConnection cnnMod) : base(cnnOrig, cnnMod) { tableName = "Components"; tableName_friendly = "Components"; // Select Command for Modified Table cmdSelMod = cnnMod.CreateCommand(); cmdSelMod.CommandType = CommandType.Text; cmdSelMod.CommandText = @"Select CmpDBid as ID, CmpName as Name, CmpUntID, CmtName as [Component Material Type], CmpCmtID, LinName as [Line], CmpLinID, SysName as [System], CmpSysID, CtpName as [Component Type], CmpCtpID, PslSchedule + ' Nom Dia: ' + STR(PslNomDia,6,3) as [Schedule], CmpPslID, CmpDrawing as [Drawing], CmpUpMainOd as [U/S Main OD], CmpUpMainTnom as [U/S Main Tnom], CmpUpMainTscr as [U/S Main Tscr], CmpDnMainOd as [D/S Main OD], CmpDnMainTnom as [D/S Main Tnom], CmpDnMainTscr as [D/S Main Tscr], CmpBranchOd as [Branch OD], CmpBranchTnom as [Branch Tnom], CmpBranchTscr as [Branch Tscr], CmpUpExtOd as [U/S Ext OD], CmpUpExtTnom as [U/S Ext Tnom], CmpUpExtTscr as [U/S Ext Tscr], CmpDnExtOd as [D/S Ext OD], CmpDnExtTnom as [D/S Ext Tnom], CmpDnExtTscr as [D/S Ext Tscr], CmpBrExtOd as [Branch Ext OD], CmpBrExtTnom as [Branch Ext Tnom], CmpBrExtTscr as [Branch Ext Tscr], CmpTimesInspected as [Times Inspected], CmpAvgInspectionTime as [Avg Inspection Time], CmpAvgCrewDose as [Avg Crew Dose], CmpPctChromeMain as [Pct Chromium Main], CmpPctChromeBranch as [Pct Chromium Branch], CmpPctChromeUsExt as [Pct Chromium U/S Ext], CmpPctChromeDsExt as [Pct Chromium D/S Ext], CmpPctChromeBrExt as [Pct Chromium Branch Ext], CmpMisc1 as [Miscellaneous 1], CmpMisc2 as [Miscellaneous 2], CmpNote as [Note], CASE WHEN CmpHighRad = 1 THEN 'Yes' WHEN CmpHighRad = 0 THEN 'No' END as [High Rad], CmpHighRad, CASE WHEN CmpHardToAccess = 1 THEN 'Yes' WHEN CmpHardToAccess = 0 THEN 'No' END as [Hard To Access], CmpHardToAccess, CASE WHEN CmpHasDs = 1 THEN 'Yes' WHEN CmpHasDs = 0 THEN 'No' END as [Has Downstream], CmpHasDs, CASE WHEN CmpHasBranch = 1 THEN 'Yes' WHEN CmpHasBranch = 0 THEN 'No' END as [Has Branch], CmpHasBranch, CmpIsLclChg, CmpUsedInOutage, CASE WHEN CmpIsActive = 1 THEN 'Active' WHEN CmpIsActive = 0 THEN 'Inactive' END as [Status], CmpIsActive from Components left outer join ComponentMaterials on CmpCmtID = CmtDBid left outer join Lines on CmpLinID = LinDBid left outer join Systems on CmpSysID = SysDBid left outer join ComponentTypes on CmpCtpID = CtpDBid left outer join PipeScheduleLookup on CmpPslID = PslDBid"; // Select Command for Original Table cmdSelOrig = cnnOrig.CreateCommand(); cmdSelOrig.CommandType = CommandType.Text; cmdSelOrig.CommandText = @"Select CmpDBid as ID, CmpName as Name, CmpUntID, CmtName as [Component Material Type], CmpCmtID, LinName as [Line], CmpLinID, SysName as [System], CmpSysID, CtpName as [Component Type], CmpCtpID, PslSchedule + ' Nom Dia: ' + STR(PslNomDia,6,3) as [Schedule], CmpPslID, CmpDrawing as [Drawing], CmpUpMainOd as [U/S Main OD], CmpUpMainTnom as [U/S Main Tnom], CmpUpMainTscr as [U/S Main Tscr], CmpDnMainOd as [D/S Main OD], CmpDnMainTnom as [D/S Main Tnom], CmpDnMainTscr as [D/S Main Tscr], CmpBranchOd as [Branch OD], CmpBranchTnom as [Branch Tnom], CmpBranchTscr as [Branch Tscr], CmpUpExtOd as [U/S Ext OD], CmpUpExtTnom as [U/S Ext Tnom], CmpUpExtTscr as [U/S Ext Tscr], CmpDnExtOd as [D/S Ext OD], CmpDnExtTnom as [D/S Ext Tnom], CmpDnExtTscr as [D/S Ext Tscr], CmpBrExtOd as [Branch Ext OD], CmpBrExtTnom as [Branch Ext Tnom], CmpBrExtTscr as [Branch Ext Tscr], CmpTimesInspected as [Times Inspected], CmpAvgInspectionTime as [Avg Inspection Time], CmpAvgCrewDose as [Avg Crew Dose], CmpPctChromeMain as [Pct Chromium Main], CmpPctChromeBranch as [Pct Chromium Branch], CmpPctChromeUsExt as [Pct Chromium U/S Ext], CmpPctChromeDsExt as [Pct Chromium D/S Ext], CmpPctChromeBrExt as [Pct Chromium Branch Ext], CmpMisc1 as [Miscellaneous 1], CmpMisc2 as [Miscellaneous 2], CmpNote as [Note], CASE WHEN CmpHighRad = 1 THEN 'Yes' WHEN CmpHighRad = 0 THEN 'No' END as [High Rad], CmpHighRad, CASE WHEN CmpHardToAccess = 1 THEN 'Yes' WHEN CmpHardToAccess = 0 THEN 'No' END as [Hard To Access], CmpHardToAccess, CASE WHEN CmpHasDs = 1 THEN 'Yes' WHEN CmpHasDs = 0 THEN 'No' END as [Has Downstream], CmpHasDs, CASE WHEN CmpHasBranch = 1 THEN 'Yes' WHEN CmpHasBranch = 0 THEN 'No' END as [Has Branch], CmpHasBranch, CmpIsLclChg, CmpUsedInOutage, CASE WHEN CmpIsActive = 1 THEN 'Active' WHEN CmpIsActive = 0 THEN 'Inactive' END as [Status], CmpIsActive from Components left outer join ComponentMaterials on CmpCmtID = CmtDBid left outer join Lines on CmpLinID = LinDBid left outer join Systems on CmpSysID = SysDBid left outer join ComponentTypes on CmpCtpID = CtpDBid left outer join PipeScheduleLookup on CmpPslID = PslDBid"; // Update Command for Original Table cmdUpdOrig = cnnOrig.CreateCommand(); cmdUpdOrig.CommandType = CommandType.Text; cmdUpdOrig.CommandText = @"Update Components set CmpName = @p1, CmpUntID = @p2, CmpCmtID = @p3, CmpLinID = @p4, CmpSysID = @p5, CmpCtpID = @p6, CmpPslID = @p7, CmpDrawing = @p8, CmpUpMainOd = @p9, CmpUpMainTnom = @p10, CmpUpMainTscr = @p11, CmpDnMainOd = @p12, CmpDnMainTnom = @p13, CmpDnMainTscr = @p14, CmpBranchOd = @p15, CmpBranchTnom = @p16, CmpBranchTscr = @p17, CmpUpExtOd = @p18, CmpUpExtTnom = @p19, CmpUpExtTscr = @p20, CmpDnExtOd = @p21, CmpDnExtTnom = @p22, CmpDnExtTscr = @p23, CmpBrExtOd = @p24, CmpBrExtTnom = @p25, CmpBrExtTscr = @p26, CmpTimesInspected = @p27, CmpAvgInspectionTime = @p28, CmpAvgCrewDose = @p29, CmpPctChromeMain = @p30, CmpPctChromeBranch = @p31, CmpPctChromeUsExt = @p32, CmpPctChromeDsExt = @p33, CmpPctChromeBrExt = @p34, CmpMisc1 = @p35, CmpMisc2 = @p36, CmpNote = @p37, CmpHighRad = @p38, CmpHardToAccess = @p39, CmpHasDs = @p40, CmpHasBranch = @p41, CmpIsLclChg = @p42, CmpUsedInOutage = @p43, CmpIsActive = @p44 Where CmpDBid = @p0"; cmdUpdOrig.Parameters.Add("@p0", SqlDbType.UniqueIdentifier, 16, "ID"); cmdUpdOrig.Parameters.Add("@p1", SqlDbType.NVarChar, 50, "Name"); cmdUpdOrig.Parameters.Add("@p2", SqlDbType.UniqueIdentifier, 16, "CmpUntID"); cmdUpdOrig.Parameters.Add("@p3", SqlDbType.UniqueIdentifier, 16, "CmpCmtID"); cmdUpdOrig.Parameters.Add("@p4", SqlDbType.UniqueIdentifier, 16, "CmpLinID"); cmdUpdOrig.Parameters.Add("@p5", SqlDbType.UniqueIdentifier, 16, "CmpSysID"); cmdUpdOrig.Parameters.Add("@p6", SqlDbType.UniqueIdentifier, 16, "CmpCtpID"); cmdUpdOrig.Parameters.Add("@p7", SqlDbType.UniqueIdentifier, 16, "CmpPslID"); cmdUpdOrig.Parameters.Add("@p8", SqlDbType.NVarChar, 50, "Drawing"); cmdUpdOrig.Parameters.Add("@p9", SqlDbType.Decimal, 6, "U/S Main OD"); cmdUpdOrig.Parameters.Add("@p10", SqlDbType.Decimal, 5, "U/S Main Tnom"); cmdUpdOrig.Parameters.Add("@p11", SqlDbType.Decimal, 5, "U/S Main Tscr"); cmdUpdOrig.Parameters.Add("@p12", SqlDbType.Decimal, 6, "D/S Main OD"); cmdUpdOrig.Parameters.Add("@p13", SqlDbType.Decimal, 5, "D/S Main Tnom"); cmdUpdOrig.Parameters.Add("@p14", SqlDbType.Decimal, 5, "D/S Main Tscr"); cmdUpdOrig.Parameters.Add("@p15", SqlDbType.Decimal, 6, "Branch OD"); cmdUpdOrig.Parameters.Add("@p16", SqlDbType.Decimal, 5, "Branch Tnom"); cmdUpdOrig.Parameters.Add("@p17", SqlDbType.Decimal, 5, "Branch Tscr"); cmdUpdOrig.Parameters.Add("@p18", SqlDbType.Decimal, 6, "U/S Ext OD"); cmdUpdOrig.Parameters.Add("@p19", SqlDbType.Decimal, 5, "U/S Ext Tnom"); cmdUpdOrig.Parameters.Add("@p20", SqlDbType.Decimal, 5, "U/S Ext Tscr"); cmdUpdOrig.Parameters.Add("@p21", SqlDbType.Decimal, 6, "D/S Ext OD"); cmdUpdOrig.Parameters.Add("@p22", SqlDbType.Decimal, 5, "D/S Ext Tnom"); cmdUpdOrig.Parameters.Add("@p23", SqlDbType.Decimal, 5, "D/S Ext Tscr"); cmdUpdOrig.Parameters.Add("@p24", SqlDbType.Decimal, 6, "Branch Ext OD"); cmdUpdOrig.Parameters.Add("@p25", SqlDbType.Decimal, 5, "Branch Ext Tnom"); cmdUpdOrig.Parameters.Add("@p26", SqlDbType.Decimal, 5, "Branch Ext Tscr"); cmdUpdOrig.Parameters.Add("@p27", SqlDbType.Int, 4, "Times Inspected"); cmdUpdOrig.Parameters.Add("@p28", SqlDbType.Float, 8, "Avg Inspection Time"); cmdUpdOrig.Parameters.Add("@p29", SqlDbType.Float, 8, "Avg Crew Dose"); cmdUpdOrig.Parameters.Add("@p30", SqlDbType.Decimal, 5, "Pct Chromium Main"); cmdUpdOrig.Parameters.Add("@p31", SqlDbType.Decimal, 5, "Pct Chromium Branch"); cmdUpdOrig.Parameters.Add("@p32", SqlDbType.Decimal, 5, "Pct Chromium U/S Ext"); cmdUpdOrig.Parameters.Add("@p33", SqlDbType.Decimal, 5, "Pct Chromium D/S Ext"); cmdUpdOrig.Parameters.Add("@p34", SqlDbType.Decimal, 5, "Pct Chromium Branch Ext"); cmdUpdOrig.Parameters.Add("@p35", SqlDbType.NVarChar, 25, "Miscellaneous 1"); cmdUpdOrig.Parameters.Add("@p36", SqlDbType.NVarChar, 25, "Miscellaneous 2"); cmdUpdOrig.Parameters.Add("@p37", SqlDbType.NVarChar, 256, "Note"); cmdUpdOrig.Parameters.Add("@p38", SqlDbType.Bit, 1, "CmpHighRad"); cmdUpdOrig.Parameters.Add("@p39", SqlDbType.Bit, 1, "CmpHardToAccess"); cmdUpdOrig.Parameters.Add("@p40", SqlDbType.Bit, 1, "CmpHasDs"); cmdUpdOrig.Parameters.Add("@p41", SqlDbType.Bit, 1, "CmpHasBranch"); cmdUpdOrig.Parameters.Add("@p42", SqlDbType.Bit, 1, "CmpIsLclChg"); cmdUpdOrig.Parameters.Add("@p43", SqlDbType.Bit, 1, "CmpUsedInOutage"); cmdUpdOrig.Parameters.Add("@p44", SqlDbType.Bit, 1, "CmpIsActive"); cmdUpdOrig.Parameters["@p0"].SourceVersion = DataRowVersion.Original; // Insert Command for Original Table cmdInsOrig = cnnOrig.CreateCommand(); cmdInsOrig.CommandType = CommandType.Text; cmdInsOrig.CommandText = @"Insert into Components ( CmpDBid, CmpName, CmpUntID, CmpCmtID, CmpLinID, CmpSysID, CmpCtpID, CmpPslID, CmpDrawing, CmpUpMainOd, CmpUpMainTnom, CmpUpMainTscr, CmpDnMainOd, CmpDnMainTnom, CmpDnMainTscr, CmpBranchOd, CmpBranchTnom, CmpBranchTscr, CmpUpExtOd, CmpUpExtTnom, CmpUpExtTscr, CmpDnExtOd, CmpDnExtTnom, CmpDnExtTscr, CmpBrExtOd, CmpBrExtTnom, CmpBrExtTscr, CmpTimesInspected, CmpAvgInspectionTime, CmpAvgCrewDose, CmpPctChromeMain, CmpPctChromeBranch, CmpPctChromeUsExt, CmpPctChromeDsExt, CmpPctChromeBrExt, CmpMisc1, CmpMisc2, CmpNote, CmpHighRad, CmpHardToAccess, CmpHasDs, CmpHasBranch, CmpIsLclChg, CmpUsedInOutage, CmpIsActive ) values (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12, @p13, @p14, @p15, @p16, @p17, @p18, @p19, @p20, @p21, @p22, @p23, @p24, @p25, @p26, @p27, @p28, @p29, @p30, @p31, @p32, @p33, @p34, @p35, @p36, @p37, @p38, @p39, @p40, @p41, @p42, @p43, @p44)"; cmdInsOrig.Parameters.Add("@p0", SqlDbType.UniqueIdentifier, 16, "ID"); cmdInsOrig.Parameters.Add("@p1", SqlDbType.NVarChar, 50, "Name"); cmdInsOrig.Parameters.Add("@p2", SqlDbType.UniqueIdentifier, 16, "CmpUntID"); cmdInsOrig.Parameters.Add("@p3", SqlDbType.UniqueIdentifier, 16, "CmpCmtID"); cmdInsOrig.Parameters.Add("@p4", SqlDbType.UniqueIdentifier, 16, "CmpLinID"); cmdInsOrig.Parameters.Add("@p5", SqlDbType.UniqueIdentifier, 16, "CmpSysID"); cmdInsOrig.Parameters.Add("@p6", SqlDbType.UniqueIdentifier, 16, "CmpCtpID"); cmdInsOrig.Parameters.Add("@p7", SqlDbType.UniqueIdentifier, 16, "CmpPslID"); cmdInsOrig.Parameters.Add("@p8", SqlDbType.NVarChar, 50, "Drawing"); cmdInsOrig.Parameters.Add("@p9", SqlDbType.Decimal, 6, "U/S Main OD"); cmdInsOrig.Parameters.Add("@p10", SqlDbType.Decimal, 5, "U/S Main Tnom"); cmdInsOrig.Parameters.Add("@p11", SqlDbType.Decimal, 5, "U/S Main Tscr"); cmdInsOrig.Parameters.Add("@p12", SqlDbType.Decimal, 6, "D/S Main OD"); cmdInsOrig.Parameters.Add("@p13", SqlDbType.Decimal, 5, "D/S Main Tnom"); cmdInsOrig.Parameters.Add("@p14", SqlDbType.Decimal, 5, "D/S Main Tscr"); cmdInsOrig.Parameters.Add("@p15", SqlDbType.Decimal, 6, "Branch OD"); cmdInsOrig.Parameters.Add("@p16", SqlDbType.Decimal, 5, "Branch Tnom"); cmdInsOrig.Parameters.Add("@p17", SqlDbType.Decimal, 5, "Branch Tscr"); cmdInsOrig.Parameters.Add("@p18", SqlDbType.Decimal, 6, "U/S Ext OD"); cmdInsOrig.Parameters.Add("@p19", SqlDbType.Decimal, 5, "U/S Ext Tnom"); cmdInsOrig.Parameters.Add("@p20", SqlDbType.Decimal, 5, "U/S Ext Tscr"); cmdInsOrig.Parameters.Add("@p21", SqlDbType.Decimal, 6, "D/S Ext OD"); cmdInsOrig.Parameters.Add("@p22", SqlDbType.Decimal, 5, "D/S Ext Tnom"); cmdInsOrig.Parameters.Add("@p23", SqlDbType.Decimal, 5, "D/S Ext Tscr"); cmdInsOrig.Parameters.Add("@p24", SqlDbType.Decimal, 6, "Branch Ext OD"); cmdInsOrig.Parameters.Add("@p25", SqlDbType.Decimal, 5, "Branch Ext Tnom"); cmdInsOrig.Parameters.Add("@p26", SqlDbType.Decimal, 5, "Branch Ext Tscr"); cmdInsOrig.Parameters.Add("@p27", SqlDbType.Int, 4, "Times Inspected"); cmdInsOrig.Parameters.Add("@p28", SqlDbType.Float, 8, "Avg Inspection Time"); cmdInsOrig.Parameters.Add("@p29", SqlDbType.Float, 8, "Avg Crew Dose"); cmdInsOrig.Parameters.Add("@p30", SqlDbType.Decimal, 5, "Pct Chromium Main"); cmdInsOrig.Parameters.Add("@p31", SqlDbType.Decimal, 5, "Pct Chromium Branch"); cmdInsOrig.Parameters.Add("@p32", SqlDbType.Decimal, 5, "Pct Chromium U/S Ext"); cmdInsOrig.Parameters.Add("@p33", SqlDbType.Decimal, 5, "Pct Chromium D/S Ext"); cmdInsOrig.Parameters.Add("@p34", SqlDbType.Decimal, 5, "Pct Chromium Branch Ext"); cmdInsOrig.Parameters.Add("@p35", SqlDbType.NVarChar, 25, "Miscellaneous 1"); cmdInsOrig.Parameters.Add("@p36", SqlDbType.NVarChar, 25, "Miscellaneous 2"); cmdInsOrig.Parameters.Add("@p37", SqlDbType.NVarChar, 256, "Note"); cmdInsOrig.Parameters.Add("@p38", SqlDbType.Bit, 1, "CmpHighRad"); cmdInsOrig.Parameters.Add("@p39", SqlDbType.Bit, 1, "CmpHardToAccess"); cmdInsOrig.Parameters.Add("@p40", SqlDbType.Bit, 1, "CmpHasDs"); cmdInsOrig.Parameters.Add("@p41", SqlDbType.Bit, 1, "CmpHasBranch"); cmdInsOrig.Parameters.Add("@p42", SqlDbType.Bit, 1, "CmpIsLclChg"); cmdInsOrig.Parameters.Add("@p43", SqlDbType.Bit, 1, "CmpUsedInOutage"); cmdInsOrig.Parameters.Add("@p44", SqlDbType.Bit, 1, "CmpIsActive"); } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Linq; using System; using Component = UnityEngine.Component; public class Binding : MonoBehaviour { #region Error strings private string bindinerError = "Invalid binding on {0}: "; private string BINDING_ERROR { get { return string.Format(bindingError, gameObject.name); } private string NOT_ASSIGNABLE_FROMTO { get { return BINDING_ERROR + "Properties are not assignable or castable from ({2}){0} to ({3}){1}"; } } private string ARGUMENT_NULL { get { return BINDING_ERROR + " Argument {0} is null"; } } #endregion public enum BindingMode { Invalid, OneWayToTarget, OneWayToSource, TwoWay, OneTime } #region Dinding Data private object lastTargetValue, lastSourceValue; public string SourceFieldName, TargetFieldName; public Component Source, Target; public BindingMode Mode; #endregion #region Cached Member Accessor Actions private Action<object, object> SetSourceValue = null; private Action<object, object> SetTargetValue = null; private Func<object, object> GetTargetValue = null; private Func<object, object> GetSourceValue = null; #endregion //Validate Binding data and report any errors //Initialize bindings and accesors void Start() { if (Source == null || Target == null) { Debug.LogError(BINDING_ERROR + (Target == null ? "Target is null" : "Source is Null")); Mode = BindingMode.Invalid; } else { SetAccessors(Source, SourceFieldName, out SetSourceValue, out GetSourceValue); SetAccessors(Target, TargetFieldName, out SetTargetValue, out GetTargetValue); } } //User reflection to identify the . delimited nested class member //Drill down into the object until the last member is found List<MemberInfo> GetMember(object obj, string field) { var names = field.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries).ToList(); List<MemberInfo> currentMembers = new List<MemberInfo>(); foreach (var name in names) { if (!currentMembers.Any()) { var objType = obj.GetType(); var members = objType.GetMember(name); currentMembers.Add(members[0]); } else { var currentMember = currentMembers.Last(); switch (currentMember.MemberType) { case MemberTypes.Field: { var currentInfo = (currentMember as FieldInfo); currentMember = currentInfo.FieldType.GetMember(name)[0]; } break; case MemberTypes.Property: { var currentInfo = (currentMember as PropertyInfo); currentMember = currentInfo.PropertyType.GetMember(name)[0]; } break; } currentMembers.Add(currentMember); } } return currentMembers; } //Reflect Setter and Getter for the specified property path on the provided object. void SetAccessors(object obj, string name, out Action<object, object> setter, out Func<object, object> getter) { List<Func<object, object>> setterPath = new List<Func<object, object>>(); List<Func<object, object>> getterPath = new List<Func<object, object>>(); Action<object, object> valueSetter = null; var members = GetMember(obj, name); foreach (var member in members) switch (member.MemberType) { case MemberTypes.Field: { var field = member as FieldInfo; if (members.Last().Equals(member)) valueSetter = (object ob, object value) => { if (!field.IsPublic) { Debug.LogError(string.Format("{0} ({1}){2} is not a public writable field.", BINDING_ERROR, field.FieldType, field.Name)); Mode = BindingMode.Invalid; return; } var converter = TypeDescriptor.GetConverter(value.GetType()); if (converter.CanConvertTo(field.FieldType)) field.SetValue(ob, converter.ConvertTo(value, field.FieldType)); else { Debug.LogError(string.Format("{0} ({1}){2} could not be converted to destination ({3}){4}.", BINDING_ERROR, value.GetType().Name, name, field.FieldType, field.Name)); Mode = BindingMode.Invalid; } }; else setterPath.Add((object o) => field.GetValue(o)); getterPath.Add((object o) => field.GetValue(o)); } break; case MemberTypes.Property: { var property = member as PropertyInfo; if (members.Last().Equals(member)) valueSetter = (object ob, object value) => { if (!property.CanWrite) { Debug.LogError(string.Format("{0} ({1}){2} is a readonly property.", BINDING_ERROR, property.PropertyType, property.Name)); Mode = BindingMode.Invalid; return; } var converter = TypeDescriptor.GetConverter(value.GetType()); if (converter.CanConvertTo(property.PropertyType)) property.SetValue(ob, converter.ConvertTo(value, property.PropertyType), null); else { Debug.LogError(string.Format("{0} ({1}){2} could not be converted to destination ({3}){4}.", BINDING_ERROR, value.GetType().Name, name, property.PropertyType, property.Name)); Mode = BindingMode.Invalid; } }; else setterPath.Add((object o) => property.GetValue(o, null)); getterPath.Add( (object o) => property.GetValue(o, null) ); } break; default: Debug.LogError(BINDING_ERROR + "(Source)" + Source.name + "." + SourceFieldName + " field/property was not found"); Mode = BindingMode.Invalid; setter = null; getter = null; break; } getter = o => { Func<object, object> lastGetter = getterPath.FirstOrDefault() as Func<object, object>; if (lastGetter == null) Debug.Log("No getters"); else if (o == null) { Debug.Log("Getter: object is null"); } else { object result = lastGetter.Invoke(o); if (result == null) Debug.Log("First getter returns null"); else for (int i = 1; i < getterPath.Count; i++) { result = getterPath[i].Invoke(result); if (result == null) Debug.Log(string.Format("Getter {0} returns null", i)); } return result; } return null; }; setter = (o, value) => { object target = o; if (target == null) Debug.Log("Setter: Object is null"); if (setterPath.Any()) { Func<object, object> pathGetter = setterPath.FirstOrDefault(); if (pathGetter == null) throw new NullReferenceException(); target = pathGetter.Invoke(target); if (target == null) throw new NullReferenceException(); for (int i = 1; i < setterPath.Count; i++) target = setterPath[i].Invoke(target); } valueSetter.Invoke(target, value); }; } //Check for changes and apply the value update. //Force will update the value regardless of if the value has changed. void UpdateTarget(bool force = false) { var sourceValue = GetSourceValue.Invoke(Source); bool sourceChanged = sourceValue.Equals(lastSourceValue); if (sourceChanged || force) { SetTargetValue.Invoke(Target, sourceValue); } } //Check for changes and apply the value update. //Force will update the value regardless of if the value has changed. void UpdateSource() { var targetValue = GetTargetValue.Invoke(Target); bool targetChanged = !targetValue.Equals(lastTargetValue); if (targetChanged) SetSourceValue.Invoke(Source, targetValue); } //Evaluate binding per frame void Update() { if (Mode == BindingMode.Invalid || SetSourceValue == null || SetTargetValue == null || GetSourceValue == null || GetTargetValue == null) return; lastSourceValue = GetSourceValue.Invoke(Source); lastTargetValue = GetTargetValue.Invoke(Target); switch (Mode) { case BindingMode.OneTime: UpdateTarget(true); Mode = BindingMode.Invalid; break; case BindingMode.OneWayToSource: UpdateSource(); break; case BindingMode.OneWayToTarget: UpdateTarget(); break; case BindingMode.TwoWay: UpdateSource(); UpdateTarget(); break; } } }
//--------------------------------------------------------------------------- // // <copyright file="ByteKeyFrameCollection.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Windows.Media.Animation; using System.Windows.Media.Media3D; namespace System.Windows.Media.Animation { /// <summary> /// This collection is used in conjunction with a KeyFrameByteAnimation /// to animate a Byte property value along a set of key frames. /// </summary> public class ByteKeyFrameCollection : Freezable, IList { #region Data private List<ByteKeyFrame> _keyFrames; private static ByteKeyFrameCollection s_emptyCollection; #endregion #region Constructors /// <Summary> /// Creates a new ByteKeyFrameCollection. /// </Summary> public ByteKeyFrameCollection() : base() { _keyFrames = new List< ByteKeyFrame>(2); } #endregion #region Static Methods /// <summary> /// An empty ByteKeyFrameCollection. /// </summary> public static ByteKeyFrameCollection Empty { get { if (s_emptyCollection == null) { ByteKeyFrameCollection emptyCollection = new ByteKeyFrameCollection(); emptyCollection._keyFrames = new List< ByteKeyFrame>(0); emptyCollection.Freeze(); s_emptyCollection = emptyCollection; } return s_emptyCollection; } } #endregion #region Freezable /// <summary> /// Creates a freezable copy of this ByteKeyFrameCollection. /// </summary> /// <returns>The copy</returns> public new ByteKeyFrameCollection Clone() { return (ByteKeyFrameCollection)base.Clone(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new ByteKeyFrameCollection(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>. /// </summary> protected override void CloneCore(Freezable sourceFreezable) { ByteKeyFrameCollection sourceCollection = (ByteKeyFrameCollection) sourceFreezable; base.CloneCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< ByteKeyFrame>(count); for (int i = 0; i < count; i++) { ByteKeyFrame keyFrame = (ByteKeyFrame)sourceCollection._keyFrames[i].Clone(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(System.Windows.Freezable)">Freezable.CloneCurrentValueCore</see>. /// </summary> protected override void CloneCurrentValueCore(Freezable sourceFreezable) { ByteKeyFrameCollection sourceCollection = (ByteKeyFrameCollection) sourceFreezable; base.CloneCurrentValueCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< ByteKeyFrame>(count); for (int i = 0; i < count; i++) { ByteKeyFrame keyFrame = (ByteKeyFrame)sourceCollection._keyFrames[i].CloneCurrentValue(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(System.Windows.Freezable)">Freezable.GetAsFrozenCore</see>. /// </summary> protected override void GetAsFrozenCore(Freezable sourceFreezable) { ByteKeyFrameCollection sourceCollection = (ByteKeyFrameCollection) sourceFreezable; base.GetAsFrozenCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< ByteKeyFrame>(count); for (int i = 0; i < count; i++) { ByteKeyFrame keyFrame = (ByteKeyFrame)sourceCollection._keyFrames[i].GetAsFrozen(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(System.Windows.Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>. /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable) { ByteKeyFrameCollection sourceCollection = (ByteKeyFrameCollection) sourceFreezable; base.GetCurrentValueAsFrozenCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< ByteKeyFrame>(count); for (int i = 0; i < count; i++) { ByteKeyFrame keyFrame = (ByteKeyFrame)sourceCollection._keyFrames[i].GetCurrentValueAsFrozen(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// /// </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); for (int i = 0; i < _keyFrames.Count && canFreeze; i++) { canFreeze &= Freezable.Freeze(_keyFrames[i], isChecking); } return canFreeze; } #endregion #region IEnumerable /// <summary> /// Returns an enumerator of the ByteKeyFrames in the collection. /// </summary> public IEnumerator GetEnumerator() { ReadPreamble(); return _keyFrames.GetEnumerator(); } #endregion #region ICollection /// <summary> /// Returns the number of ByteKeyFrames in the collection. /// </summary> public int Count { get { ReadPreamble(); return _keyFrames.Count; } } /// <summary> /// See <see cref="System.Collections.ICollection.IsSynchronized">ICollection.IsSynchronized</see>. /// </summary> public bool IsSynchronized { get { ReadPreamble(); return (IsFrozen || Dispatcher != null); } } /// <summary> /// See <see cref="System.Collections.ICollection.SyncRoot">ICollection.SyncRoot</see>. /// </summary> public object SyncRoot { get { ReadPreamble(); return ((ICollection)_keyFrames).SyncRoot; } } /// <summary> /// Copies all of the ByteKeyFrames in the collection to an /// array. /// </summary> void ICollection.CopyTo(Array array, int index) { ReadPreamble(); ((ICollection)_keyFrames).CopyTo(array, index); } /// <summary> /// Copies all of the ByteKeyFrames in the collection to an /// array of ByteKeyFrames. /// </summary> public void CopyTo(ByteKeyFrame[] array, int index) { ReadPreamble(); _keyFrames.CopyTo(array, index); } #endregion #region IList /// <summary> /// Adds a ByteKeyFrame to the collection. /// </summary> int IList.Add(object keyFrame) { return Add((ByteKeyFrame)keyFrame); } /// <summary> /// Adds a ByteKeyFrame to the collection. /// </summary> public int Add(ByteKeyFrame keyFrame) { if (keyFrame == null) { throw new ArgumentNullException("keyFrame"); } WritePreamble(); OnFreezablePropertyChanged(null, keyFrame); _keyFrames.Add(keyFrame); WritePostscript(); return _keyFrames.Count - 1; } /// <summary> /// Removes all ByteKeyFrames from the collection. /// </summary> public void Clear() { WritePreamble(); if (_keyFrames.Count > 0) { for (int i = 0; i < _keyFrames.Count; i++) { OnFreezablePropertyChanged(_keyFrames[i], null); } _keyFrames.Clear(); WritePostscript(); } } /// <summary> /// Returns true of the collection contains the given ByteKeyFrame. /// </summary> bool IList.Contains(object keyFrame) { return Contains((ByteKeyFrame)keyFrame); } /// <summary> /// Returns true of the collection contains the given ByteKeyFrame. /// </summary> public bool Contains(ByteKeyFrame keyFrame) { ReadPreamble(); return _keyFrames.Contains(keyFrame); } /// <summary> /// Returns the index of a given ByteKeyFrame in the collection. /// </summary> int IList.IndexOf(object keyFrame) { return IndexOf((ByteKeyFrame)keyFrame); } /// <summary> /// Returns the index of a given ByteKeyFrame in the collection. /// </summary> public int IndexOf(ByteKeyFrame keyFrame) { ReadPreamble(); return _keyFrames.IndexOf(keyFrame); } /// <summary> /// Inserts a ByteKeyFrame into a specific location in the collection. /// </summary> void IList.Insert(int index, object keyFrame) { Insert(index, (ByteKeyFrame)keyFrame); } /// <summary> /// Inserts a ByteKeyFrame into a specific location in the collection. /// </summary> public void Insert(int index, ByteKeyFrame keyFrame) { if (keyFrame == null) { throw new ArgumentNullException("keyFrame"); } WritePreamble(); OnFreezablePropertyChanged(null, keyFrame); _keyFrames.Insert(index, keyFrame); WritePostscript(); } /// <summary> /// Returns true if the collection is frozen. /// </summary> public bool IsFixedSize { get { ReadPreamble(); return IsFrozen; } } /// <summary> /// Returns true if the collection is frozen. /// </summary> public bool IsReadOnly { get { ReadPreamble(); return IsFrozen; } } /// <summary> /// Removes a ByteKeyFrame from the collection. /// </summary> void IList.Remove(object keyFrame) { Remove((ByteKeyFrame)keyFrame); } /// <summary> /// Removes a ByteKeyFrame from the collection. /// </summary> public void Remove(ByteKeyFrame keyFrame) { WritePreamble(); if (_keyFrames.Contains(keyFrame)) { OnFreezablePropertyChanged(keyFrame, null); _keyFrames.Remove(keyFrame); WritePostscript(); } } /// <summary> /// Removes the ByteKeyFrame at the specified index from the collection. /// </summary> public void RemoveAt(int index) { WritePreamble(); OnFreezablePropertyChanged(_keyFrames[index], null); _keyFrames.RemoveAt(index); WritePostscript(); } /// <summary> /// Gets or sets the ByteKeyFrame at a given index. /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (ByteKeyFrame)value; } } /// <summary> /// Gets or sets the ByteKeyFrame at a given index. /// </summary> public ByteKeyFrame this[int index] { get { ReadPreamble(); return _keyFrames[index]; } set { if (value == null) { throw new ArgumentNullException(String.Format(CultureInfo.InvariantCulture, "ByteKeyFrameCollection[{0}]", index)); } WritePreamble(); if (value != _keyFrames[index]) { OnFreezablePropertyChanged(_keyFrames[index], value); _keyFrames[index] = value; Debug.Assert(_keyFrames[index] != null); WritePostscript(); } } } #endregion } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.AutoScaling.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.AutoScaling.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for AutoScalingGroup Object /// </summary> public class AutoScalingGroupUnmarshaller : IUnmarshaller<AutoScalingGroup, XmlUnmarshallerContext>, IUnmarshaller<AutoScalingGroup, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public AutoScalingGroup Unmarshall(XmlUnmarshallerContext context) { AutoScalingGroup unmarshalledObject = new AutoScalingGroup(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("AutoScalingGroupARN", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.AutoScalingGroupARN = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("AutoScalingGroupName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.AutoScalingGroupName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("AvailabilityZones/member", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.AvailabilityZones.Add(item); continue; } if (context.TestExpression("CreatedTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.CreatedTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DefaultCooldown", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.DefaultCooldown = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DesiredCapacity", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.DesiredCapacity = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("EnabledMetrics/member", targetDepth)) { var unmarshaller = EnabledMetricUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.EnabledMetrics.Add(item); continue; } if (context.TestExpression("HealthCheckGracePeriod", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.HealthCheckGracePeriod = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("HealthCheckType", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.HealthCheckType = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Instances/member", targetDepth)) { var unmarshaller = InstanceUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.Instances.Add(item); continue; } if (context.TestExpression("LaunchConfigurationName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.LaunchConfigurationName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LoadBalancerNames/member", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.LoadBalancerNames.Add(item); continue; } if (context.TestExpression("MaxSize", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.MaxSize = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("MinSize", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.MinSize = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("PlacementGroup", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.PlacementGroup = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Status", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Status = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SuspendedProcesses/member", targetDepth)) { var unmarshaller = SuspendedProcessUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.SuspendedProcesses.Add(item); continue; } if (context.TestExpression("Tags/member", targetDepth)) { var unmarshaller = TagDescriptionUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.Tags.Add(item); continue; } if (context.TestExpression("TerminationPolicies/member", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.TerminationPolicies.Add(item); continue; } if (context.TestExpression("VPCZoneIdentifier", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.VPCZoneIdentifier = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <returns></returns> public AutoScalingGroup Unmarshall(JsonUnmarshallerContext context) { return null; } private static AutoScalingGroupUnmarshaller _instance = new AutoScalingGroupUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static AutoScalingGroupUnmarshaller Instance { get { return _instance; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using NUnit.Framework; using Newtonsoft.Json; using GlmSharp; // ReSharper disable InconsistentNaming namespace GlmSharpTest.Generated.Swizzle { [TestFixture] public class LongSwizzleVec2Test { [Test] public void XYZW() { { var ov = new lvec2(-1L, 3L); var v = ov.swizzle.xx; Assert.AreEqual(-1L, v.x); Assert.AreEqual(-1L, v.y); } { var ov = new lvec2(-9L, -3L); var v = ov.swizzle.xxx; Assert.AreEqual(-9L, v.x); Assert.AreEqual(-9L, v.y); Assert.AreEqual(-9L, v.z); } { var ov = new lvec2(-6L, 3L); var v = ov.swizzle.xxxx; Assert.AreEqual(-6L, v.x); Assert.AreEqual(-6L, v.y); Assert.AreEqual(-6L, v.z); Assert.AreEqual(-6L, v.w); } { var ov = new lvec2(3L, 8L); var v = ov.swizzle.xxxy; Assert.AreEqual(3L, v.x); Assert.AreEqual(3L, v.y); Assert.AreEqual(3L, v.z); Assert.AreEqual(8L, v.w); } { var ov = new lvec2(7L, -4L); var v = ov.swizzle.xxy; Assert.AreEqual(7L, v.x); Assert.AreEqual(7L, v.y); Assert.AreEqual(-4L, v.z); } { var ov = new lvec2(-5L, -2L); var v = ov.swizzle.xxyx; Assert.AreEqual(-5L, v.x); Assert.AreEqual(-5L, v.y); Assert.AreEqual(-2L, v.z); Assert.AreEqual(-5L, v.w); } { var ov = new lvec2(5L, -7L); var v = ov.swizzle.xxyy; Assert.AreEqual(5L, v.x); Assert.AreEqual(5L, v.y); Assert.AreEqual(-7L, v.z); Assert.AreEqual(-7L, v.w); } { var ov = new lvec2(-8L, -6L); var v = ov.swizzle.xy; Assert.AreEqual(-8L, v.x); Assert.AreEqual(-6L, v.y); } { var ov = new lvec2(5L, -8L); var v = ov.swizzle.xyx; Assert.AreEqual(5L, v.x); Assert.AreEqual(-8L, v.y); Assert.AreEqual(5L, v.z); } { var ov = new lvec2(-6L, 9L); var v = ov.swizzle.xyxx; Assert.AreEqual(-6L, v.x); Assert.AreEqual(9L, v.y); Assert.AreEqual(-6L, v.z); Assert.AreEqual(-6L, v.w); } { var ov = new lvec2(-5L, 0); var v = ov.swizzle.xyxy; Assert.AreEqual(-5L, v.x); Assert.AreEqual(0, v.y); Assert.AreEqual(-5L, v.z); Assert.AreEqual(0, v.w); } { var ov = new lvec2(-5L, 3L); var v = ov.swizzle.xyy; Assert.AreEqual(-5L, v.x); Assert.AreEqual(3L, v.y); Assert.AreEqual(3L, v.z); } { var ov = new lvec2(-2L, -1L); var v = ov.swizzle.xyyx; Assert.AreEqual(-2L, v.x); Assert.AreEqual(-1L, v.y); Assert.AreEqual(-1L, v.z); Assert.AreEqual(-2L, v.w); } { var ov = new lvec2(-7L, 3L); var v = ov.swizzle.xyyy; Assert.AreEqual(-7L, v.x); Assert.AreEqual(3L, v.y); Assert.AreEqual(3L, v.z); Assert.AreEqual(3L, v.w); } { var ov = new lvec2(2L, -6L); var v = ov.swizzle.yx; Assert.AreEqual(-6L, v.x); Assert.AreEqual(2L, v.y); } { var ov = new lvec2(6L, -6L); var v = ov.swizzle.yxx; Assert.AreEqual(-6L, v.x); Assert.AreEqual(6L, v.y); Assert.AreEqual(6L, v.z); } { var ov = new lvec2(6L, -2L); var v = ov.swizzle.yxxx; Assert.AreEqual(-2L, v.x); Assert.AreEqual(6L, v.y); Assert.AreEqual(6L, v.z); Assert.AreEqual(6L, v.w); } { var ov = new lvec2(-1L, -2L); var v = ov.swizzle.yxxy; Assert.AreEqual(-2L, v.x); Assert.AreEqual(-1L, v.y); Assert.AreEqual(-1L, v.z); Assert.AreEqual(-2L, v.w); } { var ov = new lvec2(-1L, 8L); var v = ov.swizzle.yxy; Assert.AreEqual(8L, v.x); Assert.AreEqual(-1L, v.y); Assert.AreEqual(8L, v.z); } { var ov = new lvec2(1, -1L); var v = ov.swizzle.yxyx; Assert.AreEqual(-1L, v.x); Assert.AreEqual(1, v.y); Assert.AreEqual(-1L, v.z); Assert.AreEqual(1, v.w); } { var ov = new lvec2(0, 8L); var v = ov.swizzle.yxyy; Assert.AreEqual(8L, v.x); Assert.AreEqual(0, v.y); Assert.AreEqual(8L, v.z); Assert.AreEqual(8L, v.w); } { var ov = new lvec2(-2L, -8L); var v = ov.swizzle.yy; Assert.AreEqual(-8L, v.x); Assert.AreEqual(-8L, v.y); } { var ov = new lvec2(-2L, -7L); var v = ov.swizzle.yyx; Assert.AreEqual(-7L, v.x); Assert.AreEqual(-7L, v.y); Assert.AreEqual(-2L, v.z); } { var ov = new lvec2(9L, -4L); var v = ov.swizzle.yyxx; Assert.AreEqual(-4L, v.x); Assert.AreEqual(-4L, v.y); Assert.AreEqual(9L, v.z); Assert.AreEqual(9L, v.w); } { var ov = new lvec2(8L, 8L); var v = ov.swizzle.yyxy; Assert.AreEqual(8L, v.x); Assert.AreEqual(8L, v.y); Assert.AreEqual(8L, v.z); Assert.AreEqual(8L, v.w); } { var ov = new lvec2(-9L, 8L); var v = ov.swizzle.yyy; Assert.AreEqual(8L, v.x); Assert.AreEqual(8L, v.y); Assert.AreEqual(8L, v.z); } { var ov = new lvec2(-1L, 6L); var v = ov.swizzle.yyyx; Assert.AreEqual(6L, v.x); Assert.AreEqual(6L, v.y); Assert.AreEqual(6L, v.z); Assert.AreEqual(-1L, v.w); } { var ov = new lvec2(-1L, -1L); var v = ov.swizzle.yyyy; Assert.AreEqual(-1L, v.x); Assert.AreEqual(-1L, v.y); Assert.AreEqual(-1L, v.z); Assert.AreEqual(-1L, v.w); } } [Test] public void RGBA() { { var ov = new lvec2(5L, -4L); var v = ov.swizzle.rr; Assert.AreEqual(5L, v.x); Assert.AreEqual(5L, v.y); } { var ov = new lvec2(-7L, -6L); var v = ov.swizzle.rrr; Assert.AreEqual(-7L, v.x); Assert.AreEqual(-7L, v.y); Assert.AreEqual(-7L, v.z); } { var ov = new lvec2(-9L, 5L); var v = ov.swizzle.rrrr; Assert.AreEqual(-9L, v.x); Assert.AreEqual(-9L, v.y); Assert.AreEqual(-9L, v.z); Assert.AreEqual(-9L, v.w); } { var ov = new lvec2(1, -3L); var v = ov.swizzle.rrrg; Assert.AreEqual(1, v.x); Assert.AreEqual(1, v.y); Assert.AreEqual(1, v.z); Assert.AreEqual(-3L, v.w); } { var ov = new lvec2(-6L, 4L); var v = ov.swizzle.rrg; Assert.AreEqual(-6L, v.x); Assert.AreEqual(-6L, v.y); Assert.AreEqual(4L, v.z); } { var ov = new lvec2(8L, 8L); var v = ov.swizzle.rrgr; Assert.AreEqual(8L, v.x); Assert.AreEqual(8L, v.y); Assert.AreEqual(8L, v.z); Assert.AreEqual(8L, v.w); } { var ov = new lvec2(0, 0); var v = ov.swizzle.rrgg; Assert.AreEqual(0, v.x); Assert.AreEqual(0, v.y); Assert.AreEqual(0, v.z); Assert.AreEqual(0, v.w); } { var ov = new lvec2(-4L, -9L); var v = ov.swizzle.rg; Assert.AreEqual(-4L, v.x); Assert.AreEqual(-9L, v.y); } { var ov = new lvec2(-9L, 0); var v = ov.swizzle.rgr; Assert.AreEqual(-9L, v.x); Assert.AreEqual(0, v.y); Assert.AreEqual(-9L, v.z); } { var ov = new lvec2(-4L, -8L); var v = ov.swizzle.rgrr; Assert.AreEqual(-4L, v.x); Assert.AreEqual(-8L, v.y); Assert.AreEqual(-4L, v.z); Assert.AreEqual(-4L, v.w); } { var ov = new lvec2(2L, -1L); var v = ov.swizzle.rgrg; Assert.AreEqual(2L, v.x); Assert.AreEqual(-1L, v.y); Assert.AreEqual(2L, v.z); Assert.AreEqual(-1L, v.w); } { var ov = new lvec2(-4L, 9L); var v = ov.swizzle.rgg; Assert.AreEqual(-4L, v.x); Assert.AreEqual(9L, v.y); Assert.AreEqual(9L, v.z); } { var ov = new lvec2(3L, -3L); var v = ov.swizzle.rggr; Assert.AreEqual(3L, v.x); Assert.AreEqual(-3L, v.y); Assert.AreEqual(-3L, v.z); Assert.AreEqual(3L, v.w); } { var ov = new lvec2(-2L, 6L); var v = ov.swizzle.rggg; Assert.AreEqual(-2L, v.x); Assert.AreEqual(6L, v.y); Assert.AreEqual(6L, v.z); Assert.AreEqual(6L, v.w); } { var ov = new lvec2(-9L, -6L); var v = ov.swizzle.gr; Assert.AreEqual(-6L, v.x); Assert.AreEqual(-9L, v.y); } { var ov = new lvec2(-2L, -5L); var v = ov.swizzle.grr; Assert.AreEqual(-5L, v.x); Assert.AreEqual(-2L, v.y); Assert.AreEqual(-2L, v.z); } { var ov = new lvec2(4L, -3L); var v = ov.swizzle.grrr; Assert.AreEqual(-3L, v.x); Assert.AreEqual(4L, v.y); Assert.AreEqual(4L, v.z); Assert.AreEqual(4L, v.w); } { var ov = new lvec2(-8L, 1); var v = ov.swizzle.grrg; Assert.AreEqual(1, v.x); Assert.AreEqual(-8L, v.y); Assert.AreEqual(-8L, v.z); Assert.AreEqual(1, v.w); } { var ov = new lvec2(-9L, 2L); var v = ov.swizzle.grg; Assert.AreEqual(2L, v.x); Assert.AreEqual(-9L, v.y); Assert.AreEqual(2L, v.z); } { var ov = new lvec2(-7L, 8L); var v = ov.swizzle.grgr; Assert.AreEqual(8L, v.x); Assert.AreEqual(-7L, v.y); Assert.AreEqual(8L, v.z); Assert.AreEqual(-7L, v.w); } { var ov = new lvec2(-9L, -8L); var v = ov.swizzle.grgg; Assert.AreEqual(-8L, v.x); Assert.AreEqual(-9L, v.y); Assert.AreEqual(-8L, v.z); Assert.AreEqual(-8L, v.w); } { var ov = new lvec2(9L, 7L); var v = ov.swizzle.gg; Assert.AreEqual(7L, v.x); Assert.AreEqual(7L, v.y); } { var ov = new lvec2(7L, -4L); var v = ov.swizzle.ggr; Assert.AreEqual(-4L, v.x); Assert.AreEqual(-4L, v.y); Assert.AreEqual(7L, v.z); } { var ov = new lvec2(1, -5L); var v = ov.swizzle.ggrr; Assert.AreEqual(-5L, v.x); Assert.AreEqual(-5L, v.y); Assert.AreEqual(1, v.z); Assert.AreEqual(1, v.w); } { var ov = new lvec2(1, -8L); var v = ov.swizzle.ggrg; Assert.AreEqual(-8L, v.x); Assert.AreEqual(-8L, v.y); Assert.AreEqual(1, v.z); Assert.AreEqual(-8L, v.w); } { var ov = new lvec2(-2L, 6L); var v = ov.swizzle.ggg; Assert.AreEqual(6L, v.x); Assert.AreEqual(6L, v.y); Assert.AreEqual(6L, v.z); } { var ov = new lvec2(-1L, -3L); var v = ov.swizzle.gggr; Assert.AreEqual(-3L, v.x); Assert.AreEqual(-3L, v.y); Assert.AreEqual(-3L, v.z); Assert.AreEqual(-1L, v.w); } { var ov = new lvec2(-9L, -5L); var v = ov.swizzle.gggg; Assert.AreEqual(-5L, v.x); Assert.AreEqual(-5L, v.y); Assert.AreEqual(-5L, v.z); Assert.AreEqual(-5L, v.w); } } [Test] public void InlineXYZW() { { var v0 = new lvec2(4L, 8L); var v1 = new lvec2(-2L, -9L); var v2 = v0.xy; v0.xy = v1; var v3 = v0.xy; Assert.AreEqual(v1, v3); Assert.AreEqual(-2L, v0.x); Assert.AreEqual(-9L, v0.y); Assert.AreEqual(4L, v2.x); Assert.AreEqual(8L, v2.y); } } [Test] public void InlineRGBA() { { var v0 = new lvec2(-5L, -7L); var v1 = 8L; var v2 = v0.r; v0.r = v1; var v3 = v0.r; Assert.AreEqual(v1, v3); Assert.AreEqual(8L, v0.x); Assert.AreEqual(-7L, v0.y); Assert.AreEqual(-5L, v2); } { var v0 = new lvec2(-8L, -4L); var v1 = 1; var v2 = v0.g; v0.g = v1; var v3 = v0.g; Assert.AreEqual(v1, v3); Assert.AreEqual(-8L, v0.x); Assert.AreEqual(1, v0.y); Assert.AreEqual(-4L, v2); } { var v0 = new lvec2(-4L, 5L); var v1 = new lvec2(-3L, -5L); var v2 = v0.rg; v0.rg = v1; var v3 = v0.rg; Assert.AreEqual(v1, v3); Assert.AreEqual(-3L, v0.x); Assert.AreEqual(-5L, v0.y); Assert.AreEqual(-4L, v2.x); Assert.AreEqual(5L, v2.y); } } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Globalization; using System.Reflection; using System.Text; #if !NETSTANDARD1_0 using System.Transactions; #endif using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; #if !NETSTANDARD using System.Configuration; using ConfigurationManager = System.Configuration.ConfigurationManager; #endif /// <summary> /// Writes log messages to the database using an ADO.NET provider. /// </summary> /// <remarks> /// - NETSTANDARD cannot load connectionstrings from .config /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/Database-target">Documentation on NLog Wiki</seealso> /// <example> /// <para> /// The configuration is dependent on the database type, because /// there are differnet methods of specifying connection string, SQL /// command and command parameters. /// </para> /// <para>MS SQL Server using System.Data.SqlClient:</para> /// <code lang="XML" source="examples/targets/Configuration File/Database/MSSQL/NLog.config" height="450" /> /// <para>Oracle using System.Data.OracleClient:</para> /// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.Native/NLog.config" height="350" /> /// <para>Oracle using System.Data.OleDBClient:</para> /// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.OleDB/NLog.config" height="350" /> /// <para>To set up the log target programmatically use code like this (an equivalent of MSSQL configuration):</para> /// <code lang="C#" source="examples/targets/Configuration API/Database/MSSQL/Example.cs" height="630" /> /// </example> [Target("Database")] public class DatabaseTarget : Target, IInstallable { private IDbConnection _activeConnection = null; private string _activeConnectionString; /// <summary> /// Initializes a new instance of the <see cref="DatabaseTarget" /> class. /// </summary> public DatabaseTarget() { Parameters = new List<DatabaseParameterInfo>(); InstallDdlCommands = new List<DatabaseCommandInfo>(); UninstallDdlCommands = new List<DatabaseCommandInfo>(); DBProvider = "sqlserver"; DBHost = "."; #if !NETSTANDARD ConnectionStringsSettings = ConfigurationManager.ConnectionStrings; #endif CommandType = CommandType.Text; OptimizeBufferReuse = GetType() == typeof(DatabaseTarget); // Class not sealed, reduce breaking changes } /// <summary> /// Initializes a new instance of the <see cref="DatabaseTarget" /> class. /// </summary> /// <param name="name">Name of the target.</param> public DatabaseTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets the name of the database provider. /// </summary> /// <remarks> /// <para> /// The parameter name should be a provider invariant name as registered in machine.config or app.config. Common values are: /// </para> /// <ul> /// <li><c>System.Data.SqlClient</c> - <see href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx">SQL Sever Client</see></li> /// <li><c>System.Data.SqlServerCe.3.5</c> - <see href="http://www.microsoft.com/sqlserver/2005/en/us/compact.aspx">SQL Sever Compact 3.5</see></li> /// <li><c>System.Data.OracleClient</c> - <see href="http://msdn.microsoft.com/en-us/library/system.data.oracleclient.aspx">Oracle Client from Microsoft</see> (deprecated in .NET Framework 4)</li> /// <li><c>Oracle.DataAccess.Client</c> - <see href="http://www.oracle.com/technology/tech/windows/odpnet/index.html">ODP.NET provider from Oracle</see></li> /// <li><c>System.Data.SQLite</c> - <see href="http://sqlite.phxsoftware.com/">System.Data.SQLite driver for SQLite</see></li> /// <li><c>Npgsql</c> - <see href="http://npgsql.projects.postgresql.org/">Npgsql driver for PostgreSQL</see></li> /// <li><c>MySql.Data.MySqlClient</c> - <see href="http://www.mysql.com/downloads/connector/net/">MySQL Connector/Net</see></li> /// </ul> /// <para>(Note that provider invariant names are not supported on .NET Compact Framework).</para> /// <para> /// Alternatively the parameter value can be be a fully qualified name of the provider /// connection type (class implementing <see cref="IDbConnection" />) or one of the following tokens: /// </para> /// <ul> /// <li><c>sqlserver</c>, <c>mssql</c>, <c>microsoft</c> or <c>msde</c> - SQL Server Data Provider</li> /// <li><c>oledb</c> - OLEDB Data Provider</li> /// <li><c>odbc</c> - ODBC Data Provider</li> /// </ul> /// </remarks> /// <docgen category='Connection Options' order='10' /> [RequiredParameter] [DefaultValue("sqlserver")] public string DBProvider { get; set; } #if !NETSTANDARD /// <summary> /// Gets or sets the name of the connection string (as specified in <see href="http://msdn.microsoft.com/en-us/library/bf7sd233.aspx">&lt;connectionStrings&gt; configuration section</see>. /// </summary> /// <docgen category='Connection Options' order='10' /> public string ConnectionStringName { get; set; } #endif /// <summary> /// Gets or sets the connection string. When provided, it overrides the values /// specified in DBHost, DBUserName, DBPassword, DBDatabase. /// </summary> /// <docgen category='Connection Options' order='10' /> public Layout ConnectionString { get; set; } /// <summary> /// Gets or sets the connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used. /// </summary> /// <docgen category='Installation Options' order='10' /> public Layout InstallConnectionString { get; set; } /// <summary> /// Gets the installation DDL commands. /// </summary> /// <docgen category='Installation Options' order='10' /> [ArrayParameter(typeof(DatabaseCommandInfo), "install-command")] public IList<DatabaseCommandInfo> InstallDdlCommands { get; private set; } /// <summary> /// Gets the uninstallation DDL commands. /// </summary> /// <docgen category='Installation Options' order='10' /> [ArrayParameter(typeof(DatabaseCommandInfo), "uninstall-command")] public IList<DatabaseCommandInfo> UninstallDdlCommands { get; private set; } /// <summary> /// Gets or sets a value indicating whether to keep the /// database connection open between the log events. /// </summary> /// <docgen category='Connection Options' order='10' /> [DefaultValue(false)] public bool KeepConnection { get; set; } /// <summary> /// Obsolete - value will be ignored! The logging code always runs outside of transaction. /// /// Gets or sets a value indicating whether to use database transactions. /// Some data providers require this. /// </summary> /// <docgen category='Connection Options' order='10' /> /// <remarks> /// This option was removed in NLog 4.0 because the logging code always runs outside of transaction. /// This ensures that the log gets written to the database if you rollback the main transaction because of an error and want to log the error. /// </remarks> [Obsolete("Value will be ignored as logging code always executes outside of a transaction. Marked obsolete on NLog 4.0 and it will be removed in NLog 6.")] public bool? UseTransactions { get; set; } /// <summary> /// Gets or sets the database host name. If the ConnectionString is not provided /// this value will be used to construct the "Server=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='10' /> public Layout DBHost { get; set; } /// <summary> /// Gets or sets the database user name. If the ConnectionString is not provided /// this value will be used to construct the "User ID=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='10' /> public Layout DBUserName { get; set; } /// <summary> /// Gets or sets the database password. If the ConnectionString is not provided /// this value will be used to construct the "Password=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='10' /> public Layout DBPassword { get; set; } /// <summary> /// Gets or sets the database name. If the ConnectionString is not provided /// this value will be used to construct the "Database=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='10' /> public Layout DBDatabase { get; set; } /// <summary> /// Gets or sets the text of the SQL command to be run on each log level. /// </summary> /// <remarks> /// Typically this is a SQL INSERT statement or a stored procedure call. /// It should use the database-specific parameters (marked as <c>@parameter</c> /// for SQL server or <c>:parameter</c> for Oracle, other data providers /// have their own notation) and not the layout renderers, /// because the latter is prone to SQL injection attacks. /// The layout renderers should be specified as &lt;parameter /&gt; elements instead. /// </remarks> /// <docgen category='SQL Statement' order='10' /> [RequiredParameter] public Layout CommandText { get; set; } /// <summary> /// Gets or sets the type of the SQL command to be run on each log level. /// </summary> /// <remarks> /// This specifies how the command text is interpreted, as "Text" (default) or as "StoredProcedure". /// When using the value StoredProcedure, the commandText-property would /// normally be the name of the stored procedure. TableDirect method is not supported in this context. /// </remarks> /// <docgen category='SQL Statement' order='11' /> [DefaultValue(CommandType.Text)] public CommandType CommandType { get; set; } /// <summary> /// Gets the collection of parameters. Each parameter contains a mapping /// between NLog layout and a database named or positional parameter. /// </summary> /// <docgen category='SQL Statement' order='12' /> [ArrayParameter(typeof(DatabaseParameterInfo), "parameter")] public IList<DatabaseParameterInfo> Parameters { get; private set; } #if !NETSTANDARD internal DbProviderFactory ProviderFactory { get; set; } // this is so we can mock the connection string without creating sub-processes internal ConnectionStringSettingsCollection ConnectionStringsSettings { get; set; } #endif internal Type ConnectionType { get; set; } /// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { RunInstallCommands(installationContext, InstallDdlCommands); } /// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { RunInstallCommands(installationContext, UninstallDdlCommands); } /// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { return null; } internal IDbConnection OpenConnection(string connectionString) { IDbConnection connection; #if !NETSTANDARD if (ProviderFactory != null) { connection = ProviderFactory.CreateConnection(); } else #endif { connection = (IDbConnection)Activator.CreateInstance(ConnectionType); } if (connection == null) { throw new NLogRuntimeException("Creation of connection failed"); } connection.ConnectionString = connectionString; connection.Open(); return connection; } /// <summary> /// Initializes the target. Can be used by inheriting classes /// to initialize logging. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "connectionStrings", Justification = "Name of the config file section.")] protected override void InitializeTarget() { base.InitializeTarget(); #pragma warning disable 618 if (UseTransactions.HasValue) #pragma warning restore 618 { InternalLogger.Warn("DatabaseTarget(Name={0}): UseTransactions property is obsolete and will not be used - will be removed in NLog 6", Name); } bool foundProvider = false; string providerName = string.Empty; #if !NETSTANDARD if (!string.IsNullOrEmpty(ConnectionStringName)) { // read connection string and provider factory from the configuration file var cs = ConnectionStringsSettings[ConnectionStringName]; if (cs == null) { throw new NLogConfigurationException($"Connection string '{ConnectionStringName}' is not declared in <connectionStrings /> section."); } if (!string.IsNullOrEmpty(cs.ConnectionString?.Trim())) { ConnectionString = SimpleLayout.Escape(cs.ConnectionString.Trim()); } providerName = cs.ProviderName?.Trim() ?? string.Empty; } #endif if (ConnectionString != null) { try { var connectionString = BuildConnectionString(LogEventInfo.CreateNullEvent()); var dbConnectionStringBuilder = new DbConnectionStringBuilder { ConnectionString = connectionString }; if (dbConnectionStringBuilder.TryGetValue("provider connection string", out var connectionStringValue)) { // Special Entity Framework Connection String if (dbConnectionStringBuilder.TryGetValue("provider", out var providerValue)) { // Provider was overriden by ConnectionString providerName = providerValue.ToString()?.Trim() ?? string.Empty; } // ConnectionString was overriden by ConnectionString :) ConnectionString = SimpleLayout.Escape(connectionStringValue.ToString()); } } catch (Exception ex) { #if !NETSTANDARD if (!string.IsNullOrEmpty(ConnectionStringName)) InternalLogger.Warn(ex, "DatabaseTarget(Name={0}): DbConnectionStringBuilder failed to parse '{1}' ConnectionString", Name, ConnectionStringName); else #endif InternalLogger.Warn(ex, "DatabaseTarget(Name={0}): DbConnectionStringBuilder failed to parse ConnectionString", Name); } } #if !NETSTANDARD if (string.IsNullOrEmpty(providerName)) { string dbProvider = DBProvider?.Trim() ?? string.Empty; if (!string.IsNullOrEmpty(dbProvider)) { foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows) { var invariantname = (string)row["InvariantName"]; if (string.Equals(invariantname, dbProvider, StringComparison.OrdinalIgnoreCase)) { providerName = invariantname; break; } } } } if (!string.IsNullOrEmpty(providerName)) { try { ProviderFactory = DbProviderFactories.GetFactory(providerName); foundProvider = true; } catch (Exception ex) { InternalLogger.Error(ex, "DatabaseTarget(Name={0}): DbProviderFactories failed to get factory from ProviderName={1}", Name, providerName); throw; } } #endif if (!foundProvider) { try { SetConnectionType(); if (ConnectionType == null) { InternalLogger.Warn("DatabaseTarget(Name={0}): No ConnectionType created from DBProvider={1}", Name, DBProvider); } } catch (Exception ex) { InternalLogger.Error(ex, "DatabaseTarget(Name={0}): Failed to create ConnectionType from DBProvider={1}", Name, DBProvider); throw; } } } /// <summary> /// Set the <see cref="ConnectionType"/> to use it for opening connections to the database. /// </summary> private void SetConnectionType() { switch (DBProvider.ToUpperInvariant()) { case "SQLSERVER": case "MSSQL": case "MICROSOFT": case "MSDE": #if NETSTANDARD case "SYSTEM.DATA.SQLCLIENT": { var assembly = Assembly.Load(new AssemblyName("System.Data.SqlClient")); #else { var assembly = typeof(IDbConnection).GetAssembly(); #endif ConnectionType = assembly.GetType("System.Data.SqlClient.SqlConnection", true, true); break; } #if !NETSTANDARD case "OLEDB": { var assembly = typeof(IDbConnection).GetAssembly(); ConnectionType = assembly.GetType("System.Data.OleDb.OleDbConnection", true, true); break; } case "ODBC": { var assembly = typeof(IDbConnection).GetAssembly(); ConnectionType = assembly.GetType("System.Data.Odbc.OdbcConnection", true, true); break; } #endif default: ConnectionType = Type.GetType(DBProvider, true, true); break; } } /// <summary> /// Closes the target and releases any unmanaged resources. /// </summary> protected override void CloseTarget() { base.CloseTarget(); InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection because of CloseTarget", Name); CloseConnection(); } /// <summary> /// Writes the specified logging event to the database. It creates /// a new database command, prepares parameters for it by calculating /// layouts and executes the command. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { try { WriteEventToDatabase(logEvent); } catch (Exception exception) { InternalLogger.Error(exception, "DatabaseTarget(Name={0}): Error when writing to database.", Name); if (exception.MustBeRethrownImmediately()) { throw; } InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection because of error", Name); CloseConnection(); throw; } finally { if (!KeepConnection) { InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection (KeepConnection = false).", Name); CloseConnection(); } } } /// <summary> /// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents) /// /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> [Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")] protected override void Write(AsyncLogEventInfo[] logEvents) { Write((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected override void Write(IList<AsyncLogEventInfo> logEvents) { var buckets = logEvents.BucketSort(c => BuildConnectionString(c.LogEvent)); try { foreach (var kvp in buckets) { for (int i = 0; i < kvp.Value.Count; i++) { AsyncLogEventInfo ev = kvp.Value[i]; try { WriteEventToDatabase(ev.LogEvent); ev.Continuation(null); } catch (Exception exception) { // in case of exception, close the connection and report it InternalLogger.Error(exception, "DatabaseTarget(Name={0}): Error when writing to database.", Name); if (exception.MustBeRethrownImmediately()) { throw; } InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection because of exception", Name); CloseConnection(); ev.Continuation(exception); if (exception.MustBeRethrown()) { throw; } } } } } finally { if (!KeepConnection) { InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection because of KeepConnection=false", Name); CloseConnection(); } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "It's up to the user to ensure proper quoting.")] private void WriteEventToDatabase(LogEventInfo logEvent) { //Always suppress transaction so that the caller does not rollback logging if they are rolling back their transaction. using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress)) { EnsureConnectionOpen(BuildConnectionString(logEvent)); using (IDbCommand command = _activeConnection.CreateCommand()) { command.CommandText = RenderLogEvent(CommandText, logEvent); command.CommandType = CommandType; InternalLogger.Trace("DatabaseTarget(Name={0}): Executing {1}: {2}", Name, command.CommandType, command.CommandText); AddParametersToCommand(command, Parameters, logEvent); int result = command.ExecuteNonQuery(); InternalLogger.Trace("DatabaseTarget(Name={0}): Finished execution, result = {1}", Name, result); } //not really needed as there is no transaction at all. transactionScope.Complete(); } } /// <summary> /// Build the connectionstring from the properties. /// </summary> /// <remarks> /// Using <see cref="ConnectionString"/> at first, and falls back to the properties <see cref="DBHost"/>, /// <see cref="DBUserName"/>, <see cref="DBPassword"/> and <see cref="DBDatabase"/> /// </remarks> /// <param name="logEvent">Event to render the layout inside the properties.</param> /// <returns></returns> protected string BuildConnectionString(LogEventInfo logEvent) { if (ConnectionString != null) { return RenderLogEvent(ConnectionString, logEvent); } var sb = new StringBuilder(); sb.Append("Server="); sb.Append(RenderLogEvent(DBHost, logEvent)); sb.Append(";"); if (DBUserName == null) { sb.Append("Trusted_Connection=SSPI;"); } else { sb.Append("User id="); sb.Append(RenderLogEvent(DBUserName, logEvent)); sb.Append(";Password="); sb.Append(RenderLogEvent(DBPassword, logEvent)); sb.Append(";"); } if (DBDatabase != null) { sb.Append("Database="); sb.Append(RenderLogEvent(DBDatabase, logEvent)); } return sb.ToString(); } private void EnsureConnectionOpen(string connectionString) { if (_activeConnection != null) { if (_activeConnectionString != connectionString) { InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection because of opening new.", Name); CloseConnection(); } } if (_activeConnection != null) { return; } InternalLogger.Trace("DatabaseTarget(Name={0}): Open connection.", Name); _activeConnection = OpenConnection(connectionString); _activeConnectionString = connectionString; } private void CloseConnection() { if (_activeConnection != null) { _activeConnection.Close(); _activeConnection.Dispose(); _activeConnection = null; _activeConnectionString = null; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "It's up to the user to ensure proper quoting.")] private void RunInstallCommands(InstallationContext installationContext, IEnumerable<DatabaseCommandInfo> commands) { // create log event that will be used to render all layouts LogEventInfo logEvent = installationContext.CreateLogEvent(); try { foreach (var commandInfo in commands) { string cs; if (commandInfo.ConnectionString != null) { // if there is connection string specified on the command info, use it cs = RenderLogEvent(commandInfo.ConnectionString, logEvent); } else if (InstallConnectionString != null) { // next, try InstallConnectionString cs = RenderLogEvent(InstallConnectionString, logEvent); } else { // if it's not defined, fall back to regular connection string cs = BuildConnectionString(logEvent); } // Set ConnectionType if it has not been initialized already if (ConnectionType == null) { SetConnectionType(); } EnsureConnectionOpen(cs); using (IDbCommand command = _activeConnection.CreateCommand()) { command.CommandType = commandInfo.CommandType; command.CommandText = RenderLogEvent(commandInfo.Text, logEvent); AddParametersToCommand(command, commandInfo.Parameters, logEvent); try { installationContext.Trace("DatabaseTarget(Name={0}) - Executing {1} '{2}'", Name, command.CommandType, command.CommandText); command.ExecuteNonQuery(); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } if (commandInfo.IgnoreFailures || installationContext.IgnoreFailures) { installationContext.Warning(exception.Message); } else { installationContext.Error(exception.Message); throw; } } } } } finally { InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection after install.", Name); CloseConnection(); } } /// <summary> /// Adds the given list of DatabaseParameterInfo to the given IDbCommand after transforming them into IDbDataParameters. /// </summary> /// <param name="command">The IDbCommand to add parameters to</param> /// <param name="databaseParameterInfos">The list of DatabaseParameterInfo to transform into IDbDataParameters and to add to the IDbCommand</param> /// <param name="logEvent">The log event to base the parameter's layout rendering on.</param> private void AddParametersToCommand(IDbCommand command, IList<DatabaseParameterInfo> databaseParameterInfos, LogEventInfo logEvent) { for(int i = 0; i < databaseParameterInfos.Count; ++i) { DatabaseParameterInfo par = databaseParameterInfos[i]; IDbDataParameter p = command.CreateParameter(); p.Direction = ParameterDirection.Input; if (par.Name != null) { p.ParameterName = par.Name; } if (par.Size != 0) { p.Size = par.Size; } if (par.Precision != 0) { p.Precision = par.Precision; } if (par.Scale != 0) { p.Scale = par.Scale; } string stringValue = RenderLogEvent(par.Layout, logEvent); p.Value = stringValue; command.Parameters.Add(p); InternalLogger.Trace(" DatabaseTarget: Parameter: '{0}' = '{1}' ({2})", p.ParameterName, p.Value, p.DbType); } } #if NETSTANDARD1_0 /// <summary> /// Fake transaction /// /// Transactions aren't in .NET Core: https://github.com/dotnet/corefx/issues/2949 /// </summary> private class TransactionScope : IDisposable { private readonly TransactionScopeOption suppress; public TransactionScope(TransactionScopeOption suppress) { this.suppress = suppress; } public void Complete() { } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { } } /// <summary> /// Fake option /// </summary> private enum TransactionScopeOption { Required, RequiresNew, Suppress, } #endif } } #endif
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2014 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 11.0Release // Tag = $Name: AKW11_000 $ //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace Dynastream.Fit { /// <summary> /// Implements the Monitoring profile message. /// </summary> public class MonitoringMesg : Mesg { #region Fields static class CyclesSubfield { public static ushort Steps = 0; public static ushort Strokes = 1; public static ushort Subfields = 2; public static ushort Active = Fit.SubfieldIndexActiveSubfield; public static ushort MainField = Fit.SubfieldIndexMainField; } #endregion #region Constructors public MonitoringMesg() : base(Profile.mesgs[Profile.MonitoringIndex]) { } public MonitoringMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the Timestamp field /// Units: s /// Comment: Must align to logging interval, for example, time must be 00:00:00 for daily log.</summary> /// <returns>Returns DateTime representing the Timestamp field</returns> public DateTime GetTimestamp() { return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set Timestamp field /// Units: s /// Comment: Must align to logging interval, for example, time must be 00:00:00 for daily log.</summary> /// <param name="timestamp_">Nullable field value to be set</param> public void SetTimestamp(DateTime timestamp_) { SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the DeviceIndex field /// Comment: Associates this data to device_info message. Not required for file with single device (sensor).</summary> /// <returns>Returns nullable byte representing the DeviceIndex field</returns> public byte? GetDeviceIndex() { return (byte?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set DeviceIndex field /// Comment: Associates this data to device_info message. Not required for file with single device (sensor).</summary> /// <param name="deviceIndex_">Nullable field value to be set</param> public void SetDeviceIndex(byte? deviceIndex_) { SetFieldValue(0, 0, deviceIndex_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Calories field /// Units: kcal /// Comment: Accumulated total calories. Maintained by MonitoringReader for each activity_type. See SDK documentation</summary> /// <returns>Returns nullable ushort representing the Calories field</returns> public ushort? GetCalories() { return (ushort?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Calories field /// Units: kcal /// Comment: Accumulated total calories. Maintained by MonitoringReader for each activity_type. See SDK documentation</summary> /// <param name="calories_">Nullable field value to be set</param> public void SetCalories(ushort? calories_) { SetFieldValue(1, 0, calories_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Distance field /// Units: m /// Comment: Accumulated distance. Maintained by MonitoringReader for each activity_type. See SDK documentation.</summary> /// <returns>Returns nullable float representing the Distance field</returns> public float? GetDistance() { return (float?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Distance field /// Units: m /// Comment: Accumulated distance. Maintained by MonitoringReader for each activity_type. See SDK documentation.</summary> /// <param name="distance_">Nullable field value to be set</param> public void SetDistance(float? distance_) { SetFieldValue(2, 0, distance_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Cycles field /// Units: cycles /// Comment: Accumulated cycles. Maintained by MonitoringReader for each activity_type. See SDK documentation.</summary> /// <returns>Returns nullable float representing the Cycles field</returns> public float? GetCycles() { return (float?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Cycles field /// Units: cycles /// Comment: Accumulated cycles. Maintained by MonitoringReader for each activity_type. See SDK documentation.</summary> /// <param name="cycles_">Nullable field value to be set</param> public void SetCycles(float? cycles_) { SetFieldValue(3, 0, cycles_, Fit.SubfieldIndexMainField); } /// <summary> /// Retrieves the Steps subfield /// Units: steps</summary> /// <returns>Nullable uint representing the Steps subfield</returns> public uint? GetSteps() { return (uint?)GetFieldValue(3, 0, CyclesSubfield.Steps); } /// <summary> /// /// Set Steps subfield /// Units: steps</summary> /// <param name="steps">Subfield value to be set</param> public void SetSteps(uint? steps) { SetFieldValue(3, 0, steps, CyclesSubfield.Steps); } /// <summary> /// Retrieves the Strokes subfield /// Units: strokes</summary> /// <returns>Nullable float representing the Strokes subfield</returns> public float? GetStrokes() { return (float?)GetFieldValue(3, 0, CyclesSubfield.Strokes); } /// <summary> /// /// Set Strokes subfield /// Units: strokes</summary> /// <param name="strokes">Subfield value to be set</param> public void SetStrokes(float? strokes) { SetFieldValue(3, 0, strokes, CyclesSubfield.Strokes); } ///<summary> /// Retrieves the ActiveTime field /// Units: s</summary> /// <returns>Returns nullable float representing the ActiveTime field</returns> public float? GetActiveTime() { return (float?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set ActiveTime field /// Units: s</summary> /// <param name="activeTime_">Nullable field value to be set</param> public void SetActiveTime(float? activeTime_) { SetFieldValue(4, 0, activeTime_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the ActivityType field</summary> /// <returns>Returns nullable ActivityType enum representing the ActivityType field</returns> public ActivityType? GetActivityType() { object obj = GetFieldValue(5, 0, Fit.SubfieldIndexMainField); ActivityType? value = obj == null ? (ActivityType?)null : (ActivityType)obj; return value; } /// <summary> /// Set ActivityType field</summary> /// <param name="activityType_">Nullable field value to be set</param> public void SetActivityType(ActivityType? activityType_) { SetFieldValue(5, 0, activityType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the ActivitySubtype field</summary> /// <returns>Returns nullable ActivitySubtype enum representing the ActivitySubtype field</returns> public ActivitySubtype? GetActivitySubtype() { object obj = GetFieldValue(6, 0, Fit.SubfieldIndexMainField); ActivitySubtype? value = obj == null ? (ActivitySubtype?)null : (ActivitySubtype)obj; return value; } /// <summary> /// Set ActivitySubtype field</summary> /// <param name="activitySubtype_">Nullable field value to be set</param> public void SetActivitySubtype(ActivitySubtype? activitySubtype_) { SetFieldValue(6, 0, activitySubtype_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the ActivityLevel field</summary> /// <returns>Returns nullable ActivityLevel enum representing the ActivityLevel field</returns> public ActivityLevel? GetActivityLevel() { object obj = GetFieldValue(7, 0, Fit.SubfieldIndexMainField); ActivityLevel? value = obj == null ? (ActivityLevel?)null : (ActivityLevel)obj; return value; } /// <summary> /// Set ActivityLevel field</summary> /// <param name="activityLevel_">Nullable field value to be set</param> public void SetActivityLevel(ActivityLevel? activityLevel_) { SetFieldValue(7, 0, activityLevel_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Distance16 field /// Units: 100 * m</summary> /// <returns>Returns nullable ushort representing the Distance16 field</returns> public ushort? GetDistance16() { return (ushort?)GetFieldValue(8, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Distance16 field /// Units: 100 * m</summary> /// <param name="distance16_">Nullable field value to be set</param> public void SetDistance16(ushort? distance16_) { SetFieldValue(8, 0, distance16_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Cycles16 field /// Units: 2 * cycles (steps)</summary> /// <returns>Returns nullable ushort representing the Cycles16 field</returns> public ushort? GetCycles16() { return (ushort?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Cycles16 field /// Units: 2 * cycles (steps)</summary> /// <param name="cycles16_">Nullable field value to be set</param> public void SetCycles16(ushort? cycles16_) { SetFieldValue(9, 0, cycles16_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the ActiveTime16 field /// Units: s</summary> /// <returns>Returns nullable ushort representing the ActiveTime16 field</returns> public ushort? GetActiveTime16() { return (ushort?)GetFieldValue(10, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set ActiveTime16 field /// Units: s</summary> /// <param name="activeTime16_">Nullable field value to be set</param> public void SetActiveTime16(ushort? activeTime16_) { SetFieldValue(10, 0, activeTime16_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LocalTimestamp field /// Comment: Must align to logging interval, for example, time must be 00:00:00 for daily log.</summary> /// <returns>Returns nullable uint representing the LocalTimestamp field</returns> public uint? GetLocalTimestamp() { return (uint?)GetFieldValue(11, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set LocalTimestamp field /// Comment: Must align to logging interval, for example, time must be 00:00:00 for daily log.</summary> /// <param name="localTimestamp_">Nullable field value to be set</param> public void SetLocalTimestamp(uint? localTimestamp_) { SetFieldValue(11, 0, localTimestamp_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Temperature field /// Units: C /// Comment: Avg temperature during the logging interval ended at timestamp</summary> /// <returns>Returns nullable float representing the Temperature field</returns> public float? GetTemperature() { return (float?)GetFieldValue(12, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Temperature field /// Units: C /// Comment: Avg temperature during the logging interval ended at timestamp</summary> /// <param name="temperature_">Nullable field value to be set</param> public void SetTemperature(float? temperature_) { SetFieldValue(12, 0, temperature_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the TemperatureMin field /// Units: C /// Comment: Min temperature during the logging interval ended at timestamp</summary> /// <returns>Returns nullable float representing the TemperatureMin field</returns> public float? GetTemperatureMin() { return (float?)GetFieldValue(14, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set TemperatureMin field /// Units: C /// Comment: Min temperature during the logging interval ended at timestamp</summary> /// <param name="temperatureMin_">Nullable field value to be set</param> public void SetTemperatureMin(float? temperatureMin_) { SetFieldValue(14, 0, temperatureMin_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the TemperatureMax field /// Units: C /// Comment: Max temperature during the logging interval ended at timestamp</summary> /// <returns>Returns nullable float representing the TemperatureMax field</returns> public float? GetTemperatureMax() { return (float?)GetFieldValue(15, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set TemperatureMax field /// Units: C /// Comment: Max temperature during the logging interval ended at timestamp</summary> /// <param name="temperatureMax_">Nullable field value to be set</param> public void SetTemperatureMax(float? temperatureMax_) { SetFieldValue(15, 0, temperatureMax_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
/////////////////////////////////////////////////////////////////////////////////// // Open 3D Model Viewer (open3mod) (v2.0) // [MeshDetailsDialog.cs] // (c) 2012-2015, Open3Mod Contributors // // Licensed under the terms and conditions of the 3-clause BSD license. See // the LICENSE file in the root folder of the repository for the details. // // HIS 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.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Windows.Forms; using Assimp; namespace open3mod { public partial class MeshDetailsDialog : Form, IHoverUpdateDialog { private const string XyzPosition = "XYZ Position"; private const string Normals = "Normals"; private const string Tangents = "Tangents"; private const string BoneWeights = "Bone Weights"; private const string VertexAnimation = "Vertex Animation"; private readonly MainWindow _host; private readonly Scene _scene; private NormalVectorGeneratorDialog _normalsDialog; private Mesh _mesh; private String _meshName; public MeshDetailsDialog(MainWindow host, Scene scene) { Debug.Assert(host != null); _host = host; _scene = scene; InitializeComponent(); // TODO(acgessler): Factor out preview generation and getting the checker pattern // background into a separate utility. pictureBoxMaterial.SizeMode = PictureBoxSizeMode.Zoom; pictureBoxMaterial.BackgroundImage = MaterialThumbnailControl.GetBackgroundImage(); pictureBoxMaterial.BackgroundImageLayout = ImageLayout.Zoom; StartUpdateMaterialPreviewLoop(); } /// <summary> /// Set current mesh for which detail information is displayed. /// </summary> /// <param name="mesh"></param> /// <param name="meshName"></param> public void SetMesh(Mesh mesh, string meshName) { Debug.Assert(mesh != null); Debug.Assert(meshName != null); if (mesh == _mesh) { return; } _mesh = mesh; _meshName = meshName; labelVertexCount.Text = mesh.VertexCount.ToString(); labelFaceCount.Text = mesh.FaceCount.ToString(); labelBoneCount.Text = mesh.BoneCount.ToString(); Text = string.Format("{0} - Mesh Details", meshName); UpdateFaceItems(); UpdateVertexItems(); // Immediate material update to avoid poll delay. UpdateMaterialPreview(); } private void UpdateFaceItems() { listBoxFaceData.Items.Clear(); if (_mesh.PrimitiveType.HasFlag(PrimitiveType.Triangle)) { listBoxFaceData.Items.Add("Triangles"); } if (_mesh.PrimitiveType.HasFlag(PrimitiveType.Line)) { listBoxFaceData.Items.Add("Single Lines"); } if (_mesh.PrimitiveType.HasFlag(PrimitiveType.Point)) { listBoxFaceData.Items.Add("Single Points"); } } private void UpdateVertexItems() { object selectedItem = listBoxVertexData.SelectedItem; listBoxVertexData.Items.Clear(); listBoxVertexData.Items.Add(XyzPosition); if (_mesh.HasNormals) { listBoxVertexData.Items.Add(Normals); } if (_mesh.HasTangentBasis) { listBoxVertexData.Items.Add(Tangents); } for (var i = 0; i < _mesh.TextureCoordinateChannelCount; ++i) { listBoxVertexData.Items.Add(UVCoordinates(i)); } for (var i = 0; i < _mesh.VertexColorChannelCount; ++i) { listBoxVertexData.Items.Add(VertexColors(i)); } if (_mesh.HasBones) { listBoxVertexData.Items.Add(BoneWeights); } if (_mesh.HasMeshAnimationAttachments) { listBoxVertexData.Items.Add(VertexAnimation); } // Restore previous selected item. foreach (var item in listBoxVertexData.Items) { if (item.Equals(selectedItem)) { listBoxVertexData.SelectedItem = item; } } } private static string VertexColors(int i) { return string.Format("Vertex Color Set (#{0})", i); } private static string UVCoordinates(int i) { return string.Format("UV Coordinates (#{0})", i); } /// <summary> /// Locate the tab within which the current mesh is. /// </summary> /// <returns></returns> private Tab GetTabForCurrentMesh() { if (_mesh == null) { return null; } Debug.Assert(_host != null); foreach (var tab in _host.UiState.TabsWithActiveScenes()) { var scene = tab.ActiveScene; Debug.Assert(scene != null); for (var i = 0; i < scene.Raw.MeshCount; ++i) { var m = scene.Raw.Meshes[i]; if (m == _mesh) { return tab; } } } return null; } private void StartUpdateMaterialPreviewLoop() { // Unholy poll. This is the only case where material previews are // needed other than the material panel itself. MainWindow.DelayExecution(new TimeSpan(0, 0, 0, 0, 1000), () => { UpdateMaterialPreview(); StartUpdateMaterialPreviewLoop(); }); } private void UpdateMaterialPreview() { var tab = GetTabForCurrentMesh(); if (tab == null) { pictureBoxMaterial.Image = null; labelMaterialName.Text = "None"; return; } var scene = tab.ActiveScene; var mat = scene.Raw.Materials[_mesh.MaterialIndex]; var ui = _host.UiForTab(tab); Debug.Assert(ui != null); var inspector = ui.GetInspector(); var thumb = inspector.Materials.GetMaterialControl(mat); pictureBoxMaterial.Image = thumb.GetCurrentPreviewImage(); labelMaterialName.Text = mat.Name.Length > 0 ? mat.Name : "Unnamed Material"; } private void OnJumpToMaterial(object sender, LinkLabelLinkClickedEventArgs e) { linkLabel1.LinkVisited = false; var tab = GetTabForCurrentMesh(); if (tab == null) { return; } var scene = tab.ActiveScene; var mat = scene.Raw.Materials[_mesh.MaterialIndex]; var ui = _host.UiForTab(tab); Debug.Assert(ui != null); var inspector = ui.GetInspector(); inspector.Materials.SelectEntry(mat); var thumb = inspector.Materials.GetMaterialControl(mat); inspector.OpenMaterialsTabAndScrollTo(thumb); } private void OnGenerateNormals(object sender, EventArgs e) { if (_normalsDialog != null) { _normalsDialog.Close(); _normalsDialog.Dispose(); _normalsDialog = null; } _normalsDialog = new NormalVectorGeneratorDialog(_scene, _mesh, _meshName); _normalsDialog.Show(this); // Disable this dialog for the duration of the NormalsVectorGeneratorDialog. // The latter replaces the mesh being displayed with a temporary preview // mesh, so changes made to the source mesh would not be visible. This is // very confusing, so disallow it. EnableDialogControls(false); _normalsDialog.FormClosed += (o, args) => { if (IsDisposed) { return; } _normalsDialog = null; EnableDialogControls(true); // Unless the user canceled the operation, Normals were added. UpdateVertexItems(); }; } private void EnableDialogControls(bool enabled) { // Only update children. If the form itself is disabled, it acts like a // blocked dialog and can no longer be moved. foreach (Control c in Controls) { c.Enabled = enabled; } } private void OnDeleteSelectedVertexComponent(object sender, EventArgs e) { string item = (string) listBoxVertexData.SelectedItem; if (item == null || item == XyzPosition) { return; } switch (item) { case Normals: DeleteVertexComponent(Normals, m => m.Normals); break; case Tangents: DeleteVertexComponent(Tangents, m => m.Tangents); // TODO(acgessler): We should also delete bitangents. break; case VertexAnimation: DeleteVertexComponent(VertexAnimation, m => m.MeshAnimationAttachments); break; case BoneWeights: DeleteVertexComponent(BoneWeights, m => m.Bones); break; default: for (var i = 0; i < _mesh.TextureCoordinateChannelCount; ++i) { if (item != UVCoordinates(i)) continue; DeleteVertexComponent(UVCoordinates(i), m => m.TextureCoordinateChannels, i); break; } for (var i = 0; i < _mesh.VertexColorChannelCount; ++i) { if (item != VertexColors(i)) continue; DeleteVertexComponent(VertexColors(i), m => m.VertexColorChannels, i); break; } break; } } private void DeleteVertexComponent<T>(string name, Expression<Func<Mesh, T>> property) where T : new() { var expr = (MemberExpression)property.Body; var prop = (PropertyInfo)expr.Member; T oldValue = (T)prop.GetValue(_mesh, null); var mesh = _mesh; _scene.UndoStack.PushAndDo(String.Format("Mesh \"{0}\": delete {1}", _meshName, name), () => prop.SetValue(mesh, new T(), null), () => prop.SetValue(mesh, oldValue, null), () => { _scene.RequestRenderRefresh(); if (mesh == _mesh) // Only update UI if the dialog instance still displays the mesh. { UpdateVertexItems(); } }); } // Version for T[] (TextureCoordChannels, VertexColorChannels). Passing in an indexed expression // directly yields a LINQ expression tree rooted at a BinaryExpression instead of MemberExpression. // TODO(acgessler): Check for a way to express this with less duplication. private void DeleteVertexComponent<T>(string name, Expression<Func<Mesh, T[]>> property, int index) where T : new() { var expr = (MemberExpression)property.Body; var prop = (PropertyInfo)expr.Member; var indexes = new object[] { index }; T oldValue = ((T[])prop.GetValue(_mesh, null))[index]; var mesh = _mesh; _scene.UndoStack.PushAndDo(String.Format("Mesh \"{0}\": delete {1}", _meshName, name), () => ((T[])prop.GetValue(_mesh, null))[index] = new T(), () => ((T[])prop.GetValue(_mesh, null))[index] = oldValue, () => { _scene.RequestRenderRefresh(); if (mesh == _mesh) { UpdateVertexItems(); } }); } private void OnSelectedVertexComponentChanged(object sender, EventArgs e) { buttonDeleteVertexData.Enabled = !listBoxVertexData.SelectedItem.Equals(XyzPosition); } public bool HoverUpdateEnabled { // Disallow Hover Update while any child dialogs are open. get { return _normalsDialog == null; } } } } /* vi: set shiftwidth=4 tabstop=4: */
using System; using System.Collections.Generic; using System.Text; using System.Drawing; namespace TicTacToe { /// <summary> /// This class represents a Tic-Tac-Toe game board. It includes logic /// to keep track of player turns and assign board squares to a player /// </summary> public class TicTacToeGame { public enum Players { Player1, Player2 }; protected bool isDraw = false; protected bool haveWinner; protected Board board; protected Stack<TicTacToeMove> moves; protected Players currentTurn = Players.Player1; // Player 1 goes first protected Board.Pieces player1Piece = Board.Pieces.X; // player 1 uses X and player 2 uses O by default protected Board.Pieces player2Piece = Board.Pieces.O; protected Board.Pieces winningPiece = Board.Pieces.Empty; protected Players winningPlayer; protected bool gameOver = false; /// <summary> /// Constructs a new TicTacToeGame using the default board pieces for player one and two /// </summary> public TicTacToeGame() : this(Board.Pieces.X, Board.Pieces.O) { } /// <summary> /// Constructs a new TicTacToe game using the specified player's pieces. /// /// </summary> /// <param name="player1Piece">Player one's piece</param> /// <param name="player2Piece">Player two's piece</param> public TicTacToeGame(Board.Pieces player1Piece, Board.Pieces player2Piece) { this.player1Piece = player1Piece; this.player2Piece = player2Piece; board = new Board(); moves = new Stack<TicTacToeMove>(); } /// <summary> /// Gets the Board associated with this game /// </summary> public Board GameBoard { get { return board; } } /// <summary> /// gets number of columns on the board /// </summary> public int Columns { get { return board.Columns; } } /// <summary> /// gets the number of rows on the game board /// </summary> public int Rows { get { return board.Rows; } } /// <summary> /// If there currently is a winner, this returns the the piece that has /// won. Otherwise it returns Pieces.Empty if there is no winner. /// </summary> public Board.Pieces WinningPiece { get { return winningPiece; } } /// <summary> /// Returns true if the game is over (if there is a winner or there is a draw) /// </summary> /// <returns>true if the game is over or false otherwise</returns> public bool IsGameOver() { return board.IsGameOver(); } /// <summary> /// Undoes the last move /// </summary> public void UndoLastMove() { TicTacToeMove lastMove = moves.Pop(); board.UndoMove(lastMove); SwapTurns(); } /// <summary> /// gets or sets Player 1's game piece /// </summary> public Board.Pieces Player1Piece { get { return player1Piece; } set { player1Piece = value; } } /// <summary> /// Gets or sets Player 2's game piece /// </summary> public Board.Pieces Player2Piece { get { return player2Piece; } set { player2Piece = value; } } /// <summary> /// Returns the player for whose turn it is /// </summary> public Players CurrentPlayerTurn { get { return this.currentTurn; } } /// <summary> /// Makes the specified move /// </summary> /// <param name="m">The TicTacToe move to be made</param> /// public void MakeMove(TicTacToeMove m) { MakeMove(m, GetPlayerWhoHasPiece(m.Piece)); } /// <summary> /// Makes the move for the specified player /// </summary> /// <param name="m">The move to make</param> /// <param name="p">The player making the move</param> public void MakeMove(TicTacToeMove m, Players p) { if (currentTurn != p) { throw new InvalidMoveException("You went out of turn!"); } if (!board.IsValidSquare(m.Position)) throw new InvalidMoveException("Pick a square on the board!"); board.MakeMove(m.Position, m.Piece); moves.Push(m); SwapTurns(); } /// <summary> /// This should not be called by clients. This is only for unit testing /// </summary> /// <param name="position">The position to take</param> /// <param name="p">The player who is taking the piece</param> public void TakeSquare(int position, Players p) { if (currentTurn != p) throw new InvalidMoveException("You tried to move out of turn!"); if (!board.IsValidSquare(position)) throw new InvalidMoveException(); board.MakeMove(position, GetPlayersPiece(p)); if (board.HasWinner()) winningPlayer = currentTurn; SwapTurns(); } // Returns the game piece for the specified player protected Board.Pieces GetPlayersPiece(Players p) { if (p == Players.Player1) return player1Piece; else return player2Piece; } // returns the Player who has the specified piece protected TicTacToeGame.Players GetPlayerWhoHasPiece(Board.Pieces piece) { if (piece == player1Piece) return Players.Player1; else return Players.Player2; } // Swap whose turn it is. // If X just moved we make it O's turn and // vice versa private void SwapTurns() { if (currentTurn == Players.Player1) currentTurn = Players.Player2; else currentTurn = Players.Player1; } } /// <summary> /// Represents a tic-tac-toe move /// </summary> public class TicTacToeMove { /// <summary> /// Constructs a TicTacToeMove /// </summary> /// <param name="position">The position to move to</param> /// <param name="piece">The piece that is moving</param> public TicTacToeMove(int position, Board.Pieces piece) { this.Position = position; this.Piece = piece; } /// <summary> /// gets or sets the position on the board /// </summary> public int Position { get; set; } /// <summary> /// Gets or sets the piece making this move /// </summary> public Board.Pieces Piece {get; set;} } /// <summary> /// An Exception representing an invalid move /// </summary> public class InvalidMoveException : Exception { public InvalidMoveException() : base() { } public InvalidMoveException(string msg) : base(msg) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Xunit; namespace System.Tests { public partial class GetEnvironmentVariable { [Fact] public void InvalidArguments_ThrowsExceptions() { AssertExtensions.Throws<ArgumentNullException>("variable", () => Environment.GetEnvironmentVariable(null)); AssertExtensions.Throws<ArgumentNullException>("variable", () => Environment.SetEnvironmentVariable(null, "test")); AssertExtensions.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable("", "test")); AssertExtensions.Throws<ArgumentException>("value", null, () => Environment.SetEnvironmentVariable("test", new string('s', 65 * 1024))); AssertExtensions.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable("", "test", EnvironmentVariableTarget.Machine)); AssertExtensions.Throws<ArgumentNullException>("variable", () => Environment.SetEnvironmentVariable(null, "test", EnvironmentVariableTarget.User)); AssertExtensions.Throws<ArgumentNullException>("variable", () => Environment.GetEnvironmentVariable(null, EnvironmentVariableTarget.Process)); AssertExtensions.Throws<ArgumentOutOfRangeException, ArgumentException>("target", null, () => Environment.GetEnvironmentVariable("test", (EnvironmentVariableTarget)42)); AssertExtensions.Throws<ArgumentOutOfRangeException, ArgumentException>("target", null, () => Environment.SetEnvironmentVariable("test", "test", (EnvironmentVariableTarget)(-1))); AssertExtensions.Throws<ArgumentOutOfRangeException, ArgumentException>("target", null, () => Environment.GetEnvironmentVariables((EnvironmentVariableTarget)(3))); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { AssertExtensions.Throws<ArgumentException>("variable", null, () => Environment.SetEnvironmentVariable(new string('s', 256), "value", EnvironmentVariableTarget.User)); } } [Fact] public void EmptyVariableReturnsNull() { Assert.Null(Environment.GetEnvironmentVariable(String.Empty)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // GetEnvironmentVariable by design doesn't respect changes via setenv public void RandomLongVariableNameCanRoundTrip() { // NOTE: The limit of 32766 characters enforced by desktop // SetEnvironmentVariable is antiquated. I was // able to create ~1GB names and values on my Windows 8.1 box. On // desktop, GetEnvironmentVariable throws OOM during its attempt to // demand huge EnvironmentPermission well before that. Also, the old // test for long name case wasn't very good: it just checked that an // arbitrary long name > 32766 characters returned null (not found), but // that had nothing to do with the limit, the variable was simply not // found! string variable = "LongVariable_" + new string('@', 33000); const string value = "TestValue"; try { SetEnvironmentVariableWithPInvoke(variable, value); Assert.Equal(value, Environment.GetEnvironmentVariable(variable)); } finally { SetEnvironmentVariableWithPInvoke(variable, null); } } [Fact] public void RandomVariableThatDoesNotExistReturnsNull() { string variable = "TestVariable_SurelyThisDoesNotExist"; Assert.Null(Environment.GetEnvironmentVariable(variable)); } [Fact] public void VariableNamesAreCaseInsensitiveAsAppropriate() { string value = "TestValue"; try { Environment.SetEnvironmentVariable("ThisIsATestEnvironmentVariable", value); Assert.Equal(value, Environment.GetEnvironmentVariable("ThisIsATestEnvironmentVariable")); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { value = null; } Assert.Equal(value, Environment.GetEnvironmentVariable("thisisatestenvironmentvariable")); Assert.Equal(value, Environment.GetEnvironmentVariable("THISISATESTENVIRONMENTVARIABLE")); Assert.Equal(value, Environment.GetEnvironmentVariable("ThISISATeSTENVIRoNMEnTVaRIABLE")); } finally { Environment.SetEnvironmentVariable("ThisIsATestEnvironmentVariable", null); } } [Fact] public void CanGetAllVariablesIndividually() { Random r = new Random(); string envVar1 = "TestVariable_CanGetVariablesIndividually_" + r.Next().ToString(); string envVar2 = "TestVariable_CanGetVariablesIndividually_" + r.Next().ToString(); try { Environment.SetEnvironmentVariable(envVar1, envVar1); Environment.SetEnvironmentVariable(envVar2, envVar2); IDictionary envBlock = Environment.GetEnvironmentVariables(); // Make sure the environment variables we set are part of the dictionary returned. Assert.True(envBlock.Contains(envVar1)); Assert.True(envBlock.Contains(envVar1)); // Make sure the values match the expected ones. Assert.Equal(envVar1, envBlock[envVar1]); Assert.Equal(envVar2, envBlock[envVar2]); // Make sure we can read the individual variables as well Assert.Equal(envVar1, Environment.GetEnvironmentVariable(envVar1)); Assert.Equal(envVar2, Environment.GetEnvironmentVariable(envVar2)); } finally { // Clear the variables we just set Environment.SetEnvironmentVariable(envVar1, null); Environment.SetEnvironmentVariable(envVar2, null); } } [Fact] public void EnumerateYieldsDictionaryEntryFromIEnumerable() { // GetEnvironmentVariables has always yielded DictionaryEntry from IEnumerable IDictionary vars = Environment.GetEnvironmentVariables(); IEnumerator enumerator = ((IEnumerable)vars).GetEnumerator(); if (enumerator.MoveNext()) { Assert.IsType<DictionaryEntry>(enumerator.Current); } else { Assert.Throws<InvalidOperationException>(() => enumerator.Current); } } [Fact] public void GetEnumerator_IDictionaryEnumerator_YieldsDictionaryEntries() { // GetEnvironmentVariables has always yielded DictionaryEntry from IDictionaryEnumerator IDictionary vars = Environment.GetEnvironmentVariables(); IDictionaryEnumerator enumerator = vars.GetEnumerator(); if (enumerator.MoveNext()) { Assert.IsType<DictionaryEntry>(enumerator.Current); } else { Assert.Throws<InvalidOperationException>(() => enumerator.Current); } } [Theory] [InlineData(null)] [InlineData(EnvironmentVariableTarget.User)] [InlineData(EnvironmentVariableTarget.Process)] [InlineData(EnvironmentVariableTarget.Machine)] public void GetEnumerator_LinqOverDictionaryEntries_Success(EnvironmentVariableTarget? target) { IDictionary envVars = target != null ? Environment.GetEnvironmentVariables(target.Value) : Environment.GetEnvironmentVariables(); Assert.IsType<Hashtable>(envVars); foreach (KeyValuePair<string, string> envVar in envVars.Cast<DictionaryEntry>().Select(de => new KeyValuePair<string, string>((string)de.Key, (string)de.Value))) { Assert.NotNull(envVar.Key); } } public void EnvironmentVariablesAreHashtable() { // On NetFX, the type returned was always Hashtable Assert.IsType<Hashtable>(Environment.GetEnvironmentVariables()); } [Theory] [InlineData(EnvironmentVariableTarget.Process)] [InlineData(EnvironmentVariableTarget.Machine)] [InlineData(EnvironmentVariableTarget.User)] public void EnvironmentVariablesAreHashtable(EnvironmentVariableTarget target) { // On NetFX, the type returned was always Hashtable Assert.IsType<Hashtable>(Environment.GetEnvironmentVariables(target)); } [Theory] [InlineData(EnvironmentVariableTarget.Process)] [InlineData(EnvironmentVariableTarget.Machine)] [InlineData(EnvironmentVariableTarget.User)] public void EnumerateYieldsDictionaryEntryFromIEnumerable(EnvironmentVariableTarget target) { // GetEnvironmentVariables has always yielded DictionaryEntry from IEnumerable IDictionary vars = Environment.GetEnvironmentVariables(target); IEnumerator enumerator = ((IEnumerable)vars).GetEnumerator(); if (enumerator.MoveNext()) { Assert.IsType<DictionaryEntry>(enumerator.Current); } else { Assert.Throws<InvalidOperationException>(() => enumerator.Current); } } [Theory] [InlineData(EnvironmentVariableTarget.Process)] [InlineData(EnvironmentVariableTarget.Machine)] [InlineData(EnvironmentVariableTarget.User)] public void EnumerateEnvironmentVariables(EnvironmentVariableTarget target) { bool lookForSetValue = (target == EnvironmentVariableTarget.Process) || PlatformDetection.IsWindowsAndElevated; string key = $"EnumerateEnvironmentVariables ({target})"; string value = Path.GetRandomFileName(); try { if (lookForSetValue) { Environment.SetEnvironmentVariable(key, value, target); Assert.Equal(value, Environment.GetEnvironmentVariable(key, target)); } IDictionary results = Environment.GetEnvironmentVariables(target); // Ensure we can walk through the results IDictionaryEnumerator enumerator = results.GetEnumerator(); while (enumerator.MoveNext()) { Assert.NotNull(enumerator.Entry); } if (lookForSetValue) { // Ensure that we got our flagged value out Assert.Equal(value, results[key]); } } finally { if (lookForSetValue) { Environment.SetEnvironmentVariable(key, null, target); Assert.Null(Environment.GetEnvironmentVariable(key, target)); } } } private static void SetEnvironmentVariableWithPInvoke(string name, string value) { bool success = #if !Unix SetEnvironmentVariable(name, value); #else (value != null ? setenv(name, value, 1) : unsetenv(name)) == 0; #endif Assert.True(success); } [DllImport("kernel32.dll", EntryPoint = "SetEnvironmentVariableW" , CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool SetEnvironmentVariable(string lpName, string lpValue); #if Unix [DllImport("libc")] private static extern int setenv(string name, string value, int overwrite); [DllImport("libc")] private static extern int unsetenv(string name); #endif } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCustomerClientLinkServiceClientTest { [Category("Autogenerated")][Test] public void GetCustomerClientLinkRequestObject() { moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient>(moq::MockBehavior.Strict); GetCustomerClientLinkRequest request = new GetCustomerClientLinkRequest { ResourceNameAsCustomerClientLinkName = gagvr::CustomerClientLinkName.FromCustomerClientCustomerManagerLink("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), }; gagvr::CustomerClientLink expectedResponse = new gagvr::CustomerClientLink { ResourceNameAsCustomerClientLinkName = gagvr::CustomerClientLinkName.FromCustomerClientCustomerManagerLink("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), Status = gagve::ManagerLinkStatusEnum.Types.ManagerLinkStatus.Inactive, ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), ManagerLinkId = 1955158851327798968L, Hidden = true, }; mockGrpcClient.Setup(x => x.GetCustomerClientLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerClientLinkServiceClient client = new CustomerClientLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerClientLink response = client.GetCustomerClientLink(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerClientLinkRequestObjectAsync() { moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient>(moq::MockBehavior.Strict); GetCustomerClientLinkRequest request = new GetCustomerClientLinkRequest { ResourceNameAsCustomerClientLinkName = gagvr::CustomerClientLinkName.FromCustomerClientCustomerManagerLink("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), }; gagvr::CustomerClientLink expectedResponse = new gagvr::CustomerClientLink { ResourceNameAsCustomerClientLinkName = gagvr::CustomerClientLinkName.FromCustomerClientCustomerManagerLink("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), Status = gagve::ManagerLinkStatusEnum.Types.ManagerLinkStatus.Inactive, ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), ManagerLinkId = 1955158851327798968L, Hidden = true, }; mockGrpcClient.Setup(x => x.GetCustomerClientLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerClientLink>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerClientLinkServiceClient client = new CustomerClientLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerClientLink responseCallSettings = await client.GetCustomerClientLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerClientLink responseCancellationToken = await client.GetCustomerClientLinkAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomerClientLink() { moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient>(moq::MockBehavior.Strict); GetCustomerClientLinkRequest request = new GetCustomerClientLinkRequest { ResourceNameAsCustomerClientLinkName = gagvr::CustomerClientLinkName.FromCustomerClientCustomerManagerLink("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), }; gagvr::CustomerClientLink expectedResponse = new gagvr::CustomerClientLink { ResourceNameAsCustomerClientLinkName = gagvr::CustomerClientLinkName.FromCustomerClientCustomerManagerLink("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), Status = gagve::ManagerLinkStatusEnum.Types.ManagerLinkStatus.Inactive, ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), ManagerLinkId = 1955158851327798968L, Hidden = true, }; mockGrpcClient.Setup(x => x.GetCustomerClientLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerClientLinkServiceClient client = new CustomerClientLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerClientLink response = client.GetCustomerClientLink(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerClientLinkAsync() { moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient>(moq::MockBehavior.Strict); GetCustomerClientLinkRequest request = new GetCustomerClientLinkRequest { ResourceNameAsCustomerClientLinkName = gagvr::CustomerClientLinkName.FromCustomerClientCustomerManagerLink("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), }; gagvr::CustomerClientLink expectedResponse = new gagvr::CustomerClientLink { ResourceNameAsCustomerClientLinkName = gagvr::CustomerClientLinkName.FromCustomerClientCustomerManagerLink("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), Status = gagve::ManagerLinkStatusEnum.Types.ManagerLinkStatus.Inactive, ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), ManagerLinkId = 1955158851327798968L, Hidden = true, }; mockGrpcClient.Setup(x => x.GetCustomerClientLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerClientLink>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerClientLinkServiceClient client = new CustomerClientLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerClientLink responseCallSettings = await client.GetCustomerClientLinkAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerClientLink responseCancellationToken = await client.GetCustomerClientLinkAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomerClientLinkResourceNames() { moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient>(moq::MockBehavior.Strict); GetCustomerClientLinkRequest request = new GetCustomerClientLinkRequest { ResourceNameAsCustomerClientLinkName = gagvr::CustomerClientLinkName.FromCustomerClientCustomerManagerLink("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), }; gagvr::CustomerClientLink expectedResponse = new gagvr::CustomerClientLink { ResourceNameAsCustomerClientLinkName = gagvr::CustomerClientLinkName.FromCustomerClientCustomerManagerLink("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), Status = gagve::ManagerLinkStatusEnum.Types.ManagerLinkStatus.Inactive, ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), ManagerLinkId = 1955158851327798968L, Hidden = true, }; mockGrpcClient.Setup(x => x.GetCustomerClientLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerClientLinkServiceClient client = new CustomerClientLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerClientLink response = client.GetCustomerClientLink(request.ResourceNameAsCustomerClientLinkName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerClientLinkResourceNamesAsync() { moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient>(moq::MockBehavior.Strict); GetCustomerClientLinkRequest request = new GetCustomerClientLinkRequest { ResourceNameAsCustomerClientLinkName = gagvr::CustomerClientLinkName.FromCustomerClientCustomerManagerLink("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), }; gagvr::CustomerClientLink expectedResponse = new gagvr::CustomerClientLink { ResourceNameAsCustomerClientLinkName = gagvr::CustomerClientLinkName.FromCustomerClientCustomerManagerLink("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), Status = gagve::ManagerLinkStatusEnum.Types.ManagerLinkStatus.Inactive, ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), ManagerLinkId = 1955158851327798968L, Hidden = true, }; mockGrpcClient.Setup(x => x.GetCustomerClientLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerClientLink>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerClientLinkServiceClient client = new CustomerClientLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerClientLink responseCallSettings = await client.GetCustomerClientLinkAsync(request.ResourceNameAsCustomerClientLinkName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerClientLink responseCancellationToken = await client.GetCustomerClientLinkAsync(request.ResourceNameAsCustomerClientLinkName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomerClientLinkRequestObject() { moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient>(moq::MockBehavior.Strict); MutateCustomerClientLinkRequest request = new MutateCustomerClientLinkRequest { CustomerId = "customer_id3b3724cb", Operation = new CustomerClientLinkOperation(), ValidateOnly = true, }; MutateCustomerClientLinkResponse expectedResponse = new MutateCustomerClientLinkResponse { Result = new MutateCustomerClientLinkResult(), }; mockGrpcClient.Setup(x => x.MutateCustomerClientLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerClientLinkServiceClient client = new CustomerClientLinkServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerClientLinkResponse response = client.MutateCustomerClientLink(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomerClientLinkRequestObjectAsync() { moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient>(moq::MockBehavior.Strict); MutateCustomerClientLinkRequest request = new MutateCustomerClientLinkRequest { CustomerId = "customer_id3b3724cb", Operation = new CustomerClientLinkOperation(), ValidateOnly = true, }; MutateCustomerClientLinkResponse expectedResponse = new MutateCustomerClientLinkResponse { Result = new MutateCustomerClientLinkResult(), }; mockGrpcClient.Setup(x => x.MutateCustomerClientLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerClientLinkResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerClientLinkServiceClient client = new CustomerClientLinkServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerClientLinkResponse responseCallSettings = await client.MutateCustomerClientLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomerClientLinkResponse responseCancellationToken = await client.MutateCustomerClientLinkAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomerClientLink() { moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient>(moq::MockBehavior.Strict); MutateCustomerClientLinkRequest request = new MutateCustomerClientLinkRequest { CustomerId = "customer_id3b3724cb", Operation = new CustomerClientLinkOperation(), }; MutateCustomerClientLinkResponse expectedResponse = new MutateCustomerClientLinkResponse { Result = new MutateCustomerClientLinkResult(), }; mockGrpcClient.Setup(x => x.MutateCustomerClientLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerClientLinkServiceClient client = new CustomerClientLinkServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerClientLinkResponse response = client.MutateCustomerClientLink(request.CustomerId, request.Operation); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomerClientLinkAsync() { moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerClientLinkService.CustomerClientLinkServiceClient>(moq::MockBehavior.Strict); MutateCustomerClientLinkRequest request = new MutateCustomerClientLinkRequest { CustomerId = "customer_id3b3724cb", Operation = new CustomerClientLinkOperation(), }; MutateCustomerClientLinkResponse expectedResponse = new MutateCustomerClientLinkResponse { Result = new MutateCustomerClientLinkResult(), }; mockGrpcClient.Setup(x => x.MutateCustomerClientLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerClientLinkResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerClientLinkServiceClient client = new CustomerClientLinkServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerClientLinkResponse responseCallSettings = await client.MutateCustomerClientLinkAsync(request.CustomerId, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomerClientLinkResponse responseCancellationToken = await client.MutateCustomerClientLinkAsync(request.CustomerId, request.Operation, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
//------------------------------------------------------------------------------ // <copyright file="MessageEnumerator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Messaging { using System.Diagnostics; using System; using System.ComponentModel; using System.Collections; using System.Messaging.Interop; /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator"]/*' /> /// <devdoc> /// <para>Provides (forward-only) /// cursor semantics to enumerate the messages contained in /// a queue.</para> /// <note type="rnotes"> /// Translate into English? /// </note> /// </devdoc> public class MessageEnumerator : MarshalByRefObject, IEnumerator, IDisposable { private MessageQueue owner; private CursorHandle handle = System.Messaging.Interop.CursorHandle.NullHandle; private int index = 0; private bool disposed = false; private bool useCorrectRemoveCurrent = false; //needed in fix for 88615 internal MessageEnumerator(MessageQueue owner, bool useCorrectRemoveCurrent) { this.owner = owner; this.useCorrectRemoveCurrent = useCorrectRemoveCurrent; } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.Current"]/*' /> /// <devdoc> /// <para>Gets the current <see cref='System.Messaging.Message'/> pointed to /// by this enumerator.</para> /// </devdoc> public Message Current { get { if (this.index == 0) throw new InvalidOperationException(Res.GetString(Res.NoCurrentMessage)); return this.owner.ReceiveCurrent(TimeSpan.Zero, NativeMethods.QUEUE_ACTION_PEEK_CURRENT, this.Handle, this.owner.MessageReadPropertyFilter, null, MessageQueueTransactionType.None); } } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.IEnumerator.Current"]/*' /> /// <internalonly/> object IEnumerator.Current { get { return this.Current; } } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.CursorHandle"]/*' /> /// <devdoc> /// <para>Gets the native Message Queuing cursor handle used to browse messages /// in the queue.</para> /// </devdoc> public IntPtr CursorHandle { get { return this.Handle.DangerousGetHandle(); } } internal CursorHandle Handle { get { //Cursor handle doesn't demand permissions since GetEnumerator will demand somehow. if (this.handle.IsInvalid) { //Cannot allocate the a new cursor if the object has been disposed, since finalization has been suppressed. if (this.disposed) throw new ObjectDisposedException(GetType().Name); CursorHandle result; int status = SafeNativeMethods.MQCreateCursor(this.owner.MQInfo.ReadHandle, out result); if (MessageQueue.IsFatalError(status)) throw new MessageQueueException(status); this.handle = result; } return this.handle; } } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.Close"]/*' /> /// <devdoc> /// <para> /// Frees the resources associated with the enumerator. /// </para> /// </devdoc> public void Close() { this.index = 0; if (!this.handle.IsInvalid) { this.handle.Close(); } } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.Dispose"]/*' /> /// <devdoc> /// </devdoc> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed")] public void Dispose() { Dispose(true); } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.Dispose1"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> protected virtual void Dispose(bool disposing) { if (disposing) { this.Close(); } this.disposed = true; } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.MoveNext"]/*' /> /// <devdoc> /// <para>Advances the enumerator to the next message in the queue, if one /// is currently available.</para> /// </devdoc> public bool MoveNext() { return MoveNext(TimeSpan.Zero); } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.MoveNext1"]/*' /> /// <devdoc> /// <para>Advances the enumerator to the next message in the /// queue. If the enumerator is positioned at the end of the queue, <see cref='System.Messaging.MessageEnumerator.MoveNext'/> waits until a message is available or the /// given <paramref name="timeout"/> /// expires.</para> /// </devdoc> public unsafe bool MoveNext(TimeSpan timeout) { long timeoutInMilliseconds = (long)timeout.TotalMilliseconds; if (timeoutInMilliseconds < 0 || timeoutInMilliseconds > UInt32.MaxValue) throw new ArgumentException(Res.GetString(Res.InvalidParameter, "timeout", timeout.ToString())); int status = 0; int action = NativeMethods.QUEUE_ACTION_PEEK_NEXT; //Peek current or next? if (this.index == 0) action = NativeMethods.QUEUE_ACTION_PEEK_CURRENT; status = owner.StaleSafeReceiveMessage((uint)timeoutInMilliseconds, action, null, null, null, this.Handle, (IntPtr)NativeMethods.QUEUE_TRANSACTION_NONE); //If the cursor reached the end of the queue. if (status == (int)MessageQueueErrorCode.IOTimeout) { this.Close(); return false; } //If all messages were removed. else if (status == (int)MessageQueueErrorCode.IllegalCursorAction) { this.index = 0; this.Close(); return false; } if (MessageQueue.IsFatalError(status)) throw new MessageQueueException(status); ++this.index; return true; } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.RemoveCurrent"]/*' /> /// <devdoc> /// <para> Removes the current message from /// the queue and returns the message to the calling application.</para> /// </devdoc> public Message RemoveCurrent() { return RemoveCurrent(TimeSpan.Zero, null, MessageQueueTransactionType.None); } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.RemoveCurrent1"]/*' /> /// <devdoc> /// <para> Removes the current message from /// the queue and returns the message to the calling application.</para> /// </devdoc> public Message RemoveCurrent(MessageQueueTransaction transaction) { if (transaction == null) throw new ArgumentNullException("transaction"); return RemoveCurrent(TimeSpan.Zero, transaction, MessageQueueTransactionType.None); } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.RemoveCurrent5"]/*' /> /// <devdoc> /// <para> Removes the current message from /// the queue and returns the message to the calling application.</para> /// </devdoc> public Message RemoveCurrent(MessageQueueTransactionType transactionType) { if (!ValidationUtility.ValidateMessageQueueTransactionType(transactionType)) throw new InvalidEnumArgumentException("transactionType", (int)transactionType, typeof(MessageQueueTransactionType)); return RemoveCurrent(TimeSpan.Zero, null, transactionType); } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.RemoveCurrent2"]/*' /> /// <devdoc> /// <para> Removes the current message from /// the queue and returns the message to the calling application within the timeout specified.</para> /// </devdoc> public Message RemoveCurrent(TimeSpan timeout) { return RemoveCurrent(timeout, null, MessageQueueTransactionType.None); } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.RemoveCurrent3"]/*' /> /// <devdoc> /// <para> Removes the current message from /// the queue and returns the message to the calling application within the timeout specified.</para> /// </devdoc> public Message RemoveCurrent(TimeSpan timeout, MessageQueueTransaction transaction) { if (transaction == null) throw new ArgumentNullException("transaction"); return RemoveCurrent(timeout, transaction, MessageQueueTransactionType.None); } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.RemoveCurrent4"]/*' /> /// <devdoc> /// <para> Removes the current message from /// the queue and returns the message to the calling application within the timeout specified.</para> /// </devdoc> public Message RemoveCurrent(TimeSpan timeout, MessageQueueTransactionType transactionType) { if (!ValidationUtility.ValidateMessageQueueTransactionType(transactionType)) throw new InvalidEnumArgumentException("transactionType", (int)transactionType, typeof(MessageQueueTransactionType)); return RemoveCurrent(timeout, null, transactionType); } private Message RemoveCurrent(TimeSpan timeout, MessageQueueTransaction transaction, MessageQueueTransactionType transactionType) { long timeoutInMilliseconds = (long)timeout.TotalMilliseconds; if (timeoutInMilliseconds < 0 || timeoutInMilliseconds > UInt32.MaxValue) throw new ArgumentException(Res.GetString(Res.InvalidParameter, "timeout", timeout.ToString())); if (this.index == 0) return null; Message message = this.owner.ReceiveCurrent(timeout, NativeMethods.QUEUE_ACTION_RECEIVE, this.Handle, this.owner.MessageReadPropertyFilter, transaction, transactionType); if (!useCorrectRemoveCurrent) --this.index; return message; } /// <include file='doc\MessageEnumerator.uex' path='docs/doc[@for="MessageEnumerator.Reset"]/*' /> /// <devdoc> /// <para> Resets the current enumerator, so it points to /// the head of the queue.</para> /// </devdoc> public void Reset() { this.Close(); } } }
// <copyright file="StreamPipeWriterService.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.Buffers; using System.IO; using System.IO.Pipelines; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace FubarDev.FtpServer.Networking { /// <summary> /// Reads from a pipe and writes to a stream. /// </summary> internal class StreamPipeWriterService : PausableFtpService { private readonly PipeReader _pipeReader; private Exception? _exception; /// <summary> /// Initializes a new instance of the <see cref="StreamPipeWriterService"/> class. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="pipeReader">The pipe to read from.</param> /// <param name="connectionClosed">Cancellation token for a closed connection.</param> /// <param name="logger">The logger.</param> public StreamPipeWriterService( Stream stream, PipeReader pipeReader, CancellationToken connectionClosed, ILogger? logger = null) : base(connectionClosed, logger) { Stream = stream; _pipeReader = pipeReader; } /// <summary> /// Gets the stream used to write the output. /// </summary> protected Stream Stream { get; } /// <inheritdoc /> public override async Task StopAsync(CancellationToken cancellationToken) { await base.StopAsync(cancellationToken) .ConfigureAwait(false); await SafeFlushAsync(cancellationToken) .ConfigureAwait(false); await OnCloseAsync(_exception, cancellationToken) .ConfigureAwait(false); } /// <inheritdoc /> protected override async Task ExecuteAsync(CancellationToken cancellationToken) { while (true) { Logger?.LogTrace("Start reading response"); var readResult = await _pipeReader.ReadAsync(cancellationToken) .ConfigureAwait(false); try { // Don't use the cancellation token source from above. Otherwise // data might be lost. await SendDataToStream(readResult.Buffer, CancellationToken.None) .ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "Sending data failed {ErrorMessage}", ex.Message); // Ensure that the read operation is finished, but keep the data. _pipeReader.AdvanceTo(readResult.Buffer.Start); throw; } _pipeReader.AdvanceTo(readResult.Buffer.End); if (readResult.IsCanceled || readResult.IsCompleted) { Logger?.LogTrace("Was cancelled or completed"); break; } } } /// <inheritdoc /> protected override Task OnPausedAsync(CancellationToken cancellationToken) { return SafeFlushAsync(cancellationToken); } /// <inheritdoc /> protected override async Task<bool> OnFailedAsync(Exception exception, CancellationToken cancellationToken) { // Error, but paused? Don't close the pipe! if (IsPauseRequested) { return false; } // Do whatever the base class wants to do. await base.OnFailedAsync(exception, cancellationToken) .ConfigureAwait(false); // Remember exception _exception = exception; return true; } /// <summary> /// Called when the stream is closed. /// </summary> /// <param name="exception">The exception that occurred during the operation.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The task.</returns> protected virtual Task OnCloseAsync(Exception? exception, CancellationToken cancellationToken) { // Tell the PipeReader that there's no more data coming _pipeReader.Complete(exception); return Task.CompletedTask; } /// <summary> /// Writes data to the stream. /// </summary> /// <param name="buffer">The buffer containing the data.</param> /// <param name="offset">The offset into the buffer.</param> /// <param name="length">The length of the data to send.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The task.</returns> protected virtual Task WriteToStreamAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { return Stream.WriteAsync(buffer, offset, length, cancellationToken); } private async Task FlushAsync( CancellationToken cancellationToken) { Logger?.LogTrace("Flushing"); while (!cancellationToken.IsCancellationRequested && _pipeReader.TryRead(out var readResult)) { try { await SendDataToStream(readResult.Buffer, CancellationToken.None) .ConfigureAwait(false); } finally { // Always advance to the end, because the data cannot // be sent anyways. _pipeReader.AdvanceTo(readResult.Buffer.End); } if (readResult.IsCanceled || readResult.IsCompleted) { break; } } Logger?.LogTrace("Flushed"); } private async Task SendDataToStream( ReadOnlySequence<byte> buffer, CancellationToken cancellationToken) { Logger?.LogTrace("Start sending"); var position = buffer.Start; while (buffer.TryGet(ref position, out var memory)) { var streamBuffer = memory.ToArray(); await WriteToStreamAsync(streamBuffer, 0, streamBuffer.Length, cancellationToken) .ConfigureAwait(false); } Logger?.LogTrace("Flushing stream"); await Stream.FlushAsync(cancellationToken).ConfigureAwait(false); } private async Task SafeFlushAsync(CancellationToken cancellationToken) { try { if (!cancellationToken.IsCancellationRequested) { await FlushAsync(cancellationToken).ConfigureAwait(false); } } catch (Exception ex) when (ex.Is<IOException>()) { // Ignored. Connection closed by client? } catch (Exception ex) when (ex.Is<OperationCanceledException>()) { // Ignored. Connection closed by server? } catch (Exception ex) { Logger?.LogWarning(0, ex, "Flush failed with: {message}", ex.Message); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Sep.Git.Tfs.Commands; using Sep.Git.Tfs.Core.TfsInterop; namespace Sep.Git.Tfs.Core { public class GitTfsRemote : IGitTfsRemote { private static readonly Regex isInDotGit = new Regex("(?:^|/)\\.git(?:/|$)"); private static readonly Regex treeShaRegex = new Regex("^tree (" + GitTfsConstants.Sha1 + ")"); private readonly Globals globals; private readonly TextWriter stdout; private readonly RemoteOptions remoteOptions; private long? maxChangesetId; private string maxCommitHash; public GitTfsRemote(RemoteOptions remoteOptions, Globals globals, ITfsHelper tfsHelper, TextWriter stdout) { this.remoteOptions = remoteOptions; this.globals = globals; this.stdout = stdout; Tfs = tfsHelper; } public void EnsureTfsAuthenticated() { Tfs.EnsureAuthenticated(); } public bool IsDerived { get { return false; } } public string Id { get; set; } public string TfsUrl { get { return Tfs.Url; } set { Tfs.Url = value; } } public bool Autotag { get; set; } public string TfsUsername { get { return Tfs.Username; } set { Tfs.Username = value; } } public string TfsPassword { get { return Tfs.Password; } set { Tfs.Password = value; } } public string TfsRepositoryPath { get; set; } public string IgnoreRegexExpression { get; set; } public IGitRepository Repository { get; set; } public ITfsHelper Tfs { get; set; } public long MaxChangesetId { get { InitHistory(); return maxChangesetId.Value; } set { maxChangesetId = value; } } public string MaxCommitHash { get { InitHistory(); return maxCommitHash; } set { maxCommitHash = value; } } private void InitHistory() { if (maxChangesetId == null) { var mostRecentUpdate = Repository.GetLastParentTfsCommits(RemoteRef).FirstOrDefault(); if (mostRecentUpdate != null) { MaxCommitHash = mostRecentUpdate.GitCommit; MaxChangesetId = mostRecentUpdate.ChangesetId; } else { MaxChangesetId = 0; } } } private string Dir { get { return Ext.CombinePaths(globals.GitDir, "tfs", Id); } } private string IndexFile { get { return Path.Combine(Dir, "index"); } } private string WorkingDirectory { get { return Path.Combine(Dir, "workspace"); } } public void CleanupWorkspace() { Tfs.CleanupWorkspaces(WorkingDirectory); } public bool ShouldSkip(string path) { return IsInDotGit(path) || IsIgnored(path, IgnoreRegexExpression) || IsIgnored(path, remoteOptions.IgnoreRegex); } private bool IsIgnored(string path, string expression) { return expression != null && new Regex(expression).IsMatch(path); } private bool IsInDotGit(string path) { return isInDotGit.IsMatch(path); } public string GetPathInGitRepo(string tfsPath) { if (tfsPath == null) return null; if(!tfsPath.StartsWith(TfsRepositoryPath,StringComparison.InvariantCultureIgnoreCase)) return null; tfsPath = tfsPath.Substring(TfsRepositoryPath.Length); while (tfsPath.StartsWith("/")) tfsPath = tfsPath.Substring(1); return tfsPath; } public void Fetch() { FetchWithMerge(-1); } public void FetchWithMerge(long mergeChangesetId, params string[] parentCommitsHashes) { foreach (var changeset in FetchChangesets()) { AssertTemporaryIndexClean(MaxCommitHash); var log = Apply(MaxCommitHash, changeset); if (changeset.Summary.ChangesetId == mergeChangesetId) { foreach (var parent in parentCommitsHashes) { log.CommitParents.Add(parent); } } UpdateRef(Commit(log), changeset.Summary.ChangesetId); DoGcIfNeeded(); } } public void Apply(ITfsChangeset changeset, string destinationRef) { var log = Apply(MaxCommitHash, changeset); var commit = Commit(log); Repository.CommandNoisy("update-ref", destinationRef, commit); } public void QuickFetch() { var changeset = Tfs.GetLatestChangeset(this); quickFetch(changeset); } public void QuickFetch(int changesetId) { var changeset = Tfs.GetChangeset(changesetId, this); quickFetch(changeset); } private void quickFetch(ITfsChangeset changeset) { AssertTemporaryIndexEmpty(); var log = CopyTree(MaxCommitHash, changeset); UpdateRef(Commit(log), changeset.Summary.ChangesetId); DoGcIfNeeded(); } private IEnumerable<ITfsChangeset> FetchChangesets() { Trace.WriteLine(RemoteRef + ": Getting changesets from " + (MaxChangesetId + 1) + " to current ...", "info"); // TFS 2010 doesn't like when we ask for history past its last changeset. if (MaxChangesetId == Tfs.GetLatestChangeset(this).Summary.ChangesetId) return Enumerable.Empty<ITfsChangeset>(); return Tfs.GetChangesets(TfsRepositoryPath, MaxChangesetId + 1, this); } public ITfsChangeset GetChangeset(long changesetId) { return Tfs.GetChangeset((int) changesetId, this); } public void UpdateRef(string commitHash, long changesetId) { MaxCommitHash = commitHash; MaxChangesetId = changesetId; Repository.CommandNoisy("update-ref", "-m", "C" + MaxChangesetId, RemoteRef, MaxCommitHash); if (Autotag) Repository.CommandNoisy("update-ref", TagPrefix + "C" + MaxChangesetId, MaxCommitHash); LogCurrentMapping(); } private void LogCurrentMapping() { stdout.WriteLine("C" + MaxChangesetId + " = " + MaxCommitHash); } private string TagPrefix { get { return "refs/tags/tfs/" + Id + "/"; } } public string RemoteRef { get { return "refs/remotes/tfs/" + Id; } } private void DoGcIfNeeded() { Trace.WriteLine("GC Countdown: " + globals.GcCountdown); if(--globals.GcCountdown < 0) { globals.GcCountdown = globals.GcPeriod; try { Repository.CommandNoisy("gc", "--auto"); } catch(Exception e) { Trace.WriteLine(e); stdout.WriteLine("Warning: `git gc` failed! Try running it after git-tfs is finished."); } } } private void AssertTemporaryIndexClean(string treeish) { if(string.IsNullOrEmpty(treeish)) { AssertTemporaryIndexEmpty(); return; } WithTemporaryIndex(() => AssertIndexClean(treeish)); } private void AssertTemporaryIndexEmpty() { if (File.Exists(IndexFile)) File.Delete(IndexFile); } private void AssertIndexClean(string treeish) { if (!File.Exists(IndexFile)) Repository.CommandNoisy("read-tree", treeish); var currentTree = Repository.CommandOneline("write-tree"); var expectedCommitInfo = Repository.Command("cat-file", "commit", treeish); var expectedCommitTree = treeShaRegex.Match(expectedCommitInfo).Groups[1].Value; if (expectedCommitTree != currentTree) { Trace.WriteLine("Index mismatch: " + expectedCommitTree + " != " + currentTree); Trace.WriteLine("rereading " + treeish); File.Delete(IndexFile); Repository.CommandNoisy("read-tree", treeish); currentTree = Repository.CommandOneline("write-tree"); if (expectedCommitTree != currentTree) { throw new Exception("Unable to create a clean temporary index: trees (" + treeish + ") " + expectedCommitTree + " != " + currentTree); } } } private LogEntry Apply(string lastCommit, ITfsChangeset changeset) { LogEntry result = null; WithTemporaryIndex( () => GitIndexInfo.Do(Repository, index => result = changeset.Apply(lastCommit, index))); WithTemporaryIndex( () => result.Tree = Repository.CommandOneline("write-tree")); if(!String.IsNullOrEmpty(lastCommit)) result.CommitParents.Add(lastCommit); return result; } private LogEntry CopyTree(string lastCommit, ITfsChangeset changeset) { LogEntry result = null; WithTemporaryIndex( () => GitIndexInfo.Do(Repository, index => result = changeset.CopyTree(index))); WithTemporaryIndex( () => result.Tree = Repository.CommandOneline("write-tree")); if (!String.IsNullOrEmpty(lastCommit)) result.CommitParents.Add(lastCommit); return result; } private string Commit(LogEntry logEntry) { string commitHash = null; WithCommitHeaderEnv(logEntry, () => commitHash = WriteCommit(logEntry)); // TODO (maybe): StoreChangesetMetadata(commitInfo); return commitHash; } private string WriteCommit(LogEntry logEntry) { // TODO (maybe): encode logEntry.Log according to 'git config --get i18n.commitencoding', if specified //var commitEncoding = Repository.CommandOneline("config", "i18n.commitencoding"); //var encoding = LookupEncoding(commitEncoding) ?? Encoding.UTF8; string commitHash = null; Repository.CommandInputOutputPipe((procIn, procOut) => { procIn.WriteLine(logEntry.Log); procIn.WriteLine(GitTfsConstants.TfsCommitInfoFormat, TfsUrl, TfsRepositoryPath, logEntry.ChangesetId); procIn.Close(); commitHash = ParseCommitInfo(procOut.ReadToEnd()); }, BuildCommitCommand(logEntry)); return commitHash; } private string[] BuildCommitCommand(LogEntry logEntry) { var tree = logEntry.Tree ?? GetTemporaryIndexTreeSha(); tree.AssertValidSha(); var commitCommand = new List<string> { "commit-tree", tree }; foreach (var parent in logEntry.CommitParents) { commitCommand.Add("-p"); commitCommand.Add(parent); } return commitCommand.ToArray(); } private string GetTemporaryIndexTreeSha() { string tree = null; WithTemporaryIndex(() => tree = Repository.CommandOneline("write-tree")); return tree; } private string ParseCommitInfo(string commitTreeOutput) { return commitTreeOutput.Trim(); } //private Encoding LookupEncoding(string encoding) //{ // if(encoding == null) // return null; // throw new NotImplementedException("Need to implement encoding lookup for " + encoding); //} private void WithCommitHeaderEnv(LogEntry logEntry, Action action) { WithTemporaryEnvironment(action, new Dictionary<string, string> { {"GIT_AUTHOR_NAME", logEntry.AuthorName}, {"GIT_AUTHOR_EMAIL", logEntry.AuthorEmail}, {"GIT_AUTHOR_DATE", logEntry.Date.FormatForGit()}, {"GIT_COMMITTER_DATE", logEntry.Date.FormatForGit()}, {"GIT_COMMITTER_NAME", logEntry.CommitterName ?? logEntry.AuthorName}, {"GIT_COMMITTER_EMAIL", logEntry.CommitterEmail ?? logEntry.AuthorEmail} }); } private void WithTemporaryIndex(Action action) { WithTemporaryEnvironment(() => { Directory.CreateDirectory(Path.GetDirectoryName(IndexFile)); action(); }, new Dictionary<string, string> {{"GIT_INDEX_FILE", IndexFile}}); } private void WithTemporaryEnvironment(Action action, IDictionary<string, string> newEnvironment) { var oldEnvironment = new Dictionary<string, string>(); PushEnvironment(newEnvironment, oldEnvironment); try { action(); } finally { PushEnvironment(oldEnvironment); } } private void PushEnvironment(IDictionary<string, string> desiredEnvironment) { PushEnvironment(desiredEnvironment, new Dictionary<string, string>()); } private void PushEnvironment(IDictionary<string, string> desiredEnvironment, IDictionary<string, string> oldEnvironment) { foreach(var key in desiredEnvironment.Keys) { oldEnvironment[key] = Environment.GetEnvironmentVariable(key); Environment.SetEnvironmentVariable(key, desiredEnvironment[key]); } } public void Unshelve(string shelvesetOwner, string shelvesetName, string destinationBranch) { var destinationRef = "refs/heads/" + destinationBranch; if (File.Exists(Path.Combine(Repository.GitDir, destinationRef))) throw new GitTfsException("ERROR: Destination branch (" + destinationBranch + ") already exists!"); var shelvesetChangeset = Tfs.GetShelvesetData(this, shelvesetOwner, shelvesetName); Apply(shelvesetChangeset, destinationRef); } public void Shelve(string shelvesetName, string head, TfsChangesetInfo parentChangeset, bool evaluateCheckinPolicies) { Tfs.WithWorkspace(WorkingDirectory, this, parentChangeset, workspace => Shelve(shelvesetName, head, parentChangeset, evaluateCheckinPolicies, workspace)); } public bool HasShelveset(string shelvesetName) { return Tfs.HasShelveset(shelvesetName); } private void Shelve(string shelvesetName, string head, TfsChangesetInfo parentChangeset, bool evaluateCheckinPolicies, ITfsWorkspace workspace) { PendChangesToWorkspace(head, parentChangeset.GitCommit, workspace); workspace.Shelve(shelvesetName, evaluateCheckinPolicies); } public long CheckinTool(string head, TfsChangesetInfo parentChangeset) { var changeset = 0L; Tfs.WithWorkspace(WorkingDirectory, this, parentChangeset, workspace => changeset = CheckinTool(head, parentChangeset, workspace)); return changeset; } private long CheckinTool(string head, TfsChangesetInfo parentChangeset, ITfsWorkspace workspace) { PendChangesToWorkspace(head, parentChangeset.GitCommit, workspace); return workspace.CheckinTool(() => Repository.GetCommitMessage(head, parentChangeset.GitCommit)); } private void PendChangesToWorkspace(string head, string parent, ITfsWorkspace workspace) { foreach (var change in Repository.GetChangedFiles(parent, head)) { change.Apply(workspace); } } public long Checkin(string head, TfsChangesetInfo parentChangeset) { var changeset = 0L; Tfs.WithWorkspace(WorkingDirectory, this, parentChangeset, workspace => changeset = Checkin(head, parentChangeset.GitCommit, workspace)); return changeset; } public long Checkin(string head, string parent, TfsChangesetInfo parentChangeset) { var changeset = 0L; Tfs.WithWorkspace(WorkingDirectory, this, parentChangeset, workspace => changeset = Checkin(head, parent, workspace)); return changeset; } private long Checkin(string head, string parent, ITfsWorkspace workspace) { PendChangesToWorkspace(head, parent, workspace); return workspace.Checkin(); } } }
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using NUnit.Framework; using XenAdmin; using System.Linq; using System.Collections.Generic; using System; namespace XenAdminTests.UnitTests.MiscTests { [TestFixture, Category(TestCategories.Unit)] internal class UtilTests { #region Test Data private Dictionary<double, string[]> memoryMBpairs = new Dictionary<double, string[]> { { 0, new[] { "0", "MB" } }, { 1, new[] { "0", "MB" } }, { 1024, new[] { "0", "MB" } }, { 100000, new[] { "0", "MB" } }, { 1048576, new[] { "1", "MB" } }, //1024*1024 { 2100000, new[] { "2", "MB" } }, { 2900000, new[] { "3", "MB" } }, { 1073741824, new[] { "1024", "MB" } }, //1024*1024*1024 { 2100000000, new[] { "2003", "MB" } }, }; private Dictionary<double, string[]> memoryVariousPairs = new Dictionary<double, string[]> { { 0, new[] { "0", "B" } }, { 1000, new[] { "1000", "B" } }, { 1024, new[] { "1", "kB" } }, { 100000, new[] { "98", "kB" } }, { 1000000, new[] { "977", "kB" } }, { 1048576, new[] { "1", "MB" } }, //1024*1024 { 2100000, new[] { "2", "MB" } }, { 2900000, new[] { "3", "MB" } }, { 1073741824, new[] { "1", "GB" } }, //1024*1024*1024 { 2100000000, new[] { "2", "GB" } }, { 2900000000, new[] { "3", "GB" } } }; private Dictionary<double, string[]> dataRatePairs = new Dictionary<double, string[]> { { 0, new[] { "0", "Bps" } }, { 1000, new[] { "1000", "Bps" } }, { 1024, new[] { "1", "kBps" } }, { 100000, new[] { "97.7", "kBps" } }, { 1000000, new[] { "976.6", "kBps" } }, { 1048576, new[] { "1", "MBps" } }, //1024*1024 { 2100000, new[] { "2", "MBps" } }, { 2900000, new[] { "2.8", "MBps" } }, { 1073741824, new[] { "1", "GBps" } }, //1024*1024*1024 { 2100000000, new[] { "2", "GBps" } }, { 2900000000, new[] { "2.7", "GBps" } } }; private Dictionary<double, string[]> nanoSecPairs = new Dictionary<double, string[]> { { 0, new[] { "0", "ns" } }, { 1, new[] { "1", "ns" } }, { 1.1, new[] { "1", "ns" } }, { 1.5, new[] { "2", "ns" } }, { 1.9, new[] { "2", "ns" } }, { 12, new[] { "12", "ns" } }, { 1100, new[] { "1", '\u03bc'+"s" } },//greek mi { 1500, new[] { "2", '\u03bc'+"s" } }, { 1900, new[] { "2", '\u03bc'+"s" } }, { 1100000, new[] { "1", "ms" } }, { 1500000, new[] { "2", "ms" } }, { 1900000, new[] { "2", "ms" } }, { 1100000000, new[] { "1", "s" } }, { 2100000000, new[] { "2", "s" } }, { 2900000000, new[] { "3", "s" } } }; private Dictionary<long, string[]> diskSizeOneDpPairs = new Dictionary<long, string[]> { { 0, new[] { "0", "B" } }, { 1000, new[] { "1000", "B" } }, { 1024, new[] { "1", "kB" } }, { 100000, new[] { "97.7", "kB" } }, { 1000000, new[] { "976.6", "kB" } }, { 1048576, new[] { "1", "MB" } }, //1024*1024 { 2100000, new[] { "2", "MB" } }, { 2900000, new[] { "2.8", "MB" } }, { 1073741824, new[] { "1", "GB" } }, //1024*1024*1024 { 2100000000, new[] { "2", "GB" } }, { 2900000000, new[] { "2.7", "GB" } } }; #endregion [Test] public void TestMemorySizeStringSuitableUnits() { var pairs = new Dictionary<string[], string> { { new [] {"1072693248", "false"}, "1023 MB"}, { new [] {"1073741824", "false"}, "1 GB"}, { new [] {"1073741824", "true"}, "1.0 GB"}, { new [] {"1825361100.8", "false"}, "1.7 GB"}, { new [] {"1825361100.8", "true"}, "1.7 GB"}, { new [] {"536870912", "true"}, "512 MB"}, { new [] {"537290342.4", "true"}, "512 MB"} }; foreach(var pair in pairs) Assert.AreEqual(pair.Value, Util.MemorySizeStringSuitableUnits(Convert.ToDouble(pair.Key[0]),Convert.ToBoolean(pair.Key[1]))); } [Test] public void TestMemorySizeStringVariousUnits() { foreach (var pair in memoryVariousPairs) { string expected = string.Format("{0} {1}", pair.Value[0], pair.Value[1]); Assert.AreEqual(expected, Util.MemorySizeStringVariousUnits(pair.Key)); } } [Test] public void TestMemorySizeValueVariousUnits() { foreach (var pair in memoryVariousPairs) { string unit; var value = Util.MemorySizeValueVariousUnits(pair.Key, out unit); Assert.AreEqual(pair.Value[0], value); Assert.AreEqual(pair.Value[1], unit); } } [Test] public void TestDataRateString() { foreach (var pair in dataRatePairs) { string expected = string.Format("{0} {1}", pair.Value[0], pair.Value[1]); Assert.AreEqual(expected, Util.DataRateString(pair.Key)); } } [Test] public void TestDataRateValue() { foreach (var pair in dataRatePairs) { string unit; var value = Util.DataRateValue(pair.Key, out unit); Assert.AreEqual(pair.Value[0], value); Assert.AreEqual(pair.Value[1], unit); } } [Test] public void TestDiskSizeStringUlong() { Assert.AreEqual("17179869184 GB", Util.DiskSizeString(ulong.MaxValue)); } [Test] public void TestDiskSizeString() { foreach (var pair in diskSizeOneDpPairs) { string expected = string.Format("{0} {1}", pair.Value[0], pair.Value[1]); Assert.AreEqual(expected, Util.DiskSizeString(pair.Key)); } } [Test] public void TestDiskSizeStringWithoutUnits() { foreach (var pair in diskSizeOneDpPairs) Assert.AreEqual(pair.Value[0], Util.DiskSizeStringWithoutUnits(pair.Key)); } [Test] public void TestDiskSizeStringVariousDp() { var pairs = new Dictionary<long[], string> { { new[] { 0, 1L }, "0 B" }, { new[] { 1000, 2L }, "1000 B" }, { new[] { 1024, 3L }, "1 kB" }, { new[] { 100000, 2L }, "97.66 kB" }, { new[] { 1000000, 1L }, "976.6 kB" }, { new[] { 1048576, 3L }, "1 MB" }, //1024*1024 { new[] { 2100000, 3L }, "2.003 MB" }, { new[] { 2900000, 2L }, "2.77 MB" }, { new[] { 1073741824, 3L }, "1 GB" }, //1024*1024*1024 { new[] { 2100000000, 3L }, "1.956 GB" } }; foreach (var pair in pairs) Assert.AreEqual(pair.Value, Util.DiskSizeString(pair.Key[0], (int)pair.Key[1])); } [Test] public void TestNanoSecondsString() { foreach (var pair in nanoSecPairs) { string expected = string.Format("{0}{1}", pair.Value[0], pair.Value[1]); Assert.AreEqual(expected, Util.NanoSecondsString(pair.Key)); } } [Test] public void TestNanoSecondsValue() { foreach (var pair in nanoSecPairs) { string unit; var value = Util.NanoSecondsValue(pair.Key, out unit); Assert.AreEqual(pair.Value[0], value); Assert.AreEqual(pair.Value[1], unit); } } [Test] public void TestCountsPerSecondString() { var pairs = new Dictionary<double, string> { {0,"0 /sec"}, {0.12,"0.12 /sec"}, {1234.56,"1234.56 /sec"} }; foreach (var pair in pairs) Assert.AreEqual(pair.Value, Util.CountsPerSecondString(pair.Key)); } [Test] public void TestPercentageString() { var pairs = new Dictionary<double, string> { { 1, "100.0%" }, { 0.12, "12.0%" }, { 0.0121, "1.2%" }, { 0.0125, "1.3%" }, { 0.0129, "1.3%" } }; foreach (var pair in pairs) Assert.AreEqual(pair.Value, Util.PercentageString(pair.Key)); } } }
// 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("index"); if (array == null) throw new ArgumentNullException("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("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("context"); if (identityValue == null) throw new ArgumentNullException("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("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("context"); if (identityValue == null) throw new ArgumentNullException("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("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("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("context"); if (identityValue == null) throw new ArgumentNullException("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; } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// PacketCapturesOperations operations. /// </summary> internal partial class PacketCapturesOperations : IServiceOperations<NetworkClient>, IPacketCapturesOperations { /// <summary> /// Initializes a new instance of the PacketCapturesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal PacketCapturesOperations(NetworkClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkClient /// </summary> public NetworkClient Client { get; private set; } /// <summary> /// Create and start a packet capture on the specified VM. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='parameters'> /// Parameters that define the create packet capture operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<PacketCaptureResult>> CreateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<PacketCaptureResult> _response = await BeginCreateWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets a packet capture session by name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PacketCaptureResult>> GetWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (packetCaptureName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("packetCaptureName", packetCaptureName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PacketCaptureResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified packet capture session. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Stops a specified packet capture session. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> StopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginStopWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Query the status of a running packet capture session. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> /// <param name='packetCaptureName'> /// The name given to the packet capture session. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<PacketCaptureQueryStatusResult>> GetStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<PacketCaptureQueryStatusResult> _response = await BeginGetStatusWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Lists all packet capture sessions within the specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<PacketCaptureResult>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<PacketCaptureResult>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<PacketCaptureResult>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create and start a packet capture on the specified VM. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='parameters'> /// Parameters that define the create packet capture operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PacketCaptureResult>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (packetCaptureName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("packetCaptureName", packetCaptureName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PacketCaptureResult>(); _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 == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified packet capture session. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (packetCaptureName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("packetCaptureName", packetCaptureName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Stops a specified packet capture session. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginStopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (packetCaptureName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("packetCaptureName", packetCaptureName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginStop", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/stop").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Query the status of a running packet capture session. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> /// <param name='packetCaptureName'> /// The name given to the packet capture session. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PacketCaptureQueryStatusResult>> BeginGetStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (packetCaptureName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("packetCaptureName", packetCaptureName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginGetStatus", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/queryStatus").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PacketCaptureQueryStatusResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureQueryStatusResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureQueryStatusResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IAppDomain ** ** <OWNER>mray</OWNER> ** ** ** Purpose: Properties and methods exposed to COM ** ** ===========================================================*/ namespace System { using System.Reflection; using System.Runtime.CompilerServices; using SecurityManager = System.Security.SecurityManager; using System.Security.Permissions; using IEvidenceFactory = System.Security.IEvidenceFactory; using System.Security.Principal; using System.Security.Policy; using System.Security; using System.Security.Util; using System.Collections; using System.Text; using System.Configuration.Assemblies; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Reflection.Emit; using CultureInfo = System.Globalization.CultureInfo; using System.IO; using System.Runtime.Versioning; [GuidAttribute("05F696DC-2B29-3663-AD8B-C4389CF2A713")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public interface _AppDomain { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); String ToString(); bool Equals (Object other); int GetHashCode (); Type GetType (); #if FEATURE_REMOTING [System.Security.SecurityCritical] // auto-generated_required Object InitializeLifetimeService (); [System.Security.SecurityCritical] // auto-generated_required Object GetLifetimeService (); #endif // FEATURE_REMOTING #if FEATURE_CAS_POLICY Evidence Evidence { get; } #endif // FEATURE_CAS_POLICY event EventHandler DomainUnload; [method:System.Security.SecurityCritical] event AssemblyLoadEventHandler AssemblyLoad; event EventHandler ProcessExit; [method:System.Security.SecurityCritical] event ResolveEventHandler TypeResolve; [method:System.Security.SecurityCritical] event ResolveEventHandler ResourceResolve; [method:System.Security.SecurityCritical] event ResolveEventHandler AssemblyResolve; [method:System.Security.SecurityCritical] event UnhandledExceptionEventHandler UnhandledException; AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access); AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, String dir); AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, Evidence evidence); AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions); AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, String dir, Evidence evidence); AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, String dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions); AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions); AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, String dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions); AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, String dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, bool isSynchronized); ObjectHandle CreateInstance(String assemblyName, String typeName); ObjectHandle CreateInstanceFrom(String assemblyFile, String typeName); ObjectHandle CreateInstance(String assemblyName, String typeName, Object[] activationAttributes); ObjectHandle CreateInstanceFrom(String assemblyFile, String typeName, Object[] activationAttributes); ObjectHandle CreateInstance(String assemblyName, String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes); ObjectHandle CreateInstanceFrom(String assemblyFile, String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes); Assembly Load(AssemblyName assemblyRef); Assembly Load(String assemblyString); Assembly Load(byte[] rawAssembly); Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore); Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence); Assembly Load(AssemblyName assemblyRef, Evidence assemblySecurity); Assembly Load(String assemblyString, Evidence assemblySecurity); [ResourceExposure(ResourceScope.Machine)] int ExecuteAssembly(String assemblyFile, Evidence assemblySecurity); [ResourceExposure(ResourceScope.Machine)] int ExecuteAssembly(String assemblyFile); [ResourceExposure(ResourceScope.Machine)] int ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args); String FriendlyName { get; } #if FEATURE_FUSION String BaseDirectory { [ResourceExposure(ResourceScope.Machine)] get; } String RelativeSearchPath { get; } bool ShadowCopyFiles { get; } #endif Assembly[] GetAssemblies(); #if FEATURE_FUSION [System.Security.SecurityCritical] // auto-generated_required void AppendPrivatePath(String path); [System.Security.SecurityCritical] // auto-generated_required void ClearPrivatePath(); [System.Security.SecurityCritical] // auto-generated_required void SetShadowCopyPath (String s); [System.Security.SecurityCritical] // auto-generated_required void ClearShadowCopyPath ( ); [System.Security.SecurityCritical] // auto-generated_required void SetCachePath (String s); #endif //FEATURE_FUSION [System.Security.SecurityCritical] // auto-generated_required void SetData(String name, Object data); #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif Object GetData(string name); #if FEATURE_CAS_POLICY [System.Security.SecurityCritical] // auto-generated_required void SetAppDomainPolicy(PolicyLevel domainPolicy); #if FEATURE_IMPERSONATION void SetThreadPrincipal(IPrincipal principal); #endif // FEATURE_IMPERSONATION void SetPrincipalPolicy(PrincipalPolicy policy); #endif #if FEATURE_REMOTING void DoCallBack(CrossAppDomainDelegate theDelegate); #endif String DynamicDirectory { get; } #endif } }
using System; using System.Data; using System.Data.Common; using bv.common; using bv.common.Core; using bv.common.db; using bv.common.db.Core; namespace EIDSS.RAM_DB.DBService.QueryBuilder { public class Query_DB : BaseDbService { public const string TasQuery = @"tasQuery"; public const string TasQueryObjectTree = @"tasQueryObjectTree"; public Query_DB() { ObjectName = @"Query"; UseDatasetCopyInPost = false; } public override DataSet GetDetail(object ID) { DataSet ds = new DataSet(); try { DbDataAdapter queryAdapter = null; IDbCommand cmd = CreateSPCommand("spAsQuery_SelectDetail", null); AddParam(cmd, "@ID", ID, ref m_Error, ParameterDirection.Input); if (m_Error != null) { return (null); } AddParam(cmd, "@LangID", bv.model.Model.Core.ModelUserContext.CurrentLanguage, ref m_Error, ParameterDirection.Input); if (m_Error != null) { return (null); } queryAdapter = CreateAdapter(cmd, false); queryAdapter.Fill(ds, TasQuery); CorrectTable(ds.Tables[0], TasQuery, "idflQuery"); CorrectTable(ds.Tables[1], TasQueryObjectTree, "idfQuerySearchObject"); ClearColumnsAttibutes(ds); if (ds.Tables[TasQuery].Rows.Count == 0) { if (Utils.IsEmpty(ID) || (!(ID is long)) || ((long)ID >= 0)) { ID = -1L; } m_IsNewObject = true; DataRow rQuery = ds.Tables[TasQuery].NewRow(); rQuery["idflQuery"] = ID; ds.EnforceConstraints = false; ds.Tables[TasQuery].Rows.Add(rQuery); } else { m_IsNewObject = false; } if (ds.Tables[TasQueryObjectTree].Rows.Count == 0) { DataRow rObject = ds.Tables[TasQueryObjectTree].NewRow(); rObject["idflQuery"] = ID; rObject["idfQuerySearchObject"] = -1L; rObject["idfParentQuerySearchObject"] = DBNull.Value; rObject["idfsSearchObject"] = 10082000; // "sobHumanCases" rObject["intOrder"] = 0; ds.EnforceConstraints = false; ds.Tables[TasQueryObjectTree].Rows.Add(rObject); } //ds.Tables[tasQuery].Columns["QueryName"].ReadOnly = false; //ds.Tables[tasQuery].Columns["QueryName"].AllowDBNull = true; ds.Tables[TasQuery].Columns["blnReadOnly"].ReadOnly = false; ds.Tables[TasQuery].Columns["blnReadOnly"].AllowDBNull = true; ds.Tables[TasQuery].Columns["QueryName"].ReadOnly = false; ds.Tables[TasQuery].Columns["QueryName"].AllowDBNull = true; ds.Tables[TasQuery].Columns["DefQueryName"].ReadOnly = false; ds.Tables[TasQuery].Columns["DefQueryName"].AllowDBNull = true; ds.Tables[TasQuery].Columns["QueryDescription"].ReadOnly = false; ds.Tables[TasQuery].Columns["QueryDescription"].AllowDBNull = true; ds.Tables[TasQuery].Columns["DefQueryDescription"].ReadOnly = false; ds.Tables[TasQuery].Columns["DefQueryDescription"].AllowDBNull = true; m_ID = ID; return (ds); } catch (Exception ex) { m_Error = new ErrorMessage(StandardError.FillDatasetError, ex); } return null; } public override void AcceptChanges(DataSet ds) { // this method shoul duplicate base method bu WITHOUT line m_IsNewObject = false foreach (DataTable table in ds.Tables) { if (!SkipAcceptChanges(table)) { table.AcceptChanges(); } } RaiseAcceptChangesEvent(ds); } private void PostObject(IDbCommand cmdObj, DataTable dtObj, DataRow rObj) { if ((cmdObj == null) || (dtObj == null) || (rObj == null)) { return; } object objID = null; if (rObj.RowState == DataRowState.Deleted) { objID = rObj["idfQuerySearchObject", DataRowVersion.Original]; if ((Utils.IsEmpty(objID) == false) && (objID is long) && ((long)objID > 0)) { SetParam(cmdObj, "@idfQuerySearchObject", objID, ParameterDirection.InputOutput); SetParam(cmdObj, "@idflQuery", -1L, ParameterDirection.Input); SetParam(cmdObj, "@idfsSearchObject", DBNull.Value, ParameterDirection.Input); SetParam(cmdObj, "@intOrder", 0, ParameterDirection.Input); SetParam(cmdObj, "@idfParentQuerySearchObject", DBNull.Value, ParameterDirection.Input); cmdObj.ExecuteNonQuery(); } return; } objID = rObj["idfQuerySearchObject"]; rObj["idflQuery"] = m_ID; SetParam(cmdObj, "@idfQuerySearchObject", objID, ParameterDirection.InputOutput); SetParam(cmdObj, "@idflQuery", m_ID, ParameterDirection.Input); SetParam(cmdObj, "@idfsSearchObject", rObj["idfsSearchObject"], ParameterDirection.Input); SetParam(cmdObj, "@intOrder", rObj["intOrder"], ParameterDirection.Input); SetParam(cmdObj, "@idfParentQuerySearchObject", rObj["idfParentQuerySearchObject"], ParameterDirection.Input); cmdObj.ExecuteNonQuery(); rObj["idfQuerySearchObject"] = ((IDataParameter) cmdObj.Parameters["@idfQuerySearchObject"]).Value; foreach (ServiceParam service in m_LinkedServices) { if (service.serviceType == RelatedPostOrder.PostLast) { if (service.service is QuerySearchObject_DB) { QuerySearchObject_DB qsoDBService = service.service as QuerySearchObject_DB; if (Utils.Str(qsoDBService.ID) == Utils.Str(objID)) { qsoDBService.QueryID = (long)m_ID; qsoDBService.QuerySearchObjectID = (long)rObj["idfQuerySearchObject"]; break; } } } } DataRow[] drObjDel = dtObj.Select(string.Format("idfParentQuerySearchObject = {0} ", objID), "idfQuerySearchObject", DataViewRowState.Deleted); foreach (DataRow r in drObjDel) { PostObject(cmdObj, dtObj, r); } DataRow[] drObj = dtObj.Select(string.Format("idfParentQuerySearchObject = {0} ", objID), "intOrder", DataViewRowState.CurrentRows); foreach (DataRow r in drObj) { DataRow childObj = dtObj.Rows.Find(r["idfQuerySearchObject"]); if (childObj != null) { childObj["idfParentQuerySearchObject"] = rObj["idfQuerySearchObject"]; } PostObject(cmdObj, dtObj, childObj); } } public override bool PostDetail(DataSet ds, int PostType, IDbTransaction transaction) { if ((ds == null)) { return true; } try { IDbCommand cmd = null; IDbCommand cmdObj = null; if (ds.Tables[TasQuery].Rows.Count > 0) { DataRow rQuery = ds.Tables[TasQuery].Rows[0]; cmd = CreateSPCommand("spAsQuery_Post", transaction); AddTypedParam(cmd, "@idflQuery", SqlDbType.BigInt, ParameterDirection.InputOutput); AddTypedParam(cmd, "@strFunctionName", SqlDbType.NVarChar, 200, ParameterDirection.InputOutput); AddTypedParam(cmd, "@idflDescription", SqlDbType.BigInt, ParameterDirection.InputOutput); AddTypedParam(cmd, "@QueryName", SqlDbType.NVarChar, 2000, ParameterDirection.Input); AddTypedParam(cmd, "@DefQueryName", SqlDbType.NVarChar, 2000, ParameterDirection.Input); AddTypedParam(cmd, "@QueryDescription", SqlDbType.NVarChar, 2000, ParameterDirection.Input); AddTypedParam(cmd, "@DefQueryDescription", SqlDbType.NVarChar, 2000, ParameterDirection.Input); AddTypedParam(cmd, "@blnAddAllKeyFieldValues", SqlDbType.Bit, ParameterDirection.Input); AddTypedParam(cmd, "@LangID", SqlDbType.NVarChar, 50, ParameterDirection.Input); SetParam(cmd, "@idflQuery", rQuery["idflQuery"], ParameterDirection.InputOutput); SetParam(cmd, "@strFunctionName", rQuery["strFunctionName"], ParameterDirection.InputOutput); SetParam(cmd, "@idflDescription", rQuery["idflDescription"], ParameterDirection.InputOutput); SetParam(cmd, "@QueryName", rQuery["QueryName"], ParameterDirection.Input); SetParam(cmd, "@DefQueryName", rQuery["DefQueryName"], ParameterDirection.Input); SetParam(cmd, "@QueryDescription", rQuery["QueryDescription"], ParameterDirection.Input); SetParam(cmd, "@DefQueryDescription", rQuery["DefQueryDescription"], ParameterDirection.Input); SetParam(cmd, "@blnAddAllKeyFieldValues", rQuery["blnAddAllKeyFieldValues"], ParameterDirection.Input); SetParam(cmd, "@LangID", bv.model.Model.Core.ModelUserContext.CurrentLanguage, ParameterDirection.Input); cmd.ExecuteNonQuery(); m_ID = ((IDataParameter) cmd.Parameters["@idflQuery"]).Value; rQuery["idflQuery"] = m_ID; rQuery["strFunctionName"] = ((IDataParameter) cmd.Parameters["@strFunctionName"]).Value; LookupCache.NotifyChange("Query", transaction, ID); cmdObj = CreateSPCommand("spAsQuerySearchObject_Post", transaction); AddTypedParam(cmdObj, "@idfQuerySearchObject", SqlDbType.BigInt, ParameterDirection.InputOutput); AddTypedParam(cmdObj, "@idflQuery", SqlDbType.BigInt, ParameterDirection.Input); AddTypedParam(cmdObj, "@idfsSearchObject", SqlDbType.VarChar, 36, ParameterDirection.Input); AddTypedParam(cmdObj, "@intOrder", SqlDbType.Int, ParameterDirection.Input); AddTypedParam(cmdObj, "@idfParentQuerySearchObject", SqlDbType.BigInt, ParameterDirection.Input); if (ds.Tables[TasQueryObjectTree].Rows.Count > 0) { DataRow[] dr = ds.Tables[TasQueryObjectTree].Select("idfParentQuerySearchObject is null", "idfQuerySearchObject", DataViewRowState.CurrentRows); if (dr.Length > 0) { DataRow rRoot = ds.Tables[TasQueryObjectTree].Rows.Find(dr[0]["idfQuerySearchObject"]); if (rRoot != null) { PostObject(cmdObj, ds.Tables[TasQueryObjectTree], rRoot); } } } m_IsNewObject = false; } } catch (Exception ex) { m_Error = new ErrorMessage(StandardError.PostError, ex); return false; } return true; } public void Copy(DataSet ds, object aID) { if ((ds == null) || (ds.Tables.Contains(TasQuery) == false) || (ds.Tables[TasQuery].Rows.Count == 0)) { return; } if (Utils.IsEmpty(aID) || (!(aID is long)) || ((long)aID >= 0)) { aID = -1L; } m_IsNewObject = true; DataRow rQuery = ds.Tables[TasQuery].Rows[0]; rQuery["idflQuery"] = aID; m_ID = aID; } public bool CreateFunction() { IDbCommand cmd = CreateSPCommand("spAsQueryFunction_Post", Connection, null); AddTypedParam(cmd, "@QueryID", SqlDbType.BigInt, ParameterDirection.Input); SetParam(cmd, "@QueryID", m_ID, ParameterDirection.Input); m_Error = ExecCommand(cmd, Connection, null, false); return (m_Error == null); } } }
using System; using System.ComponentModel; using System.Data; using DBSchemaInfo.Base; namespace CslaGenerator.Metadata { /// <summary> /// Summary description for DbBindColumn. /// </summary> [Serializable] public class DbBindColumn : ICloneable { #region Fields private ColumnOriginType _columnOriginType = ColumnOriginType.None; // these fields are used to serialize the column name so it can be loaded from a schema //private readonly string _tableName = String.Empty; //private readonly string _viewName = String.Empty; //private readonly string _spName = String.Empty; private int _spResultSetIndex; private string _columnName = String.Empty; private DbType _dataType = DbType.String; private string _nativeType = String.Empty; private long _size; private bool _isPrimaryKey; private ICatalog _catalog; private IColumnInfo _column; private string _objectName; private string _catalogName; private string _schemaName; private IDataBaseObject _databaseObject; private IResultSet _resultSet; private bool _isNullable; private bool _isIdentity; #endregion #region Properties public ColumnOriginType ColumnOriginType { set { _columnOriginType = value; } get { return _columnOriginType; } } public IColumnInfo Column { get { return _column; } } public DbType DataType { get { if (Column == null) { return _dataType; } return Column.DbType; } set { _dataType = value; } } public string NativeType { get { if (Column == null) { return _nativeType; } return Column.NativeType; } set { if (value != null) _nativeType = value; } } public long Size { get { if (Column == null) { return _size; } return Column.ColumnLength; } set { _size = value; } } public int SpResultIndex { get { return _spResultSetIndex; } set { _spResultSetIndex = value; } } [Obsolete("Use ObjectName instead")] [Browsable(false)] public string TableName { get { return _objectName; } set { if (string.IsNullOrEmpty(_objectName) && !string.IsNullOrEmpty(value)) _objectName = value; //_tableName = value; } } [Obsolete("Use ObjectName instead")] [Browsable(false)] public string ViewName { get { return _objectName; } set { if (string.IsNullOrEmpty(_objectName) && !string.IsNullOrEmpty(value)) _objectName = value; //_viewName = value; } } [Obsolete("Use ObjectName instead")] [Browsable(false)] public string SpName { get { return _objectName; } set { if (string.IsNullOrEmpty(_objectName) && !string.IsNullOrEmpty(value)) _objectName = value; //_spName = value; } } public string ColumnName { get { return _columnName; } set { _columnName = value; } } public bool IsPrimaryKey { get { return _isPrimaryKey; } set { _isPrimaryKey = value; } } public string ObjectName { get { return _objectName; } set { value = value.Trim().Replace(" ", " ").Replace(' ', '_'); _objectName = value; } } public string CatalogName { get { return _catalogName; } set { _catalogName = value; } } public string SchemaName { get { return _schemaName; } set { _schemaName = value; } } [Browsable(false)] public IDataBaseObject DatabaseObject { get { return _databaseObject; } } [Browsable(false)] public IResultSet ResultSet { get { return _resultSet; } } #endregion #region Methods internal void LoadColumn(ICatalog catalog) { _catalog = catalog; _resultSet = null; _databaseObject = null; _column = null; string cat = null; if (_catalogName != null) { if (string.Compare(_catalogName, _catalog.CatalogName, true) != 0) cat = null; //When connecting to a DB with a different name else cat = _catalogName; } try { switch (_columnOriginType) { case ColumnOriginType.Table: ITableInfo tInfo = _catalog.Tables[cat, _schemaName, _objectName]; if (tInfo != null) { _databaseObject = tInfo; _resultSet = tInfo; } break; case ColumnOriginType.View: //_Column = _Catalog.Views[_CatalogName, _SchemaName, _objectName].Columns[_columnName]; IViewInfo vInfo = _catalog.Views[cat, _schemaName, _objectName]; if (vInfo != null) { _databaseObject = vInfo; _resultSet = vInfo; } break; case ColumnOriginType.StoredProcedure: IStoredProcedureInfo pInfo = _catalog.Procedures[cat, _schemaName, _objectName]; if (pInfo != null) { _databaseObject = pInfo; if (pInfo.ResultSets.Count > _spResultSetIndex) _resultSet = pInfo.ResultSets[_spResultSetIndex]; } break; case ColumnOriginType.None: break; } } catch (Exception ex) { Console.WriteLine(ex.Message); } if (_resultSet != null) _column = _resultSet.Columns[_columnName]; ReloadColumnInfo(); } private void ReloadColumnInfo() { if (_column == null) return; if (_catalogName == null) _catalogName = _databaseObject.ObjectCatalog; if (_schemaName == null) _schemaName = _databaseObject.ObjectSchema; _isPrimaryKey = _column.IsPrimaryKey; _isNullable = _column.IsNullable; _isIdentity = _column.IsIdentity; _dataType = _column.DbType; _nativeType = _column.NativeType; } public bool IsNullable { get { return _isNullable; } set { _isNullable = value; } } public bool IsIdentity { get { return _isIdentity; } set { _isIdentity = value; } } public object Clone() { var clone = (DbBindColumn)Util.ObjectCloner.CloneShallow(this); clone.LoadColumn(_catalog); return clone; //DbBindColumn col = new DbBindColumn(); //col._columnName = this._columnName; //col._columnOriginType = this._columnOriginType; //col._spName = this._spName; //col._spResultSetIndex = this._spResultSetIndex; //col._spSchema = this._spSchema; //col._tableName = this._tableName; //col._tableSchema = this._tableSchema; //col._viewName = this._viewName; //col._viewSchema = this._viewSchema; //col._dataType = this._dataType; //col._nativeType = this._nativeType; //return col; } #endregion } }
using UnityEngine; using System.Collections; namespace UnityStandardAssets.Characters.ThirdPerson { [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(CapsuleCollider))] [RequireComponent(typeof(Animator))] public class ThirdPersonCharacter : MonoBehaviour { [SerializeField] float m_MovingTurnSpeed = 360; [SerializeField] float m_StationaryTurnSpeed = 180; [SerializeField] float m_JumpPower; private const float JumpPower_FOR_FOOT = 6f; private const float JumpPower_FOR_EXOSKELETON = 6f; private float lastJumpPressedAt; private const float EXOSKELETON_DOUBLE_JUMP_PRESS_TIME = 0.5f; private float jumpLandingTime; private float lastJumpedTime; private const float JUMP_ALLOWED_FREQUENCY = 0.3f; // if the player has landed few moments ago, his jumping speed should be increased // this variable determines the timeframe for that private const float EXOSKELETON_DOUBLE_JUMP_TIME = 0.5f; private bool justLandedFromJump = false; [Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f; [SerializeField] float m_RunCycleLegOffset = 0.2f; //specific to the character in sample assets, will need to be modified to work with others [SerializeField] float m_MoveSpeedMultiplier = 1f; private const float MoveSpeedMultiplier_FOR_FOOT = 1f; private const float MoveSpeedMultiplier_FOR_EXOSKELETON = 1.5f; [SerializeField] float m_AnimSpeedMultiplier = 1f; [SerializeField] float m_GroundCheckDistance = 0.1f; private const float GroundCheckDistance_FOR_FOOT = 0.3f; private const float GroundCheckDistance_FOR_EXOSKELETON = 0.9f; private const float COLLIDER_CENTER_FOR_FOOT = 1.08f; private const float COLLIDER_HEIGHT_FOR_FOOT = 2.16f; private const float COLLIDER_CENTER_FOR_EXOSKELETON = 0.87f; private const float COLLIDER_HEIGHT_FOR_EXOSKELETON = 2.4f; [SerializeField] bool m_HasExoskeleton = false; [SerializeField] GameObject m_ExoskeletonLeft; [SerializeField] GameObject m_ExoskeletonRight; [SerializeField] PhysicMaterial m_PhysicsMaterialForFoot; [SerializeField] PhysicMaterial m_PhysicsMaterialForExoskeleton; private bool hasJumped = false; [SerializeField] bool m_HasJetPack = false; [SerializeField] float m_JetPackForce = 15f; [SerializeField] AudioSource m_JetPackAudioSource; [SerializeField] ParticleSystem[] m_JetPackParticles; [SerializeField] GameObject m_JetPack; private const int JETPACK_LAYER_INDEX = 1; private const float JETPACK_TOP_REACH = 370; private const float JETPACK_MIN_VOLUME = 0.5f; private const float JETPACK_MIN_DOWNWARD_VELOCITY = -5f; Rigidbody m_Rigidbody; Animator m_Animator; AudioSource m_AudioSource; bool m_IsGrounded; float m_OrigGroundCheckDistance; const float k_Half = 0.5f; float m_TurnAmount; float m_ForwardAmount; Vector3 m_GroundNormal; float m_CapsuleHeight; Vector3 m_CapsuleCenter; CapsuleCollider m_Capsule; bool m_Crouching; [SerializeField] Transform m_CharacterRoot; private float lastRunClipPlayedAt; public AudioClip runClip; public AudioClip jumpClip; public AudioClip landClip; public AudioClip runClipExosKeleton; public AudioClip jumpClipExosKeleton; public AudioClip landClipExosKeleton; public static ThirdPersonCharacter Instance; void Start() { Instance = this; m_Animator = GetComponent<Animator>(); m_AudioSource = GetComponent<AudioSource>(); m_Rigidbody = GetComponent<Rigidbody>(); m_Capsule = GetComponent<CapsuleCollider>(); m_CapsuleHeight = m_Capsule.height; m_CapsuleCenter = m_Capsule.center; m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ; m_OrigGroundCheckDistance = m_GroundCheckDistance; setJetPack(m_HasJetPack, true); m_JetPackAudioSource.volume = JETPACK_MIN_VOLUME; setExoskeleton(m_HasExoskeleton, true); } public void show() { Debug.Log("ThirdPersonController Enabled"); gameObject.SetActive(true); if(m_Rigidbody != null) { m_Rigidbody.velocity = Vector3.zero; } PlayerController.TogglePlayerTransform(transform); } public void hide() { gameObject.SetActive(false); } public bool hasExoskeleton() { return m_HasExoskeleton; } public void setExoskeleton(bool val, bool force = false) { if(m_IsGrounded == false) { if(!force) { Debug.LogError("Player needs to be grounded before toggling Exoskeleton"); return; } } if(val) { m_HasExoskeleton = true; m_Capsule.height = COLLIDER_HEIGHT_FOR_EXOSKELETON; m_Capsule.center = new Vector3(m_Capsule.center.x, COLLIDER_CENTER_FOR_EXOSKELETON, m_Capsule.center.z); m_GroundCheckDistance = GroundCheckDistance_FOR_EXOSKELETON; m_JumpPower = JumpPower_FOR_EXOSKELETON; m_MoveSpeedMultiplier = MoveSpeedMultiplier_FOR_EXOSKELETON; m_Capsule.material = m_PhysicsMaterialForExoskeleton; setJetPack(false, true); } else { m_HasExoskeleton = false; m_Capsule.height = COLLIDER_HEIGHT_FOR_FOOT; m_Capsule.center = new Vector3(m_Capsule.center.x, COLLIDER_CENTER_FOR_FOOT, m_Capsule.center.z); m_GroundCheckDistance = GroundCheckDistance_FOR_FOOT; m_JumpPower = JumpPower_FOR_FOOT; m_MoveSpeedMultiplier = MoveSpeedMultiplier_FOR_FOOT; m_Capsule.material = m_PhysicsMaterialForFoot; } m_ExoskeletonLeft.SetActive(val); m_ExoskeletonRight.SetActive(val); m_CapsuleHeight = m_Capsule.height; m_CapsuleCenter = m_Capsule.center; m_OrigGroundCheckDistance = m_GroundCheckDistance; } public bool hasJetPack() { return m_HasJetPack; } public void setJetPack(bool val, bool force = false) { if(m_IsGrounded == false) { if(!force) { Debug.LogError("Player needs to be grounded before toggling JetPack"); return; } } if(val) { m_HasJetPack = true; m_Animator.SetLayerWeight(JETPACK_LAYER_INDEX, 1); setExoskeleton(false, true); } else { m_HasJetPack = false; m_Animator.SetLayerWeight(JETPACK_LAYER_INDEX, 0); } m_JetPack.SetActive(val); } public void addJetPackForce() { if(m_HasJetPack && transform.position.y < JETPACK_TOP_REACH) { hasJumped = true; // remove all his previous force m_Rigidbody.velocity = Vector3.zero; m_Rigidbody.AddForce(Vector3.up * m_JetPackForce, ForceMode.Impulse); m_JetPackAudioSource.Play(); if(m_JetPackAudioSource.volume == JETPACK_MIN_VOLUME) { m_JetPackAudioSource.volume = 1; StartCoroutine("reduceJetSound"); } else { m_JetPackAudioSource.volume = 1; } foreach(ParticleSystem ps in m_JetPackParticles) { ps.Play(); ps.startSpeed = 10f; } if(IsInvoking("reduceJetBurne")) { CancelInvoke("reduceJetBurne"); } Invoke("reduceJetBurne", 0.5f); } } void reduceJetBurne() { foreach(ParticleSystem ps in m_JetPackParticles) { ps.startSpeed = 3f; } } IEnumerator reduceJetSound() { while(m_JetPackAudioSource.volume > JETPACK_MIN_VOLUME) { m_JetPackAudioSource.volume = Mathf.Lerp(m_JetPackAudioSource.volume, JETPACK_MIN_VOLUME, Time.deltaTime * 3f); yield return null; } m_JetPackAudioSource.volume = JETPACK_MIN_VOLUME; } public void Move(Vector3 move, bool crouch, bool jump) { if(Input.GetKeyDown(KeyCode.LeftCommand)) { m_MoveSpeedMultiplier = 3; } else if(Input.GetKeyUp(KeyCode.LeftCommand)) { m_MoveSpeedMultiplier = 1; } // convert the world relative moveInput vector into a local-relative // turn amount and forward amount required to head in the desired // direction. if (move.magnitude > 1f) move.Normalize(); move = transform.InverseTransformDirection(move); CheckGroundStatus(); move = Vector3.ProjectOnPlane(move, m_GroundNormal); //Debug.Log(move); m_TurnAmount = Mathf.Atan2(move.x, move.z); //Debug.Log(m_TurnAmount); m_ForwardAmount = move.z; ApplyExtraTurnRotation(); if(jump) { lastJumpPressedAt = Time.time; } if(justLandedFromJump && m_IsGrounded && hasExoskeleton() && lastJumpPressedAt > Time.time - EXOSKELETON_DOUBLE_JUMP_PRESS_TIME) { // if the player has pressed jump button few moments ago when in air. allow it to work now that he is on ground jump = true; //Debug.Log("Delayed Jump"); } justLandedFromJump = false; // control and velocity handling is different when grounded and airborne: if(jump && m_HasJetPack) { addJetPackForce(); hasJumped = true; } else if (m_IsGrounded && !hasJumped) { HandleGroundedMovement(crouch, jump, move); } else { HandleAirborneMovement(); } ScaleCapsuleForCrouching(crouch); PreventStandingInLowHeadroom(); // send input and other state parameters to the animator UpdateAnimator(move); if(m_HasJetPack) { if(hasJumped) { // player has a jetpack and he has jumped already transform.Translate(Vector3.forward * m_ForwardAmount * m_JetPackForce * 2f * Time.deltaTime); m_Animator.SetLayerWeight(2, 1); //Debug.Log(m_Rigidbody.velocity); // rotate the player forward a bit when he is using the jet and moving forward Vector3 rotation = new Vector3(move.z == 0 ? 0 : Mathf.Clamp(15f / move.z, -15, 15) , 0, 0); //Debug.Log("Move: " + move); //Debug.Log(rotation); m_CharacterRoot.localRotation = Quaternion.Lerp(m_CharacterRoot.localRotation, Quaternion.Euler(rotation), Time.deltaTime * 10) ; } else { m_Animator.SetLayerWeight(2, 0); m_CharacterRoot.localRotation = Quaternion.Euler(Vector3.zero); } } } void ScaleCapsuleForCrouching(bool crouch) { if (m_IsGrounded && crouch) { if (m_Crouching) return; m_Capsule.height = m_Capsule.height / 2f; m_Capsule.center = m_Capsule.center / 2f; m_Crouching = true; } else { Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up); float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half; if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, ~0, QueryTriggerInteraction.Ignore)) { m_Crouching = true; return; } m_Capsule.height = m_CapsuleHeight; m_Capsule.center = m_CapsuleCenter; m_Crouching = false; } } void PreventStandingInLowHeadroom() { // prevent standing up in crouch-only zones if (!m_Crouching) { Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up); float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half; if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, ~0, QueryTriggerInteraction.Ignore)) { m_Crouching = true; } } } void UpdateAnimator(Vector3 move) { // update the animator parameters m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime); m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime); m_Animator.SetBool("Crouch", m_Crouching); m_Animator.SetBool("OnGround", m_IsGrounded); if(hasExoskeleton()) { // when player is in idle mode players leg should not move while using Exoskeleton if(m_IsGrounded && m_ForwardAmount == 0 && m_TurnAmount == 0) { m_Animator.SetLayerWeight(3, 1); } else { m_Animator.SetLayerWeight(3, 0); } } if (!m_IsGrounded && !m_HasJetPack) { m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y); } // calculate which leg is behind, so as to leave that leg trailing in the jump animation // (This code is reliant on the specific run cycle offset in our animations, // and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5) float runCycle = Mathf.Repeat( m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1); float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount; if (m_IsGrounded) { m_Animator.SetFloat("JumpLeg", jumpLeg); } // the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector, // which affects the movement speed because of the root motion. if (m_IsGrounded && move.magnitude > 0) { m_Animator.speed = m_AnimSpeedMultiplier; } else { // don't use that while airborne m_Animator.speed = 1; } } void HandleAirborneMovement() { // apply extra gravity from multiplier: Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity; m_Rigidbody.AddForce(extraGravityForce); m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f; if(m_HasJetPack && hasJumped) { // if player has jetpack, he should not have too much downward velocity if(m_Rigidbody.velocity.y < JETPACK_MIN_DOWNWARD_VELOCITY) m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, JETPACK_MIN_DOWNWARD_VELOCITY, m_Rigidbody.velocity.z); } } void HandleGroundedMovement(bool crouch, bool jump, Vector3 moveDirection) { // check whether conditions are right to allow a jump: if (jump && !crouch && lastJumpedTime < Time.time - JUMP_ALLOWED_FREQUENCY && (m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded") || (hasExoskeleton() && lastJumpPressedAt > Time.time - EXOSKELETON_DOUBLE_JUMP_PRESS_TIME ) ) ) { // jump! //m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, hasExoskeleton() && jumpLandingTime > Time.time - EXOSKELETON_DOUBLE_JUMP_TIME ? m_JumpPower * 1.25f : m_JumpPower, m_Rigidbody.velocity.z); moveDirection = transform.TransformDirection(moveDirection); //Debug.Log("Direction: " + moveDirection); //Debug.Log("Jumped"); lastJumpPressedAt = 0; lastJumpedTime = Time.time; float maxHorizontalVelocity = 6.67f * m_MoveSpeedMultiplier; Vector3 velocity = new Vector3( maxHorizontalVelocity * moveDirection.x, hasExoskeleton() && jumpLandingTime > Time.time - EXOSKELETON_DOUBLE_JUMP_TIME ? m_JumpPower * 1.25f : m_JumpPower, maxHorizontalVelocity * moveDirection.z ); m_Rigidbody.velocity = velocity; //Debug.Log("Velocity: " + m_Rigidbody.velocity); /* m_Rigidbody.AddForce(new Vector3(moveDirection.x, (hasExoskeleton() && jumpLandingTime > Time.time - EXOSKELETON_DOUBLE_JUMP_TIME ? 2f : 1.5f), moveDirection.z) * m_JumpPower, ForceMode.VelocityChange); */ m_IsGrounded = false; m_Animator.applyRootMotion = false; m_GroundCheckDistance = 0.1f; m_AudioSource.PlayOneShot(hasExoskeleton() ? jumpClipExosKeleton : jumpClip); hasJumped = true; } } void ApplyExtraTurnRotation() { // help the character turn faster (this is in addition to root rotation in the animation) float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount); transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0); } public void footPlaced() { if(Time.time - lastRunClipPlayedAt > 0.1f) { lastRunClipPlayedAt = Time.time; m_AudioSource.PlayOneShot(hasExoskeleton() ? runClipExosKeleton : runClip, m_ForwardAmount / 3f); } } public void OnAnimatorMove() { // we implement this function to override the default root motion. // this allows us to modify the positional speed before it's applied. if (m_IsGrounded && hasJumped == false && Time.deltaTime > 0) { Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime; // we preserve the existing y part of the current velocity. v.y = m_Rigidbody.velocity.y; m_Rigidbody.velocity = v; } } void CheckGroundStatus() { RaycastHit hitInfo; #if UNITY_EDITOR // helper to visualise the ground check ray in the scene view Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance)); #endif // 0.1f is a small offset to start the ray from inside the character // it is also good to note that the transform position in the sample assets is at the base of the character if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance)) { if(m_IsGrounded == false) { // player has just landed //Debug.Log("Hit Ground"); //Debug.Log("Volume: " + Mathf.Clamp01( Mathf.Abs(m_Rigidbody.velocity.y) / 7f)); m_AudioSource.PlayOneShot(hasExoskeleton() ? landClipExosKeleton : landClip, Mathf.Clamp01( Mathf.Abs(m_Rigidbody.velocity.y) / 7f) ); jumpLandingTime = Time.time; hasJumped = false; m_JetPackAudioSource.Stop(); foreach(ParticleSystem ps in m_JetPackParticles) { ps.Stop(); } justLandedFromJump = true; } m_GroundNormal = hitInfo.normal; m_IsGrounded = true; m_Animator.applyRootMotion = true; } else { m_IsGrounded = false; m_GroundNormal = Vector3.up; m_Animator.applyRootMotion = false; } } } }
// Copyright 2007-2010 Portland State University, University of Wisconsin-Madison // Author: Robert Scheller, Ben Sulman using Landis.Core; using Landis.SpatialModeling; using Edu.Wisc.Forest.Flel.Util; using Landis.Library.InitialCommunities; using Landis.Library.Succession; using Landis.Library.LeafBiomassCohorts; using Landis.Library.Climate; using Landis.Library.Metadata; using System; using System.Collections.Generic; using System.Linq; namespace Landis.Extension.Succession.NetEcosystemCN { public class PlugIn : Landis.Library.Succession.ExtensionBase { public static readonly string ExtensionName = "NECN Succession"; private static ICore modelCore; private IInputParameters parameters; private List<ISufficientLight> sufficientLight; public static string SoilCarbonMapNames = null; public static int SoilCarbonMapFrequency; public static string SoilNitrogenMapNames = null; public static int SoilNitrogenMapFrequency; public static string ANPPMapNames = null; public static int ANPPMapFrequency; public static string ANEEMapNames = null; public static int ANEEMapFrequency; public static string TotalCMapNames = null; public static int TotalCMapFrequency; public static int SuccessionTimeStep; public static double ProbEstablishAdjust; public static int FutureClimateBaseYear; //--------------------------------------------------------------------- public PlugIn() : base(ExtensionName) { } //--------------------------------------------------------------------- public override void LoadParameters(string dataFile, ICore mCore) { modelCore = mCore; SiteVars.Initialize(); InputParametersParser parser = new InputParametersParser(); parameters = Landis.Data.Load<IInputParameters>(dataFile, parser); } //--------------------------------------------------------------------- public static ICore ModelCore { get { return modelCore; } } //--------------------------------------------------------------------- public override void Initialize() { PlugIn.ModelCore.UI.WriteLine("Initializing {0} ...", ExtensionName); Timestep = parameters.Timestep; SuccessionTimeStep = Timestep; sufficientLight = parameters.LightClassProbabilities; ProbEstablishAdjust = parameters.ProbEstablishAdjustment; MetadataHandler.InitializeMetadata(Timestep, modelCore, SoilCarbonMapNames, SoilNitrogenMapNames, ANPPMapNames, ANEEMapNames, TotalCMapNames); CohortBiomass.SpinupMortalityFraction = parameters.SpinupMortalityFraction; //Initialize climate. Climate.Initialize(parameters.ClimateConfigFile, false, modelCore); FutureClimateBaseYear = Climate.Future_MonthlyData.Keys.Min(); EcoregionData.Initialize(parameters); SpeciesData.Initialize(parameters); EcoregionData.ChangeParameters(parameters); OtherData.Initialize(parameters); FunctionalType.Initialize(parameters); // Cohorts must be created before the base class is initialized // because the base class' reproduction module uses the core's // SuccessionCohorts property in its Initialization method. Library.LeafBiomassCohorts.Cohorts.Initialize(Timestep, new CohortBiomass()); // Initialize Reproduction routines: Reproduction.SufficientResources = SufficientLight; Reproduction.Establish = Establish; Reproduction.AddNewCohort = AddNewCohort; Reproduction.MaturePresent = MaturePresent; base.Initialize(modelCore, parameters.SeedAlgorithm); InitialBiomass.Initialize(Timestep); Landis.Library.BiomassCohorts.Cohort.DeathEvent += CohortDied; Landis.Library.LeafBiomassCohorts.Cohort.PartialDeathEvent += CohortPartialMortality; AgeOnlyDisturbances.Module.Initialize(parameters.AgeOnlyDisturbanceParms); Dynamic.Module.Initialize(parameters.DynamicUpdates); FireEffects.Initialize(parameters); InitializeSites(parameters.InitialCommunities, parameters.InitialCommunitiesMap, modelCore); //the spinup is heppend within this fucntion if (parameters.CalibrateMode) Outputs.CreateCalibrateLogFile(); Outputs.WritePrimaryLogFile(0); Outputs.WriteShortPrimaryLogFile(0); } //--------------------------------------------------------------------- public override void Run() { if (PlugIn.ModelCore.CurrentTime > 0) SiteVars.InitializeDisturbances(); // Update Pest only once. SpeciesData.EstablishProbability = Establishment.GenerateNewEstablishProbabilities(Timestep); EcoregionData.AnnualNDeposition = new Ecoregions.AuxParm<double>(PlugIn.ModelCore.Ecoregions); base.RunReproductionFirst(); if (ModelCore.CurrentTime % Timestep == 0) { // Write monthly log file: // Output must reflect the order of operation: int[] months = new int[12] { 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5 }; if (OtherData.CalibrateMode) months = new int[12] { 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5 }; for (int i = 0; i < 12; i++) { int month = months[i]; Outputs.WriteMonthlyLogFile(month); } Outputs.WritePrimaryLogFile(PlugIn.ModelCore.CurrentTime); Outputs.WriteShortPrimaryLogFile(PlugIn.ModelCore.CurrentTime); string pathH2O = MapNames.ReplaceTemplateVars(@"NECN_Hydro\Annual-water-budget-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster<IntPixel>(pathH2O, PlugIn.ModelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (int)((SiteVars.AnnualPPT_AET[site])); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } if (SoilCarbonMapNames != null)// && (PlugIn.ModelCore.CurrentTime % SoilCarbonMapFrequency) == 0) { string path = MapNames.ReplaceTemplateVars(SoilCarbonMapNames, PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = modelCore.CreateRaster<IntPixel>(path, modelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (int)((SiteVars.SOM1surface[site].Carbon + SiteVars.SOM1soil[site].Carbon + SiteVars.SOM2[site].Carbon + SiteVars.SOM3[site].Carbon)); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } } if (SoilNitrogenMapNames != null)// && (PlugIn.ModelCore.CurrentTime % SoilNitrogenMapFrequency) == 0) { string path2 = MapNames.ReplaceTemplateVars(SoilNitrogenMapNames, PlugIn.ModelCore.CurrentTime); using (IOutputRaster<ShortPixel> outputRaster = modelCore.CreateRaster<ShortPixel>(path2, modelCore.Landscape.Dimensions)) { ShortPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (short)(SiteVars.MineralN[site]); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } } if (ANPPMapNames != null)// && (PlugIn.ModelCore.CurrentTime % ANPPMapFrequency) == 0) { string path3 = MapNames.ReplaceTemplateVars(ANPPMapNames, PlugIn.ModelCore.CurrentTime); using (IOutputRaster<ShortPixel> outputRaster = modelCore.CreateRaster<ShortPixel>(path3, modelCore.Landscape.Dimensions)) { ShortPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (short)SiteVars.AGNPPcarbon[site]; } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } } if (ANEEMapNames != null)// && (PlugIn.ModelCore.CurrentTime % ANEEMapFrequency) == 0) { string path4 = MapNames.ReplaceTemplateVars(ANEEMapNames, PlugIn.ModelCore.CurrentTime); using (IOutputRaster<ShortPixel> outputRaster = modelCore.CreateRaster<ShortPixel>(path4, modelCore.Landscape.Dimensions)) { ShortPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (short)(SiteVars.AnnualNEE[site] + 1000); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } } if (TotalCMapNames != null)// && (PlugIn.ModelCore.CurrentTime % TotalCMapFrequency) == 0) { string path5 = MapNames.ReplaceTemplateVars(TotalCMapNames, PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = modelCore.CreateRaster<IntPixel>(path5, modelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (int)(Outputs.GetOrganicCarbon(site) + SiteVars.CohortLeafC[site] + SiteVars.CohortFRootC[site] + SiteVars.CohortWoodC[site] + SiteVars.CohortCRootC[site] + SiteVars.SurfaceDeadWood[site].Carbon + SiteVars.SoilDeadWood[site].Carbon); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } } } } //--------------------------------------------------------------------- public override byte ComputeShade(ActiveSite site) { IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site]; byte finalShade = 0; if (!ecoregion.Active) return 0; double B_MAX = (double) EcoregionData.B_MAX[ecoregion]; double oldBiomass = (double) Library.LeafBiomassCohorts.Cohorts.ComputeNonYoungBiomass(SiteVars.Cohorts[site]); int lastMortality = SiteVars.PrevYearMortality[site]; double B_ACT = Math.Min(B_MAX - lastMortality, oldBiomass); // Relative living biomass (ratio of actual to maximum site // biomass). double B_AM = B_ACT / B_MAX; for (byte shade = 5; shade >= 1; shade--) { if(EcoregionData.ShadeBiomass[shade][ecoregion] <= 0) { string mesg = string.Format("Minimum relative biomass has not been defined for ecoregion {0}", ecoregion.Name); throw new System.ApplicationException(mesg); } //PlugIn.ModelCore.UI.WriteLine("Shade Calculation: lastMort={0:0.0}, B_MAX={1}, oldB={2}, B_ACT={3}, shade={4}.", lastMortality, B_MAX,oldBiomass,B_ACT,shade); if (B_AM >= EcoregionData.ShadeBiomass[shade][ecoregion]) { finalShade = shade; break; } } //PlugIn.ModelCore.UI.WriteLine("Yr={0}, Shade Calculation: B_MAX={1}, B_ACT={2}, Shade={3}.", PlugIn.ModelCore.CurrentTime, B_MAX, B_ACT, finalShade); return finalShade; } //--------------------------------------------------------------------- protected override void InitializeSite(ActiveSite site, ICommunity initialCommunity) { InitialBiomass initialBiomass = InitialBiomass.Compute(site, initialCommunity); SiteVars.Cohorts[site] = InitialBiomass.Clone(initialBiomass.Cohorts); //IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site]; SiteVars.SurfaceDeadWood[site] = initialBiomass.SurfaceDeadWood.Clone(); SiteVars.SurfaceStructural[site] = initialBiomass.SurfaceStructural.Clone(); SiteVars.SurfaceMetabolic[site] = initialBiomass.SurfaceMetabolic.Clone(); SiteVars.SoilDeadWood[site] = initialBiomass.SoilDeadWood.Clone(); SiteVars.SoilStructural[site] = initialBiomass.SoilStructural.Clone(); SiteVars.SoilMetabolic[site] = initialBiomass.SoilMetabolic.Clone(); SiteVars.SOM1surface[site] = initialBiomass.SOM1surface.Clone(); SiteVars.SOM1soil[site] = initialBiomass.SOM1soil.Clone(); SiteVars.SOM2[site] = initialBiomass.SOM2.Clone(); SiteVars.SOM3[site] = initialBiomass.SOM3.Clone(); SiteVars.MineralN[site] = initialBiomass.MineralN; SiteVars.CohortLeafC[site] = initialBiomass.CohortLeafC; SiteVars.CohortFRootC[site] = initialBiomass.CohortFRootC; SiteVars.CohortLeafN[site] = initialBiomass.CohortLeafN; SiteVars.CohortFRootN[site] = initialBiomass.CohortFRootN; SiteVars.CohortWoodC[site] = initialBiomass.CohortWoodC; SiteVars.CohortCRootC[site] = initialBiomass.CohortCRootC; SiteVars.CohortWoodN[site] = initialBiomass.CohortWoodN; SiteVars.CohortCRootN[site] = initialBiomass.CohortCRootN; } //--------------------------------------------------------------------- public void CohortPartialMortality(object sender, Landis.Library.BiomassCohorts.PartialDeathEventArgs eventArgs) { ExtensionType disturbanceType = eventArgs.DisturbanceType; ActiveSite site = eventArgs.Site; double reduction = eventArgs.Reduction; ICohort cohort = (Landis.Library.LeafBiomassCohorts.ICohort) eventArgs.Cohort; float fractionPartialMortality = (float)eventArgs.Reduction; //PlugIn.ModelCore.UI.WriteLine("Cohort experienced partial mortality: species={0}, age={1}, wood_biomass={2}, fraction_mortality={3:0.0}.", cohort.Species.Name, cohort.Age, cohort.WoodBiomass, fractionPartialMortality); AgeOnlyDisturbances.PoolPercentages cohortReductions = AgeOnlyDisturbances.Module.Parameters.CohortReductions[disturbanceType]; float foliar = cohort.LeafBiomass * fractionPartialMortality; float wood = cohort.WoodBiomass * fractionPartialMortality; float foliarInput = AgeOnlyDisturbances.Events.ReduceInput(foliar, cohortReductions.Foliar, site); float woodInput = AgeOnlyDisturbances.Events.ReduceInput(wood, cohortReductions.Wood, site); ForestFloor.AddWoodLitter(woodInput, cohort.Species, site); ForestFloor.AddFoliageLitter(foliarInput, cohort.Species, site); Roots.AddCoarseRootLitter(woodInput, cohort, cohort.Species, site); // All of cohorts roots are killed. Roots.AddFineRootLitter(foliarInput, cohort, cohort.Species, site); //PlugIn.ModelCore.UI.WriteLine("EVENT: Cohort Partial Mortality: species={0}, age={1}, disturbance={2}.", cohort.Species.Name, cohort.Age, disturbanceType); //PlugIn.ModelCore.UI.WriteLine(" Cohort Reductions: Foliar={0:0.00}. Wood={1:0.00}.", cohortReductions.Foliar, cohortReductions.Wood); //PlugIn.ModelCore.UI.WriteLine(" InputB/TotalB: Foliar={0:0.00}/{1:0.00}, Wood={2:0.0}/{3:0.0}.", foliarInput, foliar, woodInput, wood); return; } //--------------------------------------------------------------------- public void CohortDied(object sender, Landis.Library.BiomassCohorts.DeathEventArgs eventArgs) { ExtensionType disturbanceType = eventArgs.DisturbanceType; ActiveSite site = eventArgs.Site; ICohort cohort = (Landis.Library.LeafBiomassCohorts.ICohort) eventArgs.Cohort; double foliar = (double)cohort.LeafBiomass; double wood = (double)cohort.WoodBiomass; PlugIn.ModelCore.UI.WriteLine("Cohort Died: species={0}, age={1}, biomass={2}, foliage={3}.", cohort.Species.Name, cohort.Age, cohort.Biomass, foliar); if (disturbanceType == null) { //PlugIn.ModelCore.UI.WriteLine("NO EVENT: Cohort Died: species={0}, age={1}, disturbance={2}.", cohort.Species.Name, cohort.Age, eventArgs.DisturbanceType); ForestFloor.AddWoodLitter(wood, cohort.Species, eventArgs.Site); ForestFloor.AddFoliageLitter(foliar, cohort.Species, eventArgs.Site); Roots.AddCoarseRootLitter(wood, cohort, cohort.Species, eventArgs.Site); Roots.AddFineRootLitter(foliar, cohort, cohort.Species, eventArgs.Site); } if (disturbanceType != null) { //PlugIn.ModelCore.UI.WriteLine("DISTURBANCE EVENT: Cohort Died: species={0}, age={1}, disturbance={2}.", cohort.Species.Name, cohort.Age, eventArgs.DisturbanceType); Disturbed[site] = true; if (disturbanceType.IsMemberOf("disturbance:fire")) Landis.Library.Succession.Reproduction.CheckForPostFireRegen(eventArgs.Cohort, site); else Landis.Library.Succession.Reproduction.CheckForResprouting(eventArgs.Cohort, site); } } //--------------------------------------------------------------------- //Grows the cohorts for future climate protected override void AgeCohorts(ActiveSite site, ushort years, int? successionTimestep) { Main.Run(site, years, successionTimestep.HasValue); } //--------------------------------------------------------------------- /// <summary> /// Determines if there is sufficient light at a site for a species to /// germinate/resprout. /// This is a Delegate method to base succession. /// </summary> public bool SufficientLight(ISpecies species, ActiveSite site) { //PlugIn.ModelCore.UI.WriteLine(" Calculating Sufficient Light from Succession."); byte siteShade = PlugIn.ModelCore.GetSiteVar<byte>("Shade")[site]; double lightProbability = 0.0; bool found = false; foreach (ISufficientLight lights in sufficientLight) { //PlugIn.ModelCore.UI.WriteLine("Sufficient Light: ShadeClass={0}, Prob0={1}.", lights.ShadeClass, lights.ProbabilityLight0); if (lights.ShadeClass == species.ShadeTolerance) { if (siteShade == 0) lightProbability = lights.ProbabilityLight0; if (siteShade == 1) lightProbability = lights.ProbabilityLight1; if (siteShade == 2) lightProbability = lights.ProbabilityLight2; if (siteShade == 3) lightProbability = lights.ProbabilityLight3; if (siteShade == 4) lightProbability = lights.ProbabilityLight4; if (siteShade == 5) lightProbability = lights.ProbabilityLight5; found = true; } } if (!found) PlugIn.ModelCore.UI.WriteLine("A Sufficient Light value was not found for {0}.", species.Name); return modelCore.GenerateUniform() < lightProbability; } //--------------------------------------------------------------------- /// <summary> /// Add a new cohort to a site. /// This is a Delegate method to base succession. /// </summary> public void AddNewCohort(ISpecies species, ActiveSite site) { float[] initialBiomass = CohortBiomass.InitialBiomass(species, SiteVars.Cohorts[site], site); SiteVars.Cohorts[site].AddNewCohort(species, 1, initialBiomass[0], initialBiomass[1]); } //--------------------------------------------------------------------- /// <summary> /// Determines if a species can establish on a site. /// This is a Delegate method to base succession. /// </summary> public bool Establish(ISpecies species, ActiveSite site) { IEcoregion ecoregion = modelCore.Ecoregion[site]; double establishProbability = SpeciesData.EstablishProbability[species][ecoregion]; return modelCore.GenerateUniform() < establishProbability; } //--------------------------------------------------------------------- /// <summary> /// Determines if a species can establish on a site. /// This is a Delegate method to base succession. /// </summary> public bool PlantingEstablish(ISpecies species, ActiveSite site) { IEcoregion ecoregion = modelCore.Ecoregion[site]; double establishProbability = SpeciesData.EstablishProbability[species][ecoregion]; return establishProbability > 0.0; } //--------------------------------------------------------------------- /// <summary> /// Determines if there is a mature cohort at a site. /// This is a Delegate method to base succession. /// </summary> public bool MaturePresent(ISpecies species, ActiveSite site) { return SiteVars.Cohorts[site].IsMaturePresent(species); } } }
// TaskProgressBar (Portable) // Edited By RyuaNerin using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Windows.Forms; using System.Drawing; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.ComTypes; namespace WinTaskbar { public enum TaskbarProgressBarState { NoProgress = 0x00, /// <summary>Color : Green Marquee</summary> Indeterminate = 0x01, /// <summary>Color : Green</summary> Normal = 0x02, /// <summary>Color : Red</summary> Error = 0x04, /// <summary>Color : Yellow</summary> Paused = 0x08 } public class Taskbar { static Taskbar() { Version version = Environment.OSVersion.Version; Taskbar.m_isWin7 = (version.Major > 6) || (version.Major == 6 && version.Minor >= 1); } protected static readonly bool m_isWin7; ////////////////////////////////////////////////////////////////////////// protected IntPtr m_owner = IntPtr.Zero; protected WinAPIs.ITaskbarList4 m_taskbarList = null; protected TaskbarProgress m_taskbarProgress = null; public Taskbar(Form ownerForm) : this() { this.m_owner = ownerForm.Handle; } public Taskbar(IntPtr ownerPtr) : this() { this.m_owner = ownerPtr; } private Taskbar() { if (Taskbar.m_isWin7) { this.m_taskbarList = (WinAPIs.ITaskbarList4)new WinAPIs.CTaskbarList(); m_taskbarList.HrInit(); } this.m_taskbarProgress = new TaskbarProgress(this); } public WinAPIs.ITaskbarList4 TaskbarList { get { return this.m_taskbarList; } } public TaskbarProgress ProgressBar { get { return this.m_taskbarProgress; } } public IntPtr OwnerHandle { get { return this.m_owner; } } #region ProgressBar protected int m_minimum = 0; protected int m_value = 0; protected int m_maximum = 100; protected TaskbarProgressBarState m_state = TaskbarProgressBarState.NoProgress; public class TaskbarProgress { private readonly Taskbar m_taskbar; internal TaskbarProgress(Taskbar taskbar) { m_taskbar = taskbar; } public int Minimum { get { return this.m_taskbar.m_minimum; } set { if (value < this.Maximum) throw new ArgumentOutOfRangeException("Minimum must be smaller or same than Maximum"); this.m_taskbar.m_minimum = value; if (this.m_taskbar.m_value < this.m_taskbar.m_minimum) this.m_taskbar.m_value = this.m_taskbar.m_minimum; this.m_taskbar.SetProgressValue(); } } public int Value { get { return this.m_taskbar.m_value; } set { if (value < this.m_taskbar.m_minimum) throw new ArgumentOutOfRangeException("Value must be bigger or same than Minimum"); if (value > this.m_taskbar.m_maximum) throw new ArgumentOutOfRangeException("Value must be smaller or same than Maximum"); this.m_taskbar.m_value = value; this.m_taskbar.SetProgressValue(); } } public int Maximum { get { return this.m_taskbar.m_maximum; } set { if (value < this.m_taskbar.m_minimum) throw new ArgumentOutOfRangeException("Value must be smaller or same than Maximum"); this.m_taskbar.m_maximum = value; if (this.m_taskbar.m_value > this.m_taskbar.m_maximum) this.m_taskbar.m_value = this.m_taskbar.m_maximum; this.m_taskbar.SetProgressValue(); } } public TaskbarProgressBarState State { get { return this.m_taskbar.m_state; } set { this.m_taskbar.m_state = value; this.m_taskbar.SetProgressState(this.m_taskbar.m_state); } } } public void SetProgressValue(int minimumValue, int currentValue, int maximumValue) { if (!Taskbar.m_isWin7) return; if (currentValue < minimumValue) throw new ArgumentOutOfRangeException("currentValue must be same or bigger than minimumvalue"); if (maximumValue < currentValue) throw new ArgumentOutOfRangeException("maximumValue must be same or bigger than currentValue"); if (maximumValue < minimumValue) throw new ArgumentOutOfRangeException("maximumValue must be same or bigger than minimumValue"); this.m_minimum = minimumValue; this.m_value = currentValue; this.m_maximum = maximumValue; this.SetProgressValue(); } public void SetProgressValue(int currentValue, int maximumValue) { if (maximumValue < currentValue) throw new ArgumentOutOfRangeException("maximumValue must be same or bigger than currentValue"); this.m_value = currentValue + this.m_minimum; this.m_maximum = maximumValue + this.m_minimum; this.SetProgressValue(); } protected void SetProgressValue() { if (!Taskbar.m_isWin7) return; UInt64 min, val, max; min = Convert.ToUInt64(this.m_minimum); val = Convert.ToUInt64(this.m_value); max = Convert.ToUInt64(this.m_maximum); this.m_taskbarList.SetProgressValue(this.OwnerHandle, val - min, max - min); } public void SetProgressState(TaskbarProgressBarState state) { if (!Taskbar.m_isWin7) return; this.m_state = state; this.m_taskbarList.SetProgressState(this.OwnerHandle, (WinAPIs.TBPFLAG)state); } #endregion public void SetOverlayIcon(Icon icon, string accessibilityText) { if (!Taskbar.m_isWin7) return; this.m_taskbarList.SetOverlayIcon(this.OwnerHandle, (icon != null ? icon.Handle : IntPtr.Zero), accessibilityText); } } public class WinAPIs { #pragma warning disable 108 [GuidAttribute("56FDF344-FD6D-11d0-958A-006097C9A090")] [ClassInterfaceAttribute(ClassInterfaceType.None)] [ComImportAttribute()] public class CTaskbarList { } [ComImportAttribute()] [GuidAttribute("c43dc798-95d1-4bea-9030-bb99e2983a1a")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] public interface ITaskbarList4 { [PreserveSig] void HrInit(); [PreserveSig] void AddTab(IntPtr hwnd); [PreserveSig] void DeleteTab(IntPtr hwnd); [PreserveSig] void ActivateTab(IntPtr hwnd); [PreserveSig] void SetActiveAlt(IntPtr hwnd); [PreserveSig] void MarkFullscreenWindow(IntPtr hwnd, [MarshalAs(UnmanagedType.Bool)] bool fFullscreen); [PreserveSig] void SetProgressValue(IntPtr hwnd, UInt64 ullCompleted, UInt64 ullTotal); [PreserveSig] void SetProgressState(IntPtr hwnd, TBPFLAG tbpFlags); [PreserveSig] void RegisterTab(IntPtr hwndTab, IntPtr hwndMDI); [PreserveSig] void UnregisterTab(IntPtr hwndTab); [PreserveSig] void SetTabOrder(IntPtr hwndTab, IntPtr hwndInsertBefore); [PreserveSig] void SetTabActive(IntPtr hwndTab, IntPtr hwndInsertBefore, uint dwReserved); [PreserveSig] uint ThumbBarAddButtons(IntPtr hwnd, uint cButtons, [MarshalAs(UnmanagedType.LPArray)] THUMBBUTTON[] pButtons); [PreserveSig] uint ThumbBarUpdateButtons(IntPtr hwnd, uint cButtons, [MarshalAs(UnmanagedType.LPArray)] THUMBBUTTON[] pButtons); [PreserveSig] void ThumbBarSetImageList(IntPtr hwnd, IntPtr himl); [PreserveSig] void SetOverlayIcon(IntPtr hwnd, IntPtr hIcon, [MarshalAs(UnmanagedType.LPWStr)] string pszDescription); [PreserveSig] void SetThumbnailTooltip(IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszTip); [PreserveSig] void SetThumbnailClip(IntPtr hwnd, IntPtr prcClip); void SetTabProperties(IntPtr hwndTab, STPFLAG stpFlags); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct THUMBBUTTON { [MarshalAs(UnmanagedType.U4)] internal THBMASK dwMask; internal uint iId; internal uint iBitmap; internal IntPtr hIcon; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] internal string szTip; [MarshalAs(UnmanagedType.U4)] internal THBFLAGS dwFlags; } public enum THBMASK { THB_BITMAP = 0x1, THB_ICON = 0x2, THB_TOOLTIP = 0x4, THB_FLAGS = 0x8 } public enum TBPFLAG { TBPF_NOPROGRESS = 0, TBPF_INDETERMINATE = 0x1, TBPF_NORMAL = 0x2, TBPF_ERROR = 0x4, TBPF_PAUSED = 0x8 } [Flags] public enum THBFLAGS { THBF_ENABLED = 0x00000000, THBF_DISABLED = 0x00000001, THBF_DISMISSONCLICK = 0x00000002, THBF_NOBACKGROUND = 0x00000004, THBF_HIDDEN = 0x00000008, THBF_NONINTERACTIVE = 0x00000010 } public enum STPFLAG { STPF_NONE = 0x0, STPF_USEAPPTHUMBNAILALWAYS = 0x1, STPF_USEAPPTHUMBNAILWHENACTIVE = 0x2, STPF_USEAPPPEEKALWAYS = 0x4, STPF_USEAPPPEEKWHENACTIVE = 0x8 } #pragma warning restore 108 } }
#region Copyright (c) 2004 Ian Davis and James Carlyle /*------------------------------------------------------------------------------ COPYRIGHT AND PERMISSION NOTICE Copyright (c) 2004 Ian Davis and James Carlyle Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------*/ #endregion namespace SemPlan.Spiral.Tests.Core { using NUnit.Framework; using SemPlan.Spiral.Core; using System; /// <summary> /// Programmer tests for Node class /// </summary> /// <remarks> /// $Id: PlainLiteralNodeTest.cs,v 1.2 2005/05/26 14:24:30 ian Exp $ ///</remarks> [TestFixture] public class PlainLiteralTest { [Test] public void labelIsLexicalValue() { PlainLiteral node = new PlainLiteral("whizz"); Assert.AreEqual("whizz", node.GetLabel()); } [Test] public void languageSpecifiedInConstructor() { PlainLiteral node = new PlainLiteral("whizz", "fr"); Assert.AreEqual("fr", node.GetLanguage()); } [Test] public void languageDefaultsToNull() { PlainLiteral node = new PlainLiteral("whizz"); Assert.AreEqual(null, node.GetLanguage()); } [Test] public void neverEqualsNull() { PlainLiteral instance = new PlainLiteral("whizz"); Assert.IsFalse( instance.Equals(null) ); } [Test] public void neverEqualsInstanceOfDifferentClass() { PlainLiteral instance = new PlainLiteral("whizz"); Object obj = new Object(); Assert.IsFalse( instance.Equals(obj) ); } [Test] public void alwaysEqualsSelf() { PlainLiteral instance = new PlainLiteral("whizz"); Assert.IsTrue( instance.Equals(instance) ); } [Test] public void neverEqualsInstanceOfSameClassButDifferentLexicalValueAndNoLanguage() { PlainLiteral instance = new PlainLiteral("whizz"); PlainLiteral other = new PlainLiteral("bang"); Assert.IsFalse( instance.Equals(other) ); } [Test] public void alwaysEqualsInstanceOfSameClassWithSameLexicalValueAndNoLanguage() { PlainLiteral instance = new PlainLiteral("whizz"); PlainLiteral other = new PlainLiteral("whizz"); Assert.IsTrue( instance.Equals(other) ); } [Test] public void neverEqualsInstanceOfSameClassWithSameLexicalValueAndDifferentLanguage() { PlainLiteral instance = new PlainLiteral("whizz", "en"); PlainLiteral other = new PlainLiteral("whizz", "fr"); Assert.IsFalse( instance.Equals(other) ); } [Test] public void alwaysEqualsInstanceOfSameClassWithSameLexicalValueAndSameLanguage() { PlainLiteral instance = new PlainLiteral("whizz", "en"); PlainLiteral other = new PlainLiteral("whizz", "en"); Assert.IsTrue( instance.Equals(other) ); } [Test] public void getHashCodeReturnsDifferentCodeForDifferentInstancesWithDifferentLexicalValues() { PlainLiteral instance = new PlainLiteral("whizz"); PlainLiteral other = new PlainLiteral("bang"); Assert.IsFalse( instance.GetHashCode() == other.GetHashCode() ); } [Test] public void getHashCodeReturnsSameCodeForDifferentInstancesWithSameLexicalValuesAndNoLanguage() { PlainLiteral instance = new PlainLiteral("whizz"); PlainLiteral other = new PlainLiteral("whizz"); Assert.IsTrue( instance.GetHashCode() == other.GetHashCode() ); } [Test] public void getHashCodeReturnsDifferentCodeForDifferentInstancesWithSameLexicalValuesButDifferentLanguages() { PlainLiteral instance = new PlainLiteral("whizz", "en"); PlainLiteral other = new PlainLiteral("whizz", "fr"); Assert.IsFalse( instance.GetHashCode() == other.GetHashCode() ); } [Test] public void getHashCodeReturnsSameCodeForDifferentInstancesWithSameLexicalValuesAndSameLanguage() { PlainLiteral instance = new PlainLiteral("whizz", "en"); PlainLiteral other = new PlainLiteral("whizz", "en"); Assert.IsTrue( instance.GetHashCode() == other.GetHashCode() ); } [Test] public void writeCallsWriterWritePlainLiteralOnceWithNoLanguage() { RdfWriterCounter writer = new RdfWriterCounter(); PlainLiteral instance = new PlainLiteral("whizz"); instance.Write(writer); Assert.AreEqual( 1, writer.WritePlainLiteralCalled ); } [Test] public void writeCallsWriterWritePlainLiteralOnceWithLanguage() { RdfWriterCounter writer = new RdfWriterCounter(); PlainLiteral instance = new PlainLiteral("whizz", "en"); instance.Write(writer); Assert.AreEqual( 1, writer.WritePlainLiteralLanguageCalled ); } [Test] public void writeCallsWriterWritePlainLiteralWithCorrectArgumentsWithNoLanguage() { RdfWriterStore writer = new RdfWriterStore(); PlainLiteral instance = new PlainLiteral("whizz"); instance.Write(writer); Assert.IsTrue( writer.WasWritePlainLiteralCalledWith("whizz") ); } [Test] public void writeCallsWriterWritePlainLiteralWithCorrectArgumentsWithLanguage() { RdfWriterStore writer = new RdfWriterStore(); PlainLiteral instance = new PlainLiteral("whizz", "gr"); instance.Write(writer); Assert.IsTrue( writer.WasWritePlainLiteralCalledWith("whizz", "gr") ); } [Test] public void matchesCallsMatchesPlainLiteralWithoutLanguageOnSpecifier() { ResourceSpecifierStore specifier = new ResourceSpecifierStore(); PlainLiteral instance = new PlainLiteral("whizz"); instance.Matches( specifier ); Assert.IsTrue( specifier.WasMatchesPlainLiteralCalledWith("whizz") ); } [Test] public void matchesCallsMatchesPlainLiteralWithLanguageOnSpecifier() { ResourceSpecifierStore specifier = new ResourceSpecifierStore(); PlainLiteral instance = new PlainLiteral("whizz", "de"); instance.Matches( specifier ); Assert.IsTrue( specifier.WasMatchesPlainLiteralCalledWith("whizz", "de") ); } [Test] public void matchesReturnsResponseFromMatchesPlainLiterallWithoutLanguageCall() { ResourceSpecifierResponder specifierTrue = new ResourceSpecifierResponder(true); ResourceSpecifierResponder specifierFalse = new ResourceSpecifierResponder(false); PlainLiteral instance = new PlainLiteral("whizz"); Assert.IsTrue( instance.Matches( specifierTrue )); Assert.IsFalse( instance.Matches( specifierFalse )); } [Test] public void matchesReturnsResponseFromMatchesPlainLiterallWithLanguageCall() { ResourceSpecifierResponder specifierTrue = new ResourceSpecifierResponder(true); ResourceSpecifierResponder specifierFalse = new ResourceSpecifierResponder(false); PlainLiteral instance = new PlainLiteral("whizz", "de"); Assert.IsTrue( instance.Matches( specifierTrue )); Assert.IsFalse( instance.Matches( specifierFalse )); } } }
#region Using directives #define USE_TRACING using System; using System.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Xml; #endregion ////////////////////////////////////////////////////////////////////// // contains AtomTextConstruct, the base class for all atom text representations // atomPlainTextConstruct = // atomCommonAttributes, // attribute type { "text" | "html" }?, // text // // atomXHTMLTextConstruct = // atomCommonAttributes, // attribute type { "xhtml" }, // xhtmlDiv // // atomTextConstruct = atomPlainTextConstruct | atomXHTMLTextConstruct ////////////////////////////////////////////////////////////////////// namespace Google.GData.Client { /// <summary>enum to define the AtomTextConstructs Type...</summary> public enum AtomTextConstructElementType { /// <summary>this is a Right element</summary> Rights, /// <summary>this is a title element</summary> Title, /// <summary>this is a subtitle element</summary> Subtitle, /// <summary>this is a summary element</summary> Summary } /// <summary>enum to define the AtomTextConstructs Type...</summary> public enum AtomTextConstructType { /// <summary>defines standard text</summary> text, /// <summary>defines html text</summary> html, /// <summary>defines xhtml text</summary> xhtml } ////////////////////////////////////////////////////////////////////// /// <summary>TypeConverter, so that AtomTextConstruct shows up in the property pages /// </summary> ////////////////////////////////////////////////////////////////////// [ComVisible(false)] public class AtomTextConstructConverter : ExpandableObjectConverter { ///<summary>Standard type converter method</summary> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof (AtomTextConstruct)) return true; return base.CanConvertTo(context, destinationType); } ///<summary>Standard type converter method</summary> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { AtomTextConstruct tc = value as AtomTextConstruct; if (destinationType == typeof (string) && tc != null) { return tc.Type + ": " + tc.Text; } return base.ConvertTo(context, culture, value, destinationType); } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>AtomTextConstruct object representation /// A Text construct contains human-readable text, usually in small quantities. /// The content of Text constructs is Language-Sensitive. /// </summary> ////////////////////////////////////////////////////////////////////// [TypeConverter(typeof (AtomTextConstructConverter)), Description("Expand to see details for this object.")] public class AtomTextConstruct : AtomBase { /// <summary>holds the element type</summary> private readonly AtomTextConstructElementType elementType; /// <summary>holds the text as string</summary> private string text; /// <summary>holds the type of the text</summary> private AtomTextConstructType type; /// <summary>the public constructor only exists for the pleasure of property pages</summary> public AtomTextConstruct() { } ////////////////////////////////////////////////////////////////////// /// <summary>constructor indicating the elementtype</summary> /// <param name="elementType">holds the xml elementype</param> ////////////////////////////////////////////////////////////////////// public AtomTextConstruct(AtomTextConstructElementType elementType) { this.elementType = elementType; type = AtomTextConstructType.text; // set the default to text } ////////////////////////////////////////////////////////////////////// /// <summary>constructor indicating the elementtype</summary> /// <param name="elementType">holds the xml elementype</param> /// <param name="text">holds the text string</param> ////////////////////////////////////////////////////////////////////// public AtomTextConstruct(AtomTextConstructElementType elementType, string text) : this(elementType) { this.text = text; } ///////////////////////////////////////////////////////////////////////////// // // ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public AtomTextConstructType Type</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public AtomTextConstructType Type { get { return type; } set { Dirty = true; type = value; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public string Text</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Text { get { return text; } set { Dirty = true; text = value; } } ///////////////////////////////////////////////////////////////////////////// #region Persistence overloads ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public override string XmlName { get { switch (elementType) { case AtomTextConstructElementType.Rights: return AtomParserNameTable.XmlRightsElement; case AtomTextConstructElementType.Subtitle: return AtomParserNameTable.XmlSubtitleElement; case AtomTextConstructElementType.Title: return AtomParserNameTable.XmlTitleElement; case AtomTextConstructElementType.Summary: return AtomParserNameTable.XmlSummaryElement; } return null; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>overridden to save attributes for this(XmlWriter writer)</summary> /// <param name="writer">the xmlwriter to save into </param> ////////////////////////////////////////////////////////////////////// protected override void SaveXmlAttributes(XmlWriter writer) { WriteEncodedAttributeString(writer, AtomParserNameTable.XmlAttributeType, Type.ToString()); // call base later as base takes care of writing out extension elements that might close the attribute list base.SaveXmlAttributes(writer); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>saves the inner state of the element</summary> /// <param name="writer">the xmlWriter to save into </param> ////////////////////////////////////////////////////////////////////// protected override void SaveInnerXml(XmlWriter writer) { base.SaveInnerXml(writer); if (Type == AtomTextConstructType.xhtml) { if (Utilities.IsPersistable(text)) { writer.WriteRaw(text); } } else { WriteEncodedString(writer, text); } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>figures out if this object should be persisted</summary> /// <returns> true, if it's worth saving</returns> ////////////////////////////////////////////////////////////////////// public override bool ShouldBePersisted() { if (!base.ShouldBePersisted()) { return Utilities.IsPersistable(text); } return true; } ///////////////////////////////////////////////////////////////////////////// #endregion } ///////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////////
#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.ObjectModel; namespace Newtonsoft.Json.Linq { internal class JPropertyKeyedCollection : Collection<JToken> { private static readonly IEqualityComparer<string> Comparer = StringComparer.Ordinal; private Dictionary<string, JToken> _dictionary; private void AddKey(string key, JToken item) { EnsureDictionary(); _dictionary[key] = item; } protected void ChangeItemKey(JToken item, string newKey) { if (!ContainsItem(item)) throw new ArgumentException("The specified item does not exist in this KeyedCollection."); string keyForItem = GetKeyForItem(item); if (!Comparer.Equals(keyForItem, newKey)) { if (newKey != null) AddKey(newKey, item); if (keyForItem != null) RemoveKey(keyForItem); } } protected override void ClearItems() { base.ClearItems(); if (_dictionary != null) _dictionary.Clear(); } public bool Contains(string key) { if (key == null) throw new ArgumentNullException("key"); if (_dictionary != null) return _dictionary.ContainsKey(key); return false; } private bool ContainsItem(JToken item) { if (_dictionary == null) return false; string key = GetKeyForItem(item); JToken value; return _dictionary.TryGetValue(key, out value); } private void EnsureDictionary() { if (_dictionary == null) _dictionary = new Dictionary<string, JToken>(Comparer); } private string GetKeyForItem(JToken item) { return ((JProperty)item).Name; } protected override void InsertItem(int index, JToken item) { AddKey(GetKeyForItem(item), item); base.InsertItem(index, item); } public bool Remove(string key) { if (key == null) throw new ArgumentNullException("key"); if (_dictionary != null) return _dictionary.ContainsKey(key) && Remove(_dictionary[key]); return false; } protected override void RemoveItem(int index) { string keyForItem = GetKeyForItem(Items[index]); RemoveKey(keyForItem); base.RemoveItem(index); } private void RemoveKey(string key) { if (_dictionary != null) _dictionary.Remove(key); } protected override void SetItem(int index, JToken item) { string keyForItem = GetKeyForItem(item); string keyAtIndex = GetKeyForItem(Items[index]); if (Comparer.Equals(keyAtIndex, keyForItem)) { if (_dictionary != null) _dictionary[keyForItem] = item; } else { AddKey(keyForItem, item); if (keyAtIndex != null) RemoveKey(keyAtIndex); } base.SetItem(index, item); } public JToken this[string key] { get { if (key == null) throw new ArgumentNullException("key"); if (_dictionary != null) return _dictionary[key]; throw new KeyNotFoundException(); } } public bool TryGetValue(string key, out JToken value) { if (_dictionary == null) { value = null; return false; } return _dictionary.TryGetValue(key, out value); } public ICollection<string> Keys { get { EnsureDictionary(); return _dictionary.Keys; } } public ICollection<JToken> Values { get { EnsureDictionary(); return _dictionary.Values; } } public bool Compare(JPropertyKeyedCollection other) { if (this == other) return true; // dictionaries in JavaScript aren't ordered // ignore order when comparing properties Dictionary<string, JToken> d1 = _dictionary; Dictionary<string, JToken> d2 = other._dictionary; if (d1 == null && d2 == null) return true; if (d1 == null) return (d2.Count == 0); if (d2 == null) return (d1.Count == 0); if (d1.Count != d2.Count) return false; foreach (KeyValuePair<string, JToken> keyAndProperty in d1) { JToken secondValue; if (!d2.TryGetValue(keyAndProperty.Key, out secondValue)) return false; JProperty p1 = (JProperty)keyAndProperty.Value; JProperty p2 = (JProperty)secondValue; if (!p1.Value.DeepEquals(p2.Value)) return false; } return true; } } }
using System; using System.Collections.ObjectModel; using System.Linq; using Android.Content; using Android.Graphics; using Android.Views; using Xamarin.Forms.Platform.Android; namespace XFShapeView.Droid { public class Shape : View { private readonly float _density; private readonly ShapeView _shapeView; public Shape(float density, Context context, ShapeView shapeView) : base(context) { if (shapeView == null) throw new ArgumentNullException(nameof(shapeView)); this._density = density; this._shapeView = shapeView; } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); var x = this.GetX() + this.Resize(this._shapeView.Padding.Left); var y = this.GetY() + this.Resize(this._shapeView.Padding.Top); var width = base.Width - this.Resize(this._shapeView.Padding.HorizontalThickness); var height = base.Height - this.Resize(this._shapeView.Padding.VerticalThickness); var cx = width/2f+this.Resize(this._shapeView.Padding.Left); var cy = height/2f + this.Resize(this._shapeView.Padding.Top); var strokeWidth = 0f; Paint strokePaint = null; if (this._shapeView.BorderWidth > 0 && this._shapeView.BorderColor.A > 0) { strokeWidth = this.Resize(this._shapeView.BorderWidth); strokePaint = new Paint(PaintFlags.AntiAlias); strokePaint.SetStyle(Paint.Style.Stroke); strokePaint.StrokeWidth = strokeWidth; strokePaint.StrokeCap = Paint.Cap.Round; strokePaint.Color = this._shapeView.BorderColor.ToAndroid(); x += strokeWidth/2f; y += strokeWidth/2f; width -= strokeWidth; height -= strokeWidth; } Paint fillPaint = null; if (this._shapeView.Color.A > 0) { fillPaint = new Paint(PaintFlags.AntiAlias); fillPaint.SetStyle(Paint.Style.Fill); fillPaint.Color = this._shapeView.Color.ToAndroid(); } if (this._shapeView.CornerRadius > 0) { switch (this._shapeView.ShapeType) { case ShapeType.Star: case ShapeType.Triangle: case ShapeType.Diamond: case ShapeType.Path: var cr = this.Resize(this._shapeView.CornerRadius); var cornerPathEffect = new CornerPathEffect(cr); fillPaint?.SetPathEffect(cornerPathEffect); strokePaint?.SetPathEffect(cornerPathEffect); break; } } switch (this._shapeView.ShapeType) { case ShapeType.Box: this.DrawBox(canvas, x, y, width, height, this._shapeView.CornerRadius, fillPaint, strokePaint); break; case ShapeType.Circle: this.DrawCircle(canvas, cx, cy, Math.Min(height, width)/2f, fillPaint, strokePaint); break; case ShapeType.Oval: this.DrawOval(canvas, x, y, width, height, fillPaint, strokePaint); break; case ShapeType.Star: var outerRadius = (Math.Min(height, width) - strokeWidth)/2f; var innerRadius = outerRadius*this._shapeView.RadiusRatio; this.DrawStar(canvas, cx, cy, outerRadius, innerRadius, this._shapeView.CornerRadius, this._shapeView.NumberOfPoints, fillPaint, strokePaint); break; case ShapeType.Triangle: this.DrawTriangle(canvas, x + strokeWidth/2, y + strokeWidth/2, width - strokeWidth, height - strokeWidth, fillPaint, strokePaint); break; case ShapeType.Diamond: this.DrawDiamond(canvas, x + strokeWidth/2, y + strokeWidth/2, width - strokeWidth, height - strokeWidth, fillPaint, strokePaint); break; case ShapeType.Heart: this.DrawHeart(canvas, x, y, width, height, this.Resize(this._shapeView.CornerRadius), fillPaint, strokePaint); break; case ShapeType.ProgressCircle: this.DrawCircle(canvas, cx, cy, Math.Min(height, width)/2f, fillPaint, strokePaint); if (this._shapeView.ProgressBorderWidth > 0 && this._shapeView.ProgressBorderColor.A > 0) { var progressStrokeWidth = this.Resize(this._shapeView.ProgressBorderWidth); var progressPaint = new Paint(PaintFlags.AntiAlias); progressPaint.SetStyle(Paint.Style.Stroke); progressPaint.StrokeWidth = progressStrokeWidth; progressPaint.Color = this._shapeView.ProgressBorderColor.ToAndroid(); var deltaWidth = progressStrokeWidth - strokeWidth; if (deltaWidth > 0) { width -= deltaWidth; height -= deltaWidth; } this.DrawProgressCircle(canvas, cx, cy, Math.Min(height, width)/2f, this._shapeView.Progress, progressPaint); } break; case ShapeType.Path: this.DrawPath(canvas, this._shapeView.Points, x, y, fillPaint, strokePaint); break; } } #region Drawing Methods #region Basic shapes protected virtual void DrawBox(Canvas canvas, float left, float top, float width, float height, float cornerRadius, Paint fillPaint, Paint strokePaint) { var rect = new RectF(left, top, left + width, top + height); if (cornerRadius > 0) { var cr = this.Resize(cornerRadius); if (fillPaint != null) canvas.DrawRoundRect(rect, cr, cr, fillPaint); if (strokePaint != null) canvas.DrawRoundRect(rect, cr, cr, strokePaint); } else { if (fillPaint != null) canvas.DrawRect(rect, fillPaint); if (strokePaint != null) canvas.DrawRect(rect, strokePaint); } } protected virtual void DrawCircle(Canvas canvas, float cx, float cy, float radius, Paint fillPaint, Paint strokePaint) { if (fillPaint != null) canvas.DrawCircle(cx, cy, radius, fillPaint); if (strokePaint != null) canvas.DrawCircle(cx, cy, radius, strokePaint); } protected virtual void DrawOval(Canvas canvas, float left, float top, float width, float height, Paint fillPaint, Paint strokePaint) { var rect = new RectF(left, top, left + width, top + height); if (fillPaint != null) canvas.DrawOval(rect, fillPaint); if (strokePaint != null) canvas.DrawOval(rect, strokePaint); } protected virtual void DrawProgressCircle(Canvas canvas, float cx, float cy, float radius, float progress, Paint progressPaint) { if (progressPaint != null) canvas.DrawArc(new RectF(cx - radius, cy - radius, cx + radius, cy + radius), -90, 360f*(progress/100f), false, progressPaint); } #endregion #region Path Methods protected virtual void DrawStar(Canvas canvas, float cx, float cy, float outerRadius, float innerRadius, float cornerRadius, int numberOfPoints, Paint fillPaint, Paint strokePaint) { if (numberOfPoints <= 0) return; var baseAngle = Math.PI / numberOfPoints; var isOuter = false; var xPath = cx; var yPath = innerRadius + cy; var path = new Path(); path.MoveTo(xPath, yPath); var i = baseAngle; while (i <= Math.PI * 2) { var currentRadius = isOuter ? innerRadius : outerRadius; isOuter = !isOuter; xPath = (float)(currentRadius * Math.Sin(i)) + cx; yPath = (float)(currentRadius * Math.Cos(i)) + cy; path.LineTo(xPath, yPath); i += baseAngle; } path.Close(); if (fillPaint != null) canvas.DrawPath(path, fillPaint); if (strokePaint != null) canvas.DrawPath(path, strokePaint); } protected virtual void DrawDiamond(Canvas canvas, float x, float y, float width, float height, Paint fillPaint, Paint strokePaint) { var path = new Path(); var centerX = width/2f + x; var centerY = height/2f + y; path.MoveTo(centerX, y); path.LineTo(x + width, centerY); path.LineTo(centerX, height + y); path.LineTo(x, centerY); path.Close(); this.DrawPath(canvas, path, fillPaint, strokePaint); } protected virtual void DrawTriangle(Canvas canvas, float x, float y, float width, float height, Paint fillPaint, Paint strokePaint) { var path = new Path(); path.MoveTo(x, height + y); path.LineTo(x+ width, height + y); path.LineTo(width/2f + x, y); path.Close(); this.DrawPath(canvas, path,fillPaint, strokePaint); } protected virtual void DrawHeart(Canvas canvas, float x, float y, float width, float height, float cornerRadius, Paint fillPaint, Paint strokePaint) { var length = Math.Min(height, width); var p1 = new PointF(x, y + length); var p2 = new PointF(x + 2f*length/3f, y + length); var p3 = new PointF(x + 2f*length/3f, y + length/3f); var p4 = new PointF(x, y + length/3f); var radius = length/3f; var path = new Path(); path.MoveTo(p4.X, p4.Y); path.LineTo(p1.X, p1.Y - cornerRadius); path.LineTo(p1.X + cornerRadius, p1.Y); path.LineTo(p2.X, p2.Y); path.LineTo(p3.X, p3.Y); path.Close(); if (cornerRadius > 0) path.AddArc(new RectF(p1.X, (p1.Y + p4.Y)/2f, (p2.X + p1.X)/2f, p2.Y), 90, 90); path.AddArc(new RectF(p3.X - radius, p3.Y, p3.X + radius, p2.Y), -90f, 180f); path.AddArc(new RectF(p4.X, p4.Y - radius, p3.X, p4.Y + radius), 180f, 180f); var matrix = new Matrix(); matrix.SetTranslate(-length/3f, -length*2f/3f); path.Transform(matrix); matrix.Reset(); matrix.SetRotate(-45f); path.Transform(matrix); matrix.Reset(); matrix.SetScale(0.85f, 0.85f); path.Transform(matrix); matrix.Reset(); matrix.SetTranslate(width/2f, 1.1f*height/2f); path.Transform(matrix); this.DrawPath(canvas, path, fillPaint, strokePaint); } protected virtual void DrawPath(Canvas canvas, ObservableCollection<Xamarin.Forms.Point> points, float x, float y, Paint fillPaint, Paint strokePaint) { if (points == null || points.Count == 0) return; var path = new Path(); var resizedPoints = points.Select(p => new PointF(this.Resize((double) p.X), this.Resize((double) p.Y))).ToList(); path.MoveTo((float)resizedPoints[0].X, (float)resizedPoints[0].Y); for (var i = 1; i < resizedPoints.Count; ++i) { path.LineTo((float)resizedPoints[i].X, (float)resizedPoints[i].Y); } path.Close(); var matrix = new Matrix(); matrix.SetTranslate(x, y); path.Transform(matrix); this.DrawPath(canvas, path, fillPaint, strokePaint); } protected virtual void DrawPath(Canvas canvas, Path path, Paint fillPaint, Paint strokePaint) { if (fillPaint != null) canvas.DrawPath(path, fillPaint); if (strokePaint != null) canvas.DrawPath(path, strokePaint); } #endregion #endregion #region Density Helpers protected float Resize(float input) { return input*this._density; } protected float Resize(double input) { return this.Resize((float) input); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>CustomerClientLink</c> resource.</summary> public sealed partial class CustomerClientLinkName : gax::IResourceName, sys::IEquatable<CustomerClientLinkName> { /// <summary>The possible contents of <see cref="CustomerClientLinkName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c>. /// </summary> CustomerClientCustomerManagerLink = 1, } private static gax::PathTemplate s_customerClientCustomerManagerLink = new gax::PathTemplate("customers/{customer_id}/customerClientLinks/{client_customer_id_manager_link_id}"); /// <summary>Creates a <see cref="CustomerClientLinkName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CustomerClientLinkName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CustomerClientLinkName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomerClientLinkName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CustomerClientLinkName"/> with the pattern /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clientCustomerId">The <c>ClientCustomer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="managerLinkId">The <c>ManagerLink</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CustomerClientLinkName"/> constructed from the provided ids.</returns> public static CustomerClientLinkName FromCustomerClientCustomerManagerLink(string customerId, string clientCustomerId, string managerLinkId) => new CustomerClientLinkName(ResourceNameType.CustomerClientCustomerManagerLink, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), clientCustomerId: gax::GaxPreconditions.CheckNotNullOrEmpty(clientCustomerId, nameof(clientCustomerId)), managerLinkId: gax::GaxPreconditions.CheckNotNullOrEmpty(managerLinkId, nameof(managerLinkId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerClientLinkName"/> with pattern /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clientCustomerId">The <c>ClientCustomer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="managerLinkId">The <c>ManagerLink</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerClientLinkName"/> with pattern /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c>. /// </returns> public static string Format(string customerId, string clientCustomerId, string managerLinkId) => FormatCustomerClientCustomerManagerLink(customerId, clientCustomerId, managerLinkId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerClientLinkName"/> with pattern /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clientCustomerId">The <c>ClientCustomer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="managerLinkId">The <c>ManagerLink</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerClientLinkName"/> with pattern /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c>. /// </returns> public static string FormatCustomerClientCustomerManagerLink(string customerId, string clientCustomerId, string managerLinkId) => s_customerClientCustomerManagerLink.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(clientCustomerId, nameof(clientCustomerId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(managerLinkId, nameof(managerLinkId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerClientLinkName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="customerClientLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CustomerClientLinkName"/> if successful.</returns> public static CustomerClientLinkName Parse(string customerClientLinkName) => Parse(customerClientLinkName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerClientLinkName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerClientLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CustomerClientLinkName"/> if successful.</returns> public static CustomerClientLinkName Parse(string customerClientLinkName, bool allowUnparsed) => TryParse(customerClientLinkName, allowUnparsed, out CustomerClientLinkName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerClientLinkName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="customerClientLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerClientLinkName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customerClientLinkName, out CustomerClientLinkName result) => TryParse(customerClientLinkName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerClientLinkName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerClientLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerClientLinkName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customerClientLinkName, bool allowUnparsed, out CustomerClientLinkName result) { gax::GaxPreconditions.CheckNotNull(customerClientLinkName, nameof(customerClientLinkName)); gax::TemplatedResourceName resourceName; if (s_customerClientCustomerManagerLink.TryParseName(customerClientLinkName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerClientCustomerManagerLink(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customerClientLinkName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private CustomerClientLinkName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string clientCustomerId = null, string customerId = null, string managerLinkId = null) { Type = type; UnparsedResource = unparsedResourceName; ClientCustomerId = clientCustomerId; CustomerId = customerId; ManagerLinkId = managerLinkId; } /// <summary> /// Constructs a new instance of a <see cref="CustomerClientLinkName"/> class from the component parts of /// pattern <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clientCustomerId">The <c>ClientCustomer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="managerLinkId">The <c>ManagerLink</c> ID. Must not be <c>null</c> or empty.</param> public CustomerClientLinkName(string customerId, string clientCustomerId, string managerLinkId) : this(ResourceNameType.CustomerClientCustomerManagerLink, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), clientCustomerId: gax::GaxPreconditions.CheckNotNullOrEmpty(clientCustomerId, nameof(clientCustomerId)), managerLinkId: gax::GaxPreconditions.CheckNotNullOrEmpty(managerLinkId, nameof(managerLinkId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>ClientCustomer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string ClientCustomerId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>ManagerLink</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ManagerLinkId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerClientCustomerManagerLink: return s_customerClientCustomerManagerLink.Expand(CustomerId, $"{ClientCustomerId}~{ManagerLinkId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CustomerClientLinkName); /// <inheritdoc/> public bool Equals(CustomerClientLinkName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomerClientLinkName a, CustomerClientLinkName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomerClientLinkName a, CustomerClientLinkName b) => !(a == b); } public partial class CustomerClientLink { /// <summary> /// <see cref="CustomerClientLinkName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal CustomerClientLinkName ResourceNameAsCustomerClientLinkName { get => string.IsNullOrEmpty(ResourceName) ? null : CustomerClientLinkName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="CustomerName"/>-typed view over the <see cref="ClientCustomer"/> resource name property. /// </summary> internal CustomerName ClientCustomerAsCustomerName { get => string.IsNullOrEmpty(ClientCustomer) ? null : CustomerName.Parse(ClientCustomer, allowUnparsed: true); set => ClientCustomer = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.InteropServices; using Internal.NativeCrypto; using Internal.Cryptography; using Internal.Cryptography.Pal.Native; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace Internal.Cryptography.Pal { /// <summary> /// A singleton class that encapsulates the native implementation of various X509 services. (Implementing this as a singleton makes it /// easier to split the class into abstract and implementation classes if desired.) /// </summary> internal sealed partial class X509Pal : IX509Pal { public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages) { unsafe { ushort keyUsagesAsShort = (ushort)keyUsages; CRYPT_BIT_BLOB blob = new CRYPT_BIT_BLOB() { cbData = 2, pbData = (byte*)&keyUsagesAsShort, cUnusedBits = 0, }; return Interop.crypt32.EncodeObject(CryptDecodeObjectStructType.X509_KEY_USAGE, &blob); } } public void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages) { unsafe { uint keyUsagesAsUint = 0; encoded.DecodeObject( CryptDecodeObjectStructType.X509_KEY_USAGE, delegate (void* pvDecoded) { CRYPT_BIT_BLOB* pBlob = (CRYPT_BIT_BLOB*)pvDecoded; keyUsagesAsUint = 0; if (pBlob->pbData != null) { keyUsagesAsUint = *(uint*)(pBlob->pbData); } } ); keyUsages = (X509KeyUsageFlags)keyUsagesAsUint; } } public bool SupportsLegacyBasicConstraintsExtension { get { return true; } } public byte[] EncodeX509BasicConstraints2Extension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint) { unsafe { CERT_BASIC_CONSTRAINTS2_INFO constraintsInfo = new CERT_BASIC_CONSTRAINTS2_INFO() { fCA = certificateAuthority ? 1 : 0, fPathLenConstraint = hasPathLengthConstraint ? 1 : 0, dwPathLenConstraint = pathLengthConstraint, }; return Interop.crypt32.EncodeObject(Oids.BasicConstraints2, &constraintsInfo); } } public void DecodeX509BasicConstraintsExtension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { unsafe { bool localCertificateAuthority = false; bool localHasPathLengthConstraint = false; int localPathLengthConstraint = 0; encoded.DecodeObject( CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS, delegate (void* pvDecoded) { CERT_BASIC_CONSTRAINTS_INFO* pBasicConstraints = (CERT_BASIC_CONSTRAINTS_INFO*)pvDecoded; localCertificateAuthority = (pBasicConstraints->SubjectType.pbData[0] & CERT_BASIC_CONSTRAINTS_INFO.CERT_CA_SUBJECT_FLAG) != 0; localHasPathLengthConstraint = pBasicConstraints->fPathLenConstraint != 0; localPathLengthConstraint = pBasicConstraints->dwPathLenConstraint; } ); certificateAuthority = localCertificateAuthority; hasPathLengthConstraint = localHasPathLengthConstraint; pathLengthConstraint = localPathLengthConstraint; } } public void DecodeX509BasicConstraints2Extension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { unsafe { bool localCertificateAuthority = false; bool localHasPathLengthConstraint = false; int localPathLengthConstraint = 0; encoded.DecodeObject( CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS2, delegate (void* pvDecoded) { CERT_BASIC_CONSTRAINTS2_INFO* pBasicConstraints2 = (CERT_BASIC_CONSTRAINTS2_INFO*)pvDecoded; localCertificateAuthority = pBasicConstraints2->fCA != 0; localHasPathLengthConstraint = pBasicConstraints2->fPathLenConstraint != 0; localPathLengthConstraint = pBasicConstraints2->dwPathLenConstraint; } ); certificateAuthority = localCertificateAuthority; hasPathLengthConstraint = localHasPathLengthConstraint; pathLengthConstraint = localPathLengthConstraint; } } public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages) { int numUsages; using (SafeHandle usagesSafeHandle = usages.ToLpstrArray(out numUsages)) { unsafe { CERT_ENHKEY_USAGE enhKeyUsage = new CERT_ENHKEY_USAGE() { cUsageIdentifier = numUsages, rgpszUsageIdentifier = (IntPtr*)(usagesSafeHandle.DangerousGetHandle()), }; return Interop.crypt32.EncodeObject(Oids.EnhancedKeyUsage, &enhKeyUsage); } } } public void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { OidCollection localUsages = new OidCollection(); unsafe { encoded.DecodeObject( CryptDecodeObjectStructType.X509_ENHANCED_KEY_USAGE, delegate (void* pvDecoded) { CERT_ENHKEY_USAGE* pEnhKeyUsage = (CERT_ENHKEY_USAGE*)pvDecoded; int count = pEnhKeyUsage->cUsageIdentifier; for (int i = 0; i < count; i++) { IntPtr oidValuePointer = pEnhKeyUsage->rgpszUsageIdentifier[i]; string oidValue = Marshal.PtrToStringAnsi(oidValuePointer); Oid oid = new Oid(oidValue); localUsages.Add(oid); } } ); } usages = localUsages; } public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier) { unsafe { fixed (byte* pSubkectKeyIdentifier = subjectKeyIdentifier) { CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(subjectKeyIdentifier.Length, pSubkectKeyIdentifier); return Interop.crypt32.EncodeObject(Oids.SubjectKeyIdentifier, &blob); } } } public void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier) { unsafe { byte[] localSubjectKeyIdentifier = null; encoded.DecodeObject( Oids.SubjectKeyIdentifier, delegate (void* pvDecoded) { CRYPTOAPI_BLOB* pBlob = (CRYPTOAPI_BLOB*)pvDecoded; localSubjectKeyIdentifier = pBlob->ToByteArray(); } ); subjectKeyIdentifier = localSubjectKeyIdentifier; } } public byte[] ComputeCapiSha1OfPublicKey(PublicKey key) { unsafe { fixed (byte* pszOidValue = key.Oid.ValueAsAscii()) { byte[] encodedParameters = key.EncodedParameters.RawData; fixed (byte* pEncodedParameters = encodedParameters) { byte[] encodedKeyValue = key.EncodedKeyValue.RawData; fixed (byte* pEncodedKeyValue = encodedKeyValue) { CERT_PUBLIC_KEY_INFO publicKeyInfo = new CERT_PUBLIC_KEY_INFO() { Algorithm = new CRYPT_ALGORITHM_IDENTIFIER() { pszObjId = new IntPtr(pszOidValue), Parameters = new CRYPTOAPI_BLOB(encodedParameters.Length, pEncodedParameters), }, PublicKey = new CRYPT_BIT_BLOB() { cbData = encodedKeyValue.Length, pbData = pEncodedKeyValue, cUnusedBits = 0, }, }; int cb = 20; byte[] buffer = new byte[cb]; if (!Interop.crypt32.CryptHashPublicKeyInfo(IntPtr.Zero, AlgId.CALG_SHA1, 0, CertEncodingType.All, ref publicKeyInfo, buffer, ref cb)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; if (cb < buffer.Length) { byte[] newBuffer = new byte[cb]; Buffer.BlockCopy(buffer, 0, newBuffer, 0, cb); buffer = newBuffer; } return buffer; } } } } } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using Microsoft.Win32; class Script { const string usage = "Usage: cscscript sysFindConfig ...\nDisplays configuration console to adjust system 'FindInFile' options on WindowsXP. "+ "This is the work around for WindowsXP BUG described in MSDN articles Q309173 "+ "'Using the 'A Word or Phrase in the File' Search Criterion May Not Work'.\n"; static public void Main(string[] args) { if (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")) { Console.WriteLine(usage); } else { Application.Run(new ConfigForm()); } } public class ConfigForm : System.Windows.Forms.Form { private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.TextBox textBox1; private System.ComponentModel.Container components = null; static string GUID = "{5e941d80-bf96-11cd-b579-08002b30bfeb}"; public ConfigForm() { InitializeComponent(); } protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.listBox1 = new System.Windows.Forms.ListBox(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // listBox1 // this.listBox1.Location = new System.Drawing.Point(8, 40); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(128, 199); this.listBox1.Sorted = true; this.listBox1.TabIndex = 0; this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged); // // button1 // this.button1.Enabled = false; this.button1.Location = new System.Drawing.Point(152, 8); this.button1.Name = "button1"; this.button1.TabIndex = 1; this.button1.Text = "&Add"; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Enabled = false; this.button2.Location = new System.Drawing.Point(152, 40); this.button2.Name = "button2"; this.button2.TabIndex = 2; this.button2.Tag = ""; this.button2.Text = "&Remove"; this.button2.Click += new System.EventHandler(this.button2_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(8, 8); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(128, 20); this.textBox1.TabIndex = 3; this.textBox1.Text = ""; this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(242, 246); this.Controls.Add(this.textBox1); this.Controls.Add(this.button1); this.Controls.Add(this.listBox1); this.Controls.Add(this.button2); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.MinimizeBox = false; this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "\"Find In File\" supported file extensions"; this.TopMost = true; this.Load += new System.EventHandler(this.ConfigForm_Load); this.ResumeLayout(false); } #endregion private void ConfigForm_Load(object sender, System.EventArgs e) { string[] subKeysNames = Registry.ClassesRoot.GetSubKeyNames(); foreach(string name in subKeysNames) { if (name.StartsWith(".")) { RegistryKey subKeys = Registry.ClassesRoot.OpenSubKey(name+"\\PersistentHandler"); if (subKeys != null) { object regValue = subKeys.GetValue(""); if (regValue != null && regValue.ToString() == GUID) { listBox1.Items.Add(name); } } } } } private void textBox1_TextChanged(object sender, System.EventArgs e) { button1.Enabled = textBox1.Text.Length != 0; } private void button1_Click(object sender, System.EventArgs e) { try { if (textBox1.Text.Length != 0) { int index = -1; if (!textBox1.Text.StartsWith(".")) { textBox1.Text = "." + textBox1.Text; } if (-1 != (index = listBox1.FindString(textBox1.Text))) { MessageBox.Show(textBox1.Text+" is already supported extension."); listBox1.SelectedIndex = index; } else { RegistryKey subKeys = Registry.ClassesRoot.OpenSubKey(textBox1.Text+"\\PersistentHandler", true); if (subKeys == null) { subKeys = Registry.ClassesRoot.CreateSubKey(textBox1.Text+"\\PersistentHandler"); } subKeys.SetValue("", GUID); index = listBox1.Items.Add(textBox1.Text); listBox1.SelectedIndex = index; textBox1.Text = ""; } } else { MessageBox.Show(textBox1.Text+" is not a valid file extension."); } } catch (Exception exc) { MessageBox.Show("Cannot add to the extension to the registry./n"+exc); } } private void button2_Click(object sender, System.EventArgs e) { string name = ""; try { if (listBox1.SelectedIndex != -1) { name = listBox1.Items[listBox1.SelectedIndex].ToString(); RegistryKey subKeys = Registry.ClassesRoot.OpenSubKey(name+"\\PersistentHandler", true); if (subKeys != null) { subKeys.DeleteValue(""); listBox1.Items.RemoveAt(listBox1.SelectedIndex); } } else { MessageBox.Show("Please select extension you want to remove."); } } catch (Exception exc) { MessageBox.Show("Cannot remove "+name+" extension from the registry./n"+exc); } } private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e) { button2.Enabled = (listBox1.SelectedIndex != -1); } } }
#region Apache License 2.0 // Copyright 2008-2010 Christian Rodemeyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using SharpSvn; namespace SvnQuery.Svn { public class SharpSvnApi : ISvnApi { readonly Uri _uri; readonly string _user; readonly string _password; readonly Dictionary<int, string> _messages = new Dictionary<int, string>(); readonly List<SvnClient> _clientPool = new List<SvnClient>(); public SharpSvnApi(string repositoryUri) : this(repositoryUri, "", "") {} public SharpSvnApi(string repositoryUri, string user, string password) { _uri = new Uri(repositoryUri); _user = user; _password = password; } SvnClient AllocSvnClient() { SvnClient client = null; lock (_clientPool) { int last = _clientPool.Count - 1; if (last >= 0) { client = _clientPool[last]; _clientPool.RemoveAt(last); } } return client ?? MakeNewSvnClient(); } SvnClient MakeNewSvnClient() { SvnClient client = new SvnClient(); try { // load configuration right away so exceptions during loading can be catched client.LoadConfigurationDefault(); } catch (SvnFormatException) { // workaround for exception "Can't determine the user's config path" for special users like NetworkService // -> try again loading from some specific path client.LoadConfiguration(Path.Combine(Path.GetTempPath(), "SharpSvnApi")); } client.Authentication.UserNameHandlers += (s, e) => e.UserName = _user; client.Authentication.UserNamePasswordHandlers += (s, e) => { e.UserName = _user; e.Password = _password; }; client.Authentication.SslServerTrustHandlers += (s, e) => { e.AcceptedFailures = SharpSvn.Security.SvnCertificateTrustFailures.MaskAllFailures; }; return client; } void FreeSvnClient(SvnClient client) { lock (_clientPool) _clientPool.Add(client); } SvnInfoEventArgs Info { get { if (_info == null) { SvnClient client = AllocSvnClient(); try { SvnTarget target = new SvnUriTarget(_uri); client.GetInfo(target, out _info); } finally { FreeSvnClient(client); } } return _info; } } SvnInfoEventArgs _info; public int GetYoungestRevision() { return (int) Info.LastChangeRevision; } public Guid GetRepositoryId() { return Info.RepositoryId; } public string GetLogMessage(int revision) { string message; lock (_messages) _messages.TryGetValue(revision, out message); if (message == null) { SvnClient client = AllocSvnClient(); try { if (!client.GetRevisionProperty(_uri, new SvnRevision(revision), "svn:log", out message)) message = ""; } finally { FreeSvnClient(client); } lock (_messages) _messages[revision] = message; } return message; } public List<RevisionData> GetRevisionData(int firstRevision, int lastRevision) { List<RevisionData> revisions = new List<RevisionData>(); SvnClient client = AllocSvnClient(); try { SvnLogArgs args = new SvnLogArgs(new SvnRevisionRange(firstRevision, lastRevision)); args.StrictNodeHistory = false; args.RetrieveChangedPaths = true; args.ThrowOnError = true; args.ThrowOnCancel = true; Collection<SvnLogEventArgs> logEvents; client.GetLog(_uri, args, out logEvents); foreach (SvnLogEventArgs e in logEvents) { RevisionData data = new RevisionData(); data.Revision = (int) e.Revision; data.Author = e.Author ?? ""; data.Message = e.LogMessage ?? ""; data.Timestamp = e.Time; AddChanges(data, e.ChangedPaths); revisions.Add(data); lock (_messages) _messages[data.Revision] = data.Message; } } finally { FreeSvnClient(client); } return revisions; } static void AddChanges(RevisionData data, IEnumerable<SvnChangeItem> changes) { if (changes == null) return; foreach (var item in changes) { data.Changes.Add(new PathChange { Change = ConvertActionToChange(item.Action), Revision = data.Revision, Path = item.Path, IsCopy = item.CopyFromPath != null }); } } static Change ConvertActionToChange(SvnChangeAction action) { switch (action) { case SvnChangeAction.Add: return Change.Add; case SvnChangeAction.Modify: return Change.Modify; case SvnChangeAction.Delete: return Change.Delete; case SvnChangeAction.Replace: return Change.Replace; default: throw new Exception("Invalid SvnChangeAction: " + (int) action); } } public void ForEachChild(string path, int revision, Change change, Action<PathChange> action) { SvnClient client = AllocSvnClient(); SvnTarget target = MakeTarget(path, change == Change.Delete ? revision - 1 : revision); try { SvnListArgs args = new SvnListArgs {Depth = SvnDepth.Infinity}; client.List(target, args, delegate(object s, SvnListEventArgs e) { if (string.IsNullOrEmpty(e.Path)) return; var pc = new PathChange(); { pc.Change = change; pc.Revision = revision; // to be compatible with the log output (which has no trailing '/' for directories) // we need to remove trailing '/' pc.Path = (e.BasePath.EndsWith("/") ? e.BasePath : e.BasePath + "/") + e.Path.TrimEnd('/'); } action(pc); }); } finally { FreeSvnClient(client); } } public PathInfo GetPathInfo(string path, int revision) { SvnClient client = AllocSvnClient(); try { SvnInfoEventArgs info; client.GetInfo(MakeTarget(path, revision), out info); PathInfo result = new PathInfo(); result.Size = (int) info.RepositorySize; result.Author = info.LastChangeAuthor ?? ""; result.Timestamp = info.LastChangeTime; //result.Revision = (int) info.LastChangeRevision; // wrong if data is directory result.IsDirectory = info.NodeKind == SvnNodeKind.Directory; return result; } catch (SvnException x) { if (x.SvnErrorCode == SvnErrorCode.SVN_ERR_RA_ILLEGAL_URL) { return null; } if (path.IndexOfAny(InvalidPathChars) >= 0) // this condition exists only because of a bug in the svn client for local repositoreis { Console.WriteLine("WARNING: path with invalid charactes could not be indexed: " + path + "@" + revision); return null; } throw; } finally { FreeSvnClient(client); } } static readonly char[] InvalidPathChars = new[] {':', '$', '\\'}; public IDictionary<string, string> GetPathProperties(string path, int revision) { SvnClient client = AllocSvnClient(); try { Collection<SvnPropertyListEventArgs> pc; client.GetPropertyList(MakeTarget(path, revision), out pc); Dictionary<string, string> properties = new Dictionary<string, string>(); foreach (var proplist in pc) { foreach (var property in proplist.Properties) { properties.Add(property.Key, property.StringValue.ToLowerInvariant()); } } return properties; } finally { FreeSvnClient(client); } } public string GetPathContent(string path, int revision, int size) { SvnClient client = AllocSvnClient(); try { using (MemoryStream stream = new MemoryStream(size + 512)) { client.Write(MakeTarget(path, revision), stream); stream.Position = 0; using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); // default utf-8 encoding, does not work with codepages } } } catch (SvnException x) { if (x.SvnErrorCode != SvnErrorCode.SVN_ERR_IO_INCONSISTENT_EOL) throw; Console.WriteLine("WARNIG: Could not read " + path); return ""; } finally { FreeSvnClient(client); } } SvnTarget MakeTarget(string path, int revision) { StringBuilder sb = new StringBuilder(); foreach (string part in path.Split('/')) // Build an escaped Uri in the way svn likes it { sb.Append(Uri.EscapeDataString(part)); sb.Append('/'); } sb.Length -= 1; return new SvnUriTarget(new Uri(_uri + sb.ToString()), revision); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.Collections.Tests { public class SortedList_MultiMethodsTests { [Fact] public void Test01() { SortedList slst1; Int32 iNumberOfElements; String strValue; Array ar1; // ctor(Int32) iNumberOfElements = 10; slst1 = new SortedList(iNumberOfElements); for (int i = iNumberOfElements - 1; i >= 0; i--) { slst1.Add(50 + i, "Value_" + i); } Assert.Equal(slst1.Count, iNumberOfElements); //we will assume that all the keys are sorted as the name implies. lets see //We intially filled this lit with descending and much higher keys. now we access the keys through index for (int i = 0; i < slst1.Count; i++) { strValue = "Value_" + i; Assert.Equal(strValue, slst1[slst1.GetKey(i)]); } //paramter stuff Assert.Throws<ArgumentOutOfRangeException>(() => { iNumberOfElements = -5; slst1 = new SortedList(iNumberOfElements); } ); slst1 = new SortedList(); Assert.Throws<ArgumentNullException>(() => { slst1.Add(null, 5); } ); iNumberOfElements = 10; slst1 = new SortedList(); for (int i = iNumberOfElements - 1; i >= 0; i--) { slst1.Add(i, null); } for (int i = 0; i < slst1.Count; i++) { strValue = "Value_" + i; Assert.Null(slst1.GetByIndex(i)); } //Contains() iNumberOfElements = 10; slst1 = new SortedList(iNumberOfElements); for (int i = iNumberOfElements - 1; i >= 0; i--) { slst1.Add(50 + i, "Value_" + i); } for (int i = 0; i < slst1.Count; i++) { strValue = "Value_" + i; Assert.True(slst1.Contains(50 + i)); } Assert.False(slst1.Contains(1)); Assert.False(slst1.Contains(-1)); //paramter stuff Assert.Throws<ArgumentNullException>(() => { slst1.Contains(null); } ); //get/set_Item slst1 = new SortedList(); for (int i = iNumberOfElements - 1; i >= 0; i--) { slst1[50 + i] = "Value_" + i; } Assert.Equal(slst1.Count, iNumberOfElements); for (int i = 0; i < slst1.Count; i++) { strValue = "Value_" + i; Assert.Equal(strValue, slst1[i + 50]); } //already existent ones strValue = "Value_1"; Assert.Equal(strValue, slst1[51]); strValue = "Different value"; slst1[51] = strValue; Assert.Equal(strValue, slst1[51]); //paramter stuff Assert.Throws<ArgumentNullException>(() => { slst1[null] = "Not a chance"; } ); strValue = null; slst1[51] = strValue; Assert.Null(slst1[51]); //SetByIndex - this changes the value at this specific index. Note that SortedList //does not have the equicalent Key changing means as this is a SortedList and will be done //automatically!!! iNumberOfElements = 10; slst1 = new SortedList(); for (int i = iNumberOfElements - 1; i >= 0; i--) { slst1.Add(50 + i, "Value_" + i); } for (int i = 0; i < slst1.Count; i++) { strValue = "Value_" + i + 50; slst1.SetByIndex(i, strValue); } for (int i = 0; i < slst1.Count; i++) { strValue = "Value_" + i + 50; Assert.Equal(strValue, slst1.GetByIndex(i)); } //paramter stuff Assert.Throws<ArgumentOutOfRangeException>(() => { slst1.SetByIndex(-1, strValue); } ); Assert.Throws<ArgumentOutOfRangeException>(() => { slst1.SetByIndex(slst1.Count, strValue); } ); //CopyTo() - copies the values iNumberOfElements = 10; slst1 = new SortedList(); for (int i = iNumberOfElements - 1; i >= 0; i--) { slst1.Add(50 + i, "Value_" + i); } ar1 = new DictionaryEntry[iNumberOfElements]; slst1.CopyTo(ar1, 0); for (int i = 0; i < slst1.Count; i++) { strValue = "Value_" + i; Assert.Equal(strValue, ((DictionaryEntry)ar1.GetValue(i)).Value); } //paramter stuff Assert.Throws<InvalidCastException>(() => { ar1 = new String[iNumberOfElements]; slst1.CopyTo(ar1, 0); } ); Assert.Throws<ArgumentNullException>(() => { slst1.CopyTo(null, 0); } ); Assert.Throws<ArgumentOutOfRangeException>(() => { ar1 = new DictionaryEntry[iNumberOfElements]; slst1.CopyTo(ar1, -1); } ); Assert.Throws<ArgumentException>(() => { ar1 = new String[iNumberOfElements]; slst1.CopyTo(ar1, 1); } ); ar1 = new DictionaryEntry[2 * iNumberOfElements]; slst1.CopyTo(ar1, iNumberOfElements); for (int i = 0; i < slst1.Count; i++) { strValue = "Value_" + i; Assert.Equal(strValue, ((DictionaryEntry)ar1.GetValue(iNumberOfElements + i)).Value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Text; using System.Threading.Tasks; namespace System.Xml { public interface IXmlTextWriterInitializer { void SetOutput(Stream stream, Encoding encoding, bool ownsStream); } internal class XmlUTF8TextWriter : XmlBaseWriter, IXmlTextWriterInitializer { private XmlUTF8NodeWriter _writer; public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (encoding.WebName != Encoding.UTF8.WebName) { stream = new EncodingStreamWrapper(stream, encoding, true); } if (_writer == null) { _writer = new XmlUTF8NodeWriter(); } _writer.SetOutput(stream, ownsStream, encoding); SetOutput(_writer); } } internal class XmlUTF8NodeWriter : XmlStreamNodeWriter { private byte[] _entityChars; private bool[] _isEscapedAttributeChar; private bool[] _isEscapedElementChar; private bool _inAttribute; private const int bufferLength = 512; private const int maxEntityLength = 32; private Encoding _encoding; private char[] _chars; private static readonly byte[] s_startDecl = { (byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l', (byte)' ', (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"', (byte)' ', (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=', (byte)'"', }; private static readonly byte[] s_endDecl = { (byte)'"', (byte)'?', (byte)'>' }; private static readonly byte[] s_utf8Decl = { (byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l', (byte)' ', (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"', (byte)' ', (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=', (byte)'"', (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8', (byte)'"', (byte)'?', (byte)'>' }; private static readonly byte[] s_digits = { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F' }; private static readonly bool[] s_defaultIsEscapedAttributeChar = new bool[] { true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, true, false, false, false, true, false, false, false, false, false, false, false, false, false, // '"', '&' false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false // '<', '>' }; private static readonly bool[] s_defaultIsEscapedElementChar = new bool[] { true, true, true, true, true, true, true, true, true, false, false, true, true, true, true, true, // All but 0x09, 0x0A true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, // '&' false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false // '<', '>' }; public XmlUTF8NodeWriter() : this(s_defaultIsEscapedAttributeChar, s_defaultIsEscapedElementChar) { } public XmlUTF8NodeWriter(bool[] isEscapedAttributeChar, bool[] isEscapedElementChar) { _isEscapedAttributeChar = isEscapedAttributeChar; _isEscapedElementChar = isEscapedElementChar; _inAttribute = false; } new public void SetOutput(Stream stream, bool ownsStream, Encoding encoding) { Encoding utf8Encoding = null; if (encoding != null && encoding.CodePage == Encoding.UTF8.CodePage) { utf8Encoding = encoding; encoding = null; } base.SetOutput(stream, ownsStream, utf8Encoding); _encoding = encoding; _inAttribute = false; } public Encoding Encoding { get { return _encoding; } } private byte[] GetCharEntityBuffer() { if (_entityChars == null) { _entityChars = new byte[maxEntityLength]; } return _entityChars; } private char[] GetCharBuffer(int charCount) { if (charCount >= 256) return new char[charCount]; if (_chars == null || _chars.Length < charCount) _chars = new char[charCount]; return _chars; } public override void WriteDeclaration() { if (_encoding == null) { WriteUTF8Chars(s_utf8Decl, 0, s_utf8Decl.Length); } else { WriteUTF8Chars(s_startDecl, 0, s_startDecl.Length); if (_encoding.WebName == Encoding.BigEndianUnicode.WebName) WriteUTF8Chars("utf-16BE"); else WriteUTF8Chars(_encoding.WebName); WriteUTF8Chars(s_endDecl, 0, s_endDecl.Length); } } public override void WriteCData(string text) { byte[] buffer; int offset; buffer = GetBuffer(9, out offset); buffer[offset + 0] = (byte)'<'; buffer[offset + 1] = (byte)'!'; buffer[offset + 2] = (byte)'['; buffer[offset + 3] = (byte)'C'; buffer[offset + 4] = (byte)'D'; buffer[offset + 5] = (byte)'A'; buffer[offset + 6] = (byte)'T'; buffer[offset + 7] = (byte)'A'; buffer[offset + 8] = (byte)'['; Advance(9); WriteUTF8Chars(text); buffer = GetBuffer(3, out offset); buffer[offset + 0] = (byte)']'; buffer[offset + 1] = (byte)']'; buffer[offset + 2] = (byte)'>'; Advance(3); } private void WriteStartComment() { int offset; byte[] buffer = GetBuffer(4, out offset); buffer[offset + 0] = (byte)'<'; buffer[offset + 1] = (byte)'!'; buffer[offset + 2] = (byte)'-'; buffer[offset + 3] = (byte)'-'; Advance(4); } private void WriteEndComment() { int offset; byte[] buffer = GetBuffer(3, out offset); buffer[offset + 0] = (byte)'-'; buffer[offset + 1] = (byte)'-'; buffer[offset + 2] = (byte)'>'; Advance(3); } public override void WriteComment(string text) { WriteStartComment(); WriteUTF8Chars(text); WriteEndComment(); } public override void WriteStartElement(string prefix, string localName) { WriteByte('<'); if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteLocalName(localName); } public override async Task WriteStartElementAsync(string prefix, string localName) { await WriteByteAsync('<').ConfigureAwait(false); if (prefix.Length != 0) { // This method calls into unsafe method which cannot run asyncly. WritePrefix(prefix); await WriteByteAsync(':').ConfigureAwait(false); } // This method calls into unsafe method which cannot run asyncly. WriteLocalName(localName); } public override void WriteStartElement(string prefix, XmlDictionaryString localName) { WriteStartElement(prefix, localName.Value); } public override void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteByte('<'); if (prefixLength != 0) { WritePrefix(prefixBuffer, prefixOffset, prefixLength); WriteByte(':'); } WriteLocalName(localNameBuffer, localNameOffset, localNameLength); } public override void WriteEndStartElement(bool isEmpty) { if (!isEmpty) { WriteByte('>'); } else { WriteBytes('/', '>'); } } public override async Task WriteEndStartElementAsync(bool isEmpty) { if (!isEmpty) { await WriteByteAsync('>').ConfigureAwait(false); } else { await WriteBytesAsync('/', '>').ConfigureAwait(false); } } public override void WriteEndElement(string prefix, string localName) { WriteBytes('<', '/'); if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteLocalName(localName); WriteByte('>'); } public override async Task WriteEndElementAsync(string prefix, string localName) { await WriteBytesAsync('<', '/').ConfigureAwait(false); if (prefix.Length != 0) { WritePrefix(prefix); await WriteByteAsync(':').ConfigureAwait(false); } WriteLocalName(localName); await WriteByteAsync('>').ConfigureAwait(false); } public override void WriteEndElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteBytes('<', '/'); if (prefixLength != 0) { WritePrefix(prefixBuffer, prefixOffset, prefixLength); WriteByte(':'); } WriteLocalName(localNameBuffer, localNameOffset, localNameLength); WriteByte('>'); } private void WriteStartXmlnsAttribute() { int offset; byte[] buffer = GetBuffer(6, out offset); buffer[offset + 0] = (byte)' '; buffer[offset + 1] = (byte)'x'; buffer[offset + 2] = (byte)'m'; buffer[offset + 3] = (byte)'l'; buffer[offset + 4] = (byte)'n'; buffer[offset + 5] = (byte)'s'; Advance(6); _inAttribute = true; } public override void WriteXmlnsAttribute(string prefix, string ns) { WriteStartXmlnsAttribute(); if (prefix.Length != 0) { WriteByte(':'); WritePrefix(prefix); } WriteBytes('=', '"'); WriteEscapedText(ns); WriteEndAttribute(); } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { WriteXmlnsAttribute(prefix, ns.Value); } public override void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { WriteStartXmlnsAttribute(); if (prefixLength != 0) { WriteByte(':'); WritePrefix(prefixBuffer, prefixOffset, prefixLength); } WriteBytes('=', '"'); WriteEscapedText(nsBuffer, nsOffset, nsLength); WriteEndAttribute(); } public override void WriteStartAttribute(string prefix, string localName) { WriteByte(' '); if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteLocalName(localName); WriteBytes('=', '"'); _inAttribute = true; } public override void WriteStartAttribute(string prefix, XmlDictionaryString localName) { WriteStartAttribute(prefix, localName.Value); } public override void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteByte(' '); if (prefixLength != 0) { WritePrefix(prefixBuffer, prefixOffset, prefixLength); WriteByte(':'); } WriteLocalName(localNameBuffer, localNameOffset, localNameLength); WriteBytes('=', '"'); _inAttribute = true; } public override void WriteEndAttribute() { WriteByte('"'); _inAttribute = false; } public override async Task WriteEndAttributeAsync() { await WriteByteAsync('"').ConfigureAwait(false); _inAttribute = false; } private void WritePrefix(string prefix) { if (prefix.Length == 1) { WriteUTF8Char(prefix[0]); } else { WriteUTF8Chars(prefix); } } private void WritePrefix(byte[] prefixBuffer, int prefixOffset, int prefixLength) { if (prefixLength == 1) { WriteUTF8Char((char)prefixBuffer[prefixOffset]); } else { WriteUTF8Chars(prefixBuffer, prefixOffset, prefixLength); } } private void WriteLocalName(string localName) { WriteUTF8Chars(localName); } private void WriteLocalName(byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteUTF8Chars(localNameBuffer, localNameOffset, localNameLength); } public override void WriteEscapedText(XmlDictionaryString s) { WriteEscapedText(s.Value); } public unsafe override void WriteEscapedText(string s) { int count = s.Length; if (count > 0) { fixed (char* chars = s) { UnsafeWriteEscapedText(chars, count); } } } public unsafe override void WriteEscapedText(char[] s, int offset, int count) { if (count > 0) { fixed (char* chars = &s[offset]) { UnsafeWriteEscapedText(chars, count); } } } private unsafe void UnsafeWriteEscapedText(char* chars, int count) { bool[] isEscapedChar = (_inAttribute ? _isEscapedAttributeChar : _isEscapedElementChar); int isEscapedCharLength = isEscapedChar.Length; int i = 0; for (int j = 0; j < count; j++) { char ch = chars[j]; if (ch < isEscapedCharLength && isEscapedChar[ch] || ch >= 0xFFFE) { UnsafeWriteUTF8Chars(chars + i, j - i); WriteCharEntity(ch); i = j + 1; } } UnsafeWriteUTF8Chars(chars + i, count - i); } public override void WriteEscapedText(byte[] chars, int offset, int count) { bool[] isEscapedChar = (_inAttribute ? _isEscapedAttributeChar : _isEscapedElementChar); int isEscapedCharLength = isEscapedChar.Length; int i = 0; for (int j = 0; j < count; j++) { byte ch = chars[offset + j]; if (ch < isEscapedCharLength && isEscapedChar[ch]) { WriteUTF8Chars(chars, offset + i, j - i); WriteCharEntity(ch); i = j + 1; } else if (ch == 239 && offset + j + 2 < count) { // 0xFFFE and 0xFFFF must be written as char entities // UTF8(239, 191, 190) = (char) 0xFFFE // UTF8(239, 191, 191) = (char) 0xFFFF byte ch2 = chars[offset + j + 1]; byte ch3 = chars[offset + j + 2]; if (ch2 == 191 && (ch3 == 190 || ch3 == 191)) { WriteUTF8Chars(chars, offset + i, j - i); WriteCharEntity(ch3 == 190 ? (char)0xFFFE : (char)0xFFFF); i = j + 3; } } } WriteUTF8Chars(chars, offset + i, count - i); } public void WriteText(int ch) { WriteUTF8Char(ch); } public override void WriteText(byte[] chars, int offset, int count) { WriteUTF8Chars(chars, offset, count); } public unsafe override void WriteText(char[] chars, int offset, int count) { if (count > 0) { fixed (char* pch = &chars[offset]) { UnsafeWriteUTF8Chars(pch, count); } } } public override void WriteText(string value) { WriteUTF8Chars(value); } public override void WriteText(XmlDictionaryString value) { WriteUTF8Chars(value.Value); } public void WriteLessThanCharEntity() { int offset; byte[] buffer = GetBuffer(4, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'l'; buffer[offset + 2] = (byte)'t'; buffer[offset + 3] = (byte)';'; Advance(4); } public void WriteGreaterThanCharEntity() { int offset; byte[] buffer = GetBuffer(4, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'g'; buffer[offset + 2] = (byte)'t'; buffer[offset + 3] = (byte)';'; Advance(4); } public void WriteAmpersandCharEntity() { int offset; byte[] buffer = GetBuffer(5, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'a'; buffer[offset + 2] = (byte)'m'; buffer[offset + 3] = (byte)'p'; buffer[offset + 4] = (byte)';'; Advance(5); } public void WriteApostropheCharEntity() { int offset; byte[] buffer = GetBuffer(6, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'a'; buffer[offset + 2] = (byte)'p'; buffer[offset + 3] = (byte)'o'; buffer[offset + 4] = (byte)'s'; buffer[offset + 5] = (byte)';'; Advance(6); } public void WriteQuoteCharEntity() { int offset; byte[] buffer = GetBuffer(6, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'q'; buffer[offset + 2] = (byte)'u'; buffer[offset + 3] = (byte)'o'; buffer[offset + 4] = (byte)'t'; buffer[offset + 5] = (byte)';'; Advance(6); } private void WriteHexCharEntity(int ch) { byte[] chars = GetCharEntityBuffer(); int offset = maxEntityLength; chars[--offset] = (byte)';'; offset -= ToBase16(chars, offset, (uint)ch); chars[--offset] = (byte)'x'; chars[--offset] = (byte)'#'; chars[--offset] = (byte)'&'; WriteUTF8Chars(chars, offset, maxEntityLength - offset); } public override void WriteCharEntity(int ch) { switch (ch) { case '<': WriteLessThanCharEntity(); break; case '>': WriteGreaterThanCharEntity(); break; case '&': WriteAmpersandCharEntity(); break; case '\'': WriteApostropheCharEntity(); break; case '"': WriteQuoteCharEntity(); break; default: WriteHexCharEntity(ch); break; } } private int ToBase16(byte[] chars, int offset, uint value) { int count = 0; do { count++; chars[--offset] = s_digits[(int)(value & 0x0F)]; value /= 16; } while (value != 0); return count; } public override void WriteBoolText(bool value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxBoolChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteDecimalText(decimal value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxDecimalChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteDoubleText(double value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxDoubleChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteFloatText(float value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxFloatChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteDateTimeText(DateTime value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxDateTimeChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteUniqueIdText(UniqueId value) { if (value.IsGuid) { int charCount = value.CharArrayLength; char[] chars = GetCharBuffer(charCount); value.ToCharArray(chars, 0); WriteText(chars, 0, charCount); } else { WriteEscapedText(value.ToString()); } } public override void WriteInt32Text(int value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxInt32Chars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteInt64Text(long value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxInt64Chars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteUInt64Text(ulong value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxUInt64Chars, out offset); Advance(XmlConverter.ToChars((double)value, buffer, offset)); } public override void WriteGuidText(Guid value) { WriteText(value.ToString()); } public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count) { if (trailByteCount > 0) { InternalWriteBase64Text(trailBytes, 0, trailByteCount); } InternalWriteBase64Text(buffer, offset, count); } public override async Task WriteBase64TextAsync(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count) { if (trailByteCount > 0) { await InternalWriteBase64TextAsync(trailBytes, 0, trailByteCount).ConfigureAwait(false); } await InternalWriteBase64TextAsync(buffer, offset, count).ConfigureAwait(false); } private void InternalWriteBase64Text(byte[] buffer, int offset, int count) { Base64Encoding encoding = XmlConverter.Base64Encoding; while (count >= 3) { int byteCount = Math.Min(bufferLength / 4 * 3, count - count % 3); int charCount = byteCount / 3 * 4; int charOffset; byte[] chars = GetBuffer(charCount, out charOffset); Advance(encoding.GetChars(buffer, offset, byteCount, chars, charOffset)); offset += byteCount; count -= byteCount; } if (count > 0) { int charOffset; byte[] chars = GetBuffer(4, out charOffset); Advance(encoding.GetChars(buffer, offset, count, chars, charOffset)); } } private async Task InternalWriteBase64TextAsync(byte[] buffer, int offset, int count) { Base64Encoding encoding = XmlConverter.Base64Encoding; while (count >= 3) { int byteCount = Math.Min(bufferLength / 4 * 3, count - count % 3); int charCount = byteCount / 3 * 4; int charOffset; BytesWithOffset bufferResult = await GetBufferAsync(charCount).ConfigureAwait(false); byte[] chars = bufferResult.Bytes; charOffset = bufferResult.Offset; Advance(encoding.GetChars(buffer, offset, byteCount, chars, charOffset)); offset += byteCount; count -= byteCount; } if (count > 0) { int charOffset; BytesWithOffset bufferResult = await GetBufferAsync(4).ConfigureAwait(false); byte[] chars = bufferResult.Bytes; charOffset = bufferResult.Offset; Advance(encoding.GetChars(buffer, offset, count, chars, charOffset)); } } public override void WriteTimeSpanText(TimeSpan value) { WriteText(XmlConvert.ToString(value)); } public override void WriteStartListText() { } public override void WriteListSeparator() { WriteByte(' '); } public override void WriteEndListText() { } public override void WriteQualifiedName(string prefix, XmlDictionaryString localName) { if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteText(localName); } } }
using UnityEngine; using UnityEditor; using System; using System.Linq; using System.IO; using System.Collections.Generic; using System.Text.RegularExpressions; #if UNITY_5_5_OR_NEWER using UnityEngine.Profiling; #endif using UnityEngine.AssetGraph; using Model=UnityEngine.AssetGraph.DataModel.Version2; namespace UnityEngine.AssetGraph { [CustomNode("Configure Bundle/Extract Shared Assets", 71)] public class ExtractSharedAssets : Node { enum GroupingType : int { ByFileSize, ByRuntimeMemorySize }; [SerializeField] private string m_bundleNameTemplate; [SerializeField] private SerializableMultiTargetInt m_groupExtractedAssets; [SerializeField] private SerializableMultiTargetInt m_groupSizeByte; [SerializeField] private SerializableMultiTargetInt m_groupingType; public override string ActiveStyle { get { return "node 3 on"; } } public override string InactiveStyle { get { return "node 3"; } } public override string Category { get { return "Configure"; } } public override Model.NodeOutputSemantics NodeInputType { get { return Model.NodeOutputSemantics.AssetBundleConfigurations; } } public override Model.NodeOutputSemantics NodeOutputType { get { return Model.NodeOutputSemantics.AssetBundleConfigurations; } } public override void Initialize(Model.NodeData data) { m_bundleNameTemplate = "shared_*"; m_groupExtractedAssets = new SerializableMultiTargetInt(); m_groupSizeByte = new SerializableMultiTargetInt(); m_groupingType = new SerializableMultiTargetInt(); data.AddDefaultInputPoint(); data.AddDefaultOutputPoint(); } public override Node Clone(Model.NodeData newData) { var newNode = new ExtractSharedAssets(); newNode.m_groupExtractedAssets = new SerializableMultiTargetInt(m_groupExtractedAssets); newNode.m_groupSizeByte = new SerializableMultiTargetInt(m_groupSizeByte); newNode.m_groupingType = new SerializableMultiTargetInt(m_groupingType); newNode.m_bundleNameTemplate = m_bundleNameTemplate; newData.AddDefaultInputPoint(); newData.AddDefaultOutputPoint(); return newNode; } public override void OnInspectorGUI(NodeGUI node, AssetReferenceStreamManager streamManager, NodeGUIEditor editor, Action onValueChanged) { EditorGUILayout.HelpBox("Extract Shared Assets: Extract shared assets between asset bundles and add bundle configurations.", MessageType.Info); editor.UpdateNodeName(node); GUILayout.Space(10f); var newValue = EditorGUILayout.TextField("Bundle Name Template", m_bundleNameTemplate); if(newValue != m_bundleNameTemplate) { using(new RecordUndoScope("Bundle Name Template Change", node, true)) { m_bundleNameTemplate = newValue; onValueChanged(); } } GUILayout.Space(10f); //Show target configuration tab editor.DrawPlatformSelector(node); using (new EditorGUILayout.VerticalScope(GUI.skin.box)) { var disabledScope = editor.DrawOverrideTargetToggle(node, m_groupSizeByte.ContainsValueOf(editor.CurrentEditingGroup), (bool enabled) => { using(new RecordUndoScope("Remove Target Grouping Size Settings", node, true)){ if(enabled) { m_groupExtractedAssets[editor.CurrentEditingGroup] = m_groupExtractedAssets.DefaultValue; m_groupSizeByte[editor.CurrentEditingGroup] = m_groupSizeByte.DefaultValue; m_groupingType[editor.CurrentEditingGroup] = m_groupingType.DefaultValue; } else { m_groupExtractedAssets.Remove(editor.CurrentEditingGroup); m_groupSizeByte.Remove(editor.CurrentEditingGroup); m_groupingType.Remove(editor.CurrentEditingGroup); } onValueChanged(); } }); using (disabledScope) { var useGroup = EditorGUILayout.ToggleLeft ("Subgroup shared assets by size", m_groupExtractedAssets [editor.CurrentEditingGroup] != 0); if (useGroup != (m_groupExtractedAssets [editor.CurrentEditingGroup] != 0)) { using(new RecordUndoScope("Change Grouping Type", node, true)){ m_groupExtractedAssets[editor.CurrentEditingGroup] = (useGroup)? 1:0; onValueChanged(); } } using (new EditorGUI.DisabledScope (!useGroup)) { var newType = (GroupingType)EditorGUILayout.EnumPopup("Grouping Type",(GroupingType)m_groupingType[editor.CurrentEditingGroup]); if (newType != (GroupingType)m_groupingType[editor.CurrentEditingGroup]) { using(new RecordUndoScope("Change Grouping Type", node, true)){ m_groupingType[editor.CurrentEditingGroup] = (int)newType; onValueChanged(); } } var newSizeText = EditorGUILayout.TextField("Size(KB)",m_groupSizeByte[editor.CurrentEditingGroup].ToString()); int newSize = 0; Int32.TryParse (newSizeText, out newSize); if (newSize != m_groupSizeByte[editor.CurrentEditingGroup]) { using(new RecordUndoScope("Change Grouping Size", node, true)){ m_groupSizeByte[editor.CurrentEditingGroup] = newSize; onValueChanged(); } } } } } EditorGUILayout.HelpBox("Bundle Name Template replaces \'*\' with number.", MessageType.Info); } /** * Prepare is called whenever graph needs update. */ public override void Prepare (BuildTarget target, Model.NodeData node, IEnumerable<PerformGraph.AssetGroups> incoming, IEnumerable<Model.ConnectionData> connectionsToOutput, PerformGraph.Output Output) { if(string.IsNullOrEmpty(m_bundleNameTemplate)) { throw new NodeException("Bundle Name Template is empty.", "Set valid bundle name template.",node); } if (m_groupExtractedAssets [target] != 0) { if(m_groupSizeByte[target] < 0) { throw new NodeException("Invalid size. Size property must be a positive number.", "Set valid size.", node); } } // Pass incoming assets straight to Output if(Output != null) { var destination = (connectionsToOutput == null || !connectionsToOutput.Any())? null : connectionsToOutput.First(); if(incoming != null) { var buildMap = AssetBundleBuildMap.GetBuildMap (); buildMap.ClearFromId (node.Id); var dependencyCollector = new Dictionary<string, List<string>>(); // [asset path:group name] var sharedDependency = new Dictionary<string, List<AssetReference>>(); var groupNameMap = new Dictionary<string, string>(); // build dependency map foreach(var ag in incoming) { foreach (var key in ag.assetGroups.Keys) { var assets = ag.assetGroups[key]; foreach(var a in assets) { CollectDependencies(key, new string[] { a.importFrom }, ref dependencyCollector); } } } foreach(var entry in dependencyCollector) { if(entry.Value != null && entry.Value.Count > 1) { var joinedName = string.Join("-", entry.Value.ToArray()); if(!groupNameMap.ContainsKey(joinedName)) { var count = groupNameMap.Count; var newName = m_bundleNameTemplate.Replace("*", count.ToString()); if(newName == m_bundleNameTemplate) { newName = m_bundleNameTemplate + count.ToString(); } groupNameMap.Add(joinedName, newName); } var groupName = groupNameMap[joinedName]; if(!sharedDependency.ContainsKey(groupName)) { sharedDependency[groupName] = new List<AssetReference>(); } sharedDependency[groupName].Add( AssetReference.CreateReference(entry.Key) ); } } if(sharedDependency.Keys.Count > 0) { // subgroup shared dependency bundles by size if (m_groupExtractedAssets [target] != 0) { List<string> devidingBundleNames = new List<string> (sharedDependency.Keys); long szGroup = m_groupSizeByte[target] * 1000; foreach(var bundleName in devidingBundleNames) { var assets = sharedDependency[bundleName]; int groupCount = 0; long szGroupCount = 0; foreach(var a in assets) { var subGroupName = string.Format ("{0}_{1}", bundleName, groupCount); if (!sharedDependency.ContainsKey(subGroupName)) { sharedDependency[subGroupName] = new List<AssetReference>(); } sharedDependency[subGroupName].Add(a); szGroupCount += GetSizeOfAsset(a, (GroupingType)m_groupingType[target]); if(szGroupCount >= szGroup) { szGroupCount = 0; ++groupCount; } } sharedDependency.Remove (bundleName); } } foreach(var bundleName in sharedDependency.Keys) { var bundleConfig = buildMap.GetAssetBundleWithNameAndVariant (node.Id, bundleName, string.Empty); bundleConfig.AddAssets (node.Id, sharedDependency[bundleName].Select(a => a.importFrom)); } foreach(var ag in incoming) { Output(destination, new Dictionary<string, List<AssetReference>>(ag.assetGroups)); } Output(destination, sharedDependency); } else { foreach(var ag in incoming) { Output(destination, ag.assetGroups); } } } else { // Overwrite output with empty Dictionary when no there is incoming asset Output(destination, new Dictionary<string, List<AssetReference>>()); } } } private void CollectDependencies(string groupKey, string[] assetPaths, ref Dictionary<string, List<string>> collector) { var dependencies = AssetDatabase.GetDependencies(assetPaths); foreach(var d in dependencies) { // AssetBundle must not include script asset if (TypeUtility.GetMainAssetTypeAtPath (d) == typeof(MonoScript)) { continue; } if(!collector.ContainsKey(d)) { collector[d] = new List<string>(); } if(!collector[d].Contains(groupKey)) { collector[d].Add(groupKey); collector[d].Sort(); } } } private long GetSizeOfAsset(AssetReference a, GroupingType t) { long size = 0; // You can not read scene and do estimate if (a.isSceneAsset) { t = GroupingType.ByFileSize; } if (t == GroupingType.ByRuntimeMemorySize) { var objects = a.allData; foreach (var o in objects) { #if UNITY_5_6_OR_NEWER size += Profiler.GetRuntimeMemorySizeLong (o); #else size += Profiler.GetRuntimeMemorySize(o); #endif } a.ReleaseData (); } else if (t == GroupingType.ByFileSize) { System.IO.FileInfo fileInfo = new System.IO.FileInfo(a.absolutePath); if (fileInfo.Exists) { size = fileInfo.Length; } } return size; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.DataFactories; using Microsoft.Azure.Management.DataFactories.Models; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; namespace Microsoft.Azure.Management.DataFactories { public partial class DataPipelineManagementClient : ServiceClient<DataPipelineManagementClient>, IDataPipelineManagementClient { private Uri _baseUri; /// <summary> /// The URI used as the base for all Service Management requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } set { this._baseUri = value; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// When you create a Windows Azure subscription, it is uniquely /// identified by a subscription ID. The subscription ID forms part of /// the URI for every call that you make to the Service Management /// API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } set { this._credentials = value; } } private IDataFactoryOperations _dataFactories; /// <summary> /// Operations for managing data factories. /// </summary> public virtual IDataFactoryOperations DataFactories { get { return this._dataFactories; } } private IDataSliceOperations _dataSlices; /// <summary> /// Operations for managing data slices. /// </summary> public virtual IDataSliceOperations DataSlices { get { return this._dataSlices; } } private IDataSliceRunOperations _dataSliceRuns; /// <summary> /// Operations for managing data slice runs. /// </summary> public virtual IDataSliceRunOperations DataSliceRuns { get { return this._dataSliceRuns; } } private IEncryptionCertificateOperations _encryptionCertificate; /// <summary> /// Operations for getting the encryption certificate. /// </summary> public virtual IEncryptionCertificateOperations EncryptionCertificate { get { return this._encryptionCertificate; } } private IGatewayOperations _gateways; /// <summary> /// Operations for managing data factory gateways. /// </summary> public virtual IGatewayOperations Gateways { get { return this._gateways; } } private IHubOperations _hubs; /// <summary> /// Operations for managing hubs. /// </summary> public virtual IHubOperations Hubs { get { return this._hubs; } } private ILinkedServiceOperations _linkedServices; /// <summary> /// Operations for managing data factory linkedServices. /// </summary> public virtual ILinkedServiceOperations LinkedServices { get { return this._linkedServices; } } private IPipelineOperations _pipelines; /// <summary> /// Operations for managing pipelines. /// </summary> public virtual IPipelineOperations Pipelines { get { return this._pipelines; } } private IPipelineRunOperations _pipelineRuns; /// <summary> /// Operations for managing pipeline runs. /// </summary> public virtual IPipelineRunOperations PipelineRuns { get { return this._pipelineRuns; } } private ITableOperations _tables; /// <summary> /// Operations for managing tables. /// </summary> public virtual ITableOperations Tables { get { return this._tables; } } /// <summary> /// Initializes a new instance of the DataPipelineManagementClient /// class. /// </summary> private DataPipelineManagementClient() : base() { this._dataFactories = new DataFactoryOperations(this); this._dataSlices = new DataSliceOperations(this); this._dataSliceRuns = new DataSliceRunOperations(this); this._encryptionCertificate = new EncryptionCertificateOperations(this); this._gateways = new GatewayOperations(this); this._hubs = new HubOperations(this); this._linkedServices = new LinkedServiceOperations(this); this._pipelines = new PipelineOperations(this); this._pipelineRuns = new PipelineRunOperations(this); this._tables = new TableOperations(this); this.HttpClient.Timeout = TimeSpan.FromSeconds(60); } /// <summary> /// Initializes a new instance of the DataPipelineManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> /// <param name='baseUri'> /// Optional. The URI used as the base for all Service Management /// requests. /// </param> public DataPipelineManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the DataPipelineManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> public DataPipelineManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the DataPipelineManagementClient /// class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> private DataPipelineManagementClient(HttpClient httpClient) : base(httpClient) { this._dataFactories = new DataFactoryOperations(this); this._dataSlices = new DataSliceOperations(this); this._dataSliceRuns = new DataSliceRunOperations(this); this._encryptionCertificate = new EncryptionCertificateOperations(this); this._gateways = new GatewayOperations(this); this._hubs = new HubOperations(this); this._linkedServices = new LinkedServiceOperations(this); this._pipelines = new PipelineOperations(this); this._pipelineRuns = new PipelineRunOperations(this); this._tables = new TableOperations(this); this.HttpClient.Timeout = TimeSpan.FromSeconds(60); } /// <summary> /// Initializes a new instance of the DataPipelineManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> /// <param name='baseUri'> /// Optional. The URI used as the base for all Service Management /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public DataPipelineManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the DataPipelineManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public DataPipelineManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// DataPipelineManagementClient instance /// </summary> /// <param name='client'> /// Instance of DataPipelineManagementClient to clone to /// </param> protected override void Clone(ServiceClient<DataPipelineManagementClient> client) { base.Clone(client); if (client is DataPipelineManagementClient) { DataPipelineManagementClient clonedClient = ((DataPipelineManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); Tracing.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters); } // Construct URL string url = operationStatusLink.Trim(); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-12-01-preview"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResponse result = null; result = new LongRunningOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Conflict) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.ComponentModel; using System.Drawing.Design; using System.Xml.Serialization; using CslaGenerator.Attributes; using CslaGenerator.Design; namespace CslaGenerator.Metadata { /// <summary> /// Summary description for Criteria. /// </summary> [Serializable] public class Criteria { #region Private Fields private string _name = String.Empty; private TypeInfo _customClass; private string _summary = String.Empty; private string _remarks = String.Empty; private readonly CriteriaPropertyCollection _properties = new CriteriaPropertyCollection(); private CriteriaMode _criteriaClassMode = CriteriaMode.Simple; private bool _nestedClass = true; private CriteriaUsageParameter _createOptions = new CriteriaUsageParameter(); private CriteriaUsageParameter _getOptions = new CriteriaUsageParameter(); private CriteriaUsageParameter _deleteOptions = new CriteriaUsageParameter(); private CslaObjectInfo _parentObject; #endregion #region Constructors internal Criteria() { SetHandlers(_getOptions); SetHandlers(_deleteOptions); } public Criteria(CslaObjectInfo obj) : this() { _parentObject = obj; } #endregion #region Public Properties #region 01. Definition [Category("01. Definition")] [Description("The criteria class name. This will be generated when there is the need to pass more than one parameter to the DataPortal method.")] [UserFriendlyName("Criteria Name")] public string Name { get { return _name; } set { _name = PropertyHelper.Tidy(value); } } [Category("01. Definition")] [Description("Criteria class mode. Whether to use simple criteria (automatic properties), CriteriaBase or BusinessBase for the criteria class. "+ "Silverlight generation requires CriteriaBase or BusinessBase.")] [UserFriendlyName("Criteria Class Mode")] public CriteriaMode CriteriaClassMode { get { return _criteriaClassMode; } set { if (value != _criteriaClassMode && value == CriteriaMode.BusinessBase) { foreach (var property in Properties) { property.ReadOnly = false; } } _criteriaClassMode = value; _nestedClass = false; } } [Category("01. Definition")] [Description("Whether the criteria class should be nested and protected or not nested and public." + "\r\nNote - BusinessBase criteria class is always not nested and public.")] [UserFriendlyName("Nested Class")] public bool NestedClass { get { return _nestedClass; } set { _nestedClass = value; } } [Category("01. Definition")] [Description("A project class of type Criteria")] [Editor(typeof(ObjectEditor), typeof(UITypeEditor))] [TypeConverter(typeof(TypeInfoConverter))] [UserFriendlyName("Criteria Project Class")] public TypeInfo CustomClass { get { return _customClass; } set { _customClass = value; } } [Category("01. Definition")] [Editor(typeof(PropertyCollectionForm), typeof(UITypeEditor))] [XmlArrayItem(ElementName = "Property", Type = typeof(CriteriaProperty))] [Description("Properties used by the criteria. These will be the parameters to be passed to the generated methods.")] [UserFriendlyName("Criteria Properties")] public CriteriaPropertyCollection Properties { get { return _properties; } } #endregion #region 02. Generation Options [Category("02. Generation Options")] [UserFriendlyName("Create Options")] [Description("Specifies what methods will be generated for new object creation.")] public CriteriaUsageParameter CreateOptions { get { return _createOptions; } set { _createOptions = value; } } [Category("02. Generation Options")] [UserFriendlyName("Get Options")] [Description("Specifies what methods will be generated for fetching an existing object.")] public CriteriaUsageParameter GetOptions { get { return _getOptions; } set { UnSetHandlers(_getOptions); _getOptions = value; SetHandlers(_getOptions); } } [Category("02. Generation Options")] [UserFriendlyName("Delete Options")] [Description("Specifies what methods will be generated for deleting an object.")] public CriteriaUsageParameter DeleteOptions { get { return _deleteOptions; } set { UnSetHandlers(_deleteOptions); _deleteOptions = value; SetHandlers(_deleteOptions); } } #endregion #region 03. Documentation [Category("03. Documentation")] [Editor(typeof(XmlCommentEditor), typeof(UITypeEditor))] [Description("Summary of the criteria. This will be used to document the criteria class.")] public string Summary { get { return _summary; } set { _summary = PropertyHelper.TidyXML(value); } } [Category("03. Documentation")] [Editor(typeof(XmlCommentEditor), typeof(UITypeEditor))] [Description("Remarks of the criteria. This will be used to document the criteria class.")] public string Remarks { get { return _remarks; } set { _remarks = PropertyHelper.TidyXML(value); } } #endregion [Browsable(false)] public CslaObjectInfo ParentObject { get { return _parentObject; } } [Browsable(false)] public bool IsCreator { get { //if (CreateOptions.DataPortal || CreateOptions.Factory) if (CreateOptions.DataPortal) return true; return false; } } [Browsable(false)] public bool IsGetter { get { //if (GetOptions.DataPortal || GetOptions.Factory) if (GetOptions.DataPortal) return true; return false; } } [Browsable(false)] public bool IsDeleter { get { //if (DeleteOptions.DataPortal || DeleteOptions.Factory) if (DeleteOptions.DataPortal) return true; return false; } } #endregion #region Event Handlers void SuffixChangedHandler(object sender, EventArgs e) { if (_parentObject == null || GeneratorController.Current == null || GeneratorController.Current.CurrentUnit == null) { return; } ProjectParameters p = GeneratorController.Current.CurrentUnit.Params; if (ReferenceEquals(sender, _getOptions)) _getOptions.ProcedureName = p.GetGetProcName(_parentObject.ObjectName + _getOptions.FactorySuffix); else if (ReferenceEquals(sender, _deleteOptions)) _deleteOptions.ProcedureName = p.GetDeleteProcName(_parentObject.ObjectName + _deleteOptions.FactorySuffix); } #endregion #region Private and Internal Methods private void SetHandlers(CriteriaUsageParameter p) { if (p == null) return; p.SuffixChanged += SuffixChangedHandler; } private void UnSetHandlers(CriteriaUsageParameter p) { if (p == null) return; p.SuffixChanged -= SuffixChangedHandler; } internal void SetParent(CslaObjectInfo obj) { _parentObject = obj; } #endregion #region Public Methods public void SetSprocNames() { SetSprocNames(string.Empty); } public void SetSprocNames(string getSprocName) { if (_parentObject == null) return; ProjectParameters p = GeneratorController.Current.CurrentUnit.Params; if (IsGetter) { if (getSprocName == string.Empty) _getOptions.ProcedureName = p.GetGetProcName(_parentObject.ObjectName); else _getOptions.ProcedureName = getSprocName; } if (IsDeleter) _deleteOptions.ProcedureName = p.GetDeleteProcName(_parentObject.ObjectName); } internal static Criteria Clone(Criteria masterCrit) { var newCrit = new Criteria(masterCrit.ParentObject); newCrit.Name = masterCrit.Name; newCrit.CriteriaClassMode = masterCrit.CriteriaClassMode; newCrit.NestedClass = masterCrit.NestedClass; newCrit.CustomClass = masterCrit.CustomClass; newCrit.Summary = masterCrit.Summary; newCrit.Remarks = masterCrit.Remarks; newCrit.CreateOptions = CriteriaUsageParameter.Clone(masterCrit.CreateOptions); newCrit.GetOptions = CriteriaUsageParameter.Clone(masterCrit.GetOptions); newCrit.DeleteOptions = CriteriaUsageParameter.Clone(masterCrit.DeleteOptions); newCrit.Properties.AddRange(CriteriaPropertyCollection.Clone(masterCrit.Properties)); return newCrit; } #endregion } }
using System; namespace Eto.Drawing { /// <summary> /// Defines attributes for line drawing methods in <see cref="Graphics"/> /// </summary> /// <copyright>(c) 2012-2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public sealed class Pen : IHandlerSource, IDisposable, IControlObjectSource { readonly IHandler handler; DashStyle dashStyle; /// <summary> /// Gets the control object for this widget /// </summary> /// <value>The control object for the widget</value> public object ControlObject { get; set; } /// <summary> /// Gets the platform handler object for the widget /// </summary> /// <value>The handler for the widget</value> public object Handler { get { return handler; } } /// <summary> /// Gets a delegate that can be used to create instances of the Pen with low overhead /// </summary> public static Func<Color, float, Pen> Instantiator { get { var sharedHandler = Platform.Instance.CreateShared<IHandler>(); return (color, thickness) => { var control = sharedHandler.Create(color, thickness); return new Pen(sharedHandler, control); }; } } Pen (IHandler handler, object control) { this.handler = handler; this.ControlObject = control; } /// <summary> /// Creates a new pen with the specified <paramref name="color"/> and <paramref name="thickness"/> /// </summary> /// <param name="color">Color for the new pen</param> /// <param name="thickness">Thickness of the new pen</param> public Pen(Color color, float thickness = 1f) { handler = Platform.Instance.CreateShared<IHandler>(); ControlObject = handler.Create(color, thickness); } /// <summary> /// Gets or sets the color of the pen /// </summary> /// <value>The color of the pen</value> public Color Color { get { return handler.GetColor (this); } set { handler.SetColor (this, value); } } /// <summary> /// Gets or sets the thickness (width) of the pen /// </summary> public float Thickness { get { return handler.GetThickness (this); } set { handler.SetThickness (this, value); } } /// <summary> /// Gets or sets the line join style of the pen /// </summary> /// <value>The line join style</value> public PenLineJoin LineJoin { get { return handler.GetLineJoin (this); } set { handler.SetLineJoin (this, value); } } /// <summary> /// Gets or sets the line cap style of the pen /// </summary> /// <value>The line cap style</value> public PenLineCap LineCap { get { return handler.GetLineCap (this); } set { handler.SetLineCap (this, value); } } /// <summary> /// Gets or sets the miter limit on the ratio of the length vs. the <see cref="Thickness"/> of this pen /// </summary> /// <remarks> /// This is only used if the <see cref="LineJoin"/> style is <see cref="PenLineJoin.Miter"/> /// </remarks> /// <value>The miter limit of this pen</value> public float MiterLimit { get { return handler.GetMiterLimit (this); } set { handler.SetMiterLimit (this, value); } } /// <summary> /// Gets or sets the dash style of the pen /// </summary> /// <remarks> /// The <see cref="LineCap"/> specifies the dash cap used /// </remarks> /// <value>The dash style.</value> public DashStyle DashStyle { get { return dashStyle; } set { dashStyle = value; handler.SetDashStyle (this, value); } } /// <summary> /// Releases all resource used by the <see cref="Eto.Drawing.Pen"/> object. /// </summary> /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="Eto.Drawing.Pen"/>. The /// <see cref="Dispose"/> method leaves the <see cref="Eto.Drawing.Pen"/> in an unusable state. After calling /// <see cref="Dispose"/>, you must release all references to the <see cref="Eto.Drawing.Pen"/> so the garbage /// collector can reclaim the memory that the <see cref="Eto.Drawing.Pen"/> was occupying.</remarks> public void Dispose () { var controlDispose = ControlObject as IDisposable; if (controlDispose != null) { controlDispose.Dispose (); } } #region Handler /// <summary> /// Defines a pen to be used with the <see cref="Graphics"/> drawing methods /// </summary> /// <copyright>(c) 2012-2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public interface IHandler { /// <summary> /// Creates a new pen with the specified <paramref name="color"/> and <paramref name="thickness"/> /// </summary> /// <param name="color">Color for the new pen</param> /// <param name="thickness">Thickness of the new pen</param> /// <returns>ControlObject for the pen</returns> object Create (Color color, float thickness); /// <summary> /// Gets the color of the pen /// </summary> /// <param name="widget">Pen to get the color</param> Color GetColor (Pen widget); /// <summary> /// Sets the color of the pen /// </summary> /// <param name="widget">Pen to set the color</param> /// <param name="color">Color of the pen</param> void SetColor (Pen widget, Color color); /// <summary> /// Gets or sets the thickness (width) of the pen /// </summary> /// <param name="widget">Pen to get the thickness</param> float GetThickness (Pen widget); /// <summary> /// Sets the thickness (width) of the pen /// </summary> /// <param name="widget">Pen to set the thickness</param> /// <param name="thickness">Thickness for the pen</param> void SetThickness (Pen widget, float thickness); /// <summary> /// Gets the style of line join for the pen /// </summary> /// <param name="widget">Pen to get the line join style</param> PenLineJoin GetLineJoin (Pen widget); /// <summary> /// Sets the style of line join for the pen /// </summary> /// <param name="widget">Pen to set the line join style</param> /// <param name="lineJoin">Line join to set</param> void SetLineJoin (Pen widget, PenLineJoin lineJoin); /// <summary> /// Gets the line cap style /// </summary> /// <param name="widget">Pen to get the line cap style</param> PenLineCap GetLineCap (Pen widget); /// <summary> /// Sets the line cap style /// </summary> /// <param name="widget">Pen to set the line cap</param> /// <param name="lineCap">Line cap to set</param> void SetLineCap (Pen widget, PenLineCap lineCap); /// <summary> /// Gets the miter limit for the pen /// </summary> /// <remarks> /// The miter limit specifies the maximum allowed ratio of miter lenth to stroke length in which a /// miter will be converted to a bevel. The default miter limit is 10. /// </remarks> /// <param name="widget">Pen to get the miter limit</param> float GetMiterLimit (Pen widget); /// <summary> /// Sets the miter limit of the pen /// </summary> /// <remarks> /// The miter limit specifies the maximum allowed ratio of miter lenth to stroke length in which a /// miter will be converted to a bevel. The default miter limit is 10. /// </remarks> /// <param name="widget">Pen to set the miter limit</param> /// <param name="miterLimit">Miter limit to set to the pen</param> void SetMiterLimit (Pen widget, float miterLimit); /// <summary> /// Sets the dash style of the pen /// </summary> /// <param name="widget">Pen to set the dash style</param> /// <param name="dashStyle">Dash style to set to the pen</param> void SetDashStyle (Pen widget, DashStyle dashStyle); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Globalization; using System.Threading; namespace System { public class UriBuilder { // fields private bool _changed = true; private string _fragment = string.Empty; private string _host = "localhost"; private string _password = string.Empty; private string _path = "/"; private int _port = -1; private string _query = string.Empty; private string _scheme = "http"; private string _schemeDelimiter = Uri.SchemeDelimiter; private Uri _uri; private string _username = string.Empty; // constructors public UriBuilder() { } public UriBuilder(string uri) { // setting allowRelative=true for a string like www.acme.org Uri tryUri = new Uri(uri, UriKind.RelativeOrAbsolute); if (tryUri.IsAbsoluteUri) { Init(tryUri); } else { uri = Uri.UriSchemeHttp + Uri.SchemeDelimiter + uri; Init(new Uri(uri)); } } public UriBuilder(Uri uri) { if ((object)uri == null) throw new ArgumentNullException(nameof(uri)); Init(uri); } private void Init(Uri uri) { _fragment = uri.Fragment; _query = uri.Query; _host = uri.Host; _path = uri.AbsolutePath; _port = uri.Port; _scheme = uri.Scheme; _schemeDelimiter = uri.HasAuthority ? Uri.SchemeDelimiter : ":"; string userInfo = uri.UserInfo; if (!string.IsNullOrEmpty(userInfo)) { int index = userInfo.IndexOf(':'); if (index != -1) { _password = userInfo.Substring(index + 1); _username = userInfo.Substring(0, index); } else { _username = userInfo; } } SetFieldsFromUri(uri); } public UriBuilder(string schemeName, string hostName) { Scheme = schemeName; Host = hostName; } public UriBuilder(string scheme, string host, int portNumber) : this(scheme, host) { Port = portNumber; } public UriBuilder(string scheme, string host, int port, string pathValue ) : this(scheme, host, port) { Path = pathValue; } public UriBuilder(string scheme, string host, int port, string path, string extraValue ) : this(scheme, host, port, path) { try { Extra = extraValue; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } throw new ArgumentException(SR.Argument_ExtraNotValid, nameof(extraValue)); } } // properties private string Extra { set { if (value == null) { value = string.Empty; } if (value.Length > 0) { if (value[0] == '#') { Fragment = value.Substring(1); } else if (value[0] == '?') { int end = value.IndexOf('#'); if (end == -1) { end = value.Length; } else { Fragment = value.Substring(end + 1); } Query = value.Substring(1, end - 1); } else { throw new ArgumentException(SR.Argument_ExtraNotValid, nameof(value)); } } else { Fragment = string.Empty; Query = string.Empty; } } } public string Fragment { get { return _fragment; } set { if (value == null) { value = string.Empty; } if (value.Length > 0) { value = '#' + value; } _fragment = value; _changed = true; } } public string Host { get { return _host; } set { if (value == null) { value = string.Empty; } _host = value; //probable ipv6 address - Note: this is only supported for cases where the authority is inet-based. if (_host.IndexOf(':') >= 0) { //set brackets if (_host[0] != '[') _host = "[" + _host + "]"; } _changed = true; } } public string Password { get { return _password; } set { if (value == null) { value = string.Empty; } _password = value; _changed = true; } } public string Path { get { return _path; } set { if ((value == null) || (value.Length == 0)) { value = "/"; } _path = Uri.InternalEscapeString(value.Replace('\\', '/')); _changed = true; } } public int Port { get { return _port; } set { if (value < -1 || value > 0xFFFF) { throw new ArgumentOutOfRangeException(nameof(value)); } _port = value; _changed = true; } } public string Query { get { return _query; } set { if (value == null) { value = string.Empty; } if (value.Length > 0 && value[0] != '?') { value = '?' + value; } _query = value; _changed = true; } } public string Scheme { get { return _scheme; } set { if (value == null) { value = string.Empty; } int index = value.IndexOf(':'); if (index != -1) { value = value.Substring(0, index); } if (value.Length != 0) { if (!Uri.CheckSchemeName(value)) { throw new ArgumentException(SR.net_uri_BadScheme, nameof(value)); } value = value.ToLowerInvariant(); } _scheme = value; _changed = true; } } public Uri Uri { get { if (_changed) { _uri = new Uri(ToString()); SetFieldsFromUri(_uri); _changed = false; } return _uri; } } public string UserName { get { return _username; } set { if (value == null) { value = string.Empty; } _username = value; _changed = true; } } // methods public override bool Equals(object rparam) { if (rparam == null) { return false; } return Uri.Equals(rparam.ToString()); } public override int GetHashCode() { return Uri.GetHashCode(); } private void SetFieldsFromUri(Uri uri) { _fragment = uri.Fragment; _query = uri.Query; _host = uri.Host; _path = uri.AbsolutePath; _port = uri.Port; _scheme = uri.Scheme; _schemeDelimiter = uri.HasAuthority ? Uri.SchemeDelimiter : ":"; string userInfo = uri.UserInfo; if (userInfo.Length > 0) { int index = userInfo.IndexOf(':'); if (index != -1) { _password = userInfo.Substring(index + 1); _username = userInfo.Substring(0, index); } else { _username = userInfo; } } } public override string ToString() { if (_username.Length == 0 && _password.Length > 0) { throw new UriFormatException(SR.net_uri_BadUserPassword); } if (_scheme.Length != 0) { UriParser syntax = UriParser.GetSyntax(_scheme); if (syntax != null) _schemeDelimiter = syntax.InFact(UriSyntaxFlags.MustHaveAuthority) || (_host.Length != 0 && syntax.NotAny(UriSyntaxFlags.MailToLikeUri) && syntax.InFact(UriSyntaxFlags.OptionalAuthority)) ? Uri.SchemeDelimiter : ":"; else _schemeDelimiter = _host.Length != 0 ? Uri.SchemeDelimiter : ":"; } string result = _scheme.Length != 0 ? (_scheme + _schemeDelimiter) : string.Empty; return result + _username + ((_password.Length > 0) ? (":" + _password) : string.Empty) + ((_username.Length > 0) ? "@" : string.Empty) + _host + (((_port != -1) && (_host.Length > 0)) ? (":" + _port.ToString()) : string.Empty) + (((_host.Length > 0) && (_path.Length != 0) && (_path[0] != '/')) ? "/" : string.Empty) + _path + _query + _fragment; } } }
using UnityEngine; using UnityEditor; public static class tk2dTileMapToolbar { // ---- Shared public static string tooltip = ""; static GUIStyle toolbarButtonStyle { get { return tk2dEditorSkin.GetStyle("TilemapToolbarButton"); } } static GUIStyle toolbarButtonLeftStyle { get { return tk2dEditorSkin.GetStyle("TilemapToolbarButtonLeft"); } } static GUIStyle toolbarButtonRightStyle { get { return tk2dEditorSkin.GetStyle("TilemapToolbarButtonRight"); } } static bool HiliteBtn(Texture2D texture, bool hilite, Color hiliteColor, string tooltip) { hiliteColor.a = 1.0f; if (hilite) { GUI.contentColor = (hiliteColor + new Color(0.3f,0.3f,0.3f, 0)); GUI.backgroundColor = (hiliteColor + new Color(0.3f,0.3f,0.3f, 0)); } else { GUI.contentColor = Color.white; GUI.backgroundColor = Color.gray; } bool pressed = GUILayout.Button(new GUIContent(texture, tooltip), toolbarButtonStyle); GUI.backgroundColor = Color.white; GUI.contentColor = Color.white; return pressed; } static bool ToggleBtn(bool toggled, Texture2D texture, string tooltip, GUIStyle style) { if (toggled) { GUI.contentColor = Color.white; GUI.backgroundColor = new Color(0.6f, 0.6f, 0.6f, 1.0f); } else { GUI.contentColor = Color.white; GUI.backgroundColor = Color.gray; } toggled = GUILayout.Toggle(toggled, new GUIContent(texture, tooltip), style); GUI.backgroundColor = Color.white; GUI.contentColor = Color.white; return toggled; } // ---- Paint public enum MainMode { Brush, BrushRandom, Erase, Eyedropper, Cut } public static MainMode mainMode = MainMode.Brush; public static bool workBrushFlipX = false; public static bool workBrushFlipY = false; public static bool workBrushRot90 = false; public static bool scratchpadOpen = false; public static float workBrushOpacity = 0.8f; public static void ToolbarWindow() { string pickupTooltipStr = (Application.platform == RuntimePlatform.OSXEditor) ? "Ctrl" : "Alt"; string eraseTooltipStr = (Application.platform == RuntimePlatform.OSXEditor) ? "Command" : "Ctrl"; Color lastColor = GUI.contentColor; GUILayout.BeginHorizontal(); // Main modes if (HiliteBtn(tk2dEditorSkin.GetTexture("icon_pencil"), (mainMode == MainMode.Brush), tk2dPreferences.inst.tileMapToolColor_brush, "Draw")) mainMode = MainMode.Brush; GUILayout.Space (10); if (HiliteBtn(tk2dEditorSkin.GetTexture("icon_dice"), (mainMode == MainMode.BrushRandom), tk2dPreferences.inst.tileMapToolColor_brushRandom, "Draw Random")) mainMode = MainMode.BrushRandom; GUILayout.Space (10); if (HiliteBtn(tk2dEditorSkin.GetTexture("icon_eraser"), (mainMode == MainMode.Erase), tk2dPreferences.inst.tileMapToolColor_erase, "Erase (" + eraseTooltipStr + ")")) mainMode = MainMode.Erase; GUILayout.Space (10); if (HiliteBtn(tk2dEditorSkin.GetTexture("icon_eyedropper"), (mainMode == MainMode.Eyedropper), tk2dPreferences.inst.tileMapToolColor_eyedropper, "Eyedropper (" + pickupTooltipStr + ")")) mainMode = MainMode.Eyedropper; GUILayout.Space (10); if (HiliteBtn(tk2dEditorSkin.GetTexture("icon_scissors"), (mainMode == MainMode.Cut), tk2dPreferences.inst.tileMapToolColor_cut, "Cut (" + pickupTooltipStr + "+" + eraseTooltipStr + ")")) mainMode = MainMode.Cut; GUILayout.Space (20); // Flip workbrush GUI.contentColor = Color.white; workBrushFlipX = ToggleBtn(workBrushFlipX, tk2dEditorSkin.GetTexture("icon_fliph"), "Flip Horizontal (H)", toolbarButtonStyle); workBrushFlipY = ToggleBtn(workBrushFlipY, tk2dEditorSkin.GetTexture("icon_flipv"), "Flip Vertical (J)", toolbarButtonStyle); workBrushRot90 = ToggleBtn(workBrushRot90, tk2dEditorSkin.GetTexture("icon_pencil"), "Rotate 90", toolbarButtonStyle); GUILayout.Space (20); // Scratchpad if (scratchpadOpen) GUI.contentColor = Color.white; else GUI.contentColor = new Color(0.8f, 0.8f, 0.8f); scratchpadOpen = ToggleBtn(scratchpadOpen, tk2dEditorSkin.GetTexture("icon_scratchpad"), "Scratchpad (Tab)", toolbarButtonStyle); tooltip = GUI.tooltip; GUILayout.EndHorizontal(); GUI.contentColor = lastColor; } // ---- Color public enum ColorChannelsMode { AllChannels, Red, Green, Blue } public enum ColorBlendMode { Replace, Addition, Subtraction, Eyedropper } public static Color colorBrushColor = Color.white; public static ColorChannelsMode colorChannelsMode = ColorChannelsMode.AllChannels; public static ColorBlendMode colorBlendMode = ColorBlendMode.Replace; public static float colorBrushRadius = 1.0f; public static float colorBrushIntensity = 1.0f; public static AnimationCurve colorBrushCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1)); static ColorChannelsMode newColorChannelsMode = ColorChannelsMode.AllChannels; public static void ColorToolsWindow() { Color lastColor = GUI.contentColor; GUILayout.BeginVertical(); // Channels { GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Channel Mask"); GUIContent[] contents = new GUIContent[] { new GUIContent("All", "All Channels"), new GUIContent("R", "Red"), new GUIContent("G", "Green"), new GUIContent("B", "Blue") }; ColorChannelsMode temp = (ColorChannelsMode)GUILayout.Toolbar((int)colorChannelsMode, contents, toolbarButtonStyle); if (temp != colorChannelsMode) newColorChannelsMode = temp; GUILayout.EndHorizontal(); } // Color if (colorChannelsMode == ColorChannelsMode.AllChannels) { colorBrushColor = EditorGUILayout.ColorField("Color", colorBrushColor); } // Blend { GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Mode"); GUIContent[] contents = new GUIContent[] { new GUIContent(tk2dEditorSkin.GetTexture("icon_pencil"), "Replace"), new GUIContent("+", "Addition"), new GUIContent("-", "Subtraction"), new GUIContent(tk2dEditorSkin.GetTexture("icon_eyedropper"), "Eyedropper") }; colorBlendMode = (ColorBlendMode)GUILayout.Toolbar((int)colorBlendMode, contents, toolbarButtonStyle); GUILayout.EndHorizontal(); } // Radius, Intensity { GUIContent radiusLabel = new GUIContent("Radius", "Shortcut - [, ]"); colorBrushRadius = EditorGUILayout.Slider(radiusLabel, colorBrushRadius, 1.0f, 64.0f); GUIContent intensityLabel = new GUIContent("Intensity", "Shortcut - Minus (-), Plus (+)"); colorBrushIntensity = EditorGUILayout.Slider(intensityLabel, colorBrushIntensity * 100.0f, 0.0f, 100.0f) / 100.0f; } // Curve { colorBrushCurve = EditorGUILayout.CurveField("Brush shape", colorBrushCurve); } GUILayout.EndVertical(); GUI.contentColor = lastColor; if (Event.current.type == EventType.Repaint) { colorChannelsMode = newColorChannelsMode; HandleUtility.Repaint(); } } }
using System; using MonoTouch.UIKit; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.CoreAnimation; namespace SignatureCapture { public class UISignatureView : UIView { private UIBezierPath path; private UIImage signatureImage; private PointF[] points = new PointF[5]; private uint controlPoint; private int _strokeWidth = 2; private UIColor _strokeColor = UIColor.Black; private UIColor _backgroundColor = UIColor.White; private UIColor _textColor = UIColor.Black; private bool _showShadow = true; private UIColor _shadowColor = UIColor.Black; public UIColor ShadowColor { get { return _shadowColor; } set { _shadowColor = value; SetShadow (); } } public bool ShowShadow { get { return _showShadow; } set { _showShadow = value; SetShadow (); } } public int StrokeWidth { get { return _strokeWidth; } set { _strokeWidth = value; if (path != null) path.LineWidth = _strokeWidth; } } public UIColor StrokeColor { get { return _strokeColor; } set { _strokeColor = value; } } /// <summary> /// Gets or sets the color of the view background. /// </summary> /// <value>The color of the view background. Default is White</value> public UIColor ViewBackgroundColor { get { return _backgroundColor; } set { _backgroundColor = value; InvokeOnMainThread (() => this.BackgroundColor = _backgroundColor); } } public UIColor TextColor { get { return _textColor; } set { _textColor = value; SetUIElementsColor (); } } public event EventHandler SignatureChanged; private void OnSignatureChanged() { if (SignatureChanged != null) SignatureChanged (this, EventArgs.Empty); } public UISignatureView (RectangleF rect): base(rect) { this.MultipleTouchEnabled = false; this.BackgroundColor = UIColor.White; this.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin; path = new UIBezierPath(); path.LineWidth = this.StrokeWidth; SetSize (); SetShadow (); CreateUIElements (); SubscribeToNotifications (); } public void SetShadow () { CALayer layer = this.Layer; if (!this.ShowShadow) { layer.MasksToBounds = true; layer.ShadowPath = UIBezierPath.FromRect(RectangleF.Empty).CGPath; return; } layer.MasksToBounds = false; layer.ShadowColor = this.ShadowColor.CGColor; layer.ShadowOpacity = 1.0f; layer.ShadowOffset = new SizeF(3.0f, 3.0f); layer.ShadowPath = UIBezierPath.FromRect(this.Bounds).CGPath; } private void SetSize() { var frame = this.Frame; if (frame.X == 0) { frame.X = 6; if (frame.Width == UIScreen.MainScreen.ApplicationFrame.Width) frame.Width -= 12; else frame.Width -= 9; } this.Frame = frame; } private void SubscribeToNotifications() { lineLabel.AddObserver (this, new NSString ("frame"), NSKeyValueObservingOptions.New, IntPtr.Zero); } public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) { AddBottomBorder (lineLabel); SetShadow (); } private UILabel xlabel; private UILabel lineLabel; private UILabel signHereLabel; private void CreateUIElements() { xlabel = new UILabel (new RectangleF (10, this.Frame.Height - 32, 10, 15)); xlabel.BackgroundColor = UIColor.Clear; xlabel.Font = UIFont.SystemFontOfSize (12); xlabel.Text = "X"; this.AddSubview (xlabel); lineLabel = new UILabel (new RectangleF (10, this.Frame.Height - 22, this.Frame.Width - 20, 5)); lineLabel.BackgroundColor = UIColor.Clear; lineLabel.AutoresizingMask = UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin; AddBottomBorder (lineLabel); this.AddSubview (lineLabel); float controlWidth = 75; signHereLabel = new UILabel (new RectangleF (GetMiddleOfFrame(controlWidth), this.Frame.Height - 15, controlWidth, 15)); signHereLabel.BackgroundColor = UIColor.Clear; signHereLabel.Text = "Sign here"; signHereLabel.Font = UIFont.SystemFontOfSize (12); signHereLabel.AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin; this.AddSubview (signHereLabel); } private void AddBottomBorder(UILabel label) { var layer = label.Layer; var bottomBorder = new CALayer (); bottomBorder.BorderColor = this.TextColor.CGColor; bottomBorder.BorderWidth = 1; bottomBorder.Frame = new RectangleF (-1, layer.Frame.Size.Height - 1, layer.Frame.Size.Width, 1); layer.AddSublayer (bottomBorder); } private float GetMiddleOfFrame(float widthOfControl) { var middleOfFrame = this.Frame.Width / 2; var middleOfControl = widthOfControl / 2; return middleOfFrame - middleOfControl; } private void SetUIElementsColor() { xlabel.TextColor = this.TextColor; signHereLabel.TextColor = this.TextColor; AddBottomBorder (lineLabel); } public bool IsSignatureEmpty() { return signatureImage == null && controlPoint == 0; } public void ClearSignature() { if (signatureImage != null) { signatureImage.Dispose (); signatureImage = null; } path.RemoveAllPoints (); SetNeedsDisplay (); } public override void Draw (RectangleF rect) { if (signatureImage != null) signatureImage.Draw(rect); this.StrokeColor.SetStroke (); path.Stroke(); } public override void TouchesBegan (NSSet touches, UIEvent evt) { controlPoint = 0; UITouch touch = touches.AnyObject as UITouch; points[0] = touch.LocationInView(this); } public override void TouchesMoved (NSSet touches, UIEvent evt) { if(SignatureChanged != null) OnSignatureChanged (); UITouch touch = touches.AnyObject as UITouch; PointF point = touch.LocationInView(this); controlPoint++; points[controlPoint] = point; if (controlPoint == 3) { points[2] = new PointF((points[1].X + points[3].X)/2.0f, (points[1].Y + points[3].Y)/2.0f); path.MoveTo(points[0]); path.AddQuadCurveToPoint (points [2], points [1]); this.SetNeedsDisplay (); points[0] = points[2]; points[1] = points[3]; controlPoint = 1; } } public override void TouchesEnded (NSSet touches, UIEvent evt) { if (controlPoint == 0) // only one point acquired = user tapped on the screen { path.AddArc (points [0], path.LineWidth / 2, 0, (float)(Math.PI * 2), true); } else if (controlPoint == 1) { path.MoveTo (points [0]); path.AddLineTo (points [1]); } else if (controlPoint == 2) { path.MoveTo (points [0]); path.AddQuadCurveToPoint (points [2], points [1]); } this.GetSignatureImage(); this.SetNeedsDisplay(); path.RemoveAllPoints(); controlPoint = 0; } public override void TouchesCancelled (NSSet touches, UIEvent evt) { this.TouchesEnded(touches, evt); } public UIImage GetSignatureImage () { UIGraphics.BeginImageContextWithOptions(this.Bounds.Size, false, 0); if (signatureImage == null) { signatureImage = new UIImage (); UIBezierPath rectPath = UIBezierPath.FromRect(this.Bounds); UIColor.Clear.SetFill(); rectPath.Fill(); } signatureImage.Draw(new PointF(0,0)); this.StrokeColor.SetStroke(); path.Stroke(); signatureImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return signatureImage; } } }
////////////////////////////////////////////////////////////////////////// // Code Named: VG-Ripper // Function : Extracts Images posted on RiP forums and attempts to fetch // them to disk. // // This software is licensed under the MIT license. See license.txt for // details. // // Copyright (c) The Watcher // Partial Rights Reserved. // ////////////////////////////////////////////////////////////////////////// // This file is part of the RiP Ripper project base. using System; using System.Collections; using System.IO; using System.Net; using System.Threading; namespace Ripper { using Ripper.Core.Components; using Ripper.Core.Objects; /// <summary> /// Worker class to get images from ImageCrack.com /// </summary> public class ImageCrack : ServiceTemplate { public ImageCrack(ref string sSavePath, ref string strURL, ref string thumbURL, ref string imageName, ref int imageNumber, ref Hashtable hashtable) : base(sSavePath, strURL, thumbURL, imageName, imageNumber, ref hashtable) { // Add constructor logic here } protected override bool DoDownload() { var strImgURL = this.ImageLinkURL; if (this.EventTable.ContainsKey(strImgURL)) { return true; } var strFilePath = string.Empty; var CCObj = new CacheObject(); CCObj.IsDownloaded = false; CCObj.FilePath = strFilePath; CCObj.Url = strImgURL; try { this.EventTable.Add(strImgURL, CCObj); } catch (ThreadAbortException) { return true; } catch (Exception) { if (this.EventTable.ContainsKey(strImgURL)) { return false; } else { this.EventTable.Add(strImgURL, CCObj); } } var strIVPage = this.GetImageHostPage(ref strImgURL); if (strIVPage.Length < 10) { return false; } var strNewURL = string.Empty; strNewURL = strImgURL.Substring(0, strImgURL.IndexOf("/", 8) + 1); var iStartIMG = 0; var iStartSRC = 0; var iEndSRC = 0; iStartIMG = strIVPage.IndexOf("<div align=\"center\"><span id=\"imageLabel\"><img "); if (iStartIMG < 0) { return false; } iStartSRC = strIVPage.IndexOf("src='", iStartIMG); if (iStartSRC < 0) { return false; } iStartSRC += 5; iEndSRC = strIVPage.IndexOf("' id=thepic", iStartSRC); if (iEndSRC < 0) { return false; } strNewURL = strIVPage.Substring(iStartSRC, iEndSRC - iStartSRC); strFilePath = strNewURL.Substring(strNewURL.LastIndexOf("/") + 1); strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath)); try { if (!Directory.Exists(this.SavePath)) Directory.CreateDirectory(this.SavePath); } catch (IOException ex) { // MainForm.DeleteMessage = ex.Message; // MainForm.Delete = true; return false; } ////////////////////////////////////////////////////////////////////////// HttpWebRequest lHttpWebRequest; HttpWebResponse lHttpWebResponse; Stream lHttpWebResponseStream; // FileStream lFileStream = new FileStream(strFilePath, FileMode.Create); // int bytesRead; try { lHttpWebRequest = (HttpWebRequest)WebRequest.Create(strNewURL); lHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"; lHttpWebRequest.Headers.Add("Accept-Language: en-us,en;q=0.5"); lHttpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate"); lHttpWebRequest.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"); lHttpWebRequest.Referer = strImgURL; lHttpWebRequest.Accept = "image/png,*/*;q=0.5"; lHttpWebRequest.KeepAlive = true; lHttpWebResponse = (HttpWebResponse)lHttpWebRequest.GetResponse(); lHttpWebResponseStream = lHttpWebRequest.GetResponse().GetResponseStream(); if (lHttpWebResponse.ContentType.IndexOf("image") < 0) { // if (lFileStream != null) // lFileStream.Close(); return false; } if (lHttpWebResponse.ContentType.ToLower() == "image/jpeg") strFilePath += ".jpg"; else if (lHttpWebResponse.ContentType.ToLower() == "image/gif") strFilePath += ".gif"; else if (lHttpWebResponse.ContentType.ToLower() == "image/png") strFilePath += ".png"; var NewAlteredPath = Utility.GetSuitableName(strFilePath); if (strFilePath != NewAlteredPath) { strFilePath = NewAlteredPath; ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath; } lHttpWebResponseStream.Close(); var client = new WebClient(); client.Headers.Add("Accept-Language: en-us,en;q=0.5"); client.Headers.Add("Accept-Encoding: gzip,deflate"); client.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"); client.Headers.Add("Referer: " + strImgURL); client.Headers.Add( "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"); client.DownloadFile(strNewURL, strFilePath); client.Dispose(); } catch (ThreadAbortException) { ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL); return true; } catch (IOException ex) { // MainForm.DeleteMessage = ex.Message; // MainForm.Delete = true; ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL); return true; } catch (WebException) { ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL); return false; } ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true; // CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath; CacheController.Instance().LastPic = ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath; return true; } ////////////////////////////////////////////////////////////////////////// } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; [ExecuteInEditMode] public class Puppet2D_GlobalControl : MonoBehaviour { public float startRotationY; public List<Puppet2D_SplineControl> _SplineControls = new List<Puppet2D_SplineControl>(); public List<Puppet2D_IKHandle> _Ikhandles = new List<Puppet2D_IKHandle>(); public List<Puppet2D_ParentControl> _ParentControls = new List<Puppet2D_ParentControl>(); public List<Puppet2D_FFDLineDisplay> _ffdControls = new List<Puppet2D_FFDLineDisplay>(); [HideInInspector] public List<SpriteRenderer> _Controls = new List<SpriteRenderer>(); [HideInInspector] public List<SpriteRenderer> _Bones = new List<SpriteRenderer>(); [HideInInspector] public List<SpriteRenderer> _FFDControls = new List<SpriteRenderer>(); public bool ControlsVisiblity = true; public bool BonesVisiblity = true; public bool FFD_Visiblity = true; public bool CombineMeshes = false; public bool flip = false; private bool internalFlip = false; public bool AutoRefresh = true; public bool ControlsEnabled = true; public bool lateUpdate = true; [HideInInspector] public int _flipCorrection = 1; //public float boneSize; // Use this for initialization void OnEnable () { if (AutoRefresh) { _Ikhandles.Clear(); _SplineControls.Clear(); _ParentControls.Clear(); _Controls.Clear(); _Bones.Clear(); _FFDControls.Clear(); _ffdControls.Clear(); TraverseHierarchy(transform); } } public void Refresh() { _Ikhandles.Clear(); _SplineControls.Clear(); _ParentControls.Clear(); _Controls.Clear(); _Bones.Clear(); _FFDControls.Clear(); _ffdControls.Clear(); TraverseHierarchy(transform); } void Awake () { internalFlip = flip; if(Application.isPlaying) { if(CombineMeshes) CombineAllMeshes(); } } // Update is called once per frame public void Init() { _Ikhandles.Clear(); _SplineControls.Clear(); _ParentControls.Clear(); _Controls.Clear(); _Bones.Clear(); _FFDControls.Clear(); _ffdControls.Clear(); TraverseHierarchy(transform); } void OnValidate () { if (AutoRefresh) { _Ikhandles.Clear(); _SplineControls.Clear(); _ParentControls.Clear(); _Controls.Clear(); _Bones.Clear(); _FFDControls.Clear(); _ffdControls.Clear(); TraverseHierarchy(transform); } foreach(SpriteRenderer ctrl in _Controls) { if(ctrl && ctrl.enabled != ControlsVisiblity) ctrl.enabled = ControlsVisiblity; } foreach(SpriteRenderer bone in _Bones) { if(bone && bone.enabled != BonesVisiblity) bone.enabled = BonesVisiblity; } foreach(SpriteRenderer ffdCtrl in _FFDControls) { if(ffdCtrl && ffdCtrl.transform.parent && ffdCtrl.transform.parent.gameObject && ffdCtrl.transform.parent.gameObject.activeSelf != FFD_Visiblity) ffdCtrl.transform.parent.gameObject.SetActive(FFD_Visiblity); } } void Update () { if (!lateUpdate) { #if UNITY_EDITOR if (AutoRefresh) { for (int i = _ParentControls.Count - 1; i >= 0; i--) { if (_ParentControls[i] == null) _ParentControls.RemoveAt(i); } for (int i = _Ikhandles.Count - 1; i >= 0; i--) { if (_Ikhandles[i] == null) _Ikhandles.RemoveAt(i); } for (int i = _SplineControls.Count - 1; i >= 0; i--) { if (_SplineControls[i] == null) _SplineControls.RemoveAt(i); } for (int i = _ffdControls.Count - 1; i >= 0; i--) { if (_ffdControls[i] == null) _ffdControls.RemoveAt(i); } } #endif if (ControlsEnabled) Run(); if (internalFlip != flip) { if (flip) { transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y, -transform.localScale.z); transform.localEulerAngles = new Vector3(transform.rotation.eulerAngles.x, startRotationY + 180, transform.rotation.eulerAngles.z); } else { transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x), Mathf.Abs(transform.localScale.y), Mathf.Abs(transform.localScale.z)); transform.localEulerAngles = new Vector3(transform.rotation.eulerAngles.x, startRotationY, transform.rotation.eulerAngles.z); } internalFlip = flip; Run(); } } } void LateUpdate () { if (lateUpdate) { #if UNITY_EDITOR if (AutoRefresh) { for (int i = _ParentControls.Count - 1; i >= 0; i--) { if (_ParentControls[i] == null) _ParentControls.RemoveAt(i); } for (int i = _Ikhandles.Count - 1; i >= 0; i--) { if (_Ikhandles[i] == null) _Ikhandles.RemoveAt(i); } for (int i = _SplineControls.Count - 1; i >= 0; i--) { if (_SplineControls[i] == null) _SplineControls.RemoveAt(i); } for (int i = _ffdControls.Count - 1; i >= 0; i--) { if (_ffdControls[i] == null) _ffdControls.RemoveAt(i); } } #endif if (ControlsEnabled) Run(); if (internalFlip != flip) { if (flip) { transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y, -transform.localScale.z); transform.localEulerAngles = new Vector3(transform.rotation.eulerAngles.x, startRotationY + 180, transform.rotation.eulerAngles.z); } else { transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x), Mathf.Abs(transform.localScale.y), Mathf.Abs(transform.localScale.z)); transform.localEulerAngles = new Vector3(transform.rotation.eulerAngles.x, startRotationY, transform.rotation.eulerAngles.z); } internalFlip = flip; Run(); } } } public void Run () { foreach(Puppet2D_SplineControl spline in _SplineControls) { if(spline) spline.Run(); } foreach(Puppet2D_ParentControl parentControl in _ParentControls) { if(parentControl) parentControl.ParentControlRun(); } FaceCamera(); foreach(Puppet2D_IKHandle ik in _Ikhandles) { if(ik) ik.CalculateIK(); } foreach(Puppet2D_FFDLineDisplay ffd in _ffdControls) { if(ffd) ffd.Run(); } } public void TraverseHierarchy(Transform root) { foreach (Transform child in root) { GameObject Go = child.gameObject; SpriteRenderer spriteRenderer = Go.transform.GetComponent<SpriteRenderer>(); if (spriteRenderer&& spriteRenderer.sprite) { if(spriteRenderer.sprite.name.Contains("Control")) _Controls.Add(spriteRenderer); else if(spriteRenderer.sprite.name.Contains("ffd")) _FFDControls.Add(spriteRenderer); else if(spriteRenderer.sprite.name.Contains("Bone")) _Bones.Add(spriteRenderer); } Puppet2D_ParentControl newParentCtrl = Go.transform.GetComponent<Puppet2D_ParentControl>(); if (newParentCtrl) { _ParentControls.Add(newParentCtrl); } Puppet2D_IKHandle newIKCtrl = Go.transform.GetComponent<Puppet2D_IKHandle>(); if (newIKCtrl) _Ikhandles.Add(newIKCtrl); Puppet2D_FFDLineDisplay ffdCtrl = Go.transform.GetComponent<Puppet2D_FFDLineDisplay>(); if (ffdCtrl) _ffdControls.Add(ffdCtrl); Puppet2D_SplineControl splineCtrl = Go.transform.GetComponent<Puppet2D_SplineControl>(); if (splineCtrl) _SplineControls.Add(splineCtrl); TraverseHierarchy(child); } } void CombineAllMeshes() { Vector3 originalScale = transform.localScale; Quaternion originalRot = transform.rotation; Vector3 originalPos = transform.position; transform.localScale = Vector3.one; transform.rotation = Quaternion.identity; transform.position = Vector3.zero; SkinnedMeshRenderer[] smRenderers = GetComponentsInChildren<SkinnedMeshRenderer>(); List<Transform> bones = new List<Transform>(); List<BoneWeight> boneWeights = new List<BoneWeight>(); List<CombineInstance> combineInstances = new List<CombineInstance>(); List<Texture2D> textures = new List<Texture2D>(); Material currentMaterial = null; int numSubs = 0; var smRenderersDict = new Dictionary<SkinnedMeshRenderer, float>(smRenderers.Length); bool updateWhenOffscreen = false; foreach(SkinnedMeshRenderer smr in smRenderers) { smRenderersDict.Add(smr, smr.transform.position.z); updateWhenOffscreen = smr.updateWhenOffscreen; } var items = from pair in smRenderersDict orderby pair.Key.sortingOrder ascending select pair; items = from pair in items orderby pair.Value descending select pair; foreach (KeyValuePair<SkinnedMeshRenderer, float> pair in items) { //Debug.Log(pair.Key.name + " " + pair.Value); numSubs += pair.Key.sharedMesh.subMeshCount; } int[] meshIndex = new int[numSubs]; int boneOffset = 0; int s = 0; foreach (KeyValuePair<SkinnedMeshRenderer, float> pair in items) { SkinnedMeshRenderer smr = pair.Key; if (currentMaterial == null) currentMaterial = smr.sharedMaterial; else if (currentMaterial.mainTexture && smr.sharedMaterial.mainTexture && currentMaterial.mainTexture != smr.sharedMaterial.mainTexture) continue; bool ffdMesh = false; foreach(Transform boneToCheck in smr.bones) { Puppet2D_FFDLineDisplay ffdLine = boneToCheck.GetComponent<Puppet2D_FFDLineDisplay>(); if(ffdLine && ffdLine.outputSkinnedMesh != smr) ffdMesh =true; } if(ffdMesh) continue; BoneWeight[] meshBoneweight = smr.sharedMesh.boneWeights; foreach( BoneWeight bw in meshBoneweight ) { BoneWeight bWeight = bw; bWeight.boneIndex0 += boneOffset; bWeight.boneIndex1 += boneOffset; bWeight.boneIndex2 += boneOffset; bWeight.boneIndex3 += boneOffset; boneWeights.Add( bWeight ); } boneOffset += smr.bones.Length; Transform[] meshBones = smr.bones; foreach( Transform bone in meshBones ) bones.Add( bone ); if( smr.material.mainTexture != null ) textures.Add( smr.GetComponent<Renderer>().material.mainTexture as Texture2D ); CombineInstance ci = new CombineInstance(); ci.mesh = smr.sharedMesh; meshIndex[s] = ci.mesh.vertexCount; ci.transform = smr.transform.localToWorldMatrix; combineInstances.Add( ci ); Object.Destroy( smr.gameObject ); s++; } List<Matrix4x4> bindposes = new List<Matrix4x4>(); for( int b = 0; b < bones.Count; b++ ) { if(bones[b].GetComponent<Puppet2D_FFDLineDisplay>()) { Vector3 boneparentPos = bones[b].transform.parent.parent.position; Quaternion boneparentRot = bones[b].transform.parent.parent.rotation; bones[b].transform.parent.parent.position = Vector3.zero; bones[b].transform.parent.parent.rotation = Quaternion.identity; bindposes.Add( bones[b].worldToLocalMatrix * transform.worldToLocalMatrix ); bones[b].transform.parent.parent.position = boneparentPos; bones[b].transform.parent.parent.rotation = boneparentRot; } else bindposes.Add( bones[b].worldToLocalMatrix * transform.worldToLocalMatrix ); } SkinnedMeshRenderer r = gameObject.AddComponent<SkinnedMeshRenderer>(); r.updateWhenOffscreen = updateWhenOffscreen; r.sharedMesh = new Mesh(); r.sharedMesh.CombineMeshes( combineInstances.ToArray(), true, true ); Material combinedMat; if (currentMaterial != null) combinedMat = currentMaterial; else combinedMat = new Material( Shader.Find( "Unlit/Transparent" ) ); combinedMat.mainTexture = textures[0]; r.sharedMesh.uv = r.sharedMesh.uv; r.sharedMaterial = combinedMat; r.bones = bones.ToArray(); r.sharedMesh.boneWeights = boneWeights.ToArray(); r.sharedMesh.bindposes = bindposes.ToArray(); r.sharedMesh.RecalculateBounds(); transform.localScale =originalScale; transform.rotation = originalRot; transform.position =originalPos; } void FaceCamera(){ foreach (Puppet2D_IKHandle p in _Ikhandles) { p.AimDirection = transform.forward.normalized *_flipCorrection; //change the aiming of IK to the forward vector of the camera } } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants; using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID; #if DEV14_OR_LATER using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; #endif namespace Microsoft.VisualStudioTools.Project { internal abstract class ReferenceNode : HierarchyNode { internal delegate void CannotAddReferenceErrorMessage(); #region ctors /// <summary> /// constructor for the ReferenceNode /// </summary> protected ReferenceNode(ProjectNode root, ProjectElement element) : base(root, element) { this.ExcludeNodeFromScc = true; } /// <summary> /// constructor for the ReferenceNode /// </summary> internal ReferenceNode(ProjectNode root) : base(root) { this.ExcludeNodeFromScc = true; } #endregion #region overridden properties public override int MenuCommandId { get { return VsMenus.IDM_VS_CTXT_REFERENCE; } } public override Guid ItemTypeGuid { get { return Guid.Empty; } } public override string Url { get { return String.Empty; } } public override string Caption { get { return String.Empty; } } #endregion #region overridden methods protected override NodeProperties CreatePropertiesObject() { return new ReferenceNodeProperties(this); } /// <summary> /// Get an instance of the automation object for ReferenceNode /// </summary> /// <returns>An instance of Automation.OAReferenceItem type if succeeded</returns> public override object GetAutomationObject() { if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return null; } return new Automation.OAReferenceItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this); } /// <summary> /// Disable inline editing of Caption of a ReferendeNode /// </summary> /// <returns>null</returns> public override string GetEditLabel() { return null; } #if DEV14_OR_LATER protected override bool SupportsIconMonikers { get { return true; } } protected override ImageMoniker GetIconMoniker(bool open) { return CanShowDefaultIcon() ? KnownMonikers.Reference : KnownMonikers.ReferenceWarning; } #else public override int ImageIndex { get { return ProjectMgr.GetIconIndex(CanShowDefaultIcon() ? ProjectNode.ImageName.Reference : ProjectNode.ImageName.DanglingReference ); } } #endif /// <summary> /// Not supported. /// </summary> internal override int ExcludeFromProject() { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } public override bool Remove(bool removeFromStorage) { ReferenceContainerNode parent = Parent as ReferenceContainerNode; if (base.Remove(removeFromStorage)) { if (parent != null) { parent.FireChildRemoved(this); } return true; } return false; } /// <summary> /// References node cannot be dragged. /// </summary> /// <returns>A stringbuilder.</returns> protected internal override string PrepareSelectedNodesForClipBoard() { return null; } internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) { if (cmdGroup == VsMenus.guidStandardCommandSet2K) { if ((VsCommands2K)cmd == VsCommands2K.QUICKOBJECTSEARCH) { result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } } else { return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP; } return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result); } internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (cmdGroup == VsMenus.guidStandardCommandSet2K) { if ((VsCommands2K)cmd == VsCommands2K.QUICKOBJECTSEARCH) { return this.ShowObjectBrowser(); } } return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut); } protected internal override void ShowDeleteMessage(IList<HierarchyNode> nodes, __VSDELETEITEMOPERATION action, out bool cancel, out bool useStandardDialog) { // Don't prompt if all the nodes are references useStandardDialog = !nodes.All(n => n is ReferenceNode); cancel = false; } #endregion #region methods /// <summary> /// Links a reference node to the project and hierarchy. /// </summary> public virtual void AddReference() { ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread(); ReferenceContainerNode referencesFolder = this.ProjectMgr.GetReferenceContainer() as ReferenceContainerNode; Utilities.CheckNotNull(referencesFolder, "Could not find the References node"); CannotAddReferenceErrorMessage referenceErrorMessageHandler = null; if (!this.CanAddReference(out referenceErrorMessageHandler)) { if (referenceErrorMessageHandler != null) { referenceErrorMessageHandler.DynamicInvoke(new object[] { }); } return; } // Link the node to the project file. this.BindReferenceData(); // At this point force the item to be refreshed this.ItemNode.RefreshProperties(); referencesFolder.AddChild(this); return; } /// <summary> /// Refreshes a reference by re-resolving it and redrawing the icon. /// </summary> internal virtual void RefreshReference() { this.ResolveReference(); ProjectMgr.ReDrawNode(this, UIHierarchyElement.Icon); } /// <summary> /// Resolves references. /// </summary> protected virtual void ResolveReference() { } /// <summary> /// Validates that a reference can be added. /// </summary> /// <param name="errorHandler">A CannotAddReferenceErrorMessage delegate to show the error message.</param> /// <returns>true if the reference can be added.</returns> protected virtual bool CanAddReference(out CannotAddReferenceErrorMessage errorHandler) { // When this method is called this refererence has not yet been added to the hierarchy, only instantiated. errorHandler = null; if (this.IsAlreadyAdded()) { return false; } return true; } /// <summary> /// Checks if a reference is already added. The method parses all references and compares the Url. /// </summary> /// <returns>true if the assembly has already been added.</returns> protected virtual bool IsAlreadyAdded() { ReferenceContainerNode referencesFolder = this.ProjectMgr.GetReferenceContainer() as ReferenceContainerNode; Utilities.CheckNotNull(referencesFolder, "Could not find the References node"); for (HierarchyNode n = referencesFolder.FirstChild; n != null; n = n.NextSibling) { ReferenceNode refererenceNode = n as ReferenceNode; if (null != refererenceNode) { // We check if the Url of the assemblies is the same. if (CommonUtils.IsSamePath(refererenceNode.Url, this.Url)) { return true; } } } return false; } /// <summary> /// Shows the Object Browser /// </summary> /// <returns></returns> protected virtual int ShowObjectBrowser() { if (!File.Exists(this.Url)) { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } // Request unmanaged code permission in order to be able to create the unmanaged memory representing the guid. new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); Guid guid = VSConstants.guidCOMPLUSLibrary; IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(guid.ToByteArray().Length); System.Runtime.InteropServices.Marshal.StructureToPtr(guid, ptr, false); int returnValue = VSConstants.S_OK; try { VSOBJECTINFO[] objInfo = new VSOBJECTINFO[1]; objInfo[0].pguidLib = ptr; objInfo[0].pszLibName = this.Url; IVsObjBrowser objBrowser = this.ProjectMgr.Site.GetService(typeof(SVsObjBrowser)) as IVsObjBrowser; ErrorHandler.ThrowOnFailure(objBrowser.NavigateTo(objInfo, 0)); } catch (COMException e) { Trace.WriteLine("Exception" + e.ErrorCode); returnValue = e.ErrorCode; } finally { if (ptr != IntPtr.Zero) { System.Runtime.InteropServices.Marshal.FreeCoTaskMem(ptr); } } return returnValue; } internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) { if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject) { return true; } return false; } protected abstract void BindReferenceData(); #endregion } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D03_Continent_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="D03_Continent_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="D02_Continent"/> collection. /// </remarks> [Serializable] public partial class D03_Continent_ReChild : BusinessBase<D03_Continent_ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "SubContinents Child Name"); /// <summary> /// Gets or sets the SubContinents Child Name. /// </summary> /// <value>The SubContinents Child Name.</value> public string Continent_Child_Name { get { return GetProperty(Continent_Child_NameProperty); } set { SetProperty(Continent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D03_Continent_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="D03_Continent_ReChild"/> object.</returns> internal static D03_Continent_ReChild NewD03_Continent_ReChild() { return DataPortal.CreateChild<D03_Continent_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="D03_Continent_ReChild"/> object, based on given parameters. /// </summary> /// <param name="continent_ID2">The Continent_ID2 parameter of the D03_Continent_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="D03_Continent_ReChild"/> object.</returns> internal static D03_Continent_ReChild GetD03_Continent_ReChild(int continent_ID2) { return DataPortal.FetchChild<D03_Continent_ReChild>(continent_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D03_Continent_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D03_Continent_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="D03_Continent_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="D03_Continent_ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="continent_ID2">The Continent ID2.</param> protected void Child_Fetch(int continent_ID2) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetD03_Continent_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID2", continent_ID2).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, continent_ID2); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="D03_Continent_ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_Child_NameProperty, dr.GetString("Continent_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="D03_Continent_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(D02_Continent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddD03_Continent_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID2", parent.Continent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Continent_Child_Name", ReadProperty(Continent_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="D03_Continent_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(D02_Continent parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateD03_Continent_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID2", parent.Continent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Continent_Child_Name", ReadProperty(Continent_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="D03_Continent_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(D02_Continent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteD03_Continent_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID2", parent.Continent_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudioTools.Project; namespace Microsoft.VisualStudioTools.Navigation { /// <summary> /// Inplementation of the service that builds the information to expose to the symbols /// navigation tools (class view or object browser) from the source files inside a /// hierarchy. /// </summary> internal abstract partial class LibraryManager : IDisposable, IVsRunningDocTableEvents { private readonly CommonPackage/*!*/ _package; private readonly Dictionary<uint, TextLineEventListener> _documents; private readonly Dictionary<IVsHierarchy, HierarchyInfo> _hierarchies = new Dictionary<IVsHierarchy, HierarchyInfo>(); private readonly Dictionary<ModuleId, LibraryNode> _files; private readonly Library _library; private readonly IVsEditorAdaptersFactoryService _adapterFactory; private uint _objectManagerCookie; private uint _runningDocTableCookie; public LibraryManager(CommonPackage/*!*/ package) { Contract.Assert(package != null); this._package = package; this._documents = new Dictionary<uint, TextLineEventListener>(); this._library = new Library(new Guid(CommonConstants.LibraryGuid)); this._library.LibraryCapabilities = (_LIB_FLAGS2)_LIB_FLAGS.LF_PROJECT; this._files = new Dictionary<ModuleId, LibraryNode>(); var model = ((IServiceContainer)package).GetService(typeof(SComponentModel)) as IComponentModel; this._adapterFactory = model.GetService<IVsEditorAdaptersFactoryService>(); // Register our library now so it'll be available for find all references RegisterLibrary(); } public Library Library => this._library; protected abstract LibraryNode CreateLibraryNode(LibraryNode parent, IScopeNode subItem, string namePrefix, IVsHierarchy hierarchy, uint itemid); public virtual LibraryNode CreateFileLibraryNode(LibraryNode parent, HierarchyNode hierarchy, string name, string filename, LibraryNodeType libraryNodeType) { return new LibraryNode(null, name, filename, libraryNodeType); } private object GetPackageService(Type/*!*/ type) { return ((System.IServiceProvider)this._package).GetService(type); } private void RegisterForRDTEvents() { if (0 != this._runningDocTableCookie) { return; } var rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (null != rdt) { // Do not throw here in case of error, simply skip the registration. rdt.AdviseRunningDocTableEvents(this, out this._runningDocTableCookie); } } private void UnregisterRDTEvents() { if (0 == this._runningDocTableCookie) { return; } var rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (null != rdt) { // Do not throw in case of error. rdt.UnadviseRunningDocTableEvents(this._runningDocTableCookie); } this._runningDocTableCookie = 0; } #region ILibraryManager Members public void RegisterHierarchy(IVsHierarchy hierarchy) { if ((null == hierarchy) || this._hierarchies.ContainsKey(hierarchy)) { return; } RegisterLibrary(); var commonProject = hierarchy.GetProject().GetCommonProject(); var listener = new HierarchyListener(hierarchy, this); var node = this._hierarchies[hierarchy] = new HierarchyInfo( listener, new ProjectLibraryNode(commonProject) ); this._library.AddNode(node.ProjectLibraryNode); listener.StartListening(true); RegisterForRDTEvents(); } private void RegisterLibrary() { if (0 == this._objectManagerCookie) { var objManager = GetPackageService(typeof(SVsObjectManager)) as IVsObjectManager2; if (null == objManager) { return; } Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( objManager.RegisterSimpleLibrary(this._library, out this._objectManagerCookie)); } } public void UnregisterHierarchy(IVsHierarchy hierarchy) { if ((null == hierarchy) || !this._hierarchies.ContainsKey(hierarchy)) { return; } var info = this._hierarchies[hierarchy]; if (null != info) { info.Listener.Dispose(); } this._hierarchies.Remove(hierarchy); this._library.RemoveNode(info.ProjectLibraryNode); if (0 == this._hierarchies.Count) { UnregisterRDTEvents(); } lock (this._files) { var keys = new ModuleId[this._files.Keys.Count]; this._files.Keys.CopyTo(keys, 0); foreach (var id in keys) { if (hierarchy.Equals(id.Hierarchy)) { this._library.RemoveNode(this._files[id]); this._files.Remove(id); } } } // Remove the document listeners. var docKeys = new uint[this._documents.Keys.Count]; this._documents.Keys.CopyTo(docKeys, 0); foreach (var id in docKeys) { var docListener = this._documents[id]; if (hierarchy.Equals(docListener.FileID.Hierarchy)) { this._documents.Remove(id); docListener.Dispose(); } } } public void RegisterLineChangeHandler(uint document, TextLineChangeEvent lineChanged, Action<IVsTextLines> onIdle) { this._documents[document].OnFileChangedImmediate += delegate (object sender, TextLineChange[] changes, int fLast) { lineChanged(sender, changes, fLast); }; this._documents[document].OnFileChanged += (sender, args) => onIdle(args.TextBuffer); } #endregion #region Library Member Production /// <summary> /// Overridden in the base class to receive notifications of when a file should /// be analyzed for inclusion in the library. The derived class should queue /// the parsing of the file and when it's complete it should call FileParsed /// with the provided LibraryTask and an IScopeNode which provides information /// about the members of the file. /// </summary> protected virtual void OnNewFile(LibraryTask task) { } /// <summary> /// Called by derived class when a file has been parsed. The caller should /// provide the LibraryTask received from the OnNewFile call and an IScopeNode /// which represents the contents of the library. /// /// It is safe to call this method from any thread. /// </summary> protected void FileParsed(LibraryTask task, IScopeNode scope) { try { var project = task.ModuleID.Hierarchy.GetProject().GetCommonProject(); HierarchyNode fileNode = fileNode = project.NodeFromItemId(task.ModuleID.ItemID); HierarchyInfo parent; if (fileNode == null || !this._hierarchies.TryGetValue(task.ModuleID.Hierarchy, out parent)) { return; } var module = CreateFileLibraryNode( parent.ProjectLibraryNode, fileNode, System.IO.Path.GetFileName(task.FileName), task.FileName, LibraryNodeType.Package | LibraryNodeType.Classes ); // TODO: Creating the module tree should be done lazily as needed // Currently we replace the entire tree and rely upon the libraries // update count to invalidate the whole thing. We could do this // finer grained and only update the changed nodes. But then we // need to make sure we're not mutating lists which are handed out. CreateModuleTree(module, scope, task.FileName + ":", task.ModuleID); if (null != task.ModuleID) { LibraryNode previousItem = null; lock (this._files) { if (this._files.TryGetValue(task.ModuleID, out previousItem)) { this._files.Remove(task.ModuleID); parent.ProjectLibraryNode.RemoveNode(previousItem); } } } parent.ProjectLibraryNode.AddNode(module); this._library.Update(); if (null != task.ModuleID) { lock (this._files) { this._files.Add(task.ModuleID, module); } } } catch (COMException) { // we're shutting down and can't get the project } } private void CreateModuleTree(LibraryNode current, IScopeNode scope, string namePrefix, ModuleId moduleId) { if ((null == scope) || (null == scope.NestedScopes)) { return; } foreach (var subItem in scope.NestedScopes) { var newNode = CreateLibraryNode(current, subItem, namePrefix, moduleId.Hierarchy, moduleId.ItemID); var newNamePrefix = namePrefix; current.AddNode(newNode); if ((newNode.NodeType & LibraryNodeType.Classes) != LibraryNodeType.None) { newNamePrefix = namePrefix + newNode.Name + "."; } // Now use recursion to get the other types. CreateModuleTree(newNode, subItem, newNamePrefix, moduleId); } } #endregion #region Hierarchy Events private void OnNewFile(object sender, HierarchyEventArgs args) { var hierarchy = sender as IVsHierarchy; if (null == hierarchy || IsNonMemberItem(hierarchy, args.ItemID)) { return; } ITextBuffer buffer = null; if (null != args.TextBuffer) { buffer = this._adapterFactory.GetDocumentBuffer(args.TextBuffer); } var id = new ModuleId(hierarchy, args.ItemID); OnNewFile(new LibraryTask(args.CanonicalName, buffer, new ModuleId(hierarchy, args.ItemID))); } /// <summary> /// Handles the delete event, checking to see if this is a project item. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnDeleteFile(object sender, HierarchyEventArgs args) { var hierarchy = sender as IVsHierarchy; if (null == hierarchy || IsNonMemberItem(hierarchy, args.ItemID)) { return; } OnDeleteFile(hierarchy, args); } /// <summary> /// Does a delete w/o checking if it's a non-meber item, for handling the /// transition from member item to non-member item. /// </summary> private void OnDeleteFile(IVsHierarchy hierarchy, HierarchyEventArgs args) { var id = new ModuleId(hierarchy, args.ItemID); LibraryNode node = null; lock (this._files) { if (this._files.TryGetValue(id, out node)) { this._files.Remove(id); HierarchyInfo parent; if (this._hierarchies.TryGetValue(hierarchy, out parent)) { parent.ProjectLibraryNode.RemoveNode(node); } } } if (null != node) { this._library.RemoveNode(node); } } private void IsNonMemberItemChanged(object sender, HierarchyEventArgs args) { var hierarchy = sender as IVsHierarchy; if (null == hierarchy) { return; } if (!IsNonMemberItem(hierarchy, args.ItemID)) { OnNewFile(hierarchy, args); } else { OnDeleteFile(hierarchy, args); } } /// <summary> /// Checks whether this hierarchy item is a project member (on disk items from show all /// files aren't considered project members). /// </summary> protected bool IsNonMemberItem(IVsHierarchy hierarchy, uint itemId) { object val; var hr = hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_IsNonMemberItem, out val); return ErrorHandler.Succeeded(hr) && (bool)val; } #endregion #region IVsRunningDocTableEvents Members public int OnAfterAttributeChange(uint docCookie, uint grfAttribs) { if ((grfAttribs & (uint)(__VSRDTATTRIB.RDTA_MkDocument)) == (uint)__VSRDTATTRIB.RDTA_MkDocument) { var rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt != null) { uint flags, readLocks, editLocks, itemid; IVsHierarchy hier; var docData = IntPtr.Zero; string moniker; int hr; try { hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out editLocks, out moniker, out hier, out itemid, out docData); TextLineEventListener listner; if (this._documents.TryGetValue(docCookie, out listner)) { listner.FileName = moniker; } } finally { if (IntPtr.Zero != docData) { Marshal.Release(docData); } } } } return VSConstants.S_OK; } public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame) { return VSConstants.S_OK; } public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) { return VSConstants.S_OK; } public int OnAfterSave(uint docCookie) { return VSConstants.S_OK; } public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame) { // Check if this document is in the list of the documents. if (this._documents.ContainsKey(docCookie)) { return VSConstants.S_OK; } // Get the information about this document from the RDT. var rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (null != rdt) { // Note that here we don't want to throw in case of error. uint flags; uint readLocks; uint writeLoks; string documentMoniker; IVsHierarchy hierarchy; uint itemId; IntPtr unkDocData; var hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out writeLoks, out documentMoniker, out hierarchy, out itemId, out unkDocData); try { if (Microsoft.VisualStudio.ErrorHandler.Failed(hr) || (IntPtr.Zero == unkDocData)) { return VSConstants.S_OK; } // Check if the herarchy is one of the hierarchies this service is monitoring. if (!this._hierarchies.ContainsKey(hierarchy)) { // This hierarchy is not monitored, we can exit now. return VSConstants.S_OK; } // Check the file to see if a listener is required. if (this._package.IsRecognizedFile(documentMoniker)) { return VSConstants.S_OK; } // Create the module id for this document. var docId = new ModuleId(hierarchy, itemId); // Try to get the text buffer. var buffer = Marshal.GetObjectForIUnknown(unkDocData) as IVsTextLines; // Create the listener. var listener = new TextLineEventListener(buffer, documentMoniker, docId); // Set the event handler for the change event. Note that there is no difference // between the AddFile and FileChanged operation, so we can use the same handler. listener.OnFileChanged += new EventHandler<HierarchyEventArgs>(this.OnNewFile); // Add the listener to the dictionary, so we will not create it anymore. this._documents.Add(docCookie, listener); } finally { if (IntPtr.Zero != unkDocData) { Marshal.Release(unkDocData); } } } // Always return success. return VSConstants.S_OK; } public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) { if ((0 != dwEditLocksRemaining) || (0 != dwReadLocksRemaining)) { return VSConstants.S_OK; } TextLineEventListener listener; if (!this._documents.TryGetValue(docCookie, out listener) || (null == listener)) { return VSConstants.S_OK; } using (listener) { this._documents.Remove(docCookie); // Now make sure that the information about this file are up to date (e.g. it is // possible that Class View shows something strange if the file was closed without // saving the changes). var args = new HierarchyEventArgs(listener.FileID.ItemID, listener.FileName); OnNewFile(listener.FileID.Hierarchy, args); } return VSConstants.S_OK; } #endregion public void OnIdle(IOleComponentManager compMgr) { foreach (var listener in this._documents.Values) { if (compMgr.FContinueIdle() == 0) { break; } listener.OnIdle(); } } #region IDisposable Members public void Dispose() { // Dispose all the listeners. foreach (var info in this._hierarchies.Values) { info.Listener.Dispose(); } this._hierarchies.Clear(); foreach (var textListener in this._documents.Values) { textListener.Dispose(); } this._documents.Clear(); // Remove this library from the object manager. if (0 != this._objectManagerCookie) { var mgr = GetPackageService(typeof(SVsObjectManager)) as IVsObjectManager2; if (null != mgr) { mgr.UnregisterLibrary(this._objectManagerCookie); } this._objectManagerCookie = 0; } // Unregister this object from the RDT events. UnregisterRDTEvents(); } #endregion private class HierarchyInfo { public readonly HierarchyListener Listener; public readonly ProjectLibraryNode ProjectLibraryNode; public HierarchyInfo(HierarchyListener listener, ProjectLibraryNode projectLibNode) { this.Listener = listener; this.ProjectLibraryNode = projectLibNode; } } } }
using System; using Csla; using ParentLoadSoftDelete.DataAccess; using ParentLoadSoftDelete.DataAccess.ERCLevel; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F07_Country_Child (editable child object).<br/> /// This is a generated base class of <see cref="F07_Country_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="F06_Country"/> collection. /// </remarks> [Serializable] public partial class F07_Country_Child : BusinessBase<F07_Country_Child> { #region State Fields [NotUndoable] [NonSerialized] internal int country_ID1 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Country_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Regions Child Name"); /// <summary> /// Gets or sets the Regions Child Name. /// </summary> /// <value>The Regions Child Name.</value> public string Country_Child_Name { get { return GetProperty(Country_Child_NameProperty); } set { SetProperty(Country_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F07_Country_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="F07_Country_Child"/> object.</returns> internal static F07_Country_Child NewF07_Country_Child() { return DataPortal.CreateChild<F07_Country_Child>(); } /// <summary> /// Factory method. Loads a <see cref="F07_Country_Child"/> object from the given F07_Country_ChildDto. /// </summary> /// <param name="data">The <see cref="F07_Country_ChildDto"/>.</param> /// <returns>A reference to the fetched <see cref="F07_Country_Child"/> object.</returns> internal static F07_Country_Child GetF07_Country_Child(F07_Country_ChildDto data) { F07_Country_Child obj = new F07_Country_Child(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F07_Country_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public F07_Country_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="F07_Country_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="F07_Country_Child"/> object from the given <see cref="F07_Country_ChildDto"/>. /// </summary> /// <param name="data">The F07_Country_ChildDto to use.</param> private void Fetch(F07_Country_ChildDto data) { // Value properties LoadProperty(Country_Child_NameProperty, data.Country_Child_Name); // parent properties country_ID1 = data.Parent_Country_ID; var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="F07_Country_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(F06_Country parent) { var dto = new F07_Country_ChildDto(); dto.Parent_Country_ID = parent.Country_ID; dto.Country_Child_Name = Country_Child_Name; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IF07_Country_ChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="F07_Country_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(F06_Country parent) { if (!IsDirty) return; var dto = new F07_Country_ChildDto(); dto.Parent_Country_ID = parent.Country_ID; dto.Country_Child_Name = Country_Child_Name; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IF07_Country_ChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="F07_Country_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(F06_Country parent) { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IF07_Country_ChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Country_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Linq.Expressions.Tests { public interface I { void M(); } public class C : IEquatable<C>, I { void I.M() { } public override bool Equals(object o) { return o is C && Equals((C)o); } public bool Equals(C c) { return c != null; } public override int GetHashCode() { return 0; } } public class D : C, IEquatable<D> { public int Val; public string S; public D() { } public D(int val) : this(val, "") { } public D(int val, string s) { Val = val; S = s; } public override bool Equals(object o) { return o is D && Equals((D)o); } public bool Equals(D d) { return d != null && d.Val == Val; } public override int GetHashCode() { return Val; } } public enum E { A = 1, B = 2, Red = 0, Green, Blue } public enum El : long { A, B, C } public enum Eu : uint { Foo, Bar, Baz } public struct S : IEquatable<S> { public override bool Equals(object o) { return (o is S) && Equals((S)o); } public bool Equals(S other) { return true; } public override int GetHashCode() { return 0; } } public struct Sp : IEquatable<Sp> { public Sp(int i, double d) { I = i; D = d; } public int I; public double D; public override bool Equals(object o) { return (o is Sp) && Equals((Sp)o); } public bool Equals(Sp other) { return other.I == I && other.D.Equals(D); } public override int GetHashCode() { return I.GetHashCode() ^ D.GetHashCode(); } } public struct Ss : IEquatable<Ss> { public Ss(S s) { Val = s; } public S Val; public override bool Equals(object o) { return (o is Ss) && Equals((Ss)o); } public bool Equals(Ss other) { return other.Val.Equals(Val); } public override int GetHashCode() { return Val.GetHashCode(); } } public struct Sc : IEquatable<Sc> { public Sc(string s) { S = s; } public string S; public override bool Equals(object o) { return (o is Sc) && Equals((Sc)o); } public bool Equals(Sc other) { return other.S == S; } public override int GetHashCode() { return S.GetHashCode(); } } public struct Scs : IEquatable<Scs> { public Scs(string s, S val) { S = s; Val = val; } public string S; public S Val; public override bool Equals(object o) { return (o is Scs) && Equals((Scs)o); } public bool Equals(Scs other) { return other.S == S && other.Val.Equals(Val); } public override int GetHashCode() { return S.GetHashCode() ^ Val.GetHashCode(); } } public class BaseClass { } public class FC { public int II; public static int SI; public const int CI = 42; public static readonly int RI = 42; } public struct FS { public int II; public static int SI; public const int CI = 42; public static readonly int RI = 42; } public class PC { public int II { get; set; } public static int SI { get; set; } public int this[int i] { get { return 1; } set { } } } public struct PS { public int II { get; set; } public static int SI { get; set; } } internal class CompilationTypes : IEnumerable<object[]> { private static readonly IEnumerable<object[]> Booleans = new[] { #if FEATURE_COMPILE && FEATURE_INTERPRET new object[] {false}, #endif new object[] {true}, }; public IEnumerator<object[]> GetEnumerator() => Booleans.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } internal class NoOpVisitor : ExpressionVisitor { internal static readonly NoOpVisitor Instance = new NoOpVisitor(); private NoOpVisitor() { } } public static class Unreadable<T> { public static T WriteOnly { set { } } } public class GenericClass<T> { public void Method() { } public static T Field; public static T Property => Field; } public class NonGenericClass { #pragma warning disable 0067 public event EventHandler Event; #pragma warning restore 0067 public void GenericMethod<T>() { } public static void StaticMethod() { } public static readonly NonGenericClass NonGenericField = new NonGenericClass(); public static NonGenericClass NonGenericProperty => NonGenericField; } public class InvalidTypesData : IEnumerable<object[]> { private static readonly object[] GenericTypeDefinition = new object[] { typeof(GenericClass<>) }; private static readonly object[] ContainsGenericParameters = new object[] { typeof(GenericClass<>).MakeGenericType(typeof(GenericClass<>)) }; public IEnumerator<object[]> GetEnumerator() { yield return GenericTypeDefinition; yield return ContainsGenericParameters; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } public class UnreadableExpressionsData : IEnumerable<object[]> { private static readonly object[] Property = new object[] { Expression.Property(null, typeof(Unreadable<bool>), nameof(Unreadable<bool>.WriteOnly)) }; private static readonly object[] Indexer = new object[] { Expression.Property(null, typeof(Unreadable<bool>).GetProperty(nameof(Unreadable<bool>.WriteOnly)), new Expression[0]) }; public IEnumerator<object[]> GetEnumerator() { yield return Property; yield return Indexer; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class OpenGenericMethodsData : IEnumerable<object[]> { private static readonly object[] GenericClass = new object[] { typeof(GenericClass<>).GetMethod(nameof(GenericClass<string>.Method)) }; private static readonly object[] GenericMethod = new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.GenericMethod)) }; public IEnumerator<object[]> GetEnumerator() { yield return GenericClass; yield return GenericMethod; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public enum ByteEnum : byte { A = Byte.MaxValue } public enum SByteEnum : sbyte { A = SByte.MaxValue } public enum Int16Enum : short { A = Int16.MaxValue } public enum UInt16Enum : ushort { A = UInt16.MaxValue } public enum Int32Enum : int { A = Int32.MaxValue } public enum UInt32Enum : uint { A = UInt32.MaxValue } public enum Int64Enum : long { A = Int64.MaxValue } public enum UInt64Enum : ulong { A = UInt64.MaxValue } #if FEATURE_COMPILE public static class NonCSharpTypes { private static Type _charEnumType; private static Type _boolEnumType; private static ModuleBuilder GetModuleBuilder() { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly( new AssemblyName("Name"), AssemblyBuilderAccess.Run); return assembly.DefineDynamicModule("Name"); } public static Type CharEnumType { get { if (_charEnumType == null) { EnumBuilder eb = GetModuleBuilder().DefineEnum("CharEnumType", TypeAttributes.Public, typeof(char)); eb.DefineLiteral("A", 'A'); eb.DefineLiteral("B", 'B'); eb.DefineLiteral("C", 'C'); _charEnumType = eb.CreateTypeInfo(); } return _charEnumType; } } public static Type BoolEnumType { get { if (_boolEnumType == null) { EnumBuilder eb = GetModuleBuilder().DefineEnum("BoolEnumType", TypeAttributes.Public, typeof(bool)); eb.DefineLiteral("False", false); eb.DefineLiteral("True", true); _boolEnumType = eb.CreateTypeInfo(); } return _boolEnumType; } } } #endif public class FakeExpression : Expression { public FakeExpression(ExpressionType customNodeType, Type customType) { CustomNodeType = customNodeType; CustomType = customType; } public ExpressionType CustomNodeType { get; set; } public Type CustomType { get; set; } public override ExpressionType NodeType => CustomNodeType; public override Type Type => CustomType; } public struct Number : IEquatable<Number> { private readonly int _value; public Number(int value) { _value = value; } public static readonly Number MinValue = new Number(int.MinValue); public static readonly Number MaxValue = new Number(int.MaxValue); public static Number operator +(Number l, Number r) => new Number(unchecked(l._value + r._value)); public static Number operator -(Number l, Number r) => new Number(l._value - r._value); public static Number operator *(Number l, Number r) => new Number(unchecked(l._value * r._value)); public static Number operator /(Number l, Number r) => new Number(l._value / r._value); public static Number operator %(Number l, Number r) => new Number(l._value % r._value); public static Number operator &(Number l, Number r) => new Number(l._value & r._value); public static Number operator |(Number l, Number r) => new Number(l._value | r._value); public static Number operator ^(Number l, Number r) => new Number(l._value ^ r._value); public static bool operator >(Number l, Number r) => l._value > r._value; public static bool operator >=(Number l, Number r) => l._value >= r._value; public static bool operator <(Number l, Number r) => l._value < r._value; public static bool operator <=(Number l, Number r) => l._value <= r._value; public static bool operator ==(Number l, Number r) => l._value == r._value; public static bool operator !=(Number l, Number r) => l._value != r._value; public override bool Equals(object obj) => obj is Number && Equals((Number)obj); public bool Equals(Number other) => _value == other._value; public override int GetHashCode() => _value; } public static class ExpressionAssert { public static void Verify(this LambdaExpression expression, string il, string instructions) { #if FEATURE_COMPILE expression.VerifyIL(il); #endif // FEATURE_COMPILE is not directly required, // but this functionality relies on private reflection and that would not work with AOT #if FEATURE_INTERPRET && FEATURE_COMPILE expression.VerifyInstructions(instructions); #endif } } public class RunOnceEnumerable<T> : IEnumerable<T> { private readonly IEnumerable<T> _source; private bool _called; public RunOnceEnumerable(IEnumerable<T> source) { _source = source; } public IEnumerator<T> GetEnumerator() { Assert.False(_called); _called = true; return _source.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } public class Truthiness { private bool Value { get; } public Truthiness(bool value) { Value = value; } public static implicit operator bool(Truthiness truth) => truth.Value; public static bool operator true(Truthiness truth) => truth.Value; public static bool operator false(Truthiness truth) => !truth.Value; public static Truthiness operator !(Truthiness truth) => new Truthiness(!truth.Value); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using Foodata.Areas.HelpPage.Models; namespace Foodata.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 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 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) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using OpenIddict.Abstractions; using OrchardCore.OpenId.Abstractions.Stores; using OrchardCore.OpenId.YesSql.Indexes; using OrchardCore.OpenId.YesSql.Models; using YesSql; using YesSql.Services; using static OpenIddict.Abstractions.OpenIddictConstants; namespace OrchardCore.OpenId.YesSql.Stores { public class OpenIdTokenStore<TToken> : IOpenIdTokenStore<TToken> where TToken : OpenIdToken, new() { private readonly ISession _session; public OpenIdTokenStore(ISession session) { _session = session; } /// <inheritdoc/> public virtual async ValueTask<long> CountAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return await _session.Query<TToken>().CountAsync(); } /// <inheritdoc/> public virtual ValueTask<long> CountAsync<TResult>(Func<IQueryable<TToken>, IQueryable<TResult>> query, CancellationToken cancellationToken) => throw new NotSupportedException(); /// <inheritdoc/> public virtual async ValueTask CreateAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } cancellationToken.ThrowIfCancellationRequested(); _session.Save(token); await _session.CommitAsync(); } /// <inheritdoc/> public virtual async ValueTask DeleteAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } cancellationToken.ThrowIfCancellationRequested(); _session.Delete(token); await _session.CommitAsync(); } /// <inheritdoc/> public virtual IAsyncEnumerable<TToken> FindAsync( string subject, string client, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } if (string.IsNullOrEmpty(client)) { throw new ArgumentException("The client cannot be null or empty.", nameof(client)); } cancellationToken.ThrowIfCancellationRequested(); return _session.Query<TToken, OpenIdTokenIndex>( index => index.ApplicationId == client && index.Subject == subject).ToAsyncEnumerable(); } /// <inheritdoc/> public virtual IAsyncEnumerable<TToken> FindAsync( string subject, string client, string status, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } if (string.IsNullOrEmpty(client)) { throw new ArgumentException("The client identifier cannot be null or empty.", nameof(client)); } if (string.IsNullOrEmpty(status)) { throw new ArgumentException("The status cannot be null or empty.", nameof(status)); } cancellationToken.ThrowIfCancellationRequested(); return _session.Query<TToken, OpenIdTokenIndex>( index => index.ApplicationId == client && index.Subject == subject && index.Status == status).ToAsyncEnumerable(); } /// <inheritdoc/> public virtual IAsyncEnumerable<TToken> FindAsync( string subject, string client, string status, string type, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } if (string.IsNullOrEmpty(client)) { throw new ArgumentException("The client identifier cannot be null or empty.", nameof(client)); } if (string.IsNullOrEmpty(status)) { throw new ArgumentException("The status cannot be null or empty.", nameof(status)); } if (string.IsNullOrEmpty(type)) { throw new ArgumentException("The type cannot be null or empty.", nameof(type)); } cancellationToken.ThrowIfCancellationRequested(); return _session.Query<TToken, OpenIdTokenIndex>( index => index.ApplicationId == client && index.Subject == subject && index.Status == status && index.Type == type).ToAsyncEnumerable(); } /// <inheritdoc/> public virtual IAsyncEnumerable<TToken> FindByApplicationIdAsync(string identifier, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } cancellationToken.ThrowIfCancellationRequested(); return _session.Query<TToken, OpenIdTokenIndex>(index => index.ApplicationId == identifier).ToAsyncEnumerable(); } /// <inheritdoc/> public virtual IAsyncEnumerable<TToken> FindByAuthorizationIdAsync(string identifier, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } cancellationToken.ThrowIfCancellationRequested(); return _session.Query<TToken, OpenIdTokenIndex>(index => index.AuthorizationId == identifier).ToAsyncEnumerable(); } /// <inheritdoc/> public virtual async ValueTask<TToken> FindByReferenceIdAsync(string identifier, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } cancellationToken.ThrowIfCancellationRequested(); return await _session.Query<TToken, OpenIdTokenIndex>(index => index.ReferenceId == identifier).FirstOrDefaultAsync(); } /// <inheritdoc/> public virtual async ValueTask<TToken> FindByIdAsync(string identifier, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } cancellationToken.ThrowIfCancellationRequested(); return await _session.Query<TToken, OpenIdTokenIndex>(index => index.TokenId == identifier).FirstOrDefaultAsync(); } /// <inheritdoc/> public virtual async ValueTask<TToken> FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } cancellationToken.ThrowIfCancellationRequested(); return await _session.GetAsync<TToken>(int.Parse(identifier, CultureInfo.InvariantCulture)); } /// <inheritdoc/> public virtual IAsyncEnumerable<TToken> FindBySubjectAsync(string subject, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } cancellationToken.ThrowIfCancellationRequested(); return _session.Query<TToken, OpenIdTokenIndex>(index => index.Subject == subject).ToAsyncEnumerable(); } /// <inheritdoc/> public virtual ValueTask<TResult> GetAsync<TState, TResult>( Func<IQueryable<TToken>, TState, IQueryable<TResult>> query, TState state, CancellationToken cancellationToken) => throw new NotSupportedException(); /// <inheritdoc/> public virtual ValueTask<string> GetApplicationIdAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } return new ValueTask<string>(token.ApplicationId?.ToString(CultureInfo.InvariantCulture)); } /// <inheritdoc/> public virtual ValueTask<string> GetAuthorizationIdAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } return new ValueTask<string>(token.AuthorizationId); } /// <inheritdoc/> public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } return new ValueTask<DateTimeOffset?>(token.CreationDate); } /// <inheritdoc/> public virtual ValueTask<DateTimeOffset?> GetExpirationDateAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } return new ValueTask<DateTimeOffset?>(token.ExpirationDate); } /// <inheritdoc/> public virtual ValueTask<string> GetIdAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } return new ValueTask<string>(token.TokenId); } /// <inheritdoc/> public virtual ValueTask<string> GetPayloadAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } return new ValueTask<string>(token.Payload); } /// <inheritdoc/> public virtual ValueTask<string> GetPhysicalIdAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } return new ValueTask<string>(token.Id.ToString(CultureInfo.InvariantCulture)); } /// <inheritdoc/> public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } if (token.Properties == null) { return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); } return new ValueTask<ImmutableDictionary<string, JsonElement>>( JsonSerializer.Deserialize<ImmutableDictionary<string, JsonElement>>(token.Properties.ToString())); } /// <inheritdoc/> public virtual ValueTask<string> GetReferenceIdAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } return new ValueTask<string>(token.ReferenceId); } /// <inheritdoc/> public virtual ValueTask<string> GetStatusAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } return new ValueTask<string>(token.Status); } /// <inheritdoc/> public virtual ValueTask<string> GetSubjectAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } return new ValueTask<string>(token.Subject); } /// <inheritdoc/> public virtual ValueTask<string> GetTypeAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } return new ValueTask<string>(token.Type); } /// <inheritdoc/> public virtual ValueTask<TToken> InstantiateAsync(CancellationToken cancellationToken) => new ValueTask<TToken>(new TToken { TokenId = Guid.NewGuid().ToString("n") }); /// <inheritdoc/> public virtual IAsyncEnumerable<TToken> ListAsync(int? count, int? offset, CancellationToken cancellationToken) { var query = _session.Query<TToken>(); if (offset.HasValue) { query = query.Skip(offset.Value); } if (count.HasValue) { query = query.Take(count.Value); } return query.ToAsyncEnumerable(); } /// <inheritdoc/> public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( Func<IQueryable<TToken>, TState, IQueryable<TResult>> query, TState state, CancellationToken cancellationToken) => throw new NotSupportedException(); /// <inheritdoc/> public virtual async ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken = default) { // Note: Entity Framework Core doesn't support set-based deletes, which prevents removing // entities in a single command without having to retrieve and materialize them first. // To work around this limitation, entities are manually listed and deleted using a batch logic. IList<Exception> exceptions = null; for (var offset = 0; offset < 100_000; offset = offset + 1_000) { cancellationToken.ThrowIfCancellationRequested(); var tokens = await _session.Query<TToken, OpenIdTokenIndex>( token => token.CreationDate < threshold && ((token.Status != Statuses.Inactive && token.Status != Statuses.Valid) || token.AuthorizationId.IsNotIn<OpenIdAuthorizationIndex>( authorization => authorization.AuthorizationId, authorization => authorization.Status == Statuses.Valid) || token.ExpirationDate < DateTimeOffset.UtcNow)).Skip(offset).Take(1_000).ListAsync(); foreach (var token in tokens) { _session.Delete(token); } try { await _session.CommitAsync(); } catch (Exception exception) { if (exceptions == null) { exceptions = new List<Exception>(capacity: 1); } exceptions.Add(exception); } } if (exceptions != null) { throw new AggregateException("An error occurred while pruning authorizations.", exceptions); } } /// <inheritdoc/> public virtual ValueTask SetApplicationIdAsync(TToken token, string identifier, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } if (string.IsNullOrEmpty(identifier)) { token.ApplicationId = null; } else { token.ApplicationId = identifier; } return default; } /// <inheritdoc/> public virtual ValueTask SetAuthorizationIdAsync(TToken token, string identifier, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } if (string.IsNullOrEmpty(identifier)) { token.AuthorizationId = null; } else { token.AuthorizationId = identifier; } return default; } /// <inheritdoc/> public virtual ValueTask SetCreationDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } token.CreationDate = date?.UtcDateTime; return default; } /// <inheritdoc/> public virtual ValueTask SetExpirationDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } token.ExpirationDate = date?.UtcDateTime; return default; } /// <inheritdoc/> public virtual ValueTask SetPayloadAsync(TToken token, string payload, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } token.Payload = payload; return default; } /// <inheritdoc/> public virtual ValueTask SetPropertiesAsync(TToken token, ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } if (properties == null || properties.IsEmpty) { token.Properties = null; return default; } token.Properties = JObject.Parse(JsonSerializer.Serialize(properties, new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, WriteIndented = false })); return default; } /// <inheritdoc/> public virtual ValueTask SetReferenceIdAsync(TToken token, string identifier, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } token.ReferenceId = identifier; return default; } /// <inheritdoc/> public virtual ValueTask SetStatusAsync(TToken token, string status, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } if (string.IsNullOrEmpty(status)) { throw new ArgumentException("The status cannot be null or empty.", nameof(status)); } token.Status = status; return default; } /// <inheritdoc/> public virtual ValueTask SetSubjectAsync(TToken token, string subject, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } if (string.IsNullOrEmpty(subject)) { throw new ArgumentException("The subject cannot be null or empty.", nameof(subject)); } token.Subject = subject; return default; } /// <inheritdoc/> public virtual ValueTask SetTypeAsync(TToken token, string type, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } if (string.IsNullOrEmpty(type)) { throw new ArgumentException("The token type cannot be null or empty.", nameof(type)); } token.Type = type; return default; } /// <inheritdoc/> public virtual async ValueTask UpdateAsync(TToken token, CancellationToken cancellationToken) { if (token == null) { throw new ArgumentNullException(nameof(token)); } cancellationToken.ThrowIfCancellationRequested(); _session.Save(token, checkConcurrency: true); try { await _session.CommitAsync(); } catch (ConcurrencyException exception) { throw new OpenIddictExceptions.ConcurrencyException(new StringBuilder() .AppendLine("The token was concurrently updated and cannot be persisted in its current state.") .Append("Reload the token from the database and retry the operation.") .ToString(), exception); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Policy; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Podio.API.Model; using Cometd.Client; using Cometd.Client.Transport; using Cometd.Bayeux; using Cometd.Bayeux.Client; using Cometd.Common; using Newtonsoft.Json; using System.Windows.Threading; using System.Windows.Media.Animation; namespace PodioDesktop { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> class Listener : IMessageListener { public void onMessage(IClientSessionChannel channel, IMessage message) { // Handle the message Dictionary<string, object> msg = extract_msg(message); Console.WriteLine("------------Listener------------" + msg["event"] + "\t" + msg["type"] + "\t" + msg["id"]); string push_note = msg["event"] + "\t" + msg["type"] + " " + msg["id"]; pop_alert(push_note); } private Dictionary<string, object> extract_msg(IMessage msg) { Dictionary<string, object> dic_data = (Dictionary<string, object>)msg["data"]; Dictionary<string, object> dic_data_detail = (Dictionary<string, object>)dic_data["data"]; Dictionary<string, object> dic = new Dictionary<string, object>(); string evnt = dic_data_detail["event"].ToString(); if (evnt == "viewing" || evnt == "typing") { dic.Add("event", dic_data_detail["event"]); dic.Add("type", "what to see who it is?"); dic.Add("id", "support lite!"); } else { Dictionary<string, object> dic_data_ref = (Dictionary<string, object>)dic_data_detail["data"]; Dictionary<string, object> dic_type_id = (Dictionary<string, object>)dic_data_ref["data_ref"]; dic.Add("event", dic_data_detail["event"]); dic.Add("type", dic_type_id["type"]); dic.Add("id", dic_type_id["id"]); } return dic; } private void pop_alert(string push_note) { System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new System.Action(() => { var workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea; PopAlertWindow pop = new PopAlertWindow(push_note); int window_num = System.Windows.Application.Current.Windows.Count - 1; pop.Left = workingArea.Width - 300; pop.Top = workingArea.Height - window_num * 100; pop.Show(); })); } } class Extention : IExtension { private IDictionary<String, Object> _msg_ext = new Dictionary<String, Object>(); public Extention(IDictionary<string,object> ext) { _msg_ext = ext; } public bool rcv(Cometd.Bayeux.Client.IClientSession session, Cometd.Bayeux.IMutableMessage message) { //Console.WriteLine("MSG from Extention rcv" + message); return true; } public bool rcvMeta(Cometd.Bayeux.Client.IClientSession session, Cometd.Bayeux.IMutableMessage message) { //Console.WriteLine("MSG from Extention rcvMeta" + message); return true; } public bool send(Cometd.Bayeux.Client.IClientSession session, Cometd.Bayeux.IMutableMessage message) { //Console.WriteLine("MSG from Extention send" + message); return true; } public bool sendMeta(Cometd.Bayeux.Client.IClientSession session, Cometd.Bayeux.IMutableMessage message) { message.getExt(true); message.Ext.Add("private_pub_signature", _msg_ext["private_pub_signature"]); message.Ext.Add("private_pub_timestamp", _msg_ext["private_pub_timestamp"]); //Console.WriteLine("MSG from Extention sendMeta" + message); return true; } } public partial class MainWindow : Window { /* The "id" podio gives your application when you generate a key (usually the name you give your Application) * the Client Secret Guid podio generates when you create an API Key. * your Podio login email, the password for your Podio account */ Podio.API.Client client; private int currentSpaceId = 1434205; //initiate it with podio test space public MainWindow() { client = (Podio.API.Client)System.Windows.Application.Current.Properties["podio_client"]; if (client != null) { InitializeComponent(); this.Left = 0; //minimize icon System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon(); ni.Icon = new System.Drawing.Icon("podio.ico"); ni.Visible = true; ni.DoubleClick += delegate(object sender, EventArgs args) { this.Show(); this.WindowState = WindowState.Normal; }; start_subscribe(); } else { MessageBox.Show("Unable to get the PODIO client.", "Error", MessageBoxButton.OK); App.Current.Shutdown(-1); } } protected override void OnStateChanged(EventArgs e) { if (WindowState == System.Windows.WindowState.Minimized) this.Hide(); base.OnStateChanged(e); } private void start_subscribe() { String url = "https://push.podio.com/faye"; Dictionary<string, object> push_info = new Dictionary<string,object>(); bool IsSubscribe = false; IEnumerable<Organization> orgs = client.OrganisationService.GetOrganizations(); foreach (Organization org in orgs) { foreach (Space space in client.OrganisationService.GetSpacesOnOrganization((int)org.OrgId)) { int spaceId = (int)space.SpaceId; if (spaceId == 1434205) //test: only listen to podio test { foreach (StreamObject stream in client.StreamService.GetSpaceStream(spaceId, 1, 0)) //10 will make high load { switch (stream.Type) { case "action": push_info = get_push(stream.Id.ToString(), "action"); IsSubscribe = true; break; case "file": push_info = get_push(stream.Id.ToString(), "file"); IsSubscribe = true; break; case "item": push_info = get_push(stream.Id.ToString(), "item"); IsSubscribe = true; break; case "status": push_info = get_push(stream.Id.ToString(), "status"); IsSubscribe = true; break; default: IsSubscribe = false; break; } if (IsSubscribe) { BayeuxClient fayeclient = new BayeuxClient(url, new List<ClientTransport>() { new LongPollingTransport(null) }); fayeclient.handshake(); fayeclient.waitFor(1000, new List<BayeuxClient.State>() { BayeuxClient.State.CONNECTED }); IDictionary<String, Object> Auth = new Dictionary<String, Object>(); Auth.Add("private_pub_signature", push_info["signature"]); Auth.Add("private_pub_timestamp", push_info["timestamp"]); Extention CometDext = new Extention(Auth); fayeclient.addExtension(CometDext); IClientSessionChannel channel = fayeclient.getChannel(push_info["channel"].ToString()); channel.subscribe(new Listener()); IsSubscribe = false; } } } } } } private void Home_Click(object sender, RoutedEventArgs e) { UserShow.Visibility = System.Windows.Visibility.Hidden; SpaceShow.Visibility = System.Windows.Visibility.Hidden; HomeShow.Visibility = System.Windows.Visibility.Visible; FlowDocument FlowDoc = new FlowDocument(); Paragraph para = new Paragraph(); try { IEnumerable<Organization> orgs = client.OrganisationService.GetOrganizations(); foreach (Organization org in orgs) { para.Inlines.Add(new Run(org.Name)); foreach (Space space in client.OrganisationService.GetSpacesOnOrganization((int)org.OrgId)) //client.OrganisationService.GetSpacesOnOrganization((int)orgs.First().OrgId //OrgId is nullable { Hyperlink link = new Hyperlink(); link.IsEnabled = true; link.Inlines.Add(space.Name); link.NavigateUri = new Uri(space.Url); link.CommandParameter = space.SpaceId; link.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(Workspace_Click); para.Inlines.Add("\r\n\t"); para.Inlines.Add(link); } para.Inlines.Add("\r\n"); } FlowDoc.Blocks.Add(para); RichHomeDisplay.Document = FlowDoc; } catch (Exception ex) { } } private void User_Click(object sender, RoutedEventArgs e) { SpaceShow.Visibility = System.Windows.Visibility.Hidden; HomeShow.Visibility = System.Windows.Visibility.Hidden; UserShow.Visibility = System.Windows.Visibility.Visible; string requestUrl = Podio.API.Constants.PODIOAPI_BASEURL + "/user/status"; Podio.API.Utils.PodioRestHelper.PodioResponse response = Podio.API.Utils.PodioRestHelper.Request(requestUrl, client.AuthInfo.AccessToken); string contents = response.Data; Dictionary<string, object> dic_all = JsonConvert.DeserializeObject<Dictionary<string, object>>(contents); string str_profile = dic_all["profile"].ToString(); Dictionary<string, object> dic_profile = JsonConvert.DeserializeObject<Dictionary<string, object>>(str_profile); if (UserInfo.Children.Count < 1) { TextBlock text = new TextBlock(); text.TextWrapping = TextWrapping.WrapWithOverflow; text.FontFamily = new System.Windows.Media.FontFamily("Arial"); text.FontSize = 19; Hyperlink link = new Hyperlink(); link.IsEnabled = true; link.Inlines.Add(dic_profile["name"].ToString()); link.NavigateUri = new Uri(dic_profile["link"].ToString()); link.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(link_RequestNavigate); text.Inlines.Add("User Name: "); text.Inlines.Add(link); text.Inlines.Add("\n\nUser Id: " + dic_profile["user_id"].ToString() + "\n\nLast Seen On: " + dic_profile["last_seen_on"].ToString()); string[] emails = dic_profile["mail"].ToString().Split('\"'); int email_num = (emails.Count() - 1) / 2; if (email_num > 0.5) { text.Inlines.Add("\n\nEmail: "); for (int i = 0; i < email_num; i++) { text.Inlines.Add(emails[i * 2 + 1] + " "); } } UserInfo.Children.Add(text); } } private void Workspace_Click(object sender, RoutedEventArgs e) { UserShow.Visibility = System.Windows.Visibility.Hidden; HomeShow.Visibility = System.Windows.Visibility.Hidden; SpaceShow.Visibility = System.Windows.Visibility.Visible; int spaceId; if (sender.GetType().Name == "Hyperlink") { Hyperlink lnk = (Hyperlink)sender; spaceId = (int)lnk.CommandParameter; currentSpaceId = spaceId; } else //"Button" { spaceId = currentSpaceId; } FlowDocument FlowDoc = new FlowDocument(); Paragraph para = new Paragraph(); foreach (StreamObject stream in client.StreamService.GetSpaceStream(spaceId, 10, 0))//729327 is the id of OneFix Support; 1434205 is PODIO Test { Hyperlink link = new Hyperlink(); link.IsEnabled = true; link.Inlines.Add(stream.Title); link.NavigateUri = new Uri(stream.Link); link.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(link_RequestNavigate); TextBlock blk_link = new TextBlock(); //use textblock to wrap the content if too long blk_link.TextWrapping = TextWrapping.Wrap; blk_link.Inlines.Add(link); StackPanel comm_panel = new StackPanel(); comm_panel.Margin = new Thickness(10,4,0,0); foreach (Comment comm in stream.Comments){ FlowDocument fld = new FlowDocument(); Paragraph par = new Paragraph(); par.Inlines.Add(comm.CreatedBy.Name + ": " + comm.Value); fld.Blocks.Add(par); RichTextBox comm_richbox = new RichTextBox(fld); comm_panel.Children.Add(comm_richbox); } TextBox comm_text = new TextBox(); comm_text.Height = 60; comm_text.SpellCheck.IsEnabled = true; comm_text.AcceptsReturn = true; comm_text.IsReadOnly = false; comm_text.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible; comm_text.VerticalScrollBarVisibility = ScrollBarVisibility.Visible; comm_panel.Children.Add(comm_text); Button comm_send = new Button(); comm_send.Content = "Add Comment"; //comm_send.CommandParameter = stream.Id; comm_send.Click += (click_sender, click_e) => { comm_send_Click(sender, e, comm_text.Text, stream.Id.ToString()); }; comm_panel.Children.Add(comm_send); Expander expan = new Expander(); expan.Header = blk_link; expan.Content = comm_panel; para.Inlines.Add(expan); para.Inlines.Add(new LineBreak()); } FlowDoc.Blocks.Add(para); RichSpaceDisplay.Document = FlowDoc; } private void Hide_Click(object sender, RoutedEventArgs e) { Storyboard sb = new Storyboard(); DoubleAnimation da = new DoubleAnimation(-434,new Duration(new TimeSpan(15))); Storyboard.SetTargetProperty(da, new PropertyPath("(Window.Left)")); //Do not miss the '(' and ')' sb.Children.Add(da); this.BeginStoryboard(sb); } private void comm_send_Click(object sender, EventArgs e, string comm, string streamid) { string requestUrl = Podio.API.Constants.PODIOAPI_BASEURL + "/comment/item/" + streamid + "/"; //this url will only work for app item Dictionary<string, string> commdata = new Dictionary<string, string>(); commdata.Add("value", comm); Podio.API.Utils.PodioRestHelper.PodioResponse response = Podio.API.Utils.PodioRestHelper.JSONRequest(requestUrl,client.AuthInfo.AccessToken, commdata, Podio.API.Utils.PodioRestHelper.RequestMethod.POST); Workspace_Click(sender,(RoutedEventArgs)e); //refresh } private Dictionary<string,object> get_push(string id, string type) { string requestUrl = Podio.API.Constants.PODIOAPI_BASEURL + "/" + type + "/" + id + "/"; Podio.API.Utils.PodioRestHelper.PodioResponse response = Podio.API.Utils.PodioRestHelper.Request(requestUrl, client.AuthInfo.AccessToken);//GET by default string contents = response.Data; Dictionary<string, object> dic_all = JsonConvert.DeserializeObject<Dictionary<string, object>>(contents); string push_info = dic_all["push"].ToString(); Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(push_info); return dic; } private void link_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e) { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(e.Uri.AbsoluteUri)); e.Handled = true; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using Moq; using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu.Edit.Checks; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Tests.Beatmaps; using osuTK; namespace osu.Game.Rulesets.Osu.Tests.Editor.Checks { [TestFixture] public class CheckTimeDistanceEqualityTest { private CheckTimeDistanceEquality check; [SetUp] public void Setup() { check = new CheckTimeDistanceEquality(); } [Test] public void TestCirclesEquidistant() { assertOk(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new HitCircle { StartTime = 1000, Position = new Vector2(100, 0) }, new HitCircle { StartTime = 1500, Position = new Vector2(150, 0) } } }); } [Test] public void TestCirclesOneSlightlyOff() { assertWarning(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new HitCircle { StartTime = 1000, Position = new Vector2(80, 0) }, // Distance a quite low compared to previous. new HitCircle { StartTime = 1500, Position = new Vector2(130, 0) } } }); } [Test] public void TestCirclesOneOff() { assertProblem(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new HitCircle { StartTime = 1000, Position = new Vector2(150, 0) }, // Twice the regular spacing. new HitCircle { StartTime = 1500, Position = new Vector2(100, 0) } } }); } [Test] public void TestCirclesTwoOff() { assertProblem(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new HitCircle { StartTime = 1000, Position = new Vector2(150, 0) }, // Twice the regular spacing. new HitCircle { StartTime = 1500, Position = new Vector2(250, 0) } // Also twice the regular spacing. } }, count: 2); } [Test] public void TestCirclesStacked() { assertOk(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new HitCircle { StartTime = 1000, Position = new Vector2(50, 0) }, // Stacked, is fine. new HitCircle { StartTime = 1500, Position = new Vector2(100, 0) } } }); } [Test] public void TestCirclesStacking() { assertWarning(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new HitCircle { StartTime = 1000, Position = new Vector2(50, 0), StackHeight = 1 }, new HitCircle { StartTime = 1500, Position = new Vector2(50, 0), StackHeight = 2 }, new HitCircle { StartTime = 2000, Position = new Vector2(50, 0), StackHeight = 3 }, new HitCircle { StartTime = 2500, Position = new Vector2(50, 0), StackHeight = 4 }, // Ends up far from (50; 0), causing irregular spacing. new HitCircle { StartTime = 3000, Position = new Vector2(100, 0) } } }); } [Test] public void TestCirclesHalfStack() { assertOk(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new HitCircle { StartTime = 1000, Position = new Vector2(55, 0) }, // Basically stacked, so is fine. new HitCircle { StartTime = 1500, Position = new Vector2(105, 0) } } }); } [Test] public void TestCirclesPartialOverlap() { assertProblem(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new HitCircle { StartTime = 1000, Position = new Vector2(65, 0) }, // Really low distance compared to previous. new HitCircle { StartTime = 1500, Position = new Vector2(115, 0) } } }); } [Test] public void TestCirclesSlightlyDifferent() { assertOk(new Beatmap<HitObject> { HitObjects = new List<HitObject> { // Does not need to be perfect, as long as the distance is approximately correct it's sight-readable. new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(52, 0) }, new HitCircle { StartTime = 1000, Position = new Vector2(97, 0) }, new HitCircle { StartTime = 1500, Position = new Vector2(165, 0) } } }); } [Test] public void TestCirclesSlowlyChanging() { const float multiplier = 1.2f; assertOk(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new HitCircle { StartTime = 1000, Position = new Vector2(50 + 50 * multiplier, 0) }, // This gap would be a warning if it weren't for the previous pushing the average spacing up. new HitCircle { StartTime = 1500, Position = new Vector2(50 + 50 * multiplier + 50 * multiplier * multiplier, 0) } } }); } [Test] public void TestCirclesQuicklyChanging() { const float multiplier = 1.6f; var beatmap = new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new HitCircle { StartTime = 1000, Position = new Vector2(50 + 50 * multiplier, 0) }, // Warning new HitCircle { StartTime = 1500, Position = new Vector2(50 + 50 * multiplier + 50 * multiplier * multiplier, 0) } // Problem } }; var context = new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap), DifficultyRating.Easy); var issues = check.Run(context).ToList(); Assert.That(issues, Has.Count.EqualTo(2)); Assert.That(issues.First().Template is CheckTimeDistanceEquality.IssueTemplateIrregularSpacingWarning); Assert.That(issues.Last().Template is CheckTimeDistanceEquality.IssueTemplateIrregularSpacingProblem); } [Test] public void TestCirclesTooFarApart() { assertOk(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new HitCircle { StartTime = 4000, Position = new Vector2(200, 0) }, // 2 seconds apart from previous, so can start from wherever. new HitCircle { StartTime = 4500, Position = new Vector2(250, 0) } } }); } [Test] public void TestCirclesOneOffExpert() { assertOk(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new HitCircle { StartTime = 1000, Position = new Vector2(150, 0) }, // Jumps are allowed in higher difficulties. new HitCircle { StartTime = 1500, Position = new Vector2(100, 0) } } }, DifficultyRating.Expert); } [Test] public void TestSpinner() { assertOk(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, new Spinner { StartTime = 500, EndTime = 1000 }, // Distance to and from the spinner should be ignored. If it isn't this should give a problem. new HitCircle { StartTime = 1500, Position = new Vector2(100, 0) }, new HitCircle { StartTime = 2000, Position = new Vector2(150, 0) } } }); } [Test] public void TestSliders() { assertOk(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, getSliderMock(startTime: 1000, endTime: 1500, startPosition: new Vector2(100, 0), endPosition: new Vector2(150, 0)).Object, getSliderMock(startTime: 2000, endTime: 2500, startPosition: new Vector2(200, 0), endPosition: new Vector2(250, 0)).Object, new HitCircle { StartTime = 2500, Position = new Vector2(300, 0) } } }); } [Test] public void TestSlidersOneOff() { assertProblem(new Beatmap<HitObject> { HitObjects = new List<HitObject> { new HitCircle { StartTime = 0, Position = new Vector2(0) }, new HitCircle { StartTime = 500, Position = new Vector2(50, 0) }, getSliderMock(startTime: 1000, endTime: 1500, startPosition: new Vector2(100, 0), endPosition: new Vector2(150, 0)).Object, getSliderMock(startTime: 2000, endTime: 2500, startPosition: new Vector2(250, 0), endPosition: new Vector2(300, 0)).Object, // Twice the spacing. new HitCircle { StartTime = 2500, Position = new Vector2(300, 0) } } }); } private Mock<Slider> getSliderMock(double startTime, double endTime, Vector2 startPosition, Vector2 endPosition) { var mockSlider = new Mock<Slider>(); mockSlider.SetupGet(s => s.StartTime).Returns(startTime); mockSlider.SetupGet(s => s.Position).Returns(startPosition); mockSlider.SetupGet(s => s.EndPosition).Returns(endPosition); mockSlider.As<IHasDuration>().Setup(d => d.EndTime).Returns(endTime); return mockSlider; } private void assertOk(IBeatmap beatmap, DifficultyRating difficultyRating = DifficultyRating.Easy) { var context = new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap), difficultyRating); Assert.That(check.Run(context), Is.Empty); } private void assertWarning(IBeatmap beatmap, int count = 1) { var context = new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap), DifficultyRating.Easy); var issues = check.Run(context).ToList(); Assert.That(issues, Has.Count.EqualTo(count)); Assert.That(issues.All(issue => issue.Template is CheckTimeDistanceEquality.IssueTemplateIrregularSpacingWarning)); } private void assertProblem(IBeatmap beatmap, int count = 1) { var context = new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap), DifficultyRating.Easy); var issues = check.Run(context).ToList(); Assert.That(issues, Has.Count.EqualTo(count)); Assert.That(issues.All(issue => issue.Template is CheckTimeDistanceEquality.IssueTemplateIrregularSpacingProblem)); } } }
//----------------------------------------------------------------------- // <copyright file="RequestManager.cs" company="CompanyName"> // Copyright info. // </copyright> //----------------------------------------------------------------------- namespace Distribox.Network { using System; using System.Collections.Generic; using System.Linq; using Distribox.CommonLib; using Distribox.FileSystem; // TODO use max number of connections instead of max "bandwidth" /// <summary> /// The manager of sending patches /// RequestManager will /// * Decide which Patches to request right now /// * Manage request to ensure no request will be sent twice /// * Resend request if request isn't finished /// It maintains two queues in it: TODO queue and Doing queue, the lifecycle of a request is /// getRequests FinishRequests /// TODO -------------> Doing ----------------> Done /// ----------------> Fail / Expire /// </summary> /// <remarks> /// <para /> /// </remarks> public class RequestManager { private Dictionary<FileEvent, List<Peer>> todoFileToPeer; private Dictionary<Peer, List<FileEvent>> todoPeerToFile; private List<DoingQueueItem> doing; private BandwidthEstimator estimator; private int usedBandwidth; /// <summary> /// Initializes a new instance of the <see cref="Distribox.Network.RequestManager"/> class. /// </summary> public RequestManager() { this.todoFileToPeer = new Dictionary<FileEvent, List<Peer>>(); this.todoPeerToFile = new Dictionary<Peer,List<FileEvent>>(); this.doing = new List<DoingQueueItem>(); this.estimator = new BandwidthEstimator(); this.usedBandwidth = 0; } /// <summary> /// Adds the requests. /// </summary> /// <param name='requests'> /// Requests to add. /// </param> /// <param name='peerHaveThese'> /// Peer who have these patches. /// </param> public void AddRequests(List<FileEvent> requests, Peer peerHaveThese) { lock (this) { if (!todoPeerToFile.ContainsKey(peerHaveThese)) todoPeerToFile[peerHaveThese] = new List<FileEvent>(); todoPeerToFile[peerHaveThese].AddRange(requests); foreach (FileEvent patch in requests) { if (!todoFileToPeer.ContainsKey(patch)) todoFileToPeer[patch] = new List<Peer>(); todoFileToPeer[patch].Add(peerHaveThese); } } } /// <summary> /// Gets some requests to be send to a peer. The requests will not exceed <see cref="Distribox.CommonLib.Properties.MaxRequestSize"/> /// </summary> /// <returns> /// The requests. /// </returns> public Tuple<List<FileEvent>, Peer> GetRequests() { CheckForRequestExpire(); lock (this) { // No requests if (this.todoFileToPeer.Count() == 0) { return null; } Peer bestPeer = new Peer(); List<FileEvent> bestCollection = new List<FileEvent>(); double bestScore = 0; long bestSize = 0; // For each peer foreach (KeyValuePair<Peer, List<FileEvent>> ppf in this.todoPeerToFile) { Peer peer = ppf.Key; var slist = ppf.Value.OrderBy(x => x.When.Ticks).ToList(); // Find file collections double score = Properties.RMBandwidthWeight * this.estimator.GetPeerBandwidth(peer); long currentSize = 0; List<FileEvent> currentCollection = new List<FileEvent>(); foreach (FileEvent f in slist) { if (currentSize + f.Size <= Properties.MaxRequestSize) { currentSize += f.Size; currentCollection.Add(f); double uniqueness = 1.0 / this.todoFileToPeer[f].Count(); score += Properties.RMUniquenessWeight * uniqueness; } else { break; } } score += Properties.RMSizeWeight * currentSize; // Update best solution if (score > bestScore) { bestScore = score; bestPeer = peer; bestCollection = currentCollection; bestSize = currentSize; } } // Do we have enough bandwidth ? int needBandwidth = this.estimator.GetPeerBandwidth(bestPeer); if (needBandwidth == 0) { needBandwidth = Properties.DefaultConnectionSpeed; } if (usedBandwidth + needBandwidth > Properties.DefaultBandwidth) { return null; } // Do this! Console.WriteLine("Request"); usedBandwidth += needBandwidth; DoingQueueItem dqItem = new DoingQueueItem(); dqItem.bandWidth = needBandwidth; dqItem.expireDate = DateTime.Now.AddSeconds(bestSize * Properties.ExpireSlackCoefficient / needBandwidth + Properties.DefaultDelay); dqItem.files = new List<DoingQueueFileItem>(); foreach (FileEvent file in bestCollection) { DoingQueueFileItem fileItem = new DoingQueueFileItem(); fileItem.file = file; fileItem.whoHaveMe = this.todoFileToPeer[file]; // Remove File->Peer this.todoFileToPeer.Remove(file); // Remove Peer->File foreach (Peer peer in fileItem.whoHaveMe) { this.todoPeerToFile[peer].Remove(file); } dqItem.files.Add(fileItem); } // Add it dqItem.filesHash = CommonHelper.GetHashCode(bestCollection); this.doing.Add(dqItem); this.estimator.BeginRequest(bestPeer, dqItem.filesHash, (int)bestSize); // return success return new Tuple<List<FileEvent>,Peer>(bestCollection, bestPeer); } } /// <summary> /// Remove item from doing queue, if not success, insert them back to the /// todo queue. /// </summary> /// <param name="item"></param> /// <param name="success"></param> public void FinishRequests(DoingQueueItem item, bool success) { Console.WriteLine("Finish {0}", success); this.usedBandwidth -= item.bandWidth; this.doing.Remove(item); if (!success) { // Add them back to todo (merge) foreach (DoingQueueFileItem fileItem in item.files) { if (!this.todoFileToPeer.ContainsKey(fileItem.file)) { this.todoFileToPeer[fileItem.file] = new List<Peer>(); } foreach (Peer peer in fileItem.whoHaveMe) { // Maintain Peer->File if (this.todoPeerToFile[peer].IndexOf(fileItem.file) == -1) this.todoPeerToFile[peer].Add(fileItem.file); // Maintain File->Peer if (this.todoFileToPeer[fileItem.file].IndexOf(peer) == -1) this.todoFileToPeer[fileItem.file].Add(peer); } } } } public void FinishRequests(List<FileEvent> requests) { int hash = CommonHelper.GetHashCode(requests); this.estimator.FinishRequest(hash); lock (this) { foreach (DoingQueueItem item in this.doing) { if (item.filesHash == hash) { this.estimator.FinishRequest(item.filesHash); FinishRequests(item, true); break; } } Logger.Warn("Finishing not existing requests."); } } /// <summary> /// Fails the requests. /// </summary> /// <param name='requests'> /// Requests to be moved back to TODO queue. /// </param> /// <exception cref='NotImplementedException'> /// Is thrown when a requested operation is not implemented for a given type. /// </exception> public void FailRequests(List<FileEvent> requests) { throw new NotImplementedException(); } /// <summary> /// Every time before GetRequests, this method will be invoked to move expired requests from Doing queue back to TODO queue. /// </summary> private void CheckForRequestExpire() { lock (this) { DateTime now = DateTime.Now; List<DoingQueueItem> expired = new List<DoingQueueItem>(); foreach (DoingQueueItem item in this.doing) { if (now > item.expireDate) { expired.Add(item); } } foreach (DoingQueueItem item in expired) { this.estimator.FailRequest(item.filesHash); FinishRequests(item, false); } } } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.Spatial { using System.Spatial; /// <summary> /// Base class to create a unified set of handlers for Geometry and Geography /// </summary> internal abstract class DrawBoth { /// <summary> /// Gets the draw geography. /// </summary> public virtual GeographyPipeline GeographyPipeline { get { return new DrawGeographyInput(this); } } /// <summary> /// Gets the draw geometry. /// </summary> public virtual GeometryPipeline GeometryPipeline { get { return new DrawGeometryInput(this); } } /// <summary> /// Performs an implicit conversion from <see cref="DrawBoth"/> to <see cref="SpatialPipeline"/>. /// </summary> /// <param name="both">The instance to convert.</param> /// <returns> /// The result of the conversion. /// </returns> public static implicit operator SpatialPipeline(DrawBoth both) { if (both != null) { return new SpatialPipeline(both.GeographyPipeline, both.GeometryPipeline); } return null; } /// <summary> /// Draw a point in the specified coordinate /// </summary> /// <param name="position">Next position</param> /// <returns>The position to be passed down the pipeline</returns> protected virtual GeographyPosition OnLineTo(GeographyPosition position) { return position; } /// <summary> /// Draw a point in the specified coordinate /// </summary> /// <param name="position">Next position</param> /// <returns>The position to be passed down the pipeline</returns> protected virtual GeometryPosition OnLineTo(GeometryPosition position) { return position; } /// <summary> /// Begin drawing a figure /// </summary> /// <param name="position">Next position</param> /// <returns>The position to be passed down the pipeline</returns> protected virtual GeographyPosition OnBeginFigure(GeographyPosition position) { return position; } /// <summary> /// Begin drawing a figure /// </summary> /// <param name="position">Next position</param> /// <returns>The position to be passed down the pipeline</returns> protected virtual GeometryPosition OnBeginFigure(GeometryPosition position) { return position; } /// <summary> /// Begin drawing a spatial object /// </summary> /// <param name="type">The spatial type of the object</param> /// <returns>The type to be passed down the pipeline</returns> protected virtual SpatialType OnBeginGeography(SpatialType type) { return type; } /// <summary> /// Begin drawing a spatial object /// </summary> /// <param name="type">The spatial type of the object</param> /// <returns>The type to be passed down the pipeline</returns> protected virtual SpatialType OnBeginGeometry(SpatialType type) { return type; } /// <summary> /// Ends the current figure /// </summary> protected virtual void OnEndFigure() { } /// <summary> /// Ends the current spatial object /// </summary> protected virtual void OnEndGeography() { } /// <summary> /// Ends the current spatial object /// </summary> protected virtual void OnEndGeometry() { } /// <summary> /// Setup the pipeline for reuse /// </summary> protected virtual void OnReset() { } /// <summary> /// Set the coordinate system /// </summary> /// <param name="coordinateSystem">The CoordinateSystem</param> /// <returns>the coordinate system to be passed down the pipeline</returns> protected virtual CoordinateSystem OnSetCoordinateSystem(CoordinateSystem coordinateSystem) { return coordinateSystem; } /// <summary> /// This class is responsible for taking the calls to DrawGeography and delegating them to the unified /// handlers /// </summary> private class DrawGeographyInput : GeographyPipeline { /// <summary> /// the DrawBoth instance that should be delegated to /// </summary> private readonly DrawBoth both; /// <summary> /// Initializes a new instance of the <see cref="DrawGeographyInput"/> class. /// </summary> /// <param name="both">The both.</param> public DrawGeographyInput(DrawBoth both) { this.both = both; } /// <summary> /// Draw a point in the specified coordinate /// </summary> /// <param name="position">Next position</param> public override void LineTo(GeographyPosition position) { both.OnLineTo(position); } /// <summary> /// Begin drawing a figure /// </summary> /// <param name="position">Next position</param> public override void BeginFigure(GeographyPosition position) { both.OnBeginFigure(position); } /// <summary> /// Begin drawing a spatial object /// </summary> /// <param name="type">The spatial type of the object</param> public override void BeginGeography(SpatialType type) { both.OnBeginGeography(type); } /// <summary> /// Ends the current figure /// </summary> public override void EndFigure() { both.OnEndFigure(); } /// <summary> /// Ends the current spatial object /// </summary> public override void EndGeography() { both.OnEndGeography(); } /// <summary> /// Setup the pipeline for reuse /// </summary> public override void Reset() { both.OnReset(); } /// <summary> /// Set the coordinate system /// </summary> /// <param name="coordinateSystem">The CoordinateSystem</param> public override void SetCoordinateSystem(CoordinateSystem coordinateSystem) { both.OnSetCoordinateSystem(coordinateSystem); } } /// <summary> /// This class is responsible for taking the calls to DrawGeometry and delegating them to the unified /// handlers /// </summary> private class DrawGeometryInput : GeometryPipeline { /// <summary> /// the DrawBoth instance that should be delegated to /// </summary> private readonly DrawBoth both; /// <summary> /// Initializes a new instance of the <see cref="DrawGeometryInput"/> class. /// </summary> /// <param name="both">The both.</param> public DrawGeometryInput(DrawBoth both) { this.both = both; } /// <summary> /// Draw a point in the specified coordinate /// </summary> /// <param name="position">Next position</param> public override void LineTo(GeometryPosition position) { both.OnLineTo(position); } /// <summary> /// Begin drawing a figure /// </summary> /// <param name="position">Next position</param> public override void BeginFigure(GeometryPosition position) { both.OnBeginFigure(position); } /// <summary> /// Begin drawing a spatial object /// </summary> /// <param name="type">The spatial type of the object</param> public override void BeginGeometry(SpatialType type) { both.OnBeginGeometry(type); } /// <summary> /// Ends the current figure /// </summary> public override void EndFigure() { both.OnEndFigure(); } /// <summary> /// Ends the current spatial object /// </summary> public override void EndGeometry() { both.OnEndGeometry(); } /// <summary> /// Setup the pipeline for reuse /// </summary> public override void Reset() { both.OnReset(); } /// <summary> /// Set the coordinate system /// </summary> /// <param name="coordinateSystem">The CoordinateSystem</param> public override void SetCoordinateSystem(CoordinateSystem coordinateSystem) { both.OnSetCoordinateSystem(coordinateSystem); } } } }
using System; using System.Collections; using System.Text; using Lucene.Net.Documents; using Lucene.Net.Support; namespace Lucene.Net.Search { using Lucene.Net.Randomized.Generators; using NUnit.Framework; /* * 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 Analyzer = Lucene.Net.Analysis.Analyzer; using BasicAutomata = Lucene.Net.Util.Automaton.BasicAutomata; using CharacterRunAutomaton = Lucene.Net.Util.Automaton.CharacterRunAutomaton; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockTokenizer = Lucene.Net.Analysis.MockTokenizer; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using StringField = StringField; using Term = Lucene.Net.Index.Term; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; /// <summary> /// Simple base class for checking search equivalence. /// Extend it, and write tests that create <seealso cref="#randomTerm()"/>s /// (all terms are single characters a-z), and use /// <seealso cref="#assertSameSet(Query, Query)"/> and /// <seealso cref="#assertSubsetOf(Query, Query)"/> /// </summary> public abstract class SearchEquivalenceTestBase : LuceneTestCase { protected internal static IndexSearcher S1, S2; protected internal static Directory Directory; protected internal static IndexReader Reader; protected internal static Analyzer Analyzer; protected internal static string Stopword; // we always pick a character as a stopword [SetUp] public void BeforeClass() { Random random = Random(); Directory = NewDirectory(); Stopword = "" + RandomChar(); CharacterRunAutomaton stopset = new CharacterRunAutomaton(BasicAutomata.MakeString(Stopword)); Analyzer = new MockAnalyzer(random, MockTokenizer.WHITESPACE, false, stopset); RandomIndexWriter iw = new RandomIndexWriter(random, Directory, Analyzer); Document doc = new Document(); Field id = new StringField("id", "", Field.Store.NO); Field field = new TextField("field", "", Field.Store.NO); doc.Add(id); doc.Add(field); // index some docs int numDocs = AtLeast(1000); for (int i = 0; i < numDocs; i++) { id.StringValue = Convert.ToString(i); field.StringValue = RandomFieldContents(); iw.AddDocument(doc); } // delete some docs int numDeletes = numDocs / 20; for (int i = 0; i < numDeletes; i++) { Term toDelete = new Term("id", Convert.ToString(random.Next(numDocs))); if (random.NextBoolean()) { iw.DeleteDocuments(toDelete); } else { iw.DeleteDocuments(new TermQuery(toDelete)); } } Reader = iw.Reader; S1 = NewSearcher(Reader); S2 = NewSearcher(Reader); iw.Dispose(); } [TearDown] public void AfterClass() { Reader.Dispose(); Directory.Dispose(); Analyzer.Dispose(); Reader = null; Directory = null; Analyzer = null; S1 = S2 = null; } /// <summary> /// populate a field with random contents. /// terms should be single characters in lowercase (a-z) /// tokenization can be assumed to be on whitespace. /// </summary> internal static string RandomFieldContents() { // TODO: zipf-like distribution StringBuilder sb = new StringBuilder(); int numTerms = Random().Next(15); for (int i = 0; i < numTerms; i++) { if (sb.Length > 0) { sb.Append(' '); // whitespace } sb.Append(RandomChar()); } return sb.ToString(); } /// <summary> /// returns random character (a-z) /// </summary> internal static char RandomChar() { return (char)TestUtil.NextInt(Random(), 'a', 'z'); } /// <summary> /// returns a term suitable for searching. /// terms are single characters in lowercase (a-z) /// </summary> protected internal virtual Term RandomTerm() { return new Term("field", "" + RandomChar()); } /// <summary> /// Returns a random filter over the document set /// </summary> protected internal virtual Filter RandomFilter() { return new QueryWrapperFilter(TermRangeQuery.NewStringRange("field", "a", "" + RandomChar(), true, true)); } /// <summary> /// Asserts that the documents returned by <code>q1</code> /// are the same as of those returned by <code>q2</code> /// </summary> public virtual void AssertSameSet(Query q1, Query q2) { AssertSubsetOf(q1, q2); AssertSubsetOf(q2, q1); } /// <summary> /// Asserts that the documents returned by <code>q1</code> /// are a subset of those returned by <code>q2</code> /// </summary> public virtual void AssertSubsetOf(Query q1, Query q2) { // test without a filter AssertSubsetOf(q1, q2, null); // test with a filter (this will sometimes cause advance'ing enough to test it) AssertSubsetOf(q1, q2, RandomFilter()); } /// <summary> /// Asserts that the documents returned by <code>q1</code> /// are a subset of those returned by <code>q2</code>. /// /// Both queries will be filtered by <code>filter</code> /// </summary> protected internal virtual void AssertSubsetOf(Query q1, Query q2, Filter filter) { // TRUNK ONLY: test both filter code paths if (filter != null && Random().NextBoolean()) { q1 = new FilteredQuery(q1, filter, TestUtil.RandomFilterStrategy(Random())); q2 = new FilteredQuery(q2, filter, TestUtil.RandomFilterStrategy(Random())); filter = null; } // not efficient, but simple! TopDocs td1 = S1.Search(q1, filter, Reader.MaxDoc); TopDocs td2 = S2.Search(q2, filter, Reader.MaxDoc); Assert.IsTrue(td1.TotalHits <= td2.TotalHits); // fill the superset into a bitset var bitset = new BitArray(td2.ScoreDocs.Length); for (int i = 0; i < td2.ScoreDocs.Length; i++) { bitset.SafeSet(td2.ScoreDocs[i].Doc, true); } // check in the subset, that every bit was set by the super for (int i = 0; i < td1.ScoreDocs.Length; i++) { Assert.IsTrue(bitset.SafeGet(td1.ScoreDocs[i].Doc)); } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the lambda-2015-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Lambda.Model { /// <summary> /// A complex type that describes function metadata. /// </summary> public partial class FunctionConfiguration { private long? _codeSize; private string _description; private string _functionArn; private string _functionName; private string _handler; private string _lastModified; private int? _memorySize; private string _role; private Runtime _runtime; private int? _timeout; /// <summary> /// Gets and sets the property CodeSize. /// <para> /// The size, in bytes, of the function .zip file you uploaded. /// </para> /// </summary> public long CodeSize { get { return this._codeSize.GetValueOrDefault(); } set { this._codeSize = value; } } // Check to see if CodeSize property is set internal bool IsSetCodeSize() { return this._codeSize.HasValue; } /// <summary> /// Gets and sets the property Description. /// <para> /// The user-provided description. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property FunctionArn. /// <para> /// The Amazon Resource Name (ARN) assigned to the function. /// </para> /// </summary> public string FunctionArn { get { return this._functionArn; } set { this._functionArn = value; } } // Check to see if FunctionArn property is set internal bool IsSetFunctionArn() { return this._functionArn != null; } /// <summary> /// Gets and sets the property FunctionName. /// <para> /// The name of the function. /// </para> /// </summary> public string FunctionName { get { return this._functionName; } set { this._functionName = value; } } // Check to see if FunctionName property is set internal bool IsSetFunctionName() { return this._functionName != null; } /// <summary> /// Gets and sets the property Handler. /// <para> /// The function Lambda calls to begin executing your function. /// </para> /// </summary> public string Handler { get { return this._handler; } set { this._handler = value; } } // Check to see if Handler property is set internal bool IsSetHandler() { return this._handler != null; } /// <summary> /// Gets and sets the property LastModified. /// <para> /// The timestamp of the last time you updated the function. /// </para> /// </summary> public string LastModified { get { return this._lastModified; } set { this._lastModified = value; } } // Check to see if LastModified property is set internal bool IsSetLastModified() { return this._lastModified != null; } /// <summary> /// Gets and sets the property MemorySize. /// <para> /// The memory size, in MB, you configured for the function. Must be a multiple of 64 /// MB. /// </para> /// </summary> public int MemorySize { get { return this._memorySize.GetValueOrDefault(); } set { this._memorySize = value; } } // Check to see if MemorySize property is set internal bool IsSetMemorySize() { return this._memorySize.HasValue; } /// <summary> /// Gets and sets the property Role. /// <para> /// The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it executes /// your function to access any other Amazon Web Services (AWS) resources. /// </para> /// </summary> public string Role { get { return this._role; } set { this._role = value; } } // Check to see if Role property is set internal bool IsSetRole() { return this._role != null; } /// <summary> /// Gets and sets the property Runtime. /// <para> /// The runtime environment for the Lambda function. /// </para> /// </summary> public Runtime Runtime { get { return this._runtime; } set { this._runtime = value; } } // Check to see if Runtime property is set internal bool IsSetRuntime() { return this._runtime != null; } /// <summary> /// Gets and sets the property Timeout. /// <para> /// The function execution time at which Lambda should terminate the function. Because /// the execution time has cost implications, we recommend you set this value based on /// your expected execution time. The default is 3 seconds. /// </para> /// </summary> public int Timeout { get { return this._timeout.GetValueOrDefault(); } set { this._timeout = value; } } // Check to see if Timeout property is set internal bool IsSetTimeout() { return this._timeout.HasValue; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCustomerUserAccessServiceClientTest { [Category("Autogenerated")][Test] public void GetCustomerUserAccessRequestObject() { moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient>(moq::MockBehavior.Strict); GetCustomerUserAccessRequest request = new GetCustomerUserAccessRequest { ResourceNameAsCustomerUserAccessName = gagvr::CustomerUserAccessName.FromCustomerUser("[CUSTOMER_ID]", "[USER_ID]"), }; gagvr::CustomerUserAccess expectedResponse = new gagvr::CustomerUserAccess { ResourceNameAsCustomerUserAccessName = gagvr::CustomerUserAccessName.FromCustomerUser("[CUSTOMER_ID]", "[USER_ID]"), UserId = -7972883667886640920L, EmailAddress = "email_addressf3aae0b5", AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified, AccessCreationDateTime = "access_creation_date_time7709b5b1", InviterUserEmailAddress = "inviter_user_email_address38e90785", }; mockGrpcClient.Setup(x => x.GetCustomerUserAccess(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerUserAccessServiceClient client = new CustomerUserAccessServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerUserAccess response = client.GetCustomerUserAccess(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerUserAccessRequestObjectAsync() { moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient>(moq::MockBehavior.Strict); GetCustomerUserAccessRequest request = new GetCustomerUserAccessRequest { ResourceNameAsCustomerUserAccessName = gagvr::CustomerUserAccessName.FromCustomerUser("[CUSTOMER_ID]", "[USER_ID]"), }; gagvr::CustomerUserAccess expectedResponse = new gagvr::CustomerUserAccess { ResourceNameAsCustomerUserAccessName = gagvr::CustomerUserAccessName.FromCustomerUser("[CUSTOMER_ID]", "[USER_ID]"), UserId = -7972883667886640920L, EmailAddress = "email_addressf3aae0b5", AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified, AccessCreationDateTime = "access_creation_date_time7709b5b1", InviterUserEmailAddress = "inviter_user_email_address38e90785", }; mockGrpcClient.Setup(x => x.GetCustomerUserAccessAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerUserAccess>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerUserAccessServiceClient client = new CustomerUserAccessServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerUserAccess responseCallSettings = await client.GetCustomerUserAccessAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerUserAccess responseCancellationToken = await client.GetCustomerUserAccessAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomerUserAccess() { moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient>(moq::MockBehavior.Strict); GetCustomerUserAccessRequest request = new GetCustomerUserAccessRequest { ResourceNameAsCustomerUserAccessName = gagvr::CustomerUserAccessName.FromCustomerUser("[CUSTOMER_ID]", "[USER_ID]"), }; gagvr::CustomerUserAccess expectedResponse = new gagvr::CustomerUserAccess { ResourceNameAsCustomerUserAccessName = gagvr::CustomerUserAccessName.FromCustomerUser("[CUSTOMER_ID]", "[USER_ID]"), UserId = -7972883667886640920L, EmailAddress = "email_addressf3aae0b5", AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified, AccessCreationDateTime = "access_creation_date_time7709b5b1", InviterUserEmailAddress = "inviter_user_email_address38e90785", }; mockGrpcClient.Setup(x => x.GetCustomerUserAccess(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerUserAccessServiceClient client = new CustomerUserAccessServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerUserAccess response = client.GetCustomerUserAccess(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerUserAccessAsync() { moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient>(moq::MockBehavior.Strict); GetCustomerUserAccessRequest request = new GetCustomerUserAccessRequest { ResourceNameAsCustomerUserAccessName = gagvr::CustomerUserAccessName.FromCustomerUser("[CUSTOMER_ID]", "[USER_ID]"), }; gagvr::CustomerUserAccess expectedResponse = new gagvr::CustomerUserAccess { ResourceNameAsCustomerUserAccessName = gagvr::CustomerUserAccessName.FromCustomerUser("[CUSTOMER_ID]", "[USER_ID]"), UserId = -7972883667886640920L, EmailAddress = "email_addressf3aae0b5", AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified, AccessCreationDateTime = "access_creation_date_time7709b5b1", InviterUserEmailAddress = "inviter_user_email_address38e90785", }; mockGrpcClient.Setup(x => x.GetCustomerUserAccessAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerUserAccess>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerUserAccessServiceClient client = new CustomerUserAccessServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerUserAccess responseCallSettings = await client.GetCustomerUserAccessAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerUserAccess responseCancellationToken = await client.GetCustomerUserAccessAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomerUserAccessResourceNames() { moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient>(moq::MockBehavior.Strict); GetCustomerUserAccessRequest request = new GetCustomerUserAccessRequest { ResourceNameAsCustomerUserAccessName = gagvr::CustomerUserAccessName.FromCustomerUser("[CUSTOMER_ID]", "[USER_ID]"), }; gagvr::CustomerUserAccess expectedResponse = new gagvr::CustomerUserAccess { ResourceNameAsCustomerUserAccessName = gagvr::CustomerUserAccessName.FromCustomerUser("[CUSTOMER_ID]", "[USER_ID]"), UserId = -7972883667886640920L, EmailAddress = "email_addressf3aae0b5", AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified, AccessCreationDateTime = "access_creation_date_time7709b5b1", InviterUserEmailAddress = "inviter_user_email_address38e90785", }; mockGrpcClient.Setup(x => x.GetCustomerUserAccess(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerUserAccessServiceClient client = new CustomerUserAccessServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerUserAccess response = client.GetCustomerUserAccess(request.ResourceNameAsCustomerUserAccessName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerUserAccessResourceNamesAsync() { moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient>(moq::MockBehavior.Strict); GetCustomerUserAccessRequest request = new GetCustomerUserAccessRequest { ResourceNameAsCustomerUserAccessName = gagvr::CustomerUserAccessName.FromCustomerUser("[CUSTOMER_ID]", "[USER_ID]"), }; gagvr::CustomerUserAccess expectedResponse = new gagvr::CustomerUserAccess { ResourceNameAsCustomerUserAccessName = gagvr::CustomerUserAccessName.FromCustomerUser("[CUSTOMER_ID]", "[USER_ID]"), UserId = -7972883667886640920L, EmailAddress = "email_addressf3aae0b5", AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified, AccessCreationDateTime = "access_creation_date_time7709b5b1", InviterUserEmailAddress = "inviter_user_email_address38e90785", }; mockGrpcClient.Setup(x => x.GetCustomerUserAccessAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerUserAccess>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerUserAccessServiceClient client = new CustomerUserAccessServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerUserAccess responseCallSettings = await client.GetCustomerUserAccessAsync(request.ResourceNameAsCustomerUserAccessName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerUserAccess responseCancellationToken = await client.GetCustomerUserAccessAsync(request.ResourceNameAsCustomerUserAccessName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomerUserAccessRequestObject() { moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient>(moq::MockBehavior.Strict); MutateCustomerUserAccessRequest request = new MutateCustomerUserAccessRequest { CustomerId = "customer_id3b3724cb", Operation = new CustomerUserAccessOperation(), }; MutateCustomerUserAccessResponse expectedResponse = new MutateCustomerUserAccessResponse { Result = new MutateCustomerUserAccessResult(), }; mockGrpcClient.Setup(x => x.MutateCustomerUserAccess(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerUserAccessServiceClient client = new CustomerUserAccessServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerUserAccessResponse response = client.MutateCustomerUserAccess(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomerUserAccessRequestObjectAsync() { moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient>(moq::MockBehavior.Strict); MutateCustomerUserAccessRequest request = new MutateCustomerUserAccessRequest { CustomerId = "customer_id3b3724cb", Operation = new CustomerUserAccessOperation(), }; MutateCustomerUserAccessResponse expectedResponse = new MutateCustomerUserAccessResponse { Result = new MutateCustomerUserAccessResult(), }; mockGrpcClient.Setup(x => x.MutateCustomerUserAccessAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerUserAccessResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerUserAccessServiceClient client = new CustomerUserAccessServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerUserAccessResponse responseCallSettings = await client.MutateCustomerUserAccessAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomerUserAccessResponse responseCancellationToken = await client.MutateCustomerUserAccessAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomerUserAccess() { moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient>(moq::MockBehavior.Strict); MutateCustomerUserAccessRequest request = new MutateCustomerUserAccessRequest { CustomerId = "customer_id3b3724cb", Operation = new CustomerUserAccessOperation(), }; MutateCustomerUserAccessResponse expectedResponse = new MutateCustomerUserAccessResponse { Result = new MutateCustomerUserAccessResult(), }; mockGrpcClient.Setup(x => x.MutateCustomerUserAccess(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerUserAccessServiceClient client = new CustomerUserAccessServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerUserAccessResponse response = client.MutateCustomerUserAccess(request.CustomerId, request.Operation); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomerUserAccessAsync() { moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessService.CustomerUserAccessServiceClient>(moq::MockBehavior.Strict); MutateCustomerUserAccessRequest request = new MutateCustomerUserAccessRequest { CustomerId = "customer_id3b3724cb", Operation = new CustomerUserAccessOperation(), }; MutateCustomerUserAccessResponse expectedResponse = new MutateCustomerUserAccessResponse { Result = new MutateCustomerUserAccessResult(), }; mockGrpcClient.Setup(x => x.MutateCustomerUserAccessAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerUserAccessResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerUserAccessServiceClient client = new CustomerUserAccessServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerUserAccessResponse responseCallSettings = await client.MutateCustomerUserAccessAsync(request.CustomerId, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomerUserAccessResponse responseCancellationToken = await client.MutateCustomerUserAccessAsync(request.CustomerId, request.Operation, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// 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.Globalization { using System; using System.Runtime.Serialization; using System.Threading; using System.Diagnostics.Contracts; // Gregorian Calendars use Era Info // Note: We shouldn't have to serialize this since the info doesn't change, but we have been. // (We really only need the calendar #, and maybe culture) [Serializable] internal class EraInfo { internal int era; // The value of the era. internal long ticks; // The time in ticks when the era starts internal int yearOffset; // The offset to Gregorian year when the era starts. // Gregorian Year = Era Year + yearOffset // Era Year = Gregorian Year - yearOffset internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may // be affected by the DateTime.MinValue; internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1) [OptionalField(VersionAdded = 4)] internal String eraName; // The era name [OptionalField(VersionAdded = 4)] internal String abbrevEraName; // Abbreviated Era Name [OptionalField(VersionAdded = 4)] internal String englishEraName; // English era name internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; } internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear, String eraName, String abbrevEraName, String englishEraName) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; this.eraName = eraName; this.abbrevEraName = abbrevEraName; this.englishEraName = englishEraName; } } // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) [Serializable] internal class GregorianCalendarHelper { // 1 tick = 100ns = 10E-7 second // Number of ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal int MaxYear { get { return (m_maxYear); } } internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; // Strictly these don't need serialized since they can be recreated from the calendar id [OptionalField(VersionAdded = 1)] internal int m_maxYear = 9999; [OptionalField(VersionAdded = 1)] internal int m_minYear; internal Calendar m_Cal; // Era information doesn't need serialized, its constant for the same calendars (ie: we can recreate it from the calendar id) [OptionalField(VersionAdded = 1)] internal EraInfo[] m_EraInfo; [OptionalField(VersionAdded = 1)] internal int[] m_eras = null; // m_minDate is existing here just to keep the serialization compatibility. // it has nothing to do with the code anymore. [OptionalField(VersionAdded = 1)] internal DateTime m_minDate; // Construct an instance of gregorian calendar. internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo) { m_Cal = cal; m_EraInfo = eraInfo; // m_minDate is existing here just to keep the serialization compatibility. // it has nothing to do with the code anymore. m_minDate = m_Cal.MinSupportedDateTime; m_maxYear = m_EraInfo[0].maxEraYear; m_minYear = m_EraInfo[0].minEraYear;; } /*=================================GetGregorianYear========================== **Action: Get the Gregorian year value for the specified year in an era. **Returns: The Gregorian year value. **Arguments: ** year the year value in Japanese calendar ** era the Japanese emperor era value. **Exceptions: ** ArgumentOutOfRangeException if year value is invalid or era value is invalid. ============================================================================*/ internal int GetGregorianYear(int year, int era) { if (year < 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), m_EraInfo[i].minEraYear, m_EraInfo[i].maxEraYear)); } return (m_EraInfo[i].yearOffset + year); } } throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } internal bool IsValidYear(int year, int era) { if (year < 0) { return false; } if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { return false; } return true; } } return false; } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { CheckTicksRange(ticks); // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if (y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3)); int[] days = leapYear? DaysToMonth366: DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = (n >> 5) + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366: DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay")); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal static long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day)* TicksPerDay); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { //TimeSpan.TimeToTicks is a family access function which does no error checking, so //we need to put some error checking out here. if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( "millisecond", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1)); } return (TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond);; } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond")); } internal void CheckTicksRange(long ticks) { if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException( "time", String.Format( CultureInfo.InvariantCulture, Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"), m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime)); } Contract.EndContractBlock(); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( "months", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), -120000, 120000)); } Contract.EndContractBlock(); CheckTicksRange(time.Ticks); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366: DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + (time.Ticks % TicksPerDay); Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return ((DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // [Pure] public int GetDaysInMonth(int year, int month, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365); return (days[month] - days[month - 1]); } // Returns the number of days in the year given by the year argument for the current era. // public int GetDaysInYear(int year, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366:365); } // Returns the era for the specified DateTime value. public int GetEra(DateTime time) { long ticks = time.Ticks; // The assumption here is that m_EraInfo is listed in reverse order. for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (m_EraInfo[i].era); } } throw new ArgumentOutOfRangeException("time", Environment.GetResourceString("ArgumentOutOfRange_Era")); } public int[] Eras { get { if (m_eras == null) { m_eras = new int[m_EraInfo.Length]; for (int i = 0; i < m_EraInfo.Length; i++) { m_eras[i] = m_EraInfo[i].era; } } return ((int[])m_eras.Clone()); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public int GetMonthsInYear(int year, int era) { year = GetGregorianYear(year, era); return (12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public int GetYear(DateTime time) { long ticks = time.Ticks; int year = GetDatePart(ticks, DatePartYear); for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(Environment.GetResourceString("Argument_NoEra")); } // Returns the year that match the specified Gregorian year. The returned value is an // integer between 1 and 9999. // public int GetYear(int year, DateTime time) { long ticks = time.Ticks; for (int i = 0; i < m_EraInfo.Length; i++) { // while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era // and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause // using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset // which will end up with zero as calendar year. // We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989 if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(Environment.GetResourceString("Argument_NoEra")); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public bool IsLeapDay(int year, int month, int day, int era) { // year/month/era checking is done in GetDaysInMonth() if (day < 1 || day > GetDaysInMonth(year, month, era)) { throw new ArgumentOutOfRangeException( "day", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, GetDaysInMonth(year, month, era))); } Contract.EndContractBlock(); if (!IsLeapYear(year, era)) { return (false); } if (month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public int GetLeapMonth(int year, int era) { year = GetGregorianYear(year, era); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public bool IsLeapMonth(int year, int month, int era) { year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException( "month", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, 12)); } return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public bool IsLeapYear(int year, int era) { year = GetGregorianYear(year, era); return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = GetGregorianYear(year, era); long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond); CheckTicksRange(ticks); return (new DateTime(ticks)); } public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { CheckTicksRange(time.Ticks); // Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear() // can call GetYear() that exceeds the supported range of the Gregorian-based calendars. return (GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek)); } public int ToFourDigitYear(int year, int twoDigitYearMax) { if (year < 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); if (year < 100) { int y = year % 100; return ((twoDigitYearMax/100 - ( y > twoDigitYearMax % 100 ? 1 : 0))*100 + y); } if (year < m_minYear || year > m_maxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), m_minYear, m_maxYear)); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } } }
// 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.IO; using System.Xml; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class XNodeReaderFunctionalTests : TestModule { public partial class XNodeReaderTests : XLinqTestCase { public partial class TCAttributeAccess : BridgeHelpers { //[Variation("Attribute Access test using ordinal (Ascending Order)", Priority = 0)] public void TestAttributeAccess1() { XmlReader DataReader = GetReader(); string[] astr = new string[10]; string n; string qname; PositionOnElement(DataReader, "ACT0"); int start = 1; int end = DataReader.AttributeCount; for (int i = start; i < end; i++) { astr[i - 1] = DataReader[i]; n = strAttr + (i - 1); qname = "foo:" + n; TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); TestLog.Compare(DataReader[n, strNamespace], DataReader.GetAttribute(n, strNamespace), "Compare this(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[i], DataReader[n, strNamespace], "Compare this(i) with this(name,strNamespace)"); TestLog.Compare(DataReader.MoveToAttribute(n, strNamespace), true, "MoveToAttribute(name,strNamespace)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n, strNamespace), "Compare MoveToAttribute(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[i], DataReader[qname], "Compare this(i) with this(qname)"); TestLog.Compare(DataReader.MoveToAttribute(qname), true, "MoveToAttribute(qname)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(qname), "Compare MoveToAttribute(qname) with GetAttribute(qname)"); } PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { TestLog.Compare(astr[i], DataReader.GetAttribute(i), "Compare value with GetAttribute"); TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); n = strAttr + i; TestLog.Compare(DataReader[n], DataReader.GetAttribute(n), "Compare this(name) with GetAttribute(name)"); TestLog.Compare(DataReader[i], DataReader[n], "Compare this(i) with this(name)"); TestLog.Compare(DataReader.MoveToAttribute(n), true, "MoveToAttribute(name)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n), "Compare MoveToAttribute(name) with GetAttribute(name)"); } } //[Variation("Attribute Access test using ordinal (Descending Order)")] public void TestAttributeAccess2() { XmlReader DataReader = GetReader(); string[] astr = new string[10]; string n; string qname; PositionOnElement(DataReader, "ACT0"); int start = 1; int end = DataReader.AttributeCount; for (int i = end - 1; i >= start; i--) { astr[i - 1] = DataReader[i]; n = strAttr + (i - 1); qname = "foo:" + n; TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); TestLog.Compare(DataReader[n, strNamespace], DataReader.GetAttribute(n, strNamespace), "Compare this(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[i], DataReader[n, strNamespace], "Compare this(i) with this(name,strNamespace)"); TestLog.Compare(DataReader.MoveToAttribute(n, strNamespace), true, "MoveToAttribute(name,strNamespace)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n, strNamespace), "Compare MoveToAttribute(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Compare this(qname) with GetAttribute(qname)"); TestLog.Compare(DataReader[i], DataReader[qname], "Compare this(i) with this(qname)"); TestLog.Compare(DataReader.MoveToAttribute(qname), true, "MoveToAttribute(qname)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(qname), "Compare MoveToAttribute(qname) with GetAttribute(qname)"); } PositionOnElement(DataReader, "ACT1"); for (int i = (DataReader.AttributeCount - 1); i > 0; i--) { n = strAttr + i; TestLog.Compare(astr[i], DataReader.GetAttribute(i), "Compare value with GetAttribute"); TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); TestLog.Compare(DataReader[n], DataReader.GetAttribute(n), "Compare this(name) with GetAttribute(name)"); TestLog.Compare(DataReader[i], DataReader[n], "Compare this(i) with this(name)"); TestLog.Compare(DataReader.MoveToAttribute(n), true, "MoveToAttribute(name)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n), "Compare MoveToAttribute(name) with GetAttribute(name)"); } } //[Variation("Attribute Access test using ordinal (Odd number)", Priority = 0)] public void TestAttributeAccess3() { XmlReader DataReader = GetReader(); string[] astr = new string[10]; string n; string qname; PositionOnElement(DataReader, "ACT0"); int start = 1; int end = DataReader.AttributeCount; for (int i = start; i < end; i += 2) { astr[i - 1] = DataReader[i]; n = strAttr + (i - 1); qname = "foo:" + n; TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); TestLog.Compare(DataReader[n, strNamespace], DataReader.GetAttribute(n, strNamespace), "Compare this(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[i], DataReader[n, strNamespace], "Compare this(i) with this(name,strNamespace)"); TestLog.Compare(DataReader.MoveToAttribute(n, strNamespace), true, "MoveToAttribute(name,strNamespace)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n, strNamespace), "Compare MoveToAttribute(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Compare this(qname) with GetAttribute(qname)"); TestLog.Compare(DataReader[i], DataReader[qname], "Compare this(i) with this(qname)"); TestLog.Compare(DataReader.MoveToAttribute(qname), true, "MoveToAttribute(qname)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(qname), "Compare MoveToAttribute(qname) with GetAttribute(qname)"); } PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i += 2) { TestLog.Compare(astr[i], DataReader.GetAttribute(i), "Compare value with GetAttribute"); TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); n = strAttr + i; TestLog.Compare(DataReader[n], DataReader.GetAttribute(n), "Compare this(name) with GetAttribute(name)"); TestLog.Compare(DataReader[i], DataReader[n], "Compare this(i) with this(name)"); TestLog.Compare(DataReader.MoveToAttribute(n), true, "MoveToAttribute(name)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n), "Compare MoveToAttribute(name) with GetAttribute(name)"); } } //[Variation("Attribute Access test using ordinal (Even number)")] public void TestAttributeAccess4() { XmlReader DataReader = GetReader(); string[] astr = new string[10]; string n; string qname; PositionOnElement(DataReader, "ACT0"); int start = 1; int end = DataReader.AttributeCount; for (int i = start; i < end; i += 3) { astr[i - 1] = DataReader[i]; n = strAttr + (i - 1); qname = "foo:" + n; TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); TestLog.Compare(DataReader[n, strNamespace], DataReader.GetAttribute(n, strNamespace), "Compare this(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[i], DataReader[n, strNamespace], "Compare this(i) with this(name,strNamespace)"); TestLog.Compare(DataReader.MoveToAttribute(n, strNamespace), true, "MoveToAttribute(name,strNamespace)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n, strNamespace), "Compare MoveToAttribute(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Compare this(qname) with GetAttribute(qname)"); TestLog.Compare(DataReader[i], DataReader[qname], "Compare this(i) with this(qname)"); TestLog.Compare(DataReader.MoveToAttribute(qname), true, "MoveToAttribute(qname)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(qname), "Compare MoveToAttribute(qname) with GetAttribute(qname)"); } PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i += 3) { TestLog.Compare(astr[i], DataReader.GetAttribute(i), "Compare value with GetAttribute"); TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); n = strAttr + i; TestLog.Compare(DataReader[n], DataReader.GetAttribute(n), "Compare this(name) with GetAttribute(name)"); TestLog.Compare(DataReader[i], DataReader[n], "Compare this(i) with this(name)"); TestLog.Compare(DataReader.MoveToAttribute(n), true, "MoveToAttribute(name)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n), "Compare MoveToAttribute(name) with GetAttribute(name)"); } } //[Variation("Attribute Access with namespace=null")] public void TestAttributeAccess5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); TestLog.Compare(DataReader[strAttr + 1, null], null, "Item"); TestLog.Compare(DataReader.Name, "ACT1", "Reader changed position"); } } public partial class TCThisName : BridgeHelpers { //[Variation("This[Name] Verify with GetAttribute(Name)", Priority = 0)] public void ThisWithName1() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader[strName], DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("This[Name, null] Verify with GetAttribute(Name)")] public void ThisWithName2() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader[strName, null], null, "Ordinal (" + i + "): Should have returned null"); } } //[Variation("This[Name] Verify with GetAttribute(Name,null)")] public void ThisWithName3() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader.GetAttribute(strName, null), null, "Ordinal (" + i + "): Should have returned null"); } } //[Variation("This[Name, NamespaceURI] Verify with GetAttribute(Name, NamespaceURI)", Priority = 0)] public void ThisWithName4() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader[strName, strNamespace], DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName,strNamespace) and this[strName,strNamespace]"); } } //[Variation("This[Name, null] Verify not the same as GetAttribute(Name, NamespaceURI)")] public void ThisWithName5() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); TestLog.Compare(DataReader[strName, null], null, "Ordinal (" + i + "): Should have returned null"); } } //[Variation("This[Name, NamespaceURI] Verify not the same as GetAttribute(Name, null)")] public void ThisWithName6() { string strName; XmlReader DataReader = GetReader(); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); if (DataReader.GetAttribute(strName, null) == DataReader[strName, strNamespace]) throw new TestException(TestResult.Failed, Variation.Desc); } } //[Variation("This[Name] Verify with MoveToAttribute(Name)", Priority = 0)] public void ThisWithName7() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; DataReader.MoveToAttribute(strName); TestLog.Compare(DataReader.Value, DataReader[strName], "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("This[Name, null] Verify with MoveToAttribute(Name)")] public void ThisWithName8() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; DataReader.MoveToAttribute(strName); TestLog.Compare(DataReader[strName, null], null, "Ordinal (" + i + "): Should have returned null"); } } //[Variation("This[Name] Verify with MoveToAttribute(Name,null)")] public void ThisWithName9() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader.MoveToAttribute(strName, null), false, "Ordinal (" + i + "): Reader should not have moved"); } } //[Variation("This[Name, NamespaceURI] Verify not the same as MoveToAttribute(Name, null)", Priority = 0)] public void ThisWithName10() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); TestLog.Compare(DataReader.MoveToAttribute(strName, null), false, "Ordinal (" + i + "): Reader should not have moved"); } } //[Variation("This[Name, null] Verify not the same as MoveToAttribute(Name, NamespaceURI)")] public void ThisWithName11() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; DataReader.MoveToAttribute(strName, strNamespace); TestLog.Compare(DataReader[strName, null], null, "Ordinal (" + i + "): Should have returned null"); } } //[Variation("This[Name, namespace] Verify not the same as MoveToAttribute(Name, namespace)")] public void ThisWithName12() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); DataReader.MoveToAttribute(strName, strNamespace); TestLog.Compare(DataReader.Value, DataReader[strName, strNamespace], "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("This(String.Empty)")] public void ThisWithName13() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader[String.Empty], null, "Should have returned null"); } //[Variation("This[String.Empty,String.Empty]")] public void ThisWithName14() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader[String.Empty, String.Empty], null, "Should have returned null"); } //[Variation("This[QName] Verify with GetAttribute(Name, NamespaceURI)", Priority = 0)] public void ThisWithName15() { string strName; string qname; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + i; qname = "foo:" + strName; TestLog.Compare(DataReader[qname], DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName,strNamespace) and this[qname]"); TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Ordinal (" + i + "): Compare GetAttribute(qname) and this[qname]"); } } //[Variation("This[QName] invalid Qname")] public void ThisWithName16() { string strName; string qname; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); int i = 1; strName = strAttr + i; qname = "foo1:" + strName; TestLog.Compare(DataReader.MoveToAttribute(qname), false, "MoveToAttribute(invalid qname)"); TestLog.Compare(DataReader[qname], null, "Compare this[invalid qname] with null"); TestLog.Compare(DataReader.GetAttribute(qname), null, "Compare GetAttribute(invalid qname) with null"); } } public partial class TCMoveToAttributeReader : BridgeHelpers { //[Variation("MoveToAttribute(String.Empty)")] public void MoveToAttributeWithName1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader.MoveToAttribute(String.Empty), false, "Should have returned false"); TestLog.Compare(DataReader.Value, String.Empty, "Compare MoveToAttribute with String.Empty"); } //[Variation("MoveToAttribute(String.Empty,String.Empty)")] public void MoveToAttributeWithName2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader.MoveToAttribute(String.Empty, String.Empty), false, "Compare the call to MoveToAttribute"); TestLog.Compare(DataReader.Value, String.Empty, "Compare MoveToAttribute(strName)"); } } //[TestCase(Name = "GetAttributeOrdinal", Desc = "GetAttributeOrdinal")] public partial class TCGetAttributeOrdinal : BridgeHelpers { //[Variation("GetAttribute(i) Verify with This[i] - Double Quote", Priority = 0)] public void GetAttributeWithGetAttrDoubleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 0; i < DataReader.AttributeCount; i++) { TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare GetAttribute(i) and this[i]"); } } //[Variation("GetAttribute[i] Verify with This[i] - Single Quote")] public void OrdinalWithGetAttrSingleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare GetAttribute(i) and this[i]"); } } //[Variation("GetAttribute(i) Verify with MoveToAttribute[i] - Double Quote", Priority = 0)] public void GetAttributeWithMoveAttrDoubleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 0; i < DataReader.AttributeCount; i++) { string str = DataReader.GetAttribute(i); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]"); TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string"); } } //[Variation("GetAttribute(i) Verify with MoveToAttribute[i] - Single Quote")] public void GetAttributeWithMoveAttrSingleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { string str = DataReader.GetAttribute(i); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader[i], "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]"); TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string"); } } //[Variation("GetAttribute(i) NegativeOneOrdinal", Priority = 0)] public void NegativeOneOrdinal() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string str = DataReader.GetAttribute(-1); } //[Variation("GetAttribute(i) FieldCountOrdinal")] public void FieldCountOrdinal() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string str = DataReader.GetAttribute(DataReader.AttributeCount); } //[Variation("GetAttribute(i) OrdinalPlusOne", Priority = 0)] public void OrdinalPlusOne() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string str = DataReader.GetAttribute(DataReader.AttributeCount + 1); } //[Variation("GetAttribute(i) OrdinalMinusOne")] public void OrdinalMinusOne() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string str = DataReader.GetAttribute(-2); } } //[TestCase(Name = "GetAttributeName", Desc = "GetAttributeName")] public partial class TCGetAttributeName : BridgeHelpers { //[Variation("GetAttribute(Name) Verify with This[Name]", Priority = 0)] public void GetAttributeWithName1() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader[strName], DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("GetAttribute(Name, null) Verify with This[Name]")] public void GetAttributeWithName2() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader[strName], DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("GetAttribute(Name) Verify with This[Name,null]")] public void GetAttributeWithName3() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader[strName], DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("GetAttribute(Name, NamespaceURI) Verify with This[Name, NamespaceURI]", Priority = 0)] public void GetAttributeWithName4() { string strName; string qname; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + i; qname = "foo:" + strName; TestLog.Compare(DataReader[strName, strNamespace], DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName,strNamespace) and this[strName,strNamespace]"); TestLog.Compare(DataReader[qname], DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName,strNamespace) and this[strName,strNamespace]"); TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Ordinal (" + i + "): Compare GetAttribute(qname) and this[qname]"); } } //[Variation("GetAttribute(Name, null) Verify not the same as This[Name, NamespaceURI]")] public void GetAttributeWithName5() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); if (DataReader.GetAttribute(strName) == DataReader[strName, strNamespace]) { if (DataReader[strName, strNamespace] == String.Empty) throw new TestException(TestResult.Failed, Variation.Desc); } } } //[Variation("GetAttribute(Name, NamespaceURI) Verify not the same as This[Name, null]")] public void GetAttributeWithName6() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); if (DataReader.GetAttribute(strName, strNamespace) == DataReader[strName]) throw new TestException(TestResult.Failed, Variation.Desc); } } //[Variation("GetAttribute(Name) Verify with MoveToAttribute(Name)")] public void GetAttributeWithName7() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; DataReader.MoveToAttribute(strName); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("GetAttribute(Name,null) Verify with MoveToAttribute(Name)", Priority = 1)] public void GetAttributeWithName8() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; DataReader.MoveToAttribute(strName); TestLog.Compare(DataReader.GetAttribute(strName, null), null, "Ordinal (" + i + "): Did not return null"); } } //[Variation("GetAttribute(Name) Verify with MoveToAttribute(Name,null)", Priority = 1)] public void GetAttributeWithName9() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader.MoveToAttribute(strName, null), false, "Ordinal (" + i + "): Incorrect move"); TestLog.Compare(DataReader.Value, String.Empty, "Ordinal (" + i + "): DataReader.Value should be empty string"); } } //[Variation("GetAttribute(Name, NamespaceURI) Verify not the same as MoveToAttribute(Name, null)")] public void GetAttributeWithName10() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); TestLog.Compare(DataReader.MoveToAttribute(strName, null), false, "Incorrect move"); TestLog.Compare(DataReader.Value, String.Empty, "Ordinal (" + i + "): DataReader.Value should be empty string"); } } //[Variation("GetAttribute(Name, null) Verify not the same as MoveToAttribute(Name, NamespaceURI)")] public void GetAttributeWithName11() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; DataReader.MoveToAttribute(strName, strNamespace); TestLog.Compare(DataReader.GetAttribute(strName, null), null, "Should have returned null"); } } //[Variation("GetAttribute(Name, namespace) Verify not the same as MoveToAttribute(Name, namespace)")] public void GetAttributeWithName12() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); DataReader.MoveToAttribute(strName, strNamespace); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("GetAttribute(String.Empty)")] public void GetAttributeWithName13() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); TestLog.Compare(DataReader.GetAttribute(String.Empty), null, "Should have returned null"); } //[Variation("GetAttribute(String.Empty,String.Empty)")] public void GetAttributeWithName14() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); TestLog.Compare(DataReader.GetAttribute(String.Empty, String.Empty), null, "Compare GetAttribute(strName) and this[strName]"); } } //[TestCase(Name = "ThisOrdinal", Desc = "ThisOrdinal")] public partial class TCThisOrdinal : BridgeHelpers { //[Variation("This[i] Verify with GetAttribute[i] - Double Quote", Priority = 0)] public void OrdinalWithGetAttrDoubleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 0; i < DataReader.AttributeCount; i++) { TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare GetAttribute[i] and this[i]"); } } //[Variation("This[i] Verify with GetAttribute[i] - Single Quote")] public void OrdinalWithGetAttrSingleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare GetAttribute[i] and this[i]"); } } //[Variation("This[i] Verify with MoveToAttribute[i] - Double Quote", Priority = 0)] public void OrdinalWithMoveAttrDoubleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 0; i < DataReader.AttributeCount; i++) { string str = DataReader[i]; DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader[i], "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]"); TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string"); } } //[Variation("This[i] Verify with MoveToAttribute[i] - Single Quote")] public void OrdinalWithMoveAttrSingleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { string str = DataReader[i]; DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader[i], "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]"); TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string"); } } //[Variation("ThisOrdinal NegativeOneOrdinal", Priority = 0)] public void NegativeOneOrdinal() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string str = DataReader[-1]; } //[Variation("ThisOrdinal FieldCountOrdinal")] public void FieldCountOrdinal() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string str = DataReader[DataReader.AttributeCount]; } //[Variation("ThisOrdinal OrdinalPlusOne", Priority = 0)] public void OrdinalPlusOne() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string str = DataReader[DataReader.AttributeCount + 1]; } //[Variation("ThisOrdinal OrdinalMinusOne")] public void OrdinalMinusOne() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string str = DataReader[-2]; } } //[TestCase(Name = "MoveToAttributeOrdinal", Desc = "MoveToAttributeOrdinal")] public partial class TCMoveToAttributeOrdinal : BridgeHelpers { //[Variation("MoveToAttribute(i) Verify with This[i] - Double Quote", Priority = 0)] public void MoveToAttributeWithGetAttrDoubleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 0; i < DataReader.AttributeCount; i++) { DataReader.MoveToAttribute(i); TestLog.Compare(DataReader[i], DataReader.Value, "Ordinal (" + i + "): Compare GetAttribute(i) and this[i]"); } } //[Variation("MoveToAttribute(i) Verify with This[i] - Single Quote")] public void MoveToAttributeWithGetAttrSingleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { DataReader.MoveToAttribute(i); TestLog.Compare(DataReader[i], DataReader.Value, "Ordinal (" + i + "): Compare GetAttribute(i) and this[i]"); } } //[Variation("MoveToAttribute(i) Verify with GetAttribute(i) - Double Quote", Priority = 0)] public void MoveToAttributeWithMoveAttrDoubleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 0; i < DataReader.AttributeCount; i++) { string str = DataReader.GetAttribute(i); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]"); TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string"); } } //[Variation("MoveToAttribute(i) Verify with GetAttribute[i] - Single Quote")] public void MoveToAttributeWithMoveAttrSingleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { string str = DataReader.GetAttribute(i); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader[i], "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]"); TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string"); } } //[Variation("MoveToAttribute(i) NegativeOneOrdinal", Priority = 0)] public void NegativeOneOrdinal() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); try { DataReader.MoveToAttribute(-1); } catch (ArgumentOutOfRangeException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("MoveToAttribute(i) FieldCountOrdinal")] public void FieldCountOrdinal() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); try { DataReader.MoveToAttribute(DataReader.AttributeCount); } catch (ArgumentOutOfRangeException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("MoveToAttribute(i) OrdinalPlusOne", Priority = 0)] public void OrdinalPlusOne() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); try { DataReader.MoveToAttribute(DataReader.AttributeCount + 1); } catch (ArgumentOutOfRangeException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("MoveToAttribute(i) OrdinalMinusOne")] public void OrdinalMinusOne() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); try { DataReader.MoveToAttribute(-2); } catch (ArgumentOutOfRangeException) { return; } throw new TestException(TestResult.Failed, ""); } } //[TestCase(Name = "MoveToFirstAttribute", Desc = "MoveToFirstAttribute")] public partial class TCMoveToFirstAttribute : BridgeHelpers { //[Variation("MoveToFirstAttribute() When AttributeCount=0, <EMPTY1/> ", Priority = 0)] public void MoveToFirstAttribute1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, Variation.Desc); } //[Variation("MoveToFirstAttribute() When AttributeCount=0, <NONEMPTY1>ABCDE</NONEMPTY1> ")] public void MoveToFirstAttribute2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONEMPTY1"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=0, with namespace")] public void MoveToFirstAttribute3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string strFirst; TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=0, without namespace")] public void MoveToFirstAttribute4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string strFirst; TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=mIddle, with namespace")] public void MoveToFirstAttribute5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string strFirst; DataReader.MoveToAttribute((int)((DataReader.AttributeCount) / 2)); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=mIddle, without namespace")] public void MoveToFirstAttribute6() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string strFirst; DataReader.MoveToAttribute((int)((DataReader.AttributeCount) / 2)); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=end, with namespace")] public void MoveToFirstAttribute7() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string strFirst; DataReader.MoveToAttribute((DataReader.AttributeCount) - 1); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=end, without namespace")] public void MoveToFirstAttribute8() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string strFirst; DataReader.MoveToAttribute((DataReader.AttributeCount) - 1); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } } public partial class TCMoveToNextAttribute : BridgeHelpers { //[Variation("MoveToNextAttribute() When AttributeCount=0, <EMPTY1/> ", Priority = 0)] public void MoveToNextAttribute1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, Variation.Desc); } //[Variation("MoveToNextAttribute() When AttributeCount=0, <NONEMPTY1>ABCDE</NONEMPTY1> ")] public void MoveToNextAttribute2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONEMPTY1"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, Variation.Desc); } //[Variation("MoveToNextAttribute() When iOrdinal=0, with namespace")] public void MoveToNextAttribute3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string strValue; TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc); strValue = DataReader.Value; TestLog.Compare(strValue, DataReader.GetAttribute(0), Variation.Desc); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc); strValue = DataReader.Value; TestLog.Compare(strValue, DataReader.GetAttribute(1), Variation.Desc); } //[Variation("MoveToNextAttribute() When iOrdinal=0, without namespace")] public void MoveToNextAttribute4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string strValue; TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc); strValue = DataReader.Value; TestLog.Compare(strValue, DataReader.GetAttribute(0), Variation.Desc); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc); strValue = DataReader.Value; TestLog.Compare(strValue, DataReader.GetAttribute(1), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=mIddle, with namespace")] public void MoveToFirstAttribute5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string strValue0; string strValue; int iMid = (DataReader.AttributeCount) / 2; DataReader.MoveToAttribute(iMid + 1); strValue0 = DataReader.Value; DataReader.MoveToAttribute(iMid); TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc); strValue = DataReader.Value; TestLog.Compare(strValue0, strValue, Variation.Desc); TestLog.Compare(strValue, DataReader.GetAttribute(iMid + 1), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=mIddle, without namespace")] public void MoveToFirstAttribute6() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string strValue0; string strValue; int iMid = (DataReader.AttributeCount) / 2; DataReader.MoveToAttribute(iMid + 1); strValue0 = DataReader.Value; DataReader.MoveToAttribute(iMid); TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc); strValue = DataReader.Value; TestLog.Compare(strValue0, strValue, Variation.Desc); TestLog.Compare(strValue, DataReader.GetAttribute(iMid + 1), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=end, with namespace")] public void MoveToFirstAttribute7() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string strFirst; DataReader.MoveToAttribute((DataReader.AttributeCount) - 1); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=end, without namespace")] public void MoveToFirstAttribute8() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string strFirst; DataReader.MoveToAttribute((DataReader.AttributeCount) - 1); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } } public partial class TCAttributeTest : BridgeHelpers { //[Variation("Attribute Test On None")] public void TestAttributeTestNodeType_None() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.None)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCount"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("Attribute Test On Element", Priority = 0)] public void TestAttributeTestNodeType_Element() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.Element)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("Attribute Test On Text", Priority = 0)] public void TestAttributeTestNodeType_Text() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.Text)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("Attribute Test On CDATA")] public void TestAttributeTestNodeType_CDATA() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.CDATA)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("Attribute Test On ProcessingInstruction")] public void TestAttributeTestNodeType_ProcessingInstruction() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.ProcessingInstruction)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("AttributeTest On Comment")] public void TestAttributeTestNodeType_Comment() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.Comment)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("AttributeTest On DocumentType", Priority = 0)] public void TestAttributeTestNodeType_DocumentType() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.DocumentType)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCount"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("AttributeTest On Whitespace")] public void TestAttributeTestNodeType_Whitespace() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.Whitespace)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("AttributeTest On EndElement")] public void TestAttributeTestNodeType_EndElement() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.EndElement)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCount"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("AttributeTest On XmlDeclaration", Priority = 0)] public void TestAttributeTestNodeType_XmlDeclaration() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.XmlDeclaration)) { int nCount = 3; TestLog.Compare(DataReader.AttributeCount, nCount, "Checking AttributeCount"); TestLog.Compare(DataReader.HasAttributes, true, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, "Checking MoveToFirstAttribute"); bool bNext = true; TestLog.Compare(DataReader.MoveToNextAttribute(), bNext, "Checking MoveToNextAttribute"); } } //[Variation("AttributeTest On EndEntity")] public void TestAttributeTestNodeType_EndEntity() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.EndEntity)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCount"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } } //[TestCase(Name = "ReadURI", Desc = "Read URI")] public partial class TATextReaderDocType : BridgeHelpers { //[Variation("Valid URI reference as SystemLiteral")] public void TATextReaderDocType_1() { string strxml = "<?xml version='1.0' standalone='no'?><!DOCTYPE ROOT SYSTEM 'se2.dtd'[]><ROOT/>"; XmlReader r = GetReaderStr(strxml); while (r.Read()) ; } void TestUriChar(char ch) { string filename = String.Format("f{0}.dtd", ch); string strxml = String.Format("<!DOCTYPE ROOT SYSTEM '{0}' []><ROOT></ROOT>", filename); XmlReader r = GetReaderStr(strxml); while (r.Read()) ; } // XML 1.0 SE //[Variation("URI reference with disallowed characters in SystemLiteral")] public void TATextReaderDocType_4() { string strDisallowed = " {}^`"; for (int i = 0; i < strDisallowed.Length; i++) TestUriChar(strDisallowed[i]); } } public partial class TCXmlns : BridgeHelpers { private string _ST_ENS1 = "EMPTY_NAMESPACE1"; private string _ST_NS2 = "NAMESPACE2"; //[Variation("Name, LocalName, Prefix and Value with xmlns=ns attribute", Priority = 0)] public void TXmlns1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_ENS1); DataReader.MoveToAttribute("xmlns"); TestLog.Compare(DataReader.LocalName, "xmlns", "ln"); TestLog.Compare(DataReader.Name, "xmlns", "n"); TestLog.Compare(DataReader.Prefix, String.Empty, "p"); TestLog.Compare(DataReader.Value, "14", "v"); } //[Variation("Name, LocalName, Prefix and Value with xmlns:p=ns attribute")] public void TXmlns2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_NS2); DataReader.MoveToAttribute(0); TestLog.Compare(DataReader.LocalName, "bar", "ln"); TestLog.Compare(DataReader.Name, "xmlns:bar", "n"); TestLog.Compare(DataReader.Prefix, "xmlns", "p"); TestLog.Compare(DataReader.Value, "1", "v"); } //[Variation("LookupNamespace with xmlns=ns attribute")] public void TXmlns3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_ENS1); DataReader.MoveToAttribute(1); TestLog.Compare(DataReader.LookupNamespace("xmlns"), "http://www.w3.org/2000/xmlns/", "ln"); } //[Variation("MoveToAttribute access on xmlns attribute")] public void TXmlns4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_ENS1); DataReader.MoveToAttribute(1); TestLog.Compare(DataReader.LocalName, "xmlns", "ln"); TestLog.Compare(DataReader.Name, "xmlns", "n"); TestLog.Compare(DataReader.Prefix, String.Empty, "p"); TestLog.Compare(DataReader.Value, "14", "v"); DataReader.MoveToElement(); TestLog.Compare(DataReader.MoveToAttribute("xmlns"), true, "mta(str)"); TestLog.Compare(DataReader.LocalName, "xmlns", "ln"); TestLog.Compare(DataReader.Name, "xmlns", "n"); TestLog.Compare(DataReader.Prefix, String.Empty, "p"); TestLog.Compare(DataReader.Value, "14", "v"); DataReader.MoveToElement(); TestLog.Compare(DataReader.MoveToAttribute("xmlns"), true, "mta(str, str)"); TestLog.Compare(DataReader.LocalName, "xmlns", "ln"); TestLog.Compare(DataReader.Name, "xmlns", "n"); TestLog.Compare(DataReader.Prefix, String.Empty, "p"); TestLog.Compare(DataReader.Value, "14", "v"); DataReader.MoveToElement(); TestLog.Compare(DataReader.MoveToAttribute("xmlns", "14"), false, "mta inv"); } //[Variation("GetAttribute access on xmlns attribute")] public void TXmlns5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_ENS1); TestLog.Compare(DataReader.GetAttribute(1), "14", "ga(i)"); TestLog.Compare(DataReader.GetAttribute("xmlns"), "14", "ga(str)"); TestLog.Compare(DataReader.GetAttribute("xmlns"), "14", "ga(str, str)"); TestLog.Compare(DataReader.GetAttribute("xmlns", "14"), null, "ga inv"); } //[Variation("this[xmlns] attribute access")] public void TXmlns6() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_ENS1); TestLog.Compare(DataReader[1], "14", "this[i]"); TestLog.Compare(DataReader["xmlns"], "14", "this[str]"); TestLog.Compare(DataReader["xmlns", "14"], null, "this inv"); } } public partial class TCXmlnsPrefix : BridgeHelpers { private string _ST_ENS1 = "EMPTY_NAMESPACE1"; private string _ST_NS2 = "NAMESPACE2"; private string _strXmlns = "http://www.w3.org/2000/xmlns/"; //[Variation("NamespaceURI of xmlns:a attribute", Priority = 0)] public void TXmlnsPrefix1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_NS2); DataReader.MoveToAttribute(0); TestLog.Compare(DataReader.NamespaceURI, _strXmlns, "nu"); } //[Variation("NamespaceURI of element/attribute with xmlns attribute", Priority = 0)] public void TXmlnsPrefix2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_ENS1); TestLog.Compare(DataReader.NamespaceURI, "14", "nue"); DataReader.MoveToAttribute("Attr0"); TestLog.Compare(DataReader.NamespaceURI, String.Empty, "nu"); DataReader.MoveToAttribute("xmlns"); TestLog.Compare(DataReader.NamespaceURI, _strXmlns, "nu"); } //[Variation("LookupNamespace with xmlns prefix")] public void TXmlnsPrefix3() { XmlReader DataReader = GetReader(); DataReader.Read(); TestLog.Compare(DataReader.LookupNamespace("xmlns"), null, "ln"); } //[Variation("Define prefix for 'www.w3.org/2000/xmlns'", Priority = 0)] public void TXmlnsPrefix4() { string strxml = "<ROOT xmlns:pxmlns='http://www.w3.org/2000/xmlns/'/>"; try { XmlReader DataReader = GetReaderStr(strxml); DataReader.Read(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } } //[Variation("Redefine namespace attached to xmlns prefix")] public void TXmlnsPrefix5() { string strxml = "<ROOT xmlns:xmlns='http://www.w3.org/2002/xmlns/'/>"; try { XmlReader DataReader = GetReaderStr(strxml); DataReader.Read(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } } } } } }
//------------------------------------------------------------------------------ // <copyright file="HttpCachePolicy.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * Cache Policy class * * Copyright (c) 1998 Microsoft Corporation */ namespace System.Web { using System; using System.Collections; using System.Globalization; using System.Runtime.Serialization; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Threading; using System.Web.Caching; using System.Web.Compilation; using System.Web.Configuration; using System.Web.Management; using System.Web.Security.Cryptography; using System.Web.Util; using Debug = System.Web.Util.Debug; // // Public constants for cache-control // /// <devdoc> /// <para> /// Provides enumeration values for all cache-control header settings. /// </para> /// </devdoc> public enum HttpCacheability { /// <devdoc> /// <para> /// Indicates that /// without a field name, a cache must force successful revalidation with the /// origin server before satisfying the request. With a field name, the cache may /// use the response to satisfy a subsequent request. /// </para> /// </devdoc> NoCache = 1, /// <devdoc> /// <para> /// Default value. Specifies that the response is cachable only on the client, /// not by shared caches. /// </para> /// </devdoc> Private, /// <devdoc> /// <para> /// Specifies that the response should only be cached at the server. /// Clients receive headers equivalent to a NoCache directive. /// </para> /// </devdoc> Server, ServerAndNoCache = Server, /// <devdoc> /// <para> /// Specifies that the response is cachable by clients and shared caches. /// </para> /// </devdoc> Public, ServerAndPrivate, } enum HttpCacheabilityLimits { MinValue = HttpCacheability.NoCache, MaxValue = HttpCacheability.ServerAndPrivate, None = MaxValue + 1, } /// <devdoc> /// <para> /// This class is a light abstraction over the Cache-Control: revalidation /// directives. /// </para> /// </devdoc> public enum HttpCacheRevalidation { /// <devdoc> /// <para> /// Indicates that Cache-Control: must-revalidate should be sent. /// </para> /// </devdoc> AllCaches = 1, /// <devdoc> /// <para> /// Indicates that Cache-Control: proxy-revalidate should be sent. /// </para> /// </devdoc> ProxyCaches = 2, /// <devdoc> /// <para> /// Default value. Indicates that no property has been set. If this is set, no /// cache revalitation directive is sent. /// </para> /// </devdoc> None = 3, } enum HttpCacheRevalidationLimits { MinValue = HttpCacheRevalidation.AllCaches, MaxValue = HttpCacheRevalidation.None } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public enum HttpValidationStatus { /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Invalid = 1, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> IgnoreThisRequest = 2, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Valid = 3 } /// <devdoc> /// <para>Called back when the handler wants validation on a cache /// item before it's served from the cache. If any handler invalidates /// the item, the item is evicted from the cache and the request is handled as /// if a cache miss were generated.</para> /// </devdoc> public delegate void HttpCacheValidateHandler( HttpContext context, Object data, ref HttpValidationStatus validationStatus); sealed class ValidationCallbackInfo { internal readonly HttpCacheValidateHandler handler; internal readonly Object data; internal ValidationCallbackInfo(HttpCacheValidateHandler handler, Object data) { this.handler = handler; this.data = data; } } [Serializable] sealed class HttpCachePolicySettings { /* internal access */ internal readonly bool _isModified; [NonSerialized] internal ValidationCallbackInfo[] _validationCallbackInfo; private string[] _validationCallbackInfoForSerialization; internal readonly HttpResponseHeader _headerCacheControl; internal readonly HttpResponseHeader _headerPragma; internal readonly HttpResponseHeader _headerExpires; internal readonly HttpResponseHeader _headerLastModified; internal readonly HttpResponseHeader _headerEtag; internal readonly HttpResponseHeader _headerVaryBy; /* internal access */ internal readonly bool _hasSetCookieHeader; internal readonly bool _noServerCaching; internal readonly String _cacheExtension; internal readonly bool _noTransforms; internal readonly bool _ignoreRangeRequests; internal readonly String[] _varyByContentEncodings; internal readonly String[] _varyByHeaderValues; internal readonly String[] _varyByParamValues; internal readonly string _varyByCustom; internal readonly HttpCacheability _cacheability; internal readonly bool _noStore; internal readonly String[] _privateFields; internal readonly String[] _noCacheFields; internal readonly DateTime _utcExpires; internal readonly bool _isExpiresSet; internal readonly TimeSpan _maxAge; internal readonly bool _isMaxAgeSet; internal readonly TimeSpan _proxyMaxAge; internal readonly bool _isProxyMaxAgeSet; internal readonly int _slidingExpiration; internal readonly TimeSpan _slidingDelta; internal readonly DateTime _utcTimestampCreated; internal readonly int _validUntilExpires; internal readonly int _allowInHistory; internal readonly HttpCacheRevalidation _revalidation; internal readonly DateTime _utcLastModified; internal readonly bool _isLastModifiedSet; internal readonly String _etag; internal readonly bool _generateLastModifiedFromFiles; internal readonly bool _generateEtagFromFiles; internal readonly int _omitVaryStar; internal readonly bool _hasUserProvidedDependencies; internal HttpCachePolicySettings( bool isModified, ValidationCallbackInfo[] validationCallbackInfo, bool hasSetCookieHeader, bool noServerCaching, String cacheExtension, bool noTransforms, bool ignoreRangeRequests, String[] varyByContentEncodings, String[] varyByHeaderValues, String[] varyByParamValues, string varyByCustom, HttpCacheability cacheability, bool noStore, String[] privateFields, String[] noCacheFields, DateTime utcExpires, bool isExpiresSet, TimeSpan maxAge, bool isMaxAgeSet, TimeSpan proxyMaxAge, bool isProxyMaxAgeSet, int slidingExpiration, TimeSpan slidingDelta, DateTime utcTimestampCreated, int validUntilExpires, int allowInHistory, HttpCacheRevalidation revalidation, DateTime utcLastModified, bool isLastModifiedSet, String etag, bool generateLastModifiedFromFiles, bool generateEtagFromFiles, int omitVaryStar, HttpResponseHeader headerCacheControl, HttpResponseHeader headerPragma, HttpResponseHeader headerExpires, HttpResponseHeader headerLastModified, HttpResponseHeader headerEtag, HttpResponseHeader headerVaryBy, bool hasUserProvidedDependencies) { _isModified = isModified ; _validationCallbackInfo = validationCallbackInfo ; _hasSetCookieHeader = hasSetCookieHeader ; _noServerCaching = noServerCaching ; _cacheExtension = cacheExtension ; _noTransforms = noTransforms ; _ignoreRangeRequests = ignoreRangeRequests ; _varyByContentEncodings = varyByContentEncodings ; _varyByHeaderValues = varyByHeaderValues ; _varyByParamValues = varyByParamValues ; _varyByCustom = varyByCustom ; _cacheability = cacheability ; _noStore = noStore ; _privateFields = privateFields ; _noCacheFields = noCacheFields ; _utcExpires = utcExpires ; _isExpiresSet = isExpiresSet ; _maxAge = maxAge ; _isMaxAgeSet = isMaxAgeSet ; _proxyMaxAge = proxyMaxAge ; _isProxyMaxAgeSet = isProxyMaxAgeSet ; _slidingExpiration = slidingExpiration ; _slidingDelta = slidingDelta ; _utcTimestampCreated = utcTimestampCreated ; _validUntilExpires = validUntilExpires ; _allowInHistory = allowInHistory ; _revalidation = revalidation ; _utcLastModified = utcLastModified ; _isLastModifiedSet = isLastModifiedSet ; _etag = etag ; _generateLastModifiedFromFiles = generateLastModifiedFromFiles ; _generateEtagFromFiles = generateEtagFromFiles ; _omitVaryStar = omitVaryStar ; _headerCacheControl = headerCacheControl ; _headerPragma = headerPragma ; _headerExpires = headerExpires ; _headerLastModified = headerLastModified ; _headerEtag = headerEtag ; _headerVaryBy = headerVaryBy ; _hasUserProvidedDependencies = hasUserProvidedDependencies ; } [OnSerializing()] private void OnSerializingMethod(StreamingContext context) { if (_validationCallbackInfo == null) return; // create a string representation of each callback // note that ValidationCallbackInfo.data is assumed to be null String[] callbackInfos = new String[_validationCallbackInfo.Length * 2]; for (int i = 0; i < _validationCallbackInfo.Length; i++) { Debug.Assert(_validationCallbackInfo[i].data == null, "_validationCallbackInfo[i].data == null"); HttpCacheValidateHandler handler = _validationCallbackInfo[i].handler; string targetTypeName = System.Web.UI.Util.GetAssemblyQualifiedTypeName(handler.Method.ReflectedType); string methodName = handler.Method.Name; callbackInfos[2 * i] = targetTypeName; callbackInfos[2 * i + 1] = methodName; } _validationCallbackInfoForSerialization = callbackInfos; } [OnDeserialized()] private void OnDeserializedMethod(StreamingContext context) { if (_validationCallbackInfoForSerialization == null) return; // re-create each ValidationCallbackInfo from its string representation ValidationCallbackInfo[] callbackInfos = new ValidationCallbackInfo[_validationCallbackInfoForSerialization.Length / 2]; for (int i = 0; i < _validationCallbackInfoForSerialization.Length; i += 2) { string targetTypeName = _validationCallbackInfoForSerialization[i]; string methodName = _validationCallbackInfoForSerialization[i+1]; Type target = null; if (!String.IsNullOrEmpty(targetTypeName)) { target = BuildManager.GetType(targetTypeName, true /*throwOnFail*/, false /*ignoreCase*/); } if (target == null) { throw new SerializationException(SR.GetString(SR.Type_cannot_be_resolved, targetTypeName)); } HttpCacheValidateHandler handler = (HttpCacheValidateHandler) Delegate.CreateDelegate(typeof(HttpCacheValidateHandler), target, methodName); callbackInfos[i / 2] = new ValidationCallbackInfo(handler, null); } _validationCallbackInfo = callbackInfos; } internal bool IsModified {get {return _isModified ;}} internal ValidationCallbackInfo[] ValidationCallbackInfo {get {return _validationCallbackInfo ;}} internal HttpResponseHeader HeaderCacheControl {get {return _headerCacheControl ;}} internal HttpResponseHeader HeaderPragma {get {return _headerPragma ;}} internal HttpResponseHeader HeaderExpires {get {return _headerExpires ;}} internal HttpResponseHeader HeaderLastModified {get {return _headerLastModified ;}} internal HttpResponseHeader HeaderEtag {get {return _headerEtag ;}} internal HttpResponseHeader HeaderVaryBy {get {return _headerVaryBy ;}} internal bool hasSetCookieHeader {get {return _hasSetCookieHeader ;}} internal bool NoServerCaching {get {return _noServerCaching ;}} internal String CacheExtension {get {return _cacheExtension ;}} internal bool NoTransforms {get {return _noTransforms ;}} internal bool IgnoreRangeRequests {get {return _ignoreRangeRequests ;}} internal String[] VaryByContentEncodings {get { return (_varyByContentEncodings == null) ? null : (string[]) _varyByContentEncodings.Clone() ;}} internal String[] VaryByHeaders {get { return (_varyByHeaderValues == null) ? null : (string[]) _varyByHeaderValues.Clone() ;}} internal String[] VaryByParams {get { return (_varyByParamValues == null) ? null : (string[]) _varyByParamValues.Clone() ;}} internal bool IgnoreParams {get { return _varyByParamValues != null && _varyByParamValues[0].Length == 0;}} internal HttpCacheability CacheabilityInternal {get { return _cacheability;}} internal bool NoStore {get {return _noStore ;}} internal String[] PrivateFields {get { return (_privateFields == null) ? null : (string[]) _privateFields.Clone() ;}} internal String[] NoCacheFields {get { return (_noCacheFields == null) ? null : (string[]) _noCacheFields.Clone() ;}} internal DateTime UtcExpires {get {return _utcExpires ;}} internal bool IsExpiresSet {get {return _isExpiresSet ;}} internal TimeSpan MaxAge {get {return _maxAge ;}} internal bool IsMaxAgeSet {get {return _isMaxAgeSet ;}} internal TimeSpan ProxyMaxAge {get {return _proxyMaxAge ;}} internal bool IsProxyMaxAgeSet {get {return _isProxyMaxAgeSet ;}} internal int SlidingExpirationInternal {get {return _slidingExpiration ;}} internal bool SlidingExpiration {get {return _slidingExpiration == 1 ;}} internal TimeSpan SlidingDelta {get {return _slidingDelta ;}} internal DateTime UtcTimestampCreated {get {return _utcTimestampCreated ;}} internal int ValidUntilExpiresInternal {get {return _validUntilExpires ;}} internal bool ValidUntilExpires {get { return _validUntilExpires == 1 && !SlidingExpiration && !GenerateLastModifiedFromFiles && !GenerateEtagFromFiles && ValidationCallbackInfo == null;}} internal int AllowInHistoryInternal {get {return _allowInHistory ;}} internal HttpCacheRevalidation Revalidation {get {return _revalidation ;}} internal DateTime UtcLastModified {get {return _utcLastModified ;}} internal bool IsLastModifiedSet {get {return _isLastModifiedSet ;}} internal String ETag {get {return _etag ;}} internal bool GenerateLastModifiedFromFiles {get {return _generateLastModifiedFromFiles;}} internal bool GenerateEtagFromFiles {get {return _generateEtagFromFiles ;}} internal string VaryByCustom {get {return _varyByCustom ;}} internal bool HasUserProvidedDependencies {get {return _hasUserProvidedDependencies; }} internal bool IsValidationCallbackSerializable() { if (_validationCallbackInfo != null) { foreach(ValidationCallbackInfo info in _validationCallbackInfo) { if (info.data != null || !info.handler.Method.IsStatic) { return false; } } } return true; } internal bool HasValidationPolicy() { return ValidUntilExpires || GenerateLastModifiedFromFiles || GenerateEtagFromFiles || ValidationCallbackInfo != null; } internal int OmitVaryStarInternal {get {return _omitVaryStar;}} } /// <devdoc> /// <para>Contains methods for controlling the ASP.NET output cache.</para> /// </devdoc> public sealed class HttpCachePolicy { static TimeSpan s_oneYear = new TimeSpan(TimeSpan.TicksPerDay * 365); static HttpResponseHeader s_headerPragmaNoCache; static HttpResponseHeader s_headerExpiresMinus1; bool _isModified; bool _hasSetCookieHeader; bool _noServerCaching; String _cacheExtension; bool _noTransforms; bool _ignoreRangeRequests; HttpCacheVaryByContentEncodings _varyByContentEncodings; HttpCacheVaryByHeaders _varyByHeaders; HttpCacheVaryByParams _varyByParams; string _varyByCustom; HttpCacheability _cacheability; bool _noStore; HttpDictionary _privateFields; HttpDictionary _noCacheFields; DateTime _utcExpires; bool _isExpiresSet; TimeSpan _maxAge; bool _isMaxAgeSet; TimeSpan _proxyMaxAge; bool _isProxyMaxAgeSet; int _slidingExpiration; DateTime _utcTimestampCreated; TimeSpan _slidingDelta; DateTime _utcTimestampRequest; int _validUntilExpires; int _allowInHistory; HttpCacheRevalidation _revalidation; DateTime _utcLastModified; bool _isLastModifiedSet; String _etag; bool _generateLastModifiedFromFiles; bool _generateEtagFromFiles; int _omitVaryStar; ArrayList _validationCallbackInfo; bool _useCachedHeaders; HttpResponseHeader _headerCacheControl; HttpResponseHeader _headerPragma; HttpResponseHeader _headerExpires; HttpResponseHeader _headerLastModified; HttpResponseHeader _headerEtag; HttpResponseHeader _headerVaryBy; bool _noMaxAgeInCacheControl; bool _hasUserProvidedDependencies; internal HttpCachePolicy() { _varyByContentEncodings = new HttpCacheVaryByContentEncodings(); _varyByHeaders = new HttpCacheVaryByHeaders(); _varyByParams = new HttpCacheVaryByParams(); Reset(); } /* * Restore original values */ internal void Reset() { _varyByContentEncodings.Reset(); _varyByHeaders.Reset(); _varyByParams.Reset(); _isModified = false; _hasSetCookieHeader = false; _noServerCaching = false; _cacheExtension = null; _noTransforms = false; _ignoreRangeRequests = false; _varyByCustom = null; _cacheability = (HttpCacheability) (int) HttpCacheabilityLimits.None; _noStore = false; _privateFields = null; _noCacheFields = null; _utcExpires = DateTime.MinValue; _isExpiresSet = false; _maxAge = TimeSpan.Zero; _isMaxAgeSet = false; _proxyMaxAge = TimeSpan.Zero; _isProxyMaxAgeSet = false; _slidingExpiration = -1; _slidingDelta = TimeSpan.Zero; _utcTimestampCreated = DateTime.MinValue; _utcTimestampRequest = DateTime.MinValue; _validUntilExpires = -1; _allowInHistory = -1; _revalidation = HttpCacheRevalidation.None; _utcLastModified = DateTime.MinValue; _isLastModifiedSet = false; _etag = null; _generateLastModifiedFromFiles = false; _generateEtagFromFiles = false; _validationCallbackInfo = null; _useCachedHeaders = false; _headerCacheControl = null; _headerPragma = null; _headerExpires = null; _headerLastModified = null; _headerEtag = null; _headerVaryBy = null; _noMaxAgeInCacheControl = false; _hasUserProvidedDependencies = false; _omitVaryStar = -1; } /* * Reset based on a cached response. Includes data needed to generate * header for a cached response. */ internal void ResetFromHttpCachePolicySettings( HttpCachePolicySettings settings, DateTime utcTimestampRequest) { int i, n; string[] fields; _utcTimestampRequest = utcTimestampRequest; _varyByContentEncodings.ResetFromContentEncodings(settings.VaryByContentEncodings); _varyByHeaders.ResetFromHeaders(settings.VaryByHeaders); _varyByParams.ResetFromParams(settings.VaryByParams); _isModified = settings.IsModified; _hasSetCookieHeader = settings.hasSetCookieHeader; _noServerCaching = settings.NoServerCaching; _cacheExtension = settings.CacheExtension; _noTransforms = settings.NoTransforms; _ignoreRangeRequests = settings.IgnoreRangeRequests; _varyByCustom = settings.VaryByCustom; _cacheability = settings.CacheabilityInternal; _noStore = settings.NoStore; _utcExpires = settings.UtcExpires; _isExpiresSet = settings.IsExpiresSet; _maxAge = settings.MaxAge; _isMaxAgeSet = settings.IsMaxAgeSet; _proxyMaxAge = settings.ProxyMaxAge; _isProxyMaxAgeSet = settings.IsProxyMaxAgeSet; _slidingExpiration = settings.SlidingExpirationInternal; _slidingDelta = settings.SlidingDelta; _utcTimestampCreated = settings.UtcTimestampCreated; _validUntilExpires = settings.ValidUntilExpiresInternal; _allowInHistory = settings.AllowInHistoryInternal; _revalidation = settings.Revalidation; _utcLastModified = settings.UtcLastModified; _isLastModifiedSet = settings.IsLastModifiedSet; _etag = settings.ETag; _generateLastModifiedFromFiles = settings.GenerateLastModifiedFromFiles; _generateEtagFromFiles = settings.GenerateEtagFromFiles; _omitVaryStar = settings.OmitVaryStarInternal; _hasUserProvidedDependencies = settings.HasUserProvidedDependencies; _useCachedHeaders = true; _headerCacheControl = settings.HeaderCacheControl; _headerPragma = settings.HeaderPragma; _headerExpires = settings.HeaderExpires; _headerLastModified = settings.HeaderLastModified; _headerEtag = settings.HeaderEtag; _headerVaryBy = settings.HeaderVaryBy; _noMaxAgeInCacheControl = false; fields = settings.PrivateFields; if (fields != null) { _privateFields = new HttpDictionary(); for (i = 0, n = fields.Length; i < n; i++) { _privateFields.SetValue(fields[i], fields[i]); } } fields = settings.NoCacheFields; if (fields != null) { _noCacheFields = new HttpDictionary(); for (i = 0, n = fields.Length; i < n; i++) { _noCacheFields.SetValue(fields[i], fields[i]); } } if (settings.ValidationCallbackInfo != null) { _validationCallbackInfo = new ArrayList(); for (i = 0, n = settings.ValidationCallbackInfo.Length; i < n; i++) { _validationCallbackInfo.Add(new ValidationCallbackInfo( settings.ValidationCallbackInfo[i].handler, settings.ValidationCallbackInfo[i].data)); } } } internal bool IsModified() { return _isModified || _varyByContentEncodings.IsModified() || _varyByHeaders.IsModified() || _varyByParams.IsModified(); } void Dirtied() { _isModified = true; _useCachedHeaders = false; } static internal void AppendValueToHeader(StringBuilder s, String value) { if (!String.IsNullOrEmpty(value)) { if (s.Length > 0) { s.Append(", "); } s.Append(value); } } static readonly string[] s_cacheabilityTokens = new String[] { null, // no enum "no-cache", // HttpCacheability.NoCache "private", // HttpCacheability.Private "no-cache", // HttpCacheability.ServerAndNoCache "public", // HttpCacheability.Public "private", // HttpCacheability.ServerAndPrivate null // None - not specified }; static readonly string[] s_revalidationTokens = new String[] { null, // no enum "must-revalidate", // HttpCacheRevalidation.AllCaches "proxy-revalidate", // HttpCacheRevalidation.ProxyCaches null // HttpCacheRevalidation.None }; static readonly int[] s_cacheabilityValues = new int[] { -1, // no enum 0, // HttpCacheability.NoCache 2, // HttpCacheability.Private 1, // HttpCacheability.ServerAndNoCache 4, // HttpCacheability.Public 3, // HttpCacheability.ServerAndPrivate 100, // None - though private by default, an explicit set will override }; DateTime UpdateLastModifiedTimeFromDependency(CacheDependency dep) { DateTime utcFileLastModifiedMax = dep.UtcLastModified; if (utcFileLastModifiedMax < _utcLastModified) { utcFileLastModifiedMax = _utcLastModified; } // account for difference between file system time // and DateTime.Now. On some machines it appears that // the last modified time is further in the future // that DateTime.Now DateTime utcNow = DateTime.UtcNow; if (utcFileLastModifiedMax > utcNow) { utcFileLastModifiedMax = utcNow; } return utcFileLastModifiedMax; } /* * Calculate LastModified and ETag * * The LastModified date is the latest last-modified date of * every file that is added as a dependency. * * The ETag is generated by concatentating the appdomain id, * filenames and last modified dates of all files into a single string, * then hashing it and Base 64 encoding the hash. */ void UpdateFromDependencies(HttpResponse response) { CacheDependency dep = null; // if _etag != null && _generateEtagFromFiles == true, then this HttpCachePolicy // was created from HttpCachePolicySettings and we don't need to update _etag. if (_etag == null && _generateEtagFromFiles) { dep = response.CreateCacheDependencyForResponse(); if (dep == null) { return; } string id = dep.GetUniqueID(); if (id == null) { throw new HttpException(SR.GetString(SR.No_UniqueId_Cache_Dependency)); } DateTime utcFileLastModifiedMax = UpdateLastModifiedTimeFromDependency(dep); StringBuilder sb = new StringBuilder(256); sb.Append(HttpRuntime.AppDomainIdInternal); sb.Append(id); sb.Append("+LM"); sb.Append(utcFileLastModifiedMax.Ticks.ToString(CultureInfo.InvariantCulture)); _etag = Convert.ToBase64String(CryptoUtil.ComputeSHA256Hash(Encoding.UTF8.GetBytes(sb.ToString()))); //WOS 1540412: if we generate the etag based on file dependencies, encapsulate it within quotes. _etag = "\"" + _etag + "\""; } if (_generateLastModifiedFromFiles) { if (dep == null) { dep = response.CreateCacheDependencyForResponse(); if (dep == null) { return; } } DateTime utcFileLastModifiedMax = UpdateLastModifiedTimeFromDependency(dep); UtcSetLastModified(utcFileLastModifiedMax); } } void UpdateCachedHeaders(HttpResponse response) { StringBuilder sb; HttpCacheability cacheability; int i, n; String expirationDate; String lastModifiedDate; String varyByHeaders; bool omitVaryStar; if (_useCachedHeaders) { return; } Debug.Assert((_utcTimestampCreated == DateTime.MinValue && _utcTimestampRequest == DateTime.MinValue) || (_utcTimestampCreated != DateTime.MinValue && _utcTimestampRequest != DateTime.MinValue), "_utcTimestampCreated and _utcTimestampRequest are out of [....] in UpdateCachedHeaders"); if (_utcTimestampCreated == DateTime.MinValue) { _utcTimestampCreated = _utcTimestampRequest = response.Context.UtcTimestamp; } if (_slidingExpiration != 1) { _slidingDelta = TimeSpan.Zero; } else if (_isMaxAgeSet) { _slidingDelta = _maxAge; } else if (_isExpiresSet) { _slidingDelta = _utcExpires - _utcTimestampCreated; } else { _slidingDelta = TimeSpan.Zero; } _headerCacheControl = null; _headerPragma = null; _headerExpires = null; _headerLastModified = null; _headerEtag = null; _headerVaryBy = null; UpdateFromDependencies(response); /* * Cache control header */ sb = new StringBuilder(); if (_cacheability == (HttpCacheability) (int) HttpCacheabilityLimits.None) { cacheability = HttpCacheability.Private; } else { cacheability = _cacheability; } AppendValueToHeader(sb, s_cacheabilityTokens[(int) cacheability]); if (cacheability == HttpCacheability.Public && _privateFields != null) { Debug.Assert(_privateFields.Size > 0); AppendValueToHeader(sb, "private=\""); sb.Append(_privateFields.GetKey(0)); for (i = 1, n = _privateFields.Size; i < n; i++) { AppendValueToHeader(sb, _privateFields.GetKey(i)); } sb.Append('\"'); } if ( cacheability != HttpCacheability.NoCache && cacheability != HttpCacheability.ServerAndNoCache && _noCacheFields != null) { Debug.Assert(_noCacheFields.Size > 0); AppendValueToHeader(sb, "no-cache=\""); sb.Append(_noCacheFields.GetKey(0)); for (i = 1, n = _noCacheFields.Size; i < n; i++) { AppendValueToHeader(sb, _noCacheFields.GetKey(i)); } sb.Append('\"'); } if (_noStore) { AppendValueToHeader(sb, "no-store"); } AppendValueToHeader(sb, s_revalidationTokens[(int)_revalidation]); if (_noTransforms) { AppendValueToHeader(sb, "no-transform"); } if (_cacheExtension != null) { AppendValueToHeader(sb, _cacheExtension); } /* * don't send expiration information when item shouldn't be cached * for cached header, only add max-age when it doesn't change * based on the time requested */ if ( _slidingExpiration == 1 && cacheability != HttpCacheability.NoCache && cacheability != HttpCacheability.ServerAndNoCache) { if (_isMaxAgeSet && !_noMaxAgeInCacheControl) { AppendValueToHeader(sb, "max-age=" + ((long)_maxAge.TotalSeconds).ToString(CultureInfo.InvariantCulture)); } if (_isProxyMaxAgeSet && !_noMaxAgeInCacheControl) { AppendValueToHeader(sb, "s-maxage=" + ((long)(_proxyMaxAge).TotalSeconds).ToString(CultureInfo.InvariantCulture)); } } if (sb.Length > 0) { _headerCacheControl = new HttpResponseHeader(HttpWorkerRequest.HeaderCacheControl, sb.ToString()); } /* * Pragma: no-cache and Expires: -1 */ if (cacheability == HttpCacheability.NoCache || cacheability == HttpCacheability.ServerAndNoCache) { if (s_headerPragmaNoCache == null) { s_headerPragmaNoCache = new HttpResponseHeader(HttpWorkerRequest.HeaderPragma, "no-cache"); } _headerPragma = s_headerPragmaNoCache; if (_allowInHistory != 1) { if (s_headerExpiresMinus1 == null) { s_headerExpiresMinus1 = new HttpResponseHeader(HttpWorkerRequest.HeaderExpires, "-1"); } _headerExpires = s_headerExpiresMinus1; } } else { /* * Expires header. */ if (_isExpiresSet && _slidingExpiration != 1) { expirationDate = HttpUtility.FormatHttpDateTimeUtc(_utcExpires); _headerExpires = new HttpResponseHeader(HttpWorkerRequest.HeaderExpires, expirationDate); } /* * Last Modified header. */ if (_isLastModifiedSet) { lastModifiedDate = HttpUtility.FormatHttpDateTimeUtc(_utcLastModified); _headerLastModified = new HttpResponseHeader(HttpWorkerRequest.HeaderLastModified, lastModifiedDate); } if (cacheability != HttpCacheability.Private) { /* * Etag. */ if (_etag != null) { _headerEtag = new HttpResponseHeader(HttpWorkerRequest.HeaderEtag, _etag); } /* * Vary */ varyByHeaders = null; // automatic VaryStar processing // See if anyone has explicitly set this value if (_omitVaryStar != -1) { omitVaryStar = _omitVaryStar == 1 ? true : false; } else { // If no one has set this value, go with the default from config RuntimeConfig config = RuntimeConfig.GetLKGConfig(response.Context); OutputCacheSection outputCacheConfig = config.OutputCache; if (outputCacheConfig != null) { omitVaryStar = outputCacheConfig.OmitVaryStar; } else { omitVaryStar = OutputCacheSection.DefaultOmitVaryStar; } } if (!omitVaryStar) { // Dev10 Bug 425047 - OutputCache Location="ServerAndClient" (HttpCacheability.ServerAndPrivate) should // not use "Vary: *" so the response can be cached on the client if (_varyByCustom != null || (_varyByParams.IsModified() && !_varyByParams.IgnoreParams)) { varyByHeaders = "*"; } } if (varyByHeaders == null) { varyByHeaders = _varyByHeaders.ToHeaderString(); } if (varyByHeaders != null) { _headerVaryBy = new HttpResponseHeader(HttpWorkerRequest.HeaderVary, varyByHeaders); } } } _useCachedHeaders = true; } /* * Generate headers and append them to the list */ internal void GetHeaders(ArrayList headers, HttpResponse response) { StringBuilder sb; String expirationDate; TimeSpan age, maxAge, proxyMaxAge; DateTime utcExpires; HttpResponseHeader headerExpires; HttpResponseHeader headerCacheControl; UpdateCachedHeaders(response); headerExpires = _headerExpires; headerCacheControl = _headerCacheControl; /* * reconstruct headers that vary with time * don't send expiration information when item shouldn't be cached */ if (_cacheability != HttpCacheability.NoCache && _cacheability != HttpCacheability.ServerAndNoCache) { if (_slidingExpiration == 1) { /* update Expires header */ if (_isExpiresSet) { utcExpires = _utcTimestampRequest + _slidingDelta; expirationDate = HttpUtility.FormatHttpDateTimeUtc(utcExpires); headerExpires = new HttpResponseHeader(HttpWorkerRequest.HeaderExpires, expirationDate); } } else { if (_isMaxAgeSet || _isProxyMaxAgeSet) { /* update max-age, s-maxage components of Cache-Control header */ if (headerCacheControl != null) { sb = new StringBuilder(headerCacheControl.Value); } else { sb = new StringBuilder(); } age = _utcTimestampRequest - _utcTimestampCreated; if (_isMaxAgeSet) { maxAge = _maxAge - age; if (maxAge < TimeSpan.Zero) { maxAge = TimeSpan.Zero; } if (!_noMaxAgeInCacheControl) AppendValueToHeader(sb, "max-age=" + ((long)maxAge.TotalSeconds).ToString(CultureInfo.InvariantCulture)); } if (_isProxyMaxAgeSet) { proxyMaxAge = _proxyMaxAge - age; if (proxyMaxAge < TimeSpan.Zero) { proxyMaxAge = TimeSpan.Zero; } if (!_noMaxAgeInCacheControl) AppendValueToHeader(sb, "s-maxage=" + ((long)(proxyMaxAge).TotalSeconds).ToString(CultureInfo.InvariantCulture)); } headerCacheControl = new HttpResponseHeader(HttpWorkerRequest.HeaderCacheControl, sb.ToString()); } } } if (headerCacheControl != null) { headers.Add(headerCacheControl); } if (_headerPragma != null) { headers.Add(_headerPragma); } if (headerExpires != null) { headers.Add(headerExpires); } if (_headerLastModified != null) { headers.Add(_headerLastModified); } if (_headerEtag != null) { headers.Add(_headerEtag); } if (_headerVaryBy != null) { headers.Add(_headerVaryBy); } } /* * Public methods */ internal HttpCachePolicySettings GetCurrentSettings(HttpResponse response) { String[] varyByContentEncodings; String[] varyByHeaders; String[] varyByParams; String[] privateFields; String[] noCacheFields; ValidationCallbackInfo[] validationCallbackInfo; UpdateCachedHeaders(response); varyByContentEncodings = _varyByContentEncodings.GetContentEncodings(); varyByHeaders = _varyByHeaders.GetHeaders(); varyByParams = _varyByParams.GetParams(); if (_privateFields != null) { privateFields = _privateFields.GetAllKeys(); } else { privateFields = null; } if (_noCacheFields != null) { noCacheFields = _noCacheFields.GetAllKeys(); } else { noCacheFields = null; } if (_validationCallbackInfo != null) { validationCallbackInfo = new ValidationCallbackInfo[_validationCallbackInfo.Count]; _validationCallbackInfo.CopyTo(0, validationCallbackInfo, 0, _validationCallbackInfo.Count); } else { validationCallbackInfo = null; } return new HttpCachePolicySettings( _isModified, validationCallbackInfo, _hasSetCookieHeader, _noServerCaching, _cacheExtension, _noTransforms, _ignoreRangeRequests, varyByContentEncodings, varyByHeaders, varyByParams, _varyByCustom, _cacheability, _noStore, privateFields, noCacheFields, _utcExpires, _isExpiresSet, _maxAge, _isMaxAgeSet, _proxyMaxAge, _isProxyMaxAgeSet, _slidingExpiration, _slidingDelta, _utcTimestampCreated, _validUntilExpires, _allowInHistory, _revalidation, _utcLastModified, _isLastModifiedSet, _etag, _generateLastModifiedFromFiles, _generateEtagFromFiles, _omitVaryStar, _headerCacheControl, _headerPragma, _headerExpires, _headerLastModified, _headerEtag, _headerVaryBy, _hasUserProvidedDependencies); } internal bool HasValidationPolicy() { return _generateLastModifiedFromFiles || _generateEtagFromFiles || _validationCallbackInfo != null || (_validUntilExpires == 1 && _slidingExpiration != 1); } internal bool HasExpirationPolicy() { return _slidingExpiration != 1 && (_isExpiresSet || _isMaxAgeSet); } internal bool IsKernelCacheable(HttpRequest request, bool enableKernelCacheForVaryByStar) { return _cacheability == HttpCacheability.Public && !_hasUserProvidedDependencies // Consider ([....]): rework dependency model to support user-provided dependencies && !_hasSetCookieHeader && !_noServerCaching && HasExpirationPolicy() && _cacheExtension == null && !_varyByContentEncodings.IsModified() && !_varyByHeaders.IsModified() && (!_varyByParams.IsModified() || _varyByParams.IgnoreParams || (_varyByParams.IsVaryByStar && enableKernelCacheForVaryByStar)) && !_noStore && _varyByCustom == null && _privateFields == null && _noCacheFields == null && _validationCallbackInfo == null && (request != null && request.HttpVerb == HttpVerb.GET); } // VSUQFE 4225: expose some cache policy info // because ISAPIWorkerRequestInProcForIIS6.CheckKernelModeCacheability needs to know about it internal bool IsVaryByStar {get {return _varyByParams.IsVaryByStar; }} internal DateTime UtcGetAbsoluteExpiration() { DateTime absoluteExpiration = Cache.NoAbsoluteExpiration; Debug.Assert(_utcTimestampCreated != DateTime.MinValue, "_utcTimestampCreated != DateTime.MinValue"); if (_slidingExpiration != 1) { if (_isMaxAgeSet) { absoluteExpiration = _utcTimestampCreated + _maxAge; } else if (_isExpiresSet) { absoluteExpiration = _utcExpires; } } return absoluteExpiration; } /* * Cache at server? */ /// <devdoc> /// <para>A call to this method stops all server caching for the current response. </para> /// </devdoc> public void SetNoServerCaching() { Dirtied(); _noServerCaching = true; } internal bool GetNoServerCaching() { return _noServerCaching; } internal void SetHasSetCookieHeader() { Dirtied(); _hasSetCookieHeader = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetVaryByCustom(string custom) { if (custom == null) { throw new ArgumentNullException("custom"); } if (_varyByCustom != null) { throw new InvalidOperationException(SR.GetString(SR.VaryByCustom_already_set)); } Dirtied(); _varyByCustom = custom; } /* * Cache-Control: extension */ /// <devdoc> /// <para>Appends a cache control extension directive to the Cache-Control: header.</para> /// </devdoc> public void AppendCacheExtension(String extension) { if (extension == null) { throw new ArgumentNullException("extension"); } Dirtied(); if (_cacheExtension == null) { _cacheExtension = extension; } else { _cacheExtension = _cacheExtension + ", " + extension; } } /* * Cache-Control: no-transform */ /// <devdoc> /// <para>Enables the sending of the CacheControl: /// no-transform directive.</para> /// </devdoc> public void SetNoTransforms() { Dirtied(); _noTransforms = true; } internal void SetIgnoreRangeRequests() { Dirtied(); _ignoreRangeRequests = true; } /// <devdoc> /// <para>Contains policy for the Vary: header.</para> /// </devdoc> public HttpCacheVaryByContentEncodings VaryByContentEncodings { get { return _varyByContentEncodings; } } /// <devdoc> /// <para>Contains policy for the Vary: header.</para> /// </devdoc> public HttpCacheVaryByHeaders VaryByHeaders { get { return _varyByHeaders; } } /// <devdoc> /// <para>Contains params to vary GETs and POSTs by.</para> /// </devdoc> public HttpCacheVaryByParams VaryByParams { get { return _varyByParams; } } /* * Cacheability policy * * Cache-Control: public | private[=1#field] | no-cache[=1#field] | no-store */ /// <devdoc> /// <para>Sets the Cache-Control header to one of the values of /// HttpCacheability. This is used to enable the Cache-Control: public, private, and no-cache directives.</para> /// </devdoc> public void SetCacheability(HttpCacheability cacheability) { if ((int) cacheability < (int) HttpCacheabilityLimits.MinValue || (int) HttpCacheabilityLimits.MaxValue < (int) cacheability) { throw new ArgumentOutOfRangeException("cacheability"); } if (s_cacheabilityValues[(int)cacheability] < s_cacheabilityValues[(int)_cacheability]) { Dirtied(); _cacheability = cacheability; } } internal HttpCacheability GetCacheability() { return _cacheability; } /// <devdoc> /// <para>Sets the Cache-Control header to one of the values of HttpCacheability in /// conjunction with a field-level exclusion directive.</para> /// </devdoc> public void SetCacheability(HttpCacheability cacheability, String field) { if (field == null) { throw new ArgumentNullException("field"); } switch (cacheability) { case HttpCacheability.Private: if (_privateFields == null) { _privateFields = new HttpDictionary(); } _privateFields.SetValue(field, field); break; case HttpCacheability.NoCache: if (_noCacheFields == null) { _noCacheFields = new HttpDictionary(); } _noCacheFields.SetValue(field, field); break; default: throw new ArgumentException( SR.GetString(SR.Cacheability_for_field_must_be_private_or_nocache), "cacheability"); } Dirtied(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetNoStore() { Dirtied(); _noStore = true; } internal void SetDependencies(bool hasUserProvidedDependencies) { Dirtied(); _hasUserProvidedDependencies = hasUserProvidedDependencies; } /* * Expiration policy. */ /* * Expires: RFC date */ /// <devdoc> /// <para>Sets the Expires: header to the given absolute date.</para> /// </devdoc> public void SetExpires(DateTime date) { DateTime utcDate, utcNow; utcDate = DateTimeUtil.ConvertToUniversalTime(date); utcNow = DateTime.UtcNow; if (utcDate - utcNow > s_oneYear) { utcDate = utcNow + s_oneYear; } if (!_isExpiresSet || utcDate < _utcExpires) { Dirtied(); _utcExpires = utcDate; _isExpiresSet = true; } } /* * Cache-Control: max-age=delta-seconds */ /// <devdoc> /// <para>Sets Cache-Control: s-maxage based on the specified time span</para> /// </devdoc> public void SetMaxAge(TimeSpan delta) { if (delta < TimeSpan.Zero) { throw new ArgumentOutOfRangeException("delta"); } if (s_oneYear < delta) { delta = s_oneYear; } if (!_isMaxAgeSet || delta < _maxAge) { Dirtied(); _maxAge = delta; _isMaxAgeSet = true; } } // Suppress max-age and s-maxage in cache-control header (required for IIS6 kernel mode cache) internal void SetNoMaxAgeInCacheControl() { _noMaxAgeInCacheControl = true; } /* * Cache-Control: s-maxage=delta-seconds */ /// <devdoc> /// <para>Sets the Cache-Control: s-maxage header based on the specified time span.</para> /// </devdoc> public void SetProxyMaxAge(TimeSpan delta) { if (delta < TimeSpan.Zero) { throw new ArgumentOutOfRangeException("delta"); } if (!_isProxyMaxAgeSet || delta < _proxyMaxAge) { Dirtied(); _proxyMaxAge = delta; _isProxyMaxAgeSet = true; } } /* * Sliding Expiration */ /// <devdoc> /// <para>Make expiration sliding: that is, if cached, it should be renewed with each /// response. This feature is identical in spirit to the IIS /// configuration option to add an expiration header relative to the current response /// time. This feature is identical in spirit to the IIS configuration option to add /// an expiration header relative to the current response time.</para> /// </devdoc> public void SetSlidingExpiration(bool slide) { if (_slidingExpiration == -1 || _slidingExpiration == 1) { Dirtied(); _slidingExpiration = (slide) ? 1 : 0; } } public void SetValidUntilExpires(bool validUntilExpires) { if (_validUntilExpires == -1 || _validUntilExpires == 1) { Dirtied(); _validUntilExpires = (validUntilExpires) ? 1 : 0; } } public void SetAllowResponseInBrowserHistory(bool allow) { if (_allowInHistory == -1 || _allowInHistory == 1) { Dirtied(); _allowInHistory = (allow) ? 1 : 0; } } /* * Validation policy. */ /* * Cache-control: must-revalidate | proxy-revalidate */ /// <devdoc> /// <para>Set the Cache-Control: header to reflect either the must-revalidate or /// proxy-revalidate directives based on the supplied value. The default is to /// not send either of these directives unless explicitly enabled using this /// method.</para> /// </devdoc> public void SetRevalidation(HttpCacheRevalidation revalidation) { if ((int) revalidation < (int) HttpCacheRevalidationLimits.MinValue || (int) HttpCacheRevalidationLimits.MaxValue < (int) revalidation) { throw new ArgumentOutOfRangeException("revalidation"); } if ((int) revalidation < (int) _revalidation) { Dirtied(); _revalidation = revalidation; } } /* * Etag */ /// <devdoc> /// <para>Set the ETag header to the supplied string. Once an ETag is set, /// subsequent attempts to set it will fail and an exception will be thrown.</para> /// </devdoc> public void SetETag(String etag) { if (etag == null) { throw new ArgumentNullException("etag"); } if (_etag != null) { throw new InvalidOperationException(SR.GetString(SR.Etag_already_set)); } if (_generateEtagFromFiles) { throw new InvalidOperationException(SR.GetString(SR.Cant_both_set_and_generate_Etag)); } Dirtied(); _etag = etag; } /* * Last-Modified: RFC Date */ /// <devdoc> /// <para>Set the Last-Modified: header to the DateTime value supplied. If this /// violates the restrictiveness hierarchy, this method will fail.</para> /// </devdoc> public void SetLastModified(DateTime date) { DateTime utcDate = DateTimeUtil.ConvertToUniversalTime(date); UtcSetLastModified(utcDate); } void UtcSetLastModified(DateTime utcDate) { /* * DevDiv# 545481 * Time may differ if the system time changes in the middle of the request. * Adjust the timestamp to Now if necessary. */ DateTime utcNow = DateTime.UtcNow; if (utcDate > utcNow) { utcDate = utcNow; } /* * Because HTTP dates have a resolution of 1 second, we * need to store dates with 1 second resolution or comparisons * will be off. */ utcDate = new DateTime(utcDate.Ticks - (utcDate.Ticks % TimeSpan.TicksPerSecond)); if (!_isLastModifiedSet || utcDate > _utcLastModified) { Dirtied(); _utcLastModified = utcDate; _isLastModifiedSet = true; } } /// <devdoc> /// <para>Sets the Last-Modified: header based on the timestamps of the /// file dependencies of the handler.</para> /// </devdoc> public void SetLastModifiedFromFileDependencies() { Dirtied(); _generateLastModifiedFromFiles = true; } /// <devdoc> /// <para>Sets the Etag header based on the timestamps of the file /// dependencies of the handler.</para> /// </devdoc> public void SetETagFromFileDependencies() { if (_etag != null) { throw new InvalidOperationException(SR.GetString(SR.Cant_both_set_and_generate_Etag)); } Dirtied(); _generateEtagFromFiles = true; } public void SetOmitVaryStar(bool omit) { Dirtied(); if (_omitVaryStar == -1 || _omitVaryStar == 1) { Dirtied(); _omitVaryStar = (omit) ? 1 : 0; } } /// <devdoc> /// <para>Registers a validation callback for the current response.</para> /// </devdoc> public void AddValidationCallback( HttpCacheValidateHandler handler, Object data) { if (handler == null) { throw new ArgumentNullException("handler"); } Dirtied(); if (_validationCallbackInfo == null) { _validationCallbackInfo = new ArrayList(); } _validationCallbackInfo.Add(new ValidationCallbackInfo(handler, data)); } } }
using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Security; using System.Text; // ReSharper disable once CheckNamespace namespace System.Diagnostics { /// <summary> /// Provides extension methods for <see cref="StackTrace" />. /// Based on: https://github.com/aelij/AsyncFriendlyStackTrace /// </summary> public static class StackTraceExtensions { private const string AtString = "at"; private const string LineFormat = "in {0}:line {1}"; private const string AsyncMethodPrefix = "async "; /// <summary> /// Produces an async-friendly readable representation of the stack trace. /// </summary> /// <remarks> /// The async-friendly formatting is achieved by: /// * Skipping all awaiter frames (all methods in types implementing <see cref="IAsyncStateMachine" />). /// * Inferring the original method name from the async state machine class (<see cref="IAsyncStateMachine" />) /// and removing the "MoveNext" - currently only for C#. /// * Adding the "async" prefix after "at" on each line for async invocations. /// * Appending "(?)" to the method signature to indicate that parameter information is missing. /// * Removing the "End of stack trace from previous location..." text. /// </remarks> /// <param name="stackTrace">The stack trace.</param> /// <returns>An async-friendly readable representation of the stack trace.</returns> public static string ToAsyncString(this StackTrace stackTrace) { if (stackTrace == null) throw new ArgumentNullException(nameof(stackTrace)); var stackFrames = stackTrace.GetFrames(); if (stackFrames == null) return string.Empty; var displayFilenames = true; var firstFrame = true; var stringBuilder = new StringBuilder(255); foreach (var frame in stackFrames) { var method = frame.GetMethod(); if (method == null) continue; var declaringType = method.DeclaringType?.GetTypeInfo(); // skip awaiters if (declaringType != null && (typeof(INotifyCompletion).GetTypeInfo().IsAssignableFrom(declaringType) || method.DeclaringType == typeof(ExceptionDispatchInfo))) { continue; } if (firstFrame) { firstFrame = false; } else { stringBuilder.Append(Environment.NewLine); } stringBuilder.AppendFormat(CultureInfo.InvariantCulture, " {0} ", AtString); var isAsync = FormatMethodName(stringBuilder, declaringType); if (!isAsync) { stringBuilder.Append(method.Name); if (method is MethodInfo methodInfo && methodInfo.IsGenericMethod) { FormatGenericArguments(stringBuilder, methodInfo.GetGenericArguments()); } } else if (declaringType?.IsGenericType == true) { // ReSharper disable once PossibleNullReferenceException FormatGenericArguments(stringBuilder, declaringType.GenericTypeArguments); } stringBuilder.Append("("); if (isAsync) { stringBuilder.Append("?"); } else { FormatParameters(stringBuilder, method); } stringBuilder.Append(")"); displayFilenames = FormatFileName(displayFilenames, frame, stringBuilder); } return stringBuilder.ToString(); } private static bool FormatMethodName(StringBuilder stringBuilder, TypeInfo declaringType) { if (declaringType == null) return false; var isAsync = false; var fullName = declaringType.FullName.Replace('+', '.'); if (typeof(IAsyncStateMachine).GetTypeInfo().IsAssignableFrom(declaringType)) { isAsync = true; stringBuilder.Append(AsyncMethodPrefix); var start = fullName.LastIndexOf('<'); var end = fullName.LastIndexOf('>'); if (start >= 0 && end >= 0) { stringBuilder.Append(fullName.Remove(start, 1).Substring(0, end - 1)); } else { stringBuilder.Append(fullName); } } else { stringBuilder.Append(fullName); stringBuilder.Append("."); } return isAsync; } private static bool FormatFileName(bool displayFilenames, StackFrame frame, StringBuilder stringBuilder) { if (displayFilenames && frame.GetILOffset() != -1) { string text = null; try { text = frame.GetFileName(); } catch (NotSupportedException) { displayFilenames = false; } catch (SecurityException) { displayFilenames = false; } if (text != null) { stringBuilder.Append(' '); stringBuilder.AppendFormat(CultureInfo.InvariantCulture, LineFormat, text, frame.GetFileLineNumber()); } } return displayFilenames; } private static void FormatParameters(StringBuilder stringBuilder, MethodBase method) { var parameters = method.GetParameters(); var firstParam = true; foreach (var t in parameters) { if (!firstParam) { stringBuilder.Append(", "); } else { firstParam = false; } // ReSharper disable once ConstantConditionalAccessQualifier // ReSharper disable once ConstantNullCoalescingCondition var typeName = t.ParameterType?.Name ?? "<UnknownType>"; stringBuilder.Append(typeName + " " + t.Name); } } private static void FormatGenericArguments(StringBuilder stringBuilder, Type[] genericArguments) { stringBuilder.Append("["); var k = 0; var firstTypeParam = true; while (k < genericArguments.Length) { if (!firstTypeParam) { stringBuilder.Append(","); } else { firstTypeParam = false; } stringBuilder.Append(genericArguments[k].Name); k++; } stringBuilder.Append("]"); } } }
using System; using System.Drawing; using System.Linq; using System.Windows.Forms; using hw.DebugFormatter; using hw.Helper; using JetBrains.Annotations; // ReSharper disable ConvertMethodToExpressionBody // ReSharper disable MergeConditionalExpression namespace hw.Forms { /// <summary> /// Used to persist location of window of parent /// </summary> [PublicAPI] public sealed class PositionConfig : IDisposable { readonly Func<string> GetFileName; Form InternalTarget; bool LoadPositionCalled; /// <summary> /// Ctor /// </summary> /// <param name="getFileName"> /// function to obtain filename of configuration file. /// <para>It will be called each time the name is required. </para> /// <para>Default: Target.Name</para> /// </param> public PositionConfig(Func<string> getFileName = null) => GetFileName = getFileName ?? (() => InternalTarget == null? null : InternalTarget.Name); /// <summary> /// Form that will be controlled by this instance /// </summary> public Form Target { [UsedImplicitly] get => InternalTarget; set { Disconnect(); InternalTarget = value; Connect(); } } /// <summary> /// Name that will be used as filename /// </summary> public string FileName => GetFileName(); Rectangle? Position { get => Convert (0, null, s => (Rectangle?)new RectangleConverter().ConvertFromString(s)); set => Save(value, WindowState); } string[] ParameterStrings { get { if(InternalTarget == null) return null; var content = FileHandle.String; return content == null? null : content.Split('\n'); } } SmbFile FileHandle { get { var fileName = FileName; return fileName == null? null : fileName.ToSmbFile(); } } FormWindowState WindowState { get => Convert(1, FormWindowState.Normal, s => s.Parse<FormWindowState>()); set => Save(Position, value); } void IDisposable.Dispose() { Disconnect(); } void Disconnect() { if(InternalTarget == null) return; InternalTarget.SuspendLayout(); LoadPositionCalled = false; InternalTarget.Load -= OnLoad; InternalTarget.LocationChanged -= OnLocationChanged; InternalTarget.SizeChanged -= OnLocationChanged; InternalTarget.ResumeLayout(); InternalTarget = null; } void Connect() { if(InternalTarget == null) return; InternalTarget.SuspendLayout(); LoadPositionCalled = false; InternalTarget.Load += OnLoad; InternalTarget.LocationChanged += OnLocationChanged; InternalTarget.SizeChanged += OnLocationChanged; InternalTarget.ResumeLayout(); } void OnLocationChanged(object target, EventArgs e) { if(target != InternalTarget) return; SavePosition(); } void OnLoad(object target, EventArgs e) { if(target != InternalTarget) return; LoadPosition(); } void Save(Rectangle? position, FormWindowState state) { var fileHandle = FileHandle; (fileHandle != null).Assert(); fileHandle.String = "{0}\n{1}" .ReplaceArgs ( position == null? "" : new RectangleConverter().ConvertToString(position.Value), state ); } T Convert<T>(int position, T defaultValue, Func<string, T> converter) { return ParameterStrings == null || ParameterStrings.Length <= position ? defaultValue : converter(ParameterStrings[position]); } void LoadPosition() { var fileHandle = FileHandle; (fileHandle != null).Assert(); if(fileHandle.String != null) { var position = Position; (position != null).Assert(); InternalTarget.SuspendLayout(); InternalTarget.StartPosition = FormStartPosition.Manual; InternalTarget.Bounds = EnsureVisible(position.Value); InternalTarget.WindowState = WindowState; InternalTarget.ResumeLayout(true); } LoadPositionCalled = true; } void SavePosition() { if(!LoadPositionCalled) return; if(InternalTarget.WindowState == FormWindowState.Normal) Position = InternalTarget.Bounds; WindowState = InternalTarget.WindowState; } static Rectangle EnsureVisible(Rectangle value) { var allScreens = Screen.AllScreens; if(allScreens.Any(s => s.Bounds.IntersectsWith(value))) return value; var closestScreen = Screen.FromRectangle(value); var result = value; var leftDistance = value.Left - closestScreen.Bounds.Right; var rightDistance = value.Right - closestScreen.Bounds.Left; if(leftDistance > 0 && rightDistance > 0) result.X += leftDistance < rightDistance? -(leftDistance + 10) : rightDistance + 10; var topDistance = value.Top - closestScreen.Bounds.Bottom; var bottomDistance = value.Bottom - closestScreen.Bounds.Top; if(topDistance > 0 && bottomDistance > 0) result.Y += topDistance < bottomDistance? -(topDistance + 10) : bottomDistance + 10; closestScreen.Bounds.IntersectsWith(result).Assert(); return result; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Core.Scoping; using Umbraco.Core.Services; namespace Umbraco.Core.Publishing { //TODO: Do we need this anymore?? - get rid of it! /// <summary> /// Currently acts as an interconnection between the new public api and the legacy api for publishing /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public class PublishingStrategy : BasePublishingStrategy, IPublishingStrategy2 { private readonly IScopeProvider _scopeProvider; private readonly IEventMessagesFactory _eventMessagesFactory; private readonly ILogger _logger; [Obsolete("This class is not intended to be used, it will be removed in future versions")] [EditorBrowsable(EditorBrowsableState.Never)] public PublishingStrategy(IEventMessagesFactory eventMessagesFactory, ILogger logger) { if (eventMessagesFactory == null) throw new ArgumentNullException("eventMessagesFactory"); if (logger == null) throw new ArgumentNullException("logger"); _scopeProvider = new ScopeProvider(new DefaultDatabaseFactory(Constants.System.UmbracoConnectionName, logger)); _eventMessagesFactory = eventMessagesFactory; _logger = logger; } [EditorBrowsable(EditorBrowsableState.Never)] public PublishingStrategy(IScopeProvider scopeProvider, IEventMessagesFactory eventMessagesFactory, ILogger logger) { if (eventMessagesFactory == null) throw new ArgumentNullException("eventMessagesFactory"); if (logger == null) throw new ArgumentNullException("logger"); _scopeProvider = scopeProvider; _eventMessagesFactory = eventMessagesFactory; _logger = logger; } /// <summary> /// Publishes a single piece of Content /// </summary> /// <param name="uow"></param> /// <param name="content"><see cref="IContent"/> to publish</param> /// <param name="userId">Id of the User issueing the publish operation</param> Attempt<PublishStatus> IPublishingStrategy2.Publish(IScopeUnitOfWork uow, IContent content, int userId) { var evtMsgs = _eventMessagesFactory.Get(); if (uow.Events.DispatchCancelable(Publishing, this, new PublishEventArgs<IContent>(content, evtMsgs), "Publishing")) { _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' will not be published, the event was cancelled.", content.Name, content.Id)); return Attempt<PublishStatus>.Fail(new PublishStatus(content, PublishStatusType.FailedCancelledByEvent, evtMsgs)); } //Check if the Content is Expired to verify that it can in fact be published if (content.Status == ContentStatus.Expired) { _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' has expired and could not be published.", content.Name, content.Id)); return Attempt<PublishStatus>.Fail(new PublishStatus(content, PublishStatusType.FailedHasExpired, evtMsgs)); } //Check if the Content is Awaiting Release to verify that it can in fact be published if (content.Status == ContentStatus.AwaitingRelease) { _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' is awaiting release and could not be published.", content.Name, content.Id)); return Attempt<PublishStatus>.Fail(new PublishStatus(content, PublishStatusType.FailedAwaitingRelease, evtMsgs)); } //Check if the Content is Trashed to verify that it can in fact be published if (content.Status == ContentStatus.Trashed) { _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' is trashed and could not be published.", content.Name, content.Id)); return Attempt<PublishStatus>.Fail(new PublishStatus(content, PublishStatusType.FailedIsTrashed, evtMsgs)); } content.ChangePublishedState(PublishedState.Published); _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' has been published.", content.Name, content.Id)); return Attempt.Succeed(new PublishStatus(content, evtMsgs)); } /// <summary> /// Publishes a single piece of Content /// </summary> /// <param name="content"><see cref="IContent"/> to publish</param> /// <param name="userId">Id of the User issueing the publish operation</param> /// <returns>True if the publish operation was successfull and not cancelled, otherwise false</returns> public override bool Publish(IContent content, int userId) { using (var uow = new ScopeUnitOfWork(_scopeProvider)) { uow.Commit(); return ((IPublishingStrategy2)this).Publish(uow, content, userId).Success; } } /// <summary> /// Publishes a list of content items /// </summary> /// <param name="uow"></param> /// <param name="content"></param> /// <param name="userId"></param> /// <param name="includeUnpublishedDocuments"> /// By default this is set to true which means that it will publish any content item in the list that is completely unpublished and /// not visible on the front-end. If set to false, this will only publish content that is live on the front-end but has new versions /// that have yet to be published. /// </param> /// <returns></returns> /// <remarks> /// /// This method becomes complex once we start to be able to cancel events or stop publishing a content item in any way because if a /// content item is not published then it's children shouldn't be published either. This rule will apply for the following conditions: /// * If a document fails to be published, do not proceed to publish it's children if: /// ** The document does not have a publish version /// ** The document does have a published version but the includeUnpublishedDocuments = false /// /// In order to do this, we will order the content by level and begin by publishing each item at that level, then proceed to the next /// level and so on. If we detect that the above rule applies when the document publishing is cancelled we'll add it to the list of /// parentsIdsCancelled so that it's children don't get published. /// /// Its important to note that all 'root' documents included in the list *will* be published regardless of the rules mentioned /// above (unless it is invalid)!! By 'root' documents we are referring to documents in the list with the minimum value for their 'level'. /// In most cases the 'root' documents will only be one document since under normal circumstance we only publish one document and /// its children. The reason we have to do this is because if a user is publishing a document and it's children, it is implied that /// the user definitely wants to publish it even if it has never been published before. /// /// </remarks> IEnumerable<Attempt<PublishStatus>> IPublishingStrategy2.PublishWithChildren(IScopeUnitOfWork uow, IEnumerable<IContent> content, int userId, bool includeUnpublishedDocuments) { var statuses = new List<Attempt<PublishStatus>>(); //a list of all document ids that had their publishing cancelled during these iterations. //this helps us apply the rule listed in the notes above by checking if a document's parent id //matches one in this list. var parentsIdsCancelled = new List<int>(); //group by levels and iterate over the sorted ascending level. //TODO: This will cause all queries to execute, they will not be lazy but I'm not really sure being lazy actually made // much difference because we iterate over them all anyways?? Morten? // Because we're grouping I think this will execute all the queries anyways so need to fetch it all first. var fetchedContent = content.ToArray(); var evtMsgs = _eventMessagesFactory.Get(); //We're going to populate the statuses with all content that is already published because below we are only going to iterate over // content that is not published. We'll set the status to "AlreadyPublished" statuses.AddRange(fetchedContent.Where(x => x.Published) .Select(x => Attempt.Succeed(new PublishStatus(x, PublishStatusType.SuccessAlreadyPublished, evtMsgs)))); int? firstLevel = null; //group by level and iterate over each level (sorted ascending) var levelGroups = fetchedContent.GroupBy(x => x.Level); foreach (var level in levelGroups.OrderBy(x => x.Key)) { //set the first level flag, used to ensure that all documents at the first level will //be published regardless of the rules mentioned in the remarks. if (!firstLevel.HasValue) { firstLevel = level.Key; } /* Only update content thats not already been published - we want to loop through * all unpublished content to write skipped content (expired and awaiting release) to log. */ foreach (var item in level.Where(x => x.Published == false)) { //Check if this item should be excluded because it's parent's publishing has failed/cancelled if (parentsIdsCancelled.Contains(item.ParentId)) { _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' will not be published because it's parent's publishing action failed or was cancelled.", item.Name, item.Id)); //if this cannot be published, ensure that it's children can definitely not either! parentsIdsCancelled.Add(item.Id); continue; } //Check if this item has never been published (and that it is not at the root level) if (item.Level != firstLevel && !includeUnpublishedDocuments && !item.HasPublishedVersion()) { //this item does not have a published version and the flag is set to not include them parentsIdsCancelled.Add(item.Id); continue; } //Fire Publishing event if (uow.Events.DispatchCancelable(Publishing, this, new PublishEventArgs<IContent>(item, evtMsgs), "Publishing")) { //the publishing has been cancelled. _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' will not be published, the event was cancelled.", item.Name, item.Id)); statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedCancelledByEvent, evtMsgs))); //Does this document apply to our rule to cancel it's children being published? CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments); continue; } //Check if the content is valid if the flag is set to check if (item.IsValid() == false) { _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' will not be published because some of it's content is not passing validation rules.", item.Name, item.Id)); statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedContentInvalid, evtMsgs) { InvalidProperties = ((ContentBase)item).LastInvalidProperties })); //Does this document apply to our rule to cancel it's children being published? CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments); continue; } //Check if the Content is Expired to verify that it can in fact be published if (item.Status == ContentStatus.Expired) { _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' has expired and could not be published.", item.Name, item.Id)); statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedHasExpired, evtMsgs))); //Does this document apply to our rule to cancel it's children being published? CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments); continue; } //Check if the Content is Awaiting Release to verify that it can in fact be published if (item.Status == ContentStatus.AwaitingRelease) { _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' is awaiting release and could not be published.", item.Name, item.Id)); statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedAwaitingRelease, evtMsgs))); //Does this document apply to our rule to cancel it's children being published? CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments); continue; } //Check if the Content is Trashed to verify that it can in fact be published if (item.Status == ContentStatus.Trashed) { _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' is trashed and could not be published.", item.Name, item.Id)); statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedIsTrashed, evtMsgs))); //Does this document apply to our rule to cancel it's children being published? CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments); continue; } item.ChangePublishedState(PublishedState.Published); _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' has been published.", item.Name, item.Id)); statuses.Add(Attempt.Succeed(new PublishStatus(item, evtMsgs))); } } return statuses; } /// <summary> /// Based on the information provider we'll check if we should cancel the publishing of this document's children /// </summary> /// <param name="content"></param> /// <param name="parentsIdsCancelled"></param> /// <param name="includeUnpublishedDocuments"></param> /// <remarks> /// See remarks on method: PublishWithChildrenInternal /// </remarks> private void CheckCancellingOfChildPublishing(IContent content, List<int> parentsIdsCancelled, bool includeUnpublishedDocuments) { //Does this document apply to our rule to cancel it's children being published? //TODO: We're going back to the service layer here... not sure how to avoid this? And this will add extra overhead to // any document that fails to publish... var hasPublishedVersion = ApplicationContext.Current.Services.ContentService.HasPublishedVersion(content.Id); if (hasPublishedVersion && includeUnpublishedDocuments == false) { //it has a published version but our flag tells us to not include un-published documents and therefore we should // not be forcing decendant/child documents to be published if their parent fails. parentsIdsCancelled.Add(content.Id); } else if (hasPublishedVersion == false) { //it doesn't have a published version so we certainly cannot publish it's children. parentsIdsCancelled.Add(content.Id); } } /// <summary> /// Publishes a list of Content /// </summary> /// <param name="content">An enumerable list of <see cref="IContent"/></param> /// <param name="userId">Id of the User issueing the publish operation</param> /// <returns>True if the publish operation was successfull and not cancelled, otherwise false</returns> public override bool PublishWithChildren(IEnumerable<IContent> content, int userId) { using (var uow = new ScopeUnitOfWork(_scopeProvider)) { var result = ((IPublishingStrategy2)this).PublishWithChildren(uow, content, userId, true); uow.Commit(); //NOTE: This previously always returned true so I've left it that way. It returned true because (from Morten)... // ... if one item couldn't be published it wouldn't be correct to return false. // in retrospect it should have returned a list of with Ids and Publish Status // come to think of it ... the cache would still be updated for a failed item or at least tried updated. // It would call the Published event for the entire list, but if the Published property isn't set to True it // wouldn't actually update the cache for that item. But not really ideal nevertheless... return true; } } /// <summary> /// Unpublishes a single piece of Content /// </summary> /// <param name="content"><see cref="IContent"/> to unpublish</param> /// <param name="userId">Id of the User issueing the unpublish operation</param> /// <returns>True if the unpublish operation was successfull and not cancelled, otherwise false</returns> public override bool UnPublish(IContent content, int userId) { using (var uow = new ScopeUnitOfWork(_scopeProvider)) { uow.Commit(); return ((IPublishingStrategy2)this).UnPublish(uow, content, userId).Success; } } /// <summary> /// Unpublishes a list of Content /// </summary> /// <param name="uow"></param> /// <param name="content">An enumerable list of <see cref="IContent"/></param> /// <param name="userId">Id of the User issueing the unpublish operation</param> /// <returns>A list of publish statuses</returns> private IEnumerable<Attempt<PublishStatus>> UnPublishInternal(IScopeUnitOfWork uow, IEnumerable<IContent> content, int userId) { return content.Select(x => ((IPublishingStrategy2)this).UnPublish(uow, x, userId)); } Attempt<PublishStatus> IPublishingStrategy2.UnPublish(IScopeUnitOfWork uow, IContent content, int userId) { // content should (is assumed to ) be the newest version, which may not be published // don't know how to test this, so it's not verified // NOTE // if published != newest, then the published flags need to be reseted by whoever is calling that method // at the moment it's done by the content service var evtMsgs = _eventMessagesFactory.Get(); //Fire UnPublishing event if (uow.Events.DispatchCancelable(UnPublishing, this, new PublishEventArgs<IContent>(content, evtMsgs), "UnPublishing")) { _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' will not be unpublished, the event was cancelled.", content.Name, content.Id)); return Attempt.Fail(new PublishStatus(content, PublishStatusType.FailedCancelledByEvent, evtMsgs)); } //If Content has a release date set to before now, it should be removed so it doesn't interrupt an unpublish //Otherwise it would remain released == published if (content.ReleaseDate.HasValue && content.ReleaseDate.Value <= DateTime.Now) { content.ReleaseDate = null; _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' had its release date removed, because it was unpublished.", content.Name, content.Id)); } // make sure we dirty .Published and always unpublish // the version we have here could be the newest, !Published content.ChangePublishedState(PublishedState.Published); content.ChangePublishedState(PublishedState.Unpublished); _logger.Info<PublishingStrategy>( string.Format("Content '{0}' with Id '{1}' has been unpublished.", content.Name, content.Id)); return Attempt.Succeed(new PublishStatus(content, evtMsgs)); } /// <summary> /// Unpublishes a list of Content /// </summary> /// <param name="content">An enumerable list of <see cref="IContent"/></param> /// <param name="userId">Id of the User issueing the unpublish operation</param> /// <returns>True if the unpublish operation was successfull and not cancelled, otherwise false</returns> public override bool UnPublish(IEnumerable<IContent> content, int userId) { using (var uow = new ScopeUnitOfWork(_scopeProvider)) { var result = UnPublishInternal(uow, content, userId); uow.Commit(); //NOTE: This previously always returned true so I've left it that way. It returned true because (from Morten)... // ... if one item couldn't be published it wouldn't be correct to return false. // in retrospect it should have returned a list of with Ids and Publish Status // come to think of it ... the cache would still be updated for a failed item or at least tried updated. // It would call the Published event for the entire list, but if the Published property isn't set to True it // wouldn't actually update the cache for that item. But not really ideal nevertheless... return true; } } /// <summary> /// Call to fire event that updating the published content has finalized. /// </summary> /// <remarks> /// This seperation of the OnPublished event is done to ensure that the Content /// has been properly updated (committed unit of work) and xml saved in the db. /// </remarks> /// <param name="content"><see cref="IContent"/> thats being published</param> public override void PublishingFinalized(IContent content) { using (var uow = new ScopeUnitOfWork(_scopeProvider)) { ((IPublishingStrategy2) this).PublishingFinalized(uow, content); uow.Commit(); } } /// <summary> /// Call to fire event that updating the published content has finalized. /// </summary> /// <param name="content">An enumerable list of <see cref="IContent"/> thats being published</param> /// <param name="isAllRepublished">Boolean indicating whether its all content that is republished</param> public override void PublishingFinalized(IEnumerable<IContent> content, bool isAllRepublished) { using (var uow = new ScopeUnitOfWork(_scopeProvider)) { ((IPublishingStrategy2)this).PublishingFinalized(uow, content, isAllRepublished); uow.Commit(); } } /// <summary> /// Call to fire event that updating the unpublished content has finalized. /// </summary> /// <param name="content"><see cref="IContent"/> thats being unpublished</param> public override void UnPublishingFinalized(IContent content) { using (var uow = new ScopeUnitOfWork(_scopeProvider)) { ((IPublishingStrategy2)this).UnPublishingFinalized(uow, content); uow.Commit(); } } /// <summary> /// Call to fire event that updating the unpublished content has finalized. /// </summary> /// <param name="content">An enumerable list of <see cref="IContent"/> thats being unpublished</param> public override void UnPublishingFinalized(IEnumerable<IContent> content) { using (var uow = new ScopeUnitOfWork(_scopeProvider)) { ((IPublishingStrategy2)this).UnPublishingFinalized(uow, content); uow.Commit(); } } /// <summary> /// Occurs before publish /// </summary> [Obsolete("Use events on the ContentService")] [EditorBrowsable(EditorBrowsableState.Never)] public static event TypedEventHandler<IPublishingStrategy, PublishEventArgs<IContent>> Publishing; /// <summary> /// Occurs after publish /// </summary> [Obsolete("Use events on the ContentService")] [EditorBrowsable(EditorBrowsableState.Never)] public static event TypedEventHandler<IPublishingStrategy, PublishEventArgs<IContent>> Published; /// <summary> /// Occurs before unpublish /// </summary> [Obsolete("Use events on the ContentService")] [EditorBrowsable(EditorBrowsableState.Never)] public static event TypedEventHandler<IPublishingStrategy, PublishEventArgs<IContent>> UnPublishing; /// <summary> /// Occurs after unpublish /// </summary> [Obsolete("Use events on the ContentService")] [EditorBrowsable(EditorBrowsableState.Never)] public static event TypedEventHandler<IPublishingStrategy, PublishEventArgs<IContent>> UnPublished; void IPublishingStrategy2.PublishingFinalized(IScopeUnitOfWork uow, IContent content) { var evtMsgs = _eventMessagesFactory.Get(); uow.Events.Dispatch(Published, this, new PublishEventArgs<IContent>(content, false, false, evtMsgs), "Published"); } void IPublishingStrategy2.PublishingFinalized(IScopeUnitOfWork uow, IEnumerable<IContent> content, bool isAllRepublished) { var evtMsgs = _eventMessagesFactory.Get(); uow.Events.Dispatch(Published, this, new PublishEventArgs<IContent>(content, false, isAllRepublished, evtMsgs), "Published"); } void IPublishingStrategy2.UnPublishingFinalized(IScopeUnitOfWork uow, IContent content) { var evtMsgs = _eventMessagesFactory.Get(); uow.Events.Dispatch(UnPublished, this, new PublishEventArgs<IContent>(content, false, false, evtMsgs), "UnPublished"); } void IPublishingStrategy2.UnPublishingFinalized(IScopeUnitOfWork uow, IEnumerable<IContent> content) { var evtMsgs = _eventMessagesFactory.Get(); uow.Events.Dispatch(UnPublished, this, new PublishEventArgs<IContent>(content, false, false, evtMsgs), "UnPublished"); } } }
namespace AgileObjects.AgileMapper.Extensions.Internal { using System; using System.Collections.Generic; #if NET35 using Microsoft.Scripting.Ast; #else using System.Linq.Expressions; #endif using NetStandardPolyfills; #if NET35 using static Microsoft.Scripting.Ast.ExpressionType; using LinqExp = System.Linq.Expressions; #else using static System.Linq.Expressions.ExpressionType; #endif internal static class ExpressionEvaluation { public static readonly IEqualityComparer<Expression> Equator = new ExpressionEquator(MemberAccessesAreEqual); public static readonly IEqualityComparer<Expression> Equivalator = new ExpressionEquator((x, y, e) => MemberAccessesAreEquivalent(x, y)); public static bool AreEqual(Expression x, Expression y) => Equator.Equals(x, y); public static bool AreEquivalent(Expression x, Expression y) => Equivalator.Equals(x, y); #region Member Access Evaluation private static bool MemberAccessesAreEqual( MemberExpression x, MemberExpression y, ExpressionEquator equator) { return MemberAccessesAreEquivalent(x, y) && equator.Equals(x.Expression, y.Expression); } public static bool MemberAccessesAreEquivalent(MemberExpression x, MemberExpression y) { if (ReferenceEquals(x.Member, y.Member)) { return true; } // ReSharper disable once PossibleNullReferenceException return (x.Member.Name == y.Member.Name) && x.Member.DeclaringType.IsAssignableTo(y.Member.DeclaringType); } #endregion private delegate bool MemberAccessComparer( MemberExpression x, MemberExpression y, ExpressionEquator e); private class ExpressionEquator : IEqualityComparer<Expression> { private readonly MemberAccessComparer _memberAccessComparer; public ExpressionEquator(MemberAccessComparer memberAccessComparer) { _memberAccessComparer = memberAccessComparer; } public bool Equals(Expression x, Expression y) { if (x == y) { return true; } while (true) { // ReSharper disable PossibleNullReferenceException if (x.NodeType != y.NodeType) { return false; } // ReSharper restore PossibleNullReferenceException switch (x.NodeType) { case Block: return AllEqual(((BlockExpression)x).Expressions, ((BlockExpression)y).Expressions); case Call: return AreEqual((MethodCallExpression)x, (MethodCallExpression)y); case Conditional: return AreEqual((ConditionalExpression)x, (ConditionalExpression)y); case Constant: #if NET35 return AreEqualNet35((ConstantExpression)x, (ConstantExpression)y); #else return AreEqual((ConstantExpression)x, (ConstantExpression)y); #endif case ArrayLength: case ExpressionType.Convert: case Negate: case NegateChecked: case Not: case TypeAs: return AreEqual((UnaryExpression)x, (UnaryExpression)y); case Default: return ((DefaultExpression)x).Type == ((DefaultExpression)y).Type; case Index: return AreEqual((IndexExpression)x, (IndexExpression)y); case Invoke: return AreEqual((InvocationExpression)x, (InvocationExpression)y); case Lambda: x = ((LambdaExpression)x).Body; y = ((LambdaExpression)y).Body; continue; case ListInit: return AreEqual((ListInitExpression)x, (ListInitExpression)y); case MemberAccess: return _memberAccessComparer.Invoke((MemberExpression)x, (MemberExpression)y, this); case Add: case AddChecked: case And: case AndAlso: case ArrayIndex: case Coalesce: case Divide: case Equal: case ExclusiveOr: case GreaterThan: case GreaterThanOrEqual: case LeftShift: case LessThan: case LessThanOrEqual: case Modulo: case Multiply: case MultiplyChecked: case NotEqual: case Or: case OrElse: case RightShift: case Subtract: case SubtractChecked: return AreEqual((BinaryExpression)x, (BinaryExpression)y); case MemberInit: return AreEqual((MemberInitExpression)x, (MemberInitExpression)y); case New: return AreEqual((NewExpression)x, (NewExpression)y); case NewArrayBounds: case NewArrayInit: return AreEqual((NewArrayExpression)x, (NewArrayExpression)y); case Parameter: return AreEqual((ParameterExpression)x, (ParameterExpression)y); case Quote: x = ((UnaryExpression)x).Operand; y = ((UnaryExpression)y).Operand; continue; case TypeIs: return AreEqual((TypeBinaryExpression)x, (TypeBinaryExpression)y); } throw new NotImplementedException("Unable to equate Expressions of type " + x.NodeType); } } private bool AllEqual(IList<Expression> xItems, IList<Expression> yItems) { if (xItems.Count != yItems.Count) { return false; } for (var i = 0; i < xItems.Count; i++) { if (!Equals(xItems[i], yItems[i])) { return false; } } return true; } private bool AreEqual(MethodCallExpression x, MethodCallExpression y) { return ReferenceEquals(x.Method, y.Method) && (((x.Object == null) && (y.Object == null)) || ((x.Object != null) && Equals(x.Object, y.Object))) && AllEqual(x.Arguments, y.Arguments); } private bool AreEqual(ConditionalExpression x, ConditionalExpression y) { return (x.Type == y.Type) && Equals(x.Test, y.Test) && Equals(x.IfTrue, y.IfTrue) && Equals(x.IfFalse, y.IfFalse); } #if NET35 private bool AreEqualNet35(ConstantExpression x, ConstantExpression y) { if (AreEqual(x, y)) { return true; } return (x.Type == y.Type) && (x.Value is LinqExp.Expression xExpression) && Equals(xExpression.ToDlrExpression(), ((LinqExp.Expression)y.Value).ToDlrExpression()); } #endif private static bool AreEqual(ConstantExpression x, ConstantExpression y) => ReferenceEquals(x.Value, y.Value) || x.Value.Equals(y.Value); private bool AreEqual(UnaryExpression x, UnaryExpression y) { return (x.Type == y.Type) && Equals(x.Operand, y.Operand); } private bool AreEqual(IndexExpression x, IndexExpression y) { return ReferenceEquals(x.Indexer, y.Indexer) && AllEqual(x.Arguments, y.Arguments); } private bool AreEqual(InvocationExpression x, InvocationExpression y) { return ReferenceEquals(x.Expression, y.Expression) && AllEqual(x.Arguments, y.Arguments); } private bool AreEqual(ListInitExpression x, ListInitExpression y) { return (x.Type == y.Type) && Equals(x.NewExpression, y.NewExpression) && AllEqual(x.Initializers, y.Initializers); } private bool AllEqual(IList<ElementInit> xInitializers, IList<ElementInit> yInitializers) { if (xInitializers.Count != yInitializers.Count) { return false; } for (var i = 0; i < xInitializers.Count; i++) { var x = xInitializers[i]; var y = yInitializers[i]; if (!ReferenceEquals(x.AddMethod, y.AddMethod) || !AllEqual(x.Arguments, y.Arguments)) { return false; } } return true; } private bool AreEqual(BinaryExpression x, BinaryExpression y) { return ReferenceEquals(x.Method, y.Method) && Equals(x.Left, y.Left) && Equals(x.Right, y.Right); } private bool AreEqual(MemberInitExpression x, MemberInitExpression y) { return Equals(x.NewExpression, y.NewExpression) && AllEqual(x.Bindings, y.Bindings); } private bool AllEqual(IList<MemberBinding> xBindings, IList<MemberBinding> yBindings) { if (xBindings.Count != yBindings.Count) { return false; } for (var i = 0; i < xBindings.Count; i++) { var x = xBindings[i]; var y = yBindings[i]; if ((x.BindingType != y.BindingType) || !ReferenceEquals(x.Member, y.Member)) { return false; } switch (x.BindingType) { case MemberBindingType.Assignment: if (Equals(((MemberAssignment)x).Expression, ((MemberAssignment)y).Expression)) { break; } return false; case MemberBindingType.MemberBinding: if (AllEqual(((MemberMemberBinding)x).Bindings, ((MemberMemberBinding)y).Bindings)) { break; } return false; case MemberBindingType.ListBinding: if (AreEqual((MemberListBinding)x, (MemberListBinding)y)) { break; } return false; } } return true; } private bool AreEqual(MemberListBinding x, MemberListBinding y) { if (x.Initializers.Count != y.Initializers.Count) { return false; } for (var i = 0; i < x.Initializers.Count; i++) { var xInitialiser = x.Initializers[i]; var yInitialiser = y.Initializers[i]; if (!ReferenceEquals(xInitialiser.AddMethod, yInitialiser.AddMethod) || !AllEqual(xInitialiser.Arguments, yInitialiser.Arguments)) { return false; } } return true; } private bool AreEqual(NewExpression x, NewExpression y) { return (x.Type == y.Type) && ReferenceEquals(x.Constructor, y.Constructor) && AllEqual(x.Arguments, y.Arguments); } private bool AreEqual(NewArrayExpression x, NewArrayExpression y) { return (x.Type == y.Type) && AllEqual(x.Expressions, y.Expressions); } private static bool AreEqual(ParameterExpression x, ParameterExpression y) { return (x.Type == y.Type) && (x.Name == y.Name); } private bool AreEqual(TypeBinaryExpression x, TypeBinaryExpression y) => (x.TypeOperand == y.TypeOperand) && Equals(x.Expression, y.Expression); public int GetHashCode(Expression obj) => 0; } } }
// 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.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsResourceFlattening { using System; using System.Collections.Generic; using System.Diagnostics; 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 System.Linq; using Microsoft.Rest.Azure; using Models; /// <summary> /// Resource Flattening for AutoRest /// </summary> public partial class AutoRestResourceFlatteningTestService : ServiceClient<AutoRestResourceFlatteningTestService>, IAutoRestResourceFlatteningTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// The management credentials for Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// The retry timeout for Long Running Operations. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> public AutoRestResourceFlatteningTestService() : base() { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestResourceFlatteningTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestResourceFlatteningTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestResourceFlatteningTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestResourceFlatteningTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestResourceFlatteningTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new Uri("http://localhost"); this.AcceptLanguage = "en-US"; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver() }; SerializationSettings.Converters.Add(new ResourceJsonConverter()); DeserializationSettings = new JsonSerializerSettings{ DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver() }; DeserializationSettings.Converters.Add(new ResourceJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Put External Resource as an Array /// </summary> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> PutArrayWithHttpMessagesAsync(IList<Resource> resourceArray = default(IList<Resource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceArray", resourceArray); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutArray", tracingParameters); } // Construct URL var url = new Uri(this.BaseUri, "/azure/resource-flatten/array").ToString(); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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); } } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Serialize Request string requestContent = JsonConvert.SerializeObject(resourceArray, this.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get External Resource as an Array /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IList<FlattenedProduct>>> GetArrayWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetArray", tracingParameters); } // Construct URL var url = new Uri(this.BaseUri, "/azure/resource-flatten/array").ToString(); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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); } } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<IList<FlattenedProduct>>(); 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 (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<IList<FlattenedProduct>>(responseContent, this.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put External Resource as a Dictionary /// </summary> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> PutDictionaryWithHttpMessagesAsync(IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceDictionary", resourceDictionary); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutDictionary", tracingParameters); } // Construct URL var url = new Uri(this.BaseUri, "/azure/resource-flatten/dictionary").ToString(); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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); } } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Serialize Request string requestContent = JsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get External Resource as a Dictionary /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IDictionary<string, FlattenedProduct>>> GetDictionaryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetDictionary", tracingParameters); } // Construct URL var url = new Uri(this.BaseUri, "/azure/resource-flatten/dictionary").ToString(); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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); } } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<IDictionary<string, FlattenedProduct>>(); 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 (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<IDictionary<string, FlattenedProduct>>(responseContent, this.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put External Resource as a ResourceCollection /// </summary> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> PutResourceCollectionWithHttpMessagesAsync(ResourceCollection resourceComplexObject = default(ResourceCollection), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceComplexObject", resourceComplexObject); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutResourceCollection", tracingParameters); } // Construct URL var url = new Uri(this.BaseUri, "/azure/resource-flatten/resourcecollection").ToString(); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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); } } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Serialize Request string requestContent = JsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get External Resource as a ResourceCollection /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ResourceCollection>> GetResourceCollectionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetResourceCollection", tracingParameters); } // Construct URL var url = new Uri(this.BaseUri, "/azure/resource-flatten/resourcecollection").ToString(); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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); } } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ResourceCollection>(); 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 (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ResourceCollection>(responseContent, this.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; namespace Microsoft.CodeAnalysis.MSBuild { public class SolutionFile { private readonly IEnumerable<string> headerLines; private readonly string visualStudioVersionLineOpt; private readonly string minimumVisualStudioVersionLineOpt; private readonly IEnumerable<ProjectBlock> projectBlocks; private readonly IEnumerable<SectionBlock> globalSectionBlocks; internal SolutionFile( IEnumerable<string> headerLines, string visualStudioVersionLineOpt, string minimumVisualStudioVersionLineOpt, IEnumerable<ProjectBlock> projectBlocks, IEnumerable<SectionBlock> globalSectionBlocks) { if (headerLines == null) { //throw new ArgumentNullException("headerLines"); throw new ArgumentException(); } if (projectBlocks == null) { //throw new ArgumentNullException("projectBlocks"); throw new ArgumentException(); } if (globalSectionBlocks == null) { //throw new ArgumentNullException("globalSectionBlocks"); throw new ArgumentException(); } this.headerLines = headerLines.ToList(); this.visualStudioVersionLineOpt = visualStudioVersionLineOpt; this.minimumVisualStudioVersionLineOpt = minimumVisualStudioVersionLineOpt; this.projectBlocks = projectBlocks.ToList(); this.globalSectionBlocks = globalSectionBlocks.ToList(); } public IEnumerable<string> HeaderLines { get { return headerLines; } } public string VisualStudioVersionLineOpt { get { return visualStudioVersionLineOpt; } } public string MinimumVisualStudioVersionLineOpt { get { return minimumVisualStudioVersionLineOpt; } } public IEnumerable<ProjectBlock> ProjectBlocks { get { return projectBlocks; } } public IEnumerable<SectionBlock> GlobalSectionBlocks { get { return globalSectionBlocks; } } public string GetText() { var builder = new StringBuilder(); builder.AppendLine(); foreach (var headerLine in headerLines) { builder.AppendLine(headerLine); } foreach (var block in projectBlocks) { builder.Append(block.GetText()); } builder.AppendLine("Global"); foreach (var block in globalSectionBlocks) { builder.Append(block.GetText(indent: 1)); } builder.AppendLine("EndGlobal"); return builder.ToString(); } public static SolutionFile Parse(TextReader reader) { var headerLines = new List<string>(); var headerLine1 = GetNextNonEmptyLine(reader); if (headerLine1 == null || !headerLine1.StartsWith("Microsoft Visual Studio Solution File")) { //throw new Exception(string.Format(WorkspacesResources.MissingHeaderInSolutionFile, "Microsoft Visual Studio Solution File")); throw new Exception(); } headerLines.Add(headerLine1); // skip comment lines and empty lines while (reader.Peek() != -1 && "#\r\n".Contains((char)reader.Peek())) { headerLines.Add(reader.ReadLine()); } string visualStudioVersionLineOpt = null; if (reader.Peek() == 'V') { visualStudioVersionLineOpt = GetNextNonEmptyLine(reader); if (!visualStudioVersionLineOpt.StartsWith("VisualStudioVersion")) { //throw new Exception(string.Format(WorkspacesResources.MissingHeaderInSolutionFile, "VisualStudioVersion")); throw new Exception(); } } string minimumVisualStudioVersionLineOpt = null; if (reader.Peek() == 'M') { minimumVisualStudioVersionLineOpt = GetNextNonEmptyLine(reader); if (!minimumVisualStudioVersionLineOpt.StartsWith("MinimumVisualStudioVersion")) { //throw new Exception(string.Format(WorkspacesResources.MissingHeaderInSolutionFile, "MinimumVisualStudioVersion")); throw new Exception(); } } var projectBlocks = new List<ProjectBlock>(); // Parse project blocks while we have them while (reader.Peek() == 'P') { projectBlocks.Add(ProjectBlock.Parse(reader)); while (reader.Peek() != -1 && "#\r\n".Contains((char)reader.Peek())) { // Comments and Empty Lines between the Project Blocks are skipped reader.ReadLine(); } } // We now have a global block var globalSectionBlocks = ParseGlobal(reader); // We should now be at the end of the file if (reader.Peek() != -1) { //throw new Exception(WorkspacesResources.MissingEndOfFileInSolutionFile); throw new Exception(); } return new SolutionFile(headerLines, visualStudioVersionLineOpt, minimumVisualStudioVersionLineOpt, projectBlocks, globalSectionBlocks); } //[SuppressMessage("", "RS0001")] // TODO: This suppression should be removed once we have rulesets in place for Roslyn.sln private static IEnumerable<SectionBlock> ParseGlobal(TextReader reader) { if (reader.Peek() == -1) { return Enumerable.Empty<SectionBlock>(); } if (GetNextNonEmptyLine(reader) != "Global") { //throw new Exception(string.Format(WorkspacesResources.MissingLineInSolutionFile, "Global")); throw new Exception(); } var globalSectionBlocks = new List<SectionBlock>(); // The blocks inside here are indented while (reader.Peek() != -1 && char.IsWhiteSpace((char)reader.Peek())) { globalSectionBlocks.Add(SectionBlock.Parse(reader)); ConsumeEmptyLines(reader); } if (GetNextNonEmptyLine(reader) != "EndGlobal") { //throw new Exception(string.Format(WorkspacesResources.MissingLineInSolutionFile, "EndGlobal")); throw new Exception(); } ConsumeEmptyLines(reader); return globalSectionBlocks; } private static void ConsumeEmptyLines(TextReader reader) { // Consume potential empty lines at the end of the global block while (reader.Peek() != -1 && "\r\n".Contains((char)reader.Peek())) { reader.ReadLine(); } } private static string GetNextNonEmptyLine(TextReader reader) { string line = null; do { line = reader.ReadLine(); } while (line != null && line.Trim() == string.Empty); return line; } } }
using System; using System.Data.Linq; using System.Data.SqlTypes; using System.IO; using System.Linq.Expressions; using System.Text; using System.Xml; namespace LinqToDB.DataProvider.SqlServer { using Common; using Expressions; using Mapping; using SqlQuery; public class SqlServerMappingSchema : MappingSchema { public SqlServerMappingSchema() : base(ProviderName.SqlServer) { SetConvertExpression<SqlXml,XmlReader>( s => s.IsNull ? DefaultValue<XmlReader>.Value : s.CreateReader(), s => s.CreateReader()); SetConvertExpression<string,SqlXml>(s => new SqlXml(new MemoryStream(Encoding.UTF8.GetBytes(s)))); AddScalarType(typeof(SqlBinary), SqlBinary. Null, true, DataType.VarBinary); AddScalarType(typeof(SqlBoolean), SqlBoolean. Null, true, DataType.Boolean); AddScalarType(typeof(SqlByte), SqlByte. Null, true, DataType.Byte); AddScalarType(typeof(SqlDateTime), SqlDateTime.Null, true, DataType.DateTime); AddScalarType(typeof(SqlDecimal), SqlDecimal. Null, true, DataType.Decimal); AddScalarType(typeof(SqlDouble), SqlDouble. Null, true, DataType.Double); AddScalarType(typeof(SqlGuid), SqlGuid. Null, true, DataType.Guid); AddScalarType(typeof(SqlInt16), SqlInt16. Null, true, DataType.Int16); AddScalarType(typeof(SqlInt32), SqlInt32. Null, true, DataType.Int32); AddScalarType(typeof(SqlInt64), SqlInt64. Null, true, DataType.Int64); AddScalarType(typeof(SqlMoney), SqlMoney. Null, true, DataType.Money); AddScalarType(typeof(SqlSingle), SqlSingle. Null, true, DataType.Single); AddScalarType(typeof(SqlString), SqlString. Null, true, DataType.NVarChar); AddScalarType(typeof(SqlXml), SqlXml. Null, true, DataType.Xml); try { foreach (var typeInfo in new[] { new { Type = SqlServerTools.SqlHierarchyIdType, Name = "SqlHierarchyId" }, new { Type = SqlServerTools.SqlGeographyType, Name = "SqlGeography" }, new { Type = SqlServerTools.SqlGeometryType, Name = "SqlGeometry" }, }) { var type = typeInfo.Type ?? Type.GetType("Microsoft.SqlServer.Types.{0}, Microsoft.SqlServer.Types".Args(typeInfo.Name)); if (type == null) continue; var p = type.GetProperty("Null"); var l = Expression.Lambda<Func<object>>( Expression.Convert(Expression.Property(null, p), typeof(object))); var nullValue = l.Compile()(); AddScalarType(type, nullValue, true, DataType.Udt); SqlServerDataProvider.SetUdtType(type, typeInfo.Name.Substring(3).ToLower()); } } catch { } SetValueToSqlConverter(typeof(String), (sb,dt,v) => ConvertStringToSql (sb, dt, v.ToString())); SetValueToSqlConverter(typeof(Char), (sb,dt,v) => ConvertCharToSql (sb, dt, (char)v)); SetValueToSqlConverter(typeof(DateTime), (sb,dt,v) => ConvertDateTimeToSql (sb, (DateTime)v)); SetValueToSqlConverter(typeof(TimeSpan), (sb,dt,v) => ConvertTimeSpanToSql (sb, dt, (TimeSpan)v)); SetValueToSqlConverter(typeof(DateTimeOffset), (sb,dt,v) => ConvertDateTimeOffsetToSql(sb, dt, (DateTimeOffset)v)); SetValueToSqlConverter(typeof(byte[]), (sb,dt,v) => ConvertBinaryToSql (sb, (byte[])v)); SetValueToSqlConverter(typeof(Binary), (sb,dt,v) => ConvertBinaryToSql (sb, ((Binary)v).ToArray())); SetDataType(typeof(string), new SqlDataType(DataType.NVarChar, typeof(string), int.MaxValue)); } internal static SqlServerMappingSchema Instance = new SqlServerMappingSchema(); public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { if (@from != to && @from.FullName == to.FullName && @from.Namespace == "Microsoft.SqlServer.Types") { var p = Expression.Parameter(@from); return Expression.Lambda( Expression.Call(to, "Parse", new Type[0], Expression.New( MemberHelper.ConstructorOf(() => new SqlString("")), Expression.Call( Expression.Convert(p, typeof(object)), "ToString", new Type[0]))), p); } return base.TryGetConvertExpression(@from, to); } static void AppendConversion(StringBuilder stringBuilder, int value) { stringBuilder .Append("char(") .Append(value) .Append(')') ; } static void ConvertStringToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, string value) { string start; switch (sqlDataType.DataType) { case DataType.Char : case DataType.VarChar : case DataType.Text : start = "'"; break; default : start = "N'"; break; } DataTools.ConvertStringToSql(stringBuilder, "+", start, AppendConversion, value); } static void ConvertCharToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, char value) { string start; switch (sqlDataType.DataType) { case DataType.Char : case DataType.VarChar : case DataType.Text : start = "'"; break; default : start = "N'"; break; } DataTools.ConvertCharToSql(stringBuilder, start, AppendConversion, value); } static void ConvertDateTimeToSql(StringBuilder stringBuilder, DateTime value) { var format = value.Millisecond == 0 ? value.Hour == 0 && value.Minute == 0 && value.Second == 0 ? "yyyy-MM-dd" : "yyyy-MM-ddTHH:mm:ss" : "yyyy-MM-ddTHH:mm:ss.fff"; stringBuilder .Append('\'') .Append(value.ToString(format)) .Append('\'') ; } static void ConvertTimeSpanToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, TimeSpan value) { if (sqlDataType.DataType == DataType.Int64) { stringBuilder.Append(value.Ticks); } else { var format = value.Days > 0 ? value.Milliseconds > 0 ? "d\\.hh\\:mm\\:ss\\.fff" : "d\\.hh\\:mm\\:ss" : value.Milliseconds > 0 ? "hh\\:mm\\:ss\\.fff" : "hh\\:mm\\:ss"; stringBuilder .Append('\'') .Append(value.ToString(format)) .Append('\'') ; } } static void ConvertDateTimeOffsetToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, DateTimeOffset value) { var format = "'{0:yyyy-MM-dd HH:mm:ss.fffffff zzz}'"; switch (sqlDataType.Precision ?? sqlDataType.Scale) { case 0 : format = "'{0:yyyy-MM-dd HH:mm:ss zzz}'"; break; case 1 : format = "'{0:yyyy-MM-dd HH:mm:ss.f zzz}'"; break; case 2 : format = "'{0:yyyy-MM-dd HH:mm:ss.ff zzz}'"; break; case 3 : format = "'{0:yyyy-MM-dd HH:mm:ss.fff zzz}'"; break; case 4 : format = "'{0:yyyy-MM-dd HH:mm:ss.ffff zzz}'"; break; case 5 : format = "'{0:yyyy-MM-dd HH:mm:ss.fffff zzz}'"; break; case 6 : format = "'{0:yyyy-MM-dd HH:mm:ss.ffffff zzz}'"; break; case 7 : format = "'{0:yyyy-MM-dd HH:mm:ss.fffffff zzz}'"; break; } stringBuilder.AppendFormat(format, value); } static void ConvertBinaryToSql(StringBuilder stringBuilder, byte[] value) { stringBuilder.Append("0x"); foreach (var b in value) stringBuilder.Append(b.ToString("X2")); } } public class SqlServer2000MappingSchema : MappingSchema { public SqlServer2000MappingSchema() : base(ProviderName.SqlServer2000, SqlServerMappingSchema.Instance) { } public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2005MappingSchema : MappingSchema { public SqlServer2005MappingSchema() : base(ProviderName.SqlServer2005, SqlServerMappingSchema.Instance) { } public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2008MappingSchema : MappingSchema { public SqlServer2008MappingSchema() : base(ProviderName.SqlServer2008, SqlServerMappingSchema.Instance) { } public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2012MappingSchema : MappingSchema { public SqlServer2012MappingSchema() : base(ProviderName.SqlServer2012, SqlServerMappingSchema.Instance) { } public override LambdaExpression TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } }
// 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.Monitor { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// MetricDefinitionsOperations operations. /// </summary> internal partial class MetricDefinitionsOperations : IServiceOperations<MonitorClient>, IMetricDefinitionsOperations { /// <summary> /// Initializes a new instance of the MetricDefinitionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal MetricDefinitionsOperations(MonitorClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the MonitorClient /// </summary> public MonitorClient Client { get; private set; } /// <summary> /// Lists the metric definitions for the resource. /// </summary> /// <param name='resourceUri'> /// The identifier of the resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<MetricDefinition>>> ListWithHttpMessagesAsync(string resourceUri, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceUri == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri"); } string apiVersion = "2017-05-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/metricDefinitions").ToString(); _url = _url.Replace("{resourceUri}", resourceUri); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<MetricDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<MetricDefinition>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Composition.Convention; using System.Composition.Hosting; using System.Composition.Hosting.Core; using System.Composition.TypedParts.ActivationFeatures; using System.Linq; using System.Reflection; namespace System.Composition.TypedParts.Discovery { internal class TypeInspector { private static readonly IDictionary<string, object> s_noMetadata = new Dictionary<string, object>(); private readonly ActivationFeature[] _activationFeatures; private readonly AttributedModelProvider _attributeContext; public TypeInspector(AttributedModelProvider attributeContext, ActivationFeature[] activationFeatures) { _attributeContext = attributeContext; _activationFeatures = activationFeatures; } public bool InspectTypeForPart(TypeInfo type, out DiscoveredPart part) { part = null; if (type.IsAbstract || !type.IsClass || _attributeContext.GetDeclaredAttribute<PartNotDiscoverableAttribute>(type.AsType(), type) != null) return false; foreach (var export in DiscoverExports(type)) { part = part ?? new DiscoveredPart(type, _attributeContext, _activationFeatures); part.AddDiscoveredExport(export); } return part != null; } private IEnumerable<DiscoveredExport> DiscoverExports(TypeInfo partType) { foreach (var export in DiscoverInstanceExports(partType)) yield return export; foreach (var export in DiscoverPropertyExports(partType)) yield return export; } private IEnumerable<DiscoveredExport> DiscoverInstanceExports(TypeInfo partType) { var partTypeAsType = partType.AsType(); foreach (var export in _attributeContext.GetDeclaredAttributes<ExportAttribute>(partTypeAsType, partType)) { IDictionary<string, object> metadata = new Dictionary<string, object>(); ReadMetadataAttribute(export, metadata); var applied = _attributeContext.GetDeclaredAttributes(partTypeAsType, partType); ReadLooseMetadata(applied, metadata); var contractType = export.ContractType ?? partTypeAsType; CheckInstanceExportCompatibility(partType, contractType.GetTypeInfo()); var exportKey = new CompositionContract(contractType, export.ContractName); if (metadata.Count == 0) metadata = s_noMetadata; yield return new DiscoveredInstanceExport(exportKey, metadata); } } private IEnumerable<DiscoveredExport> DiscoverPropertyExports(TypeInfo partType) { var partTypeAsType = partType.AsType(); foreach (var property in partTypeAsType.GetRuntimeProperties() .Where(pi => pi.CanRead && pi.GetMethod.IsPublic && !pi.GetMethod.IsStatic)) { foreach (var export in _attributeContext.GetDeclaredAttributes<ExportAttribute>(partTypeAsType, property)) { IDictionary<string, object> metadata = new Dictionary<string, object>(); ReadMetadataAttribute(export, metadata); var applied = _attributeContext.GetDeclaredAttributes(partTypeAsType, property); ReadLooseMetadata(applied, metadata); var contractType = export.ContractType ?? property.PropertyType; CheckPropertyExportCompatibility(partType, property, contractType.GetTypeInfo()); var exportKey = new CompositionContract(export.ContractType ?? property.PropertyType, export.ContractName); if (metadata.Count == 0) metadata = s_noMetadata; yield return new DiscoveredPropertyExport(exportKey, metadata, property); } } } private void ReadLooseMetadata(object[] appliedAttributes, IDictionary<string, object> metadata) { foreach (var attribute in appliedAttributes) { if (attribute is ExportAttribute) continue; var ema = attribute as ExportMetadataAttribute; if (ema != null) { var valueType = ema.Value?.GetType() ?? typeof(object); AddMetadata(metadata, ema.Name, valueType, ema.Value); } else { ReadMetadataAttribute((Attribute)attribute, metadata); } } } private void AddMetadata(IDictionary<string, object> metadata, string name, Type valueType, object value) { object existingValue; if (!metadata.TryGetValue(name, out existingValue)) { metadata.Add(name, value); return; } var existingArray = existingValue as Array; if (existingArray != null) { var newArray = Array.CreateInstance(valueType, existingArray.Length + 1); Array.Copy(existingArray, newArray, existingArray.Length); newArray.SetValue(value, existingArray.Length); metadata[name] = newArray; } else { var newArray = Array.CreateInstance(valueType, 2); newArray.SetValue(existingValue, 0); newArray.SetValue(value, 1); metadata[name] = newArray; } } private void ReadMetadataAttribute(Attribute attribute, IDictionary<string, object> metadata) { var attrType = attribute.GetType(); // Note, we don't support ReflectionContext in this scenario as if (attrType.GetTypeInfo().GetCustomAttribute<MetadataAttributeAttribute>(true) == null) return; foreach (var prop in attrType .GetRuntimeProperties() .Where(p => p.DeclaringType == attrType && p.CanRead)) { AddMetadata(metadata, prop.Name, prop.PropertyType, prop.GetValue(attribute, null)); } } private static void CheckPropertyExportCompatibility(TypeInfo partType, PropertyInfo property, TypeInfo contractType) { if (partType.IsGenericTypeDefinition) { CheckGenericContractCompatibility(partType, property.PropertyType.GetTypeInfo(), contractType); } else if (!contractType.IsAssignableFrom(property.PropertyType.GetTypeInfo())) { string message = SR.Format(SR.TypeInspector_ExportedContractTypeNotAssignable, contractType.Name, property.Name, partType.Name); throw new CompositionFailedException(message); } } private static void CheckGenericContractCompatibility(TypeInfo partType, TypeInfo exportingMemberType, TypeInfo contractType) { if (!contractType.IsGenericTypeDefinition) { string message = SR.Format(SR.TypeInspector_NoExportNonGenericContract, partType.Name, contractType.Name); throw new CompositionFailedException(message); } var compatible = false; foreach (var ifce in GetAssignableTypes(exportingMemberType)) { if (ifce == contractType || (ifce.IsGenericType && ifce.GetGenericTypeDefinition() == contractType.AsType())) { var mappedType = ifce; if (!(mappedType == partType || mappedType.GenericTypeArguments.SequenceEqual(partType.GenericTypeParameters))) { string message = SR.Format(SR.TypeInspector_ArgumentMissmatch, contractType.Name, partType.Name); throw new CompositionFailedException(message); } compatible = true; break; } } if (!compatible) { string message = SR.Format(SR.TypeInspector_ExportNotCompatible, exportingMemberType.Name, partType.Name, contractType.Name); throw new CompositionFailedException(message); } } private static IEnumerable<TypeInfo> GetAssignableTypes(TypeInfo exportingMemberType) { foreach (var ifce in exportingMemberType.ImplementedInterfaces) yield return ifce.GetTypeInfo(); var b = exportingMemberType; while (b != null) { yield return b; b = b.BaseType?.GetTypeInfo(); } } private static void CheckInstanceExportCompatibility(TypeInfo partType, TypeInfo contractType) { if (partType.IsGenericTypeDefinition) { CheckGenericContractCompatibility(partType, partType, contractType); } else if (!contractType.IsAssignableFrom(partType)) { string message = string.Format(SR.TypeInspector_ContractNotAssignable, contractType.Name, partType.Name); throw new CompositionFailedException(message); } } } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Diagnostics; using System.Globalization; using System.Threading; #if !NUNITLITE using System.Security.Principal; #endif using NUnit.Framework.Api; #if !SILVERLIGHT && !NETCF using System.Runtime.Remoting.Messaging; #endif namespace NUnit.Framework.Internal { /// <summary> /// Helper class used to save and restore certain static or /// singleton settings in the environment that affect tests /// or which might be changed by the user tests. /// /// An internal class is used to hold settings and a stack /// of these objects is pushed and popped as Save and Restore /// are called. /// /// Static methods for each setting forward to the internal /// object on the top of the stack. /// </summary> public class TestExecutionContext #if !SILVERLIGHT && !NETCF : ILogicalThreadAffinative #endif { #region Instance Fields /// <summary> /// Link to a prior saved context /// </summary> public TestExecutionContext prior; /// <summary> /// The currently executing test /// </summary> private Test currentTest; /// <summary> /// The time the test began execution /// </summary> private DateTime startTime; /// <summary> /// The active TestResult for the current test /// </summary> private TestResult currentResult; /// <summary> /// The work directory to receive test output /// </summary> private string workDirectory; /// <summary> /// The object on which tests are currently being executed - i.e. the user fixture object /// </summary> private object testObject; /// <summary> /// The event listener currently receiving notifications /// </summary> private ITestListener listener = TestListener.NULL; /// <summary> /// The number of assertions for the current test /// </summary> private int assertCount; /// <summary> /// Indicates whether execution should terminate after the first error /// </summary> private bool stopOnError; /// <summary> /// Default timeout for test cases /// </summary> private int testCaseTimeout; private RandomGenerator randomGenerator; #if !NETCF /// <summary> /// The current culture /// </summary> private CultureInfo currentCulture; /// <summary> /// The current UI culture /// </summary> private CultureInfo currentUICulture; #endif #if !NETCF && !SILVERLIGHT /// <summary> /// Destination for standard output /// </summary> private TextWriter outWriter; /// <summary> /// Destination for standard error /// </summary> private TextWriter errorWriter; /// <summary> /// Indicates whether trace is enabled /// </summary> private bool tracing; /// <summary> /// Destination for Trace output /// </summary> private TextWriter traceWriter; #endif #if !NUNITLITE /// <summary> /// Indicates whether logging is enabled /// </summary> private bool logging; /// <summary> /// The current working directory /// </summary> private string currentDirectory; private Log4NetCapture logCapture; /// <summary> /// The current Principal. /// </summary> private IPrincipal currentPrincipal; #endif #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="TestExecutionContext"/> class. /// </summary> public TestExecutionContext() { this.prior = null; this.testCaseTimeout = 0; #if !NETCF this.currentCulture = CultureInfo.CurrentCulture; this.currentUICulture = CultureInfo.CurrentUICulture; #endif #if !NETCF && !SILVERLIGHT this.outWriter = Console.Out; this.errorWriter = Console.Error; this.traceWriter = null; this.tracing = false; #endif #if !NUNITLITE this.logging = false; this.currentDirectory = Environment.CurrentDirectory; this.logCapture = new Log4NetCapture(); this.currentPrincipal = Thread.CurrentPrincipal; #endif } /// <summary> /// Initializes a new instance of the <see cref="TestExecutionContext"/> class. /// </summary> /// <param name="other">An existing instance of TestExecutionContext.</param> public TestExecutionContext( TestExecutionContext other ) { this.prior = other; this.currentTest = other.currentTest; this.currentResult = other.currentResult; this.testObject = other.testObject; this.workDirectory = other.workDirectory; this.listener = other.listener; this.stopOnError = other.stopOnError; this.testCaseTimeout = other.testCaseTimeout; #if !NETCF this.currentCulture = CultureInfo.CurrentCulture; this.currentUICulture = CultureInfo.CurrentUICulture; #endif #if !NETCF && !SILVERLIGHT this.outWriter = other.outWriter; this.errorWriter = other.errorWriter; this.traceWriter = other.traceWriter; this.tracing = other.tracing; #endif #if !NUNITLITE this.logging = other.logging; this.currentDirectory = Environment.CurrentDirectory; this.logCapture = other.logCapture; this.currentPrincipal = Thread.CurrentPrincipal; #endif } #endregion #region Static Singleton Instance /// <summary> /// The current context, head of the list of saved contexts. /// </summary> #if SILVERLIGHT || NETCF #if (CLR_2_0 || CLR_4_0) && !NETCF [ThreadStatic] #endif private static TestExecutionContext current; #else private static readonly string CONTEXT_KEY = "NUnit.Framework.TestContext"; #endif /// <summary> /// Gets the current context. /// </summary> /// <value>The current context.</value> public static TestExecutionContext CurrentContext { get { #if SILVERLIGHT || NETCF if (current == null) current = new TestExecutionContext(); return current; #else var context = GetTestExecutionContext(); if (context == null) // This can happen on Mono { context = new TestExecutionContext(); CallContext.SetData(CONTEXT_KEY, context); } return context; #endif } } public static TestExecutionContext GetTestExecutionContext() { return CallContext.GetData(CONTEXT_KEY) as TestExecutionContext; } #endregion #region Static Methods internal static void SetCurrentContext(TestExecutionContext ec) { #if SILVERLIGHT || NETCF current = ec; #else CallContext.SetData(CONTEXT_KEY, ec); #endif } #endregion #region Properties /// <summary> /// Gets or sets the current test /// </summary> public Test CurrentTest { get { return currentTest; } set { currentTest = value; } } /// <summary> /// The time the current test started execution /// </summary> public DateTime StartTime { get { return startTime; } set { startTime = value; } } /// <summary> /// Gets or sets the current test result /// </summary> public TestResult CurrentResult { get { return currentResult; } set { currentResult = value; } } /// <summary> /// The current test object - that is the user fixture /// object on which tests are being executed. /// </summary> public object TestObject { get { return testObject; } set { testObject = value; } } /// <summary> /// Get or set the working directory /// </summary> public string WorkDirectory { get { return workDirectory; } set { workDirectory = value; } } /// <summary> /// Get or set indicator that run should stop on the first error /// </summary> public bool StopOnError { get { return stopOnError; } set { stopOnError = value; } } /// <summary> /// The current test event listener /// </summary> internal ITestListener Listener { get { return listener; } set { listener = value; } } /// <summary> /// Gets the RandomGenerator specific to this Test /// </summary> public RandomGenerator RandomGenerator { get { if (randomGenerator == null) { randomGenerator = new RandomGenerator(currentTest.Seed); } return randomGenerator; } } /// <summary> /// Gets the assert count. /// </summary> /// <value>The assert count.</value> internal int AssertCount { get { return assertCount; } set { assertCount = value; } } /// <summary> /// Gets or sets the test case timeout value /// </summary> public int TestCaseTimeout { get { return testCaseTimeout; } set { testCaseTimeout = value; } } #if !NETCF /// <summary> /// Saves or restores the CurrentCulture /// </summary> public CultureInfo CurrentCulture { get { return currentCulture; } set { currentCulture = value; Thread.CurrentThread.CurrentCulture = currentCulture; } } /// <summary> /// Saves or restores the CurrentUICulture /// </summary> public CultureInfo CurrentUICulture { get { return currentUICulture; } set { currentUICulture = value; Thread.CurrentThread.CurrentUICulture = currentUICulture; } } #endif #if !NETCF && !SILVERLIGHT /// <summary> /// Controls where Console.Out is directed /// </summary> internal TextWriter Out { get { return outWriter; } set { if ( outWriter != value ) { outWriter = value; Console.Out.Flush(); Console.SetOut( outWriter ); } } } /// <summary> /// Controls where Console.Error is directed /// </summary> internal TextWriter Error { get { return errorWriter; } set { if ( errorWriter != value ) { errorWriter = value; Console.Error.Flush(); Console.SetError( errorWriter ); } } } /// <summary> /// Controls whether trace and debug output are written /// to the standard output. /// </summary> internal bool Tracing { get { return tracing; } set { if (tracing != value) { if (traceWriter != null && tracing) StopTracing(); tracing = value; if (traceWriter != null && tracing) StartTracing(); } } } /// <summary> /// Controls where Trace output is directed /// </summary> internal TextWriter TraceWriter { get { return traceWriter; } set { if ( traceWriter != value ) { if ( traceWriter != null && tracing ) StopTracing(); traceWriter = value; if ( traceWriter != null && tracing ) StartTracing(); } } } private void StopTracing() { traceWriter.Close(); System.Diagnostics.Trace.Listeners.Remove( "NUnit" ); } private void StartTracing() { System.Diagnostics.Trace.Listeners.Add( new TextWriterTraceListener( traceWriter, "NUnit" ) ); } #endif #if !NUNITLITE /// <summary> /// Controls whether log output is captured /// </summary> public bool Logging { get { return logCapture.Enabled; } set { logCapture.Enabled = value; } } /// <summary> /// Gets or sets the Log writer, which is actually held by a log4net /// TextWriterAppender. When first set, the appender will be created /// and will thereafter send any log events to the writer. /// /// In normal operation, LogWriter is set to an EventListenerTextWriter /// connected to the EventQueue in the test domain. The events are /// subsequently captured in the Gui an the output displayed in /// the Log tab. The application under test does not need to define /// any additional appenders. /// </summary> public TextWriter LogWriter { get { return logCapture.Writer; } set { logCapture.Writer = value; } } /// <summary> /// Saves and restores the CurrentDirectory /// </summary> public string CurrentDirectory { get { return currentDirectory; } set { currentDirectory = value; Environment.CurrentDirectory = currentDirectory; } } /// <summary> /// Gets or sets the current <see cref="IPrincipal"/> for the Thread. /// </summary> public IPrincipal CurrentPrincipal { get { return this.currentPrincipal; } set { this.currentPrincipal = value; Thread.CurrentPrincipal = this.currentPrincipal; } } #endif #endregion #region Instance Methods /// <summary> /// Saves the old context and returns a fresh one /// with the same settings. /// </summary> public TestExecutionContext Save() { return new TestExecutionContext(this); } /// <summary> /// Restores the last saved context and puts /// any saved settings back into effect. /// </summary> public TestExecutionContext Restore() { if (prior == null) throw new InvalidOperationException("TestContext: too many Restores"); this.TestCaseTimeout = prior.TestCaseTimeout; #if !NETCF this.CurrentCulture = prior.CurrentCulture; this.CurrentUICulture = prior.CurrentUICulture; #endif #if !NETCF && !SILVERLIGHT this.Out = prior.Out; this.Error = prior.Error; this.Tracing = prior.Tracing; #endif #if !NUNITLITE this.CurrentDirectory = prior.CurrentDirectory; this.CurrentPrincipal = prior.CurrentPrincipal; #endif return prior; } /// <summary> /// Record any changes in the environment made by /// the test code in the execution context so it /// will be passed on to lower level tests. /// </summary> public void UpdateContext() { #if !NETCF this.currentCulture = CultureInfo.CurrentCulture; this.currentUICulture = CultureInfo.CurrentUICulture; #endif #if !NUNITLITE this.currentDirectory = Environment.CurrentDirectory; this.currentPrincipal = System.Threading.Thread.CurrentPrincipal; #endif } /// <summary> /// Increments the assert count. /// </summary> public void IncrementAssertCount() { System.Threading.Interlocked.Increment(ref assertCount); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="XmlMessageFormatter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Messaging { using System; using System.IO; using System.Xml; using System.Collections; using System.Xml.Serialization; using System.ComponentModel; using System.Security.Permissions; /// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter"]/*' /> /// <devdoc> /// Formatter class that serializes and deserializes objects into /// and from MessageQueue messages using Xml. /// </devdoc> public class XmlMessageFormatter : IMessageFormatter { private Type[] targetTypes; private string[] targetTypeNames; Hashtable targetSerializerTable = new Hashtable(); private bool typeNamesAdded; private bool typesAdded; /// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter.XmlMessageFormatter"]/*' /> /// <devdoc> /// Creates a new Xml message formatter object. /// </devdoc> public XmlMessageFormatter() { this.TargetTypes = new Type[0]; this.TargetTypeNames = new string[0]; } /// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter.XmlMessageFormatter1"]/*' /> /// <devdoc> /// Creates a new Xml message formatter object, /// using the given properties. /// </devdoc> public XmlMessageFormatter(string[] targetTypeNames) { this.TargetTypeNames = targetTypeNames; this.TargetTypes = new Type[0]; } /// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter.XmlMessageFormatter2"]/*' /> /// <devdoc> /// Creates a new Xml message formatter object, /// using the given properties. /// </devdoc> public XmlMessageFormatter(Type[] targetTypes) { this.TargetTypes = targetTypes; this.TargetTypeNames = new string[0]; } /// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter.TargetTypeNames"]/*' /> /// <devdoc> /// Specifies the set of possible types that will /// be deserialized by the formatter from the /// message provided. /// </devdoc> [MessagingDescription(Res.XmlMsgTargetTypeNames)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public string[] TargetTypeNames { get { return this.targetTypeNames; } set { if (value == null) throw new ArgumentNullException("value"); this.typeNamesAdded = false; this.targetTypeNames = value; } } /// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter.TargetTypes"]/*' /> /// <devdoc> /// Specifies the set of possible types that will /// be deserialized by the formatter from the /// message provided. /// </devdoc> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MessagingDescription(Res.XmlMsgTargetTypes)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Type[] TargetTypes { get { return this.targetTypes; } set { if (value == null) throw new ArgumentNullException("value"); this.typesAdded = false; this.targetTypes = value; } } /// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter.CanRead"]/*' /> /// <devdoc> /// When this method is called, the formatter will attempt to determine /// if the contents of the message are something the formatter can deal with. /// </devdoc> public bool CanRead(Message message) { if (message == null) throw new ArgumentNullException("message"); this.CreateTargetSerializerTable(); Stream stream = message.BodyStream; XmlTextReader reader = new XmlTextReader(stream); reader.WhitespaceHandling = WhitespaceHandling.Significant; reader.DtdProcessing = DtdProcessing.Prohibit; bool result = false; foreach (XmlSerializer serializer in targetSerializerTable.Values) { if (serializer.CanDeserialize(reader)) { result = true; break; } } message.BodyStream.Position = 0; // reset stream in case CanRead is followed by Deserialize return result; } /// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter.Clone"]/*' /> /// <devdoc> /// This method is needed to improve scalability on Receive and ReceiveAsync scenarios. Not requiring /// thread safety on read and write. /// </devdoc> public object Clone() { XmlMessageFormatter formatter = new XmlMessageFormatter(); formatter.targetTypes = targetTypes; formatter.targetTypeNames = targetTypeNames; formatter.typesAdded = typesAdded; formatter.typeNamesAdded = typeNamesAdded; foreach (Type targetType in targetSerializerTable.Keys) formatter.targetSerializerTable[targetType] = new XmlSerializer(targetType); return formatter; } /// <internalonly/> private void CreateTargetSerializerTable() { if (!this.typeNamesAdded) { for (int index = 0; index < this.targetTypeNames.Length; ++index) { Type targetType = Type.GetType(this.targetTypeNames[index], true); if (targetType != null) this.targetSerializerTable[targetType] = new XmlSerializer(targetType); } this.typeNamesAdded = true; } if (!this.typesAdded) { for (int index = 0; index < this.targetTypes.Length; ++index) this.targetSerializerTable[this.targetTypes[index]] = new XmlSerializer(this.targetTypes[index]); this.typesAdded = true; } if (this.targetSerializerTable.Count == 0) throw new InvalidOperationException(Res.GetString(Res.TypeListMissing)); } /// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter.Read"]/*' /> /// <devdoc> /// This method is used to read the contents from the given message /// and create an object. /// </devdoc> public object Read(Message message) { if (message == null) throw new ArgumentNullException("message"); this.CreateTargetSerializerTable(); Stream stream = message.BodyStream; XmlTextReader reader = new XmlTextReader(stream); reader.WhitespaceHandling = WhitespaceHandling.Significant; reader.DtdProcessing = DtdProcessing.Prohibit; foreach (XmlSerializer serializer in targetSerializerTable.Values) { if (serializer.CanDeserialize(reader)) return serializer.Deserialize(reader); } throw new InvalidOperationException(Res.GetString(Res.InvalidTypeDeserialization)); } /// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter.Write"]/*' /> /// <devdoc> /// This method is used to write the given object into the given message. /// If the formatter cannot understand the given object, an exception is thrown. /// </devdoc> public void Write(Message message, object obj) { if (message == null) throw new ArgumentNullException("message"); if (obj == null) throw new ArgumentNullException("obj"); Stream stream = new MemoryStream(); Type serializedType = obj.GetType(); XmlSerializer serializer = null; if (this.targetSerializerTable.ContainsKey(serializedType)) serializer = (XmlSerializer)this.targetSerializerTable[serializedType]; else { serializer = new XmlSerializer(serializedType); this.targetSerializerTable[serializedType] = serializer; } serializer.Serialize(stream, obj); message.BodyStream = stream; //Need to reset the body type, in case the same message //is reused by some other formatter. message.BodyType = 0; } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Signum.Analyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class AutoExpressionFieldAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "SF0001"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, "Call As.Expression in a method or property with AutoExpressionFieldAttribute", "'{0}' should call As.Expression(() => ...) ({1})", "Expressions", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: "A Property or Method can use AutoExpressionFieldAttribute and As.Expression(() => ...) to extract their implementation to a hidden static field with the expression tree, that will be used by Signum LINQ provider to translate it to SQL"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterSyntaxNodeAction(AnalyzeAttributeSymbol, SyntaxKind.Attribute); } static void AnalyzeAttributeSymbol(SyntaxNodeAnalysisContext context) { try { var att = (AttributeSyntax)context.Node; var name = att.Name.ToString(); if (name != "AutoExpressionField") return; var member = att.FirstAncestorOrSelf<MemberDeclarationSyntax>(); var method = member as MethodDeclarationSyntax; var prop = member as PropertyDeclarationSyntax; var ident = prop?.Identifier.ToString() ?? method?.Identifier.ToString(); if (method != null) { if (method.ReturnType.ToString() == "void") { Diagnostic(context, ident, method.ReturnType.GetLocation(), "no return type"); return; } foreach (var param in method.ParameterList.Parameters) { if (param.Modifiers.Any(a => a.Kind() != SyntaxKind.ThisKeyword)) { Diagnostic(context, ident, param.Modifiers.First().GetLocation(), "complex parameter '" + param.Identifier.ToString() + "'"); return; } } } ExpressionSyntax expr = GetSingleBody(context, ident, att, member); if (expr == null) return; var inv = expr as InvocationExpressionSyntax; if (inv == null || !(context.SemanticModel.GetSymbolInfo(inv) is SymbolInfo si)) { Diagnostic(context, ident, att.GetLocation(), "no As.Expression", fixable: true); return; } if (si.Symbol != null ? !IsExpressionAs(si.Symbol) : !si.CandidateSymbols.Any(s => IsExpressionAs(s))) { Diagnostic(context, ident, att.GetLocation(), "no As.Expression", fixable: true); return; } var args = inv.ArgumentList.Arguments; if (args.Count == 0 || !(args[0].Expression is ParenthesizedLambdaExpressionSyntax)) { Diagnostic(context, ident, att.GetLocation(), "the call to As.Expression should have a lambda as argument", fixable: false); return; } var type = context.SemanticModel.GetTypeInfo(inv); if(!type.ConvertedNullability.Equals(type.Nullability) || !type.Type.Equals(type.ConvertedType, SymbolEqualityComparer.IncludeNullability)) { var position = member.GetLocation().SourceSpan.Start; var current = type.Type.ToMinimalDisplayString(context.SemanticModel, type.Nullability.FlowState, position); var converted = type.ConvertedType.ToMinimalDisplayString(context.SemanticModel, type.ConvertedNullability.FlowState, position); Diagnostic(context, ident, att.GetLocation(), $"the call to As.Expression returns '{current}' but is implicitly converted to '{converted}'", fixable: true, explicitConvert: converted); return; } } catch (Exception e) { throw new Exception(context.SemanticModel.SyntaxTree.FilePath + "\r\n" + e.Message + "\r\n" + e.StackTrace); } } private static bool IsExpressionAs(ISymbol symbol) { return symbol.Name == "Expression" && symbol.ContainingType.Name == "As" && symbol.ContainingNamespace.ToString() == "Signum.Utilities"; } public static ExpressionSyntax GetSingleBody(SyntaxNodeAnalysisContext context, string ident, AttributeSyntax att, MemberDeclarationSyntax member) { if (member is MethodDeclarationSyntax) { var method = (MethodDeclarationSyntax)member; if (method.ExpressionBody != null) return method.ExpressionBody.Expression; return OnlyReturn(context, ident, att, method.Body.Statements); } else if (member is PropertyDeclarationSyntax) { var property = (PropertyDeclarationSyntax)member; if (property.ExpressionBody != null) return property.ExpressionBody.Expression; var getter = property.AccessorList.Accessors.SingleOrDefault(a => a.Kind() == SyntaxKind.GetAccessorDeclaration); if (getter == null) { Diagnostic(context, ident, att.GetLocation(), "no getter"); return null; } if (property.AccessorList.Accessors.Any(a => a.Kind() == SyntaxKind.SetAccessorDeclaration)) { Diagnostic(context, ident, att.GetLocation(), "setter not allowed"); return null; } if (getter.Body == null) { Diagnostic(context, ident, getter.GetLocation(), "no getter body"); return null; } return OnlyReturn(context, ident, att, getter.Body.Statements); } Diagnostic(context, ident, att.GetLocation(), "no property or method"); return null; } internal static ExpressionSyntax OnlyReturn(SyntaxNodeAnalysisContext context, string ident, AttributeSyntax att, SyntaxList<StatementSyntax> statements) { var only = statements.Only(); if (only == null) { Diagnostic(context, ident, att.GetLocation(), statements.Count + " statements"); return null; } var ret = only as ReturnStatementSyntax; if (ret == null) { Diagnostic(context, ident, only.GetLocation(), "no return"); return null; } if (ret.Expression == null) { Diagnostic(context, ident, only.GetLocation(), "no return expression"); return null; } return ret.Expression; } private static void Diagnostic(SyntaxNodeAnalysisContext context, string identifier, Location location, string error, bool fixable = false, string explicitConvert = null) { var properties = ImmutableDictionary<string, string>.Empty.Add("fixable", fixable.ToString()); if (explicitConvert != null) properties = properties.Add("explicitConvert", explicitConvert); var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(Rule, location, properties, identifier, error); context.ReportDiagnostic(diagnostic); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Moq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests { public class InteractiveWindowTests : IDisposable { #region Helpers private InteractiveWindowTestHost _testHost; private List<InteractiveWindow.State> _states; public InteractiveWindowTests() { _states = new List<InteractiveWindow.State>(); _testHost = new InteractiveWindowTestHost(_states.Add); } void IDisposable.Dispose() { _testHost.Dispose(); } private IInteractiveWindow Window => _testHost.Window; private static IEnumerable<IInteractiveWindowCommand> MockCommands(params string[] commandNames) { foreach (var name in commandNames) { var mock = new Mock<IInteractiveWindowCommand>(); mock.Setup(m => m.Names).Returns(new[] { name }); yield return mock.Object; } } private static ITextSnapshot MockSnapshot(string content) { var snapshotMock = new Mock<ITextSnapshot>(); snapshotMock.Setup(m => m[It.IsAny<int>()]).Returns<int>(index => content[index]); snapshotMock.Setup(m => m.Length).Returns(content.Length); snapshotMock.Setup(m => m.GetText()).Returns(content); snapshotMock.Setup(m => m.GetText(It.IsAny<int>(), It.IsAny<int>())).Returns<int, int>((start, length) => content.Substring(start, length)); snapshotMock.Setup(m => m.GetText(It.IsAny<Span>())).Returns<Span>(span => content.Substring(span.Start, span.Length)); return snapshotMock.Object; } private string GetTextFromCurrentLanguageBuffer() { return Window.CurrentLanguageBuffer.CurrentSnapshot.GetText(); } #endregion [Fact] public void InteractiveWindow__CommandParsing() { var commandList = MockCommands("foo", "bar", "bz", "command1").ToArray(); var commands = new Commands.Commands(null, "%", commandList); AssertEx.Equal(commands.GetCommands(), commandList); var cmdBar = commandList[1]; Assert.Equal("bar", cmdBar.Names.First()); Assert.Equal("%", commands.CommandPrefix); commands.CommandPrefix = "#"; Assert.Equal("#", commands.CommandPrefix); //// 111111 //// 0123456789012345 var s1 = MockSnapshot("#bar arg1 arg2 "); SnapshotSpan prefixSpan, commandSpan, argsSpan; IInteractiveWindowCommand cmd; cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 0)), out prefixSpan, out commandSpan, out argsSpan); Assert.Null(cmd); cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 1)), out prefixSpan, out commandSpan, out argsSpan); Assert.Null(cmd); cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 2)), out prefixSpan, out commandSpan, out argsSpan); Assert.Null(cmd); Assert.Equal(0, prefixSpan.Start); Assert.Equal(1, prefixSpan.End); Assert.Equal(1, commandSpan.Start); Assert.Equal(2, commandSpan.End); Assert.Equal(2, argsSpan.Start); Assert.Equal(2, argsSpan.End); cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 3)), out prefixSpan, out commandSpan, out argsSpan); Assert.Null(cmd); Assert.Equal(0, prefixSpan.Start); Assert.Equal(1, prefixSpan.End); Assert.Equal(1, commandSpan.Start); Assert.Equal(3, commandSpan.End); Assert.Equal(3, argsSpan.Start); Assert.Equal(3, argsSpan.End); cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 4)), out prefixSpan, out commandSpan, out argsSpan); Assert.Equal(cmdBar, cmd); Assert.Equal(0, prefixSpan.Start); Assert.Equal(1, prefixSpan.End); Assert.Equal(1, commandSpan.Start); Assert.Equal(4, commandSpan.End); Assert.Equal(4, argsSpan.Start); Assert.Equal(4, argsSpan.End); cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 5)), out prefixSpan, out commandSpan, out argsSpan); Assert.Equal(cmdBar, cmd); Assert.Equal(0, prefixSpan.Start); Assert.Equal(1, prefixSpan.End); Assert.Equal(1, commandSpan.Start); Assert.Equal(4, commandSpan.End); Assert.Equal(5, argsSpan.Start); Assert.Equal(5, argsSpan.End); cmd = commands.TryParseCommand(s1.GetExtent(), out prefixSpan, out commandSpan, out argsSpan); Assert.Equal(cmdBar, cmd); Assert.Equal(0, prefixSpan.Start); Assert.Equal(1, prefixSpan.End); Assert.Equal(1, commandSpan.Start); Assert.Equal(4, commandSpan.End); Assert.Equal(5, argsSpan.Start); Assert.Equal(14, argsSpan.End); //// //// 0123456789 var s2 = MockSnapshot(" #bar "); cmd = commands.TryParseCommand(s2.GetExtent(), out prefixSpan, out commandSpan, out argsSpan); Assert.Equal(cmdBar, cmd); Assert.Equal(2, prefixSpan.Start); Assert.Equal(3, prefixSpan.End); Assert.Equal(3, commandSpan.Start); Assert.Equal(6, commandSpan.End); Assert.Equal(9, argsSpan.Start); Assert.Equal(9, argsSpan.End); //// 111111 //// 0123456789012345 var s3 = MockSnapshot(" # bar args"); cmd = commands.TryParseCommand(s3.GetExtent(), out prefixSpan, out commandSpan, out argsSpan); Assert.Equal(cmdBar, cmd); Assert.Equal(2, prefixSpan.Start); Assert.Equal(3, prefixSpan.End); Assert.Equal(6, commandSpan.Start); Assert.Equal(9, commandSpan.End); Assert.Equal(11, argsSpan.Start); Assert.Equal(15, argsSpan.End); } [Fact] public void InteractiveWindow_GetCommands() { var interactiveCommands = new InteractiveCommandsFactory(null, null).CreateInteractiveCommands( Window, "#", _testHost.ExportProvider.GetExports<IInteractiveWindowCommand>().Select(x => x.Value).ToArray()); var commands = interactiveCommands.GetCommands(); Assert.NotEmpty(commands); Assert.Equal(2, commands.Where(n => n.Names.First() == "cls").Count()); Assert.Equal(2, commands.Where(n => n.Names.Last() == "clear").Count()); Assert.NotNull(commands.Where(n => n.Names.First() == "help").SingleOrDefault()); Assert.NotNull(commands.Where(n => n.Names.First() == "reset").SingleOrDefault()); } [WorkItem(3970, "https://github.com/dotnet/roslyn/issues/3970")] [Fact] public void ResetStateTransitions() { Window.Operations.ResetAsync().PumpingWait(); Assert.Equal(_states, new[] { InteractiveWindow.State.Initializing, InteractiveWindow.State.WaitingForInput, InteractiveWindow.State.Resetting, InteractiveWindow.State.WaitingForInput, }); } [Fact] public void DoubleInitialize() { try { Window.InitializeAsync().PumpingWait(); Assert.True(false); } catch (AggregateException e) { Assert.IsType<InvalidOperationException>(e.InnerExceptions.Single()); } } [Fact] public void AccessPropertiesOnUIThread() { foreach (var property in typeof(IInteractiveWindow).GetProperties()) { Assert.Null(property.SetMethod); property.GetMethod.Invoke(Window, Array.Empty<object>()); } Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties()); } [Fact] public void AccessPropertiesOnNonUIThread() { foreach (var property in typeof(IInteractiveWindow).GetProperties()) { Assert.Null(property.SetMethod); Task.Run(() => property.GetMethod.Invoke(Window, Array.Empty<object>())).PumpingWait(); } Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties()); } /// <remarks> /// Confirm that we are, in fact, running on a non-UI thread. /// </remarks> [Fact] public void NonUIThread() { Task.Run(() => Assert.False(((InteractiveWindow)Window).OnUIThread())).PumpingWait(); } [Fact] public void CallCloseOnNonUIThread() { Task.Run(() => Window.Close()).PumpingWait(); } [Fact] public void CallInsertCodeOnNonUIThread() { // TODO (https://github.com/dotnet/roslyn/issues/3984): InsertCode is a no-op unless standard input is being collected. Task.Run(() => Window.InsertCode("1")).PumpingWait(); } [Fact] public void CallSubmitAsyncOnNonUIThread() { Task.Run(() => Window.SubmitAsync(Array.Empty<string>()).GetAwaiter().GetResult()).PumpingWait(); } [Fact] public void CallWriteOnNonUIThread() { Task.Run(() => Window.WriteLine("1")).PumpingWait(); Task.Run(() => Window.Write("1")).PumpingWait(); Task.Run(() => Window.WriteErrorLine("1")).PumpingWait(); Task.Run(() => Window.WriteError("1")).PumpingWait(); } [Fact] public void CallFlushOutputOnNonUIThread() { Window.Write("1"); // Something to flush. Task.Run(() => Window.FlushOutput()).PumpingWait(); } [Fact] public void CallAddInputOnNonUIThread() { Task.Run(() => Window.AddInput("1")).PumpingWait(); } /// <remarks> /// Call is blocking, so we can't write a simple non-failing test. /// </remarks> [Fact] public void CallReadStandardInputOnUIThread() { Assert.Throws<InvalidOperationException>(() => Window.ReadStandardInput()); } [Fact] public void CallBackspaceOnNonUIThread() { Window.InsertCode("1"); // Something to backspace. Task.Run(() => Window.Operations.Backspace()).PumpingWait(); } [Fact] public void CallBreakLineOnNonUIThread() { Task.Run(() => Window.Operations.BreakLine()).PumpingWait(); } [Fact] public void CallClearHistoryOnNonUIThread() { Window.AddInput("1"); // Need a history entry. Task.Run(() => Window.Operations.ClearHistory()).PumpingWait(); } [Fact] public void CallClearViewOnNonUIThread() { Window.InsertCode("1"); // Something to clear. Task.Run(() => Window.Operations.ClearView()).PumpingWait(); } [Fact] public void CallHistoryNextOnNonUIThread() { Window.AddInput("1"); // Need a history entry. Task.Run(() => Window.Operations.HistoryNext()).PumpingWait(); } [Fact] public void CallHistoryPreviousOnNonUIThread() { Window.AddInput("1"); // Need a history entry. Task.Run(() => Window.Operations.HistoryPrevious()).PumpingWait(); } [Fact] public void CallHistorySearchNextOnNonUIThread() { Window.AddInput("1"); // Need a history entry. Task.Run(() => Window.Operations.HistorySearchNext()).PumpingWait(); } [Fact] public void CallHistorySearchPreviousOnNonUIThread() { Window.AddInput("1"); // Need a history entry. Task.Run(() => Window.Operations.HistorySearchPrevious()).PumpingWait(); } [Fact] public void CallHomeOnNonUIThread() { Window.Operations.BreakLine(); // Distinguish Home from End. Task.Run(() => Window.Operations.Home(true)).PumpingWait(); } [Fact] public void CallEndOnNonUIThread() { Window.Operations.BreakLine(); // Distinguish Home from End. Task.Run(() => Window.Operations.End(true)).PumpingWait(); } [Fact] public void CallSelectAllOnNonUIThread() { Window.InsertCode("1"); // Something to select. Task.Run(() => Window.Operations.SelectAll()).PumpingWait(); } [Fact] public void CallPasteOnNonUIThread() { Task.Run(() => Window.Operations.Paste()).PumpingWait(); } [Fact] public void CallCutOnNonUIThread() { Task.Run(() => Window.Operations.Cut()).PumpingWait(); } [Fact] public void CallDeleteOnNonUIThread() { Task.Run(() => Window.Operations.Delete()).PumpingWait(); } [Fact] public void CallReturnOnNonUIThread() { Task.Run(() => Window.Operations.Return()).PumpingWait(); } [Fact] public void CallTrySubmitStandardInputOnNonUIThread() { Task.Run(() => Window.Operations.TrySubmitStandardInput()).PumpingWait(); } [Fact] public void CallResetAsyncOnNonUIThread() { Task.Run(() => Window.Operations.ResetAsync()).PumpingWait(); } [Fact] public void CallExecuteInputOnNonUIThread() { Task.Run(() => Window.Operations.ExecuteInput()).PumpingWait(); } [Fact] public void CallCancelOnNonUIThread() { Task.Run(() => Window.Operations.Cancel()).PumpingWait(); } [WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")] [Fact] public void TestIndentation1() { TestIndentation(indentSize: 1); } [WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")] [Fact] public void TestIndentation2() { TestIndentation(indentSize: 2); } [WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")] [Fact] public void TestIndentation3() { TestIndentation(indentSize: 3); } [WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")] [Fact] public void TestIndentation4() { TestIndentation(indentSize: 4); } private void TestIndentation(int indentSize) { const int promptWidth = 2; _testHost.ExportProvider.GetExport<TestSmartIndentProvider>().Value.SmartIndent = new TestSmartIndent( promptWidth, promptWidth + indentSize, promptWidth ); AssertCaretVirtualPosition(0, promptWidth); Window.InsertCode("{"); AssertCaretVirtualPosition(0, promptWidth + 1); Window.Operations.BreakLine(); AssertCaretVirtualPosition(1, promptWidth + indentSize); Window.InsertCode("Console.WriteLine();"); Window.Operations.BreakLine(); AssertCaretVirtualPosition(2, promptWidth); Window.InsertCode("}"); AssertCaretVirtualPosition(2, promptWidth + 1); } private void AssertCaretVirtualPosition(int expectedLine, int expectedColumn) { ITextSnapshotLine actualLine; int actualColumn; Window.TextView.Caret.Position.VirtualBufferPosition.GetLineAndColumn(out actualLine, out actualColumn); Assert.Equal(expectedLine, actualLine.LineNumber); Assert.Equal(expectedColumn, actualColumn); } [Fact] public void CheckHistoryPrevious() { const string inputString = "1 "; Window.InsertCode(inputString); Assert.Equal(inputString, GetTextFromCurrentLanguageBuffer()); Task.Run(() => Window.Operations.ExecuteInput()).PumpingWait(); Window.Operations.HistoryPrevious(); Assert.Equal(inputString, GetTextFromCurrentLanguageBuffer()); } [Fact] public void CheckHistoryPreviousAfterReset() { const string resetCommand = "#reset"; Window.InsertCode(resetCommand); Assert.Equal(resetCommand, GetTextFromCurrentLanguageBuffer()); Task.Run(() => Window.Operations.ExecuteInput()).PumpingWait(); Window.Operations.HistoryPrevious(); Assert.Equal(resetCommand, GetTextFromCurrentLanguageBuffer()); } [Fact] public void ResetCommandArgumentParsing_Success() { bool initialize; Assert.True(ResetCommand.TryParseArguments("", out initialize)); Assert.True(initialize); Assert.True(ResetCommand.TryParseArguments(" ", out initialize)); Assert.True(initialize); Assert.True(ResetCommand.TryParseArguments("\r\n", out initialize)); Assert.True(initialize); Assert.True(ResetCommand.TryParseArguments("noconfig", out initialize)); Assert.False(initialize); Assert.True(ResetCommand.TryParseArguments(" noconfig ", out initialize)); Assert.False(initialize); Assert.True(ResetCommand.TryParseArguments("\r\nnoconfig\r\n", out initialize)); Assert.False(initialize); } [Fact] public void ResetCommandArgumentParsing_Failure() { bool initialize; Assert.False(ResetCommand.TryParseArguments("a", out initialize)); Assert.False(ResetCommand.TryParseArguments("noconfi", out initialize)); Assert.False(ResetCommand.TryParseArguments("noconfig1", out initialize)); Assert.False(ResetCommand.TryParseArguments("noconfig 1", out initialize)); Assert.False(ResetCommand.TryParseArguments("1 noconfig", out initialize)); Assert.False(ResetCommand.TryParseArguments("noconfig\r\na", out initialize)); Assert.False(ResetCommand.TryParseArguments("nOcOnfIg", out initialize)); } [Fact] public void ResetCommandNoConfigClassification() { Assert.Empty(ResetCommand.GetNoConfigPositions("")); Assert.Empty(ResetCommand.GetNoConfigPositions("a")); Assert.Empty(ResetCommand.GetNoConfigPositions("noconfi")); Assert.Empty(ResetCommand.GetNoConfigPositions("noconfig1")); Assert.Empty(ResetCommand.GetNoConfigPositions("1noconfig")); Assert.Empty(ResetCommand.GetNoConfigPositions("1noconfig1")); Assert.Empty(ResetCommand.GetNoConfigPositions("nOcOnfIg")); Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig")); Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig ")); Assert.Equal(new[] { 1 }, ResetCommand.GetNoConfigPositions(" noconfig")); Assert.Equal(new[] { 1 }, ResetCommand.GetNoConfigPositions(" noconfig ")); Assert.Equal(new[] { 2 }, ResetCommand.GetNoConfigPositions("\r\nnoconfig")); Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig\r\n")); Assert.Equal(new[] { 2 }, ResetCommand.GetNoConfigPositions("\r\nnoconfig\r\n")); Assert.Equal(new[] { 6 }, ResetCommand.GetNoConfigPositions("error noconfig")); Assert.Equal(new[] { 0, 9 }, ResetCommand.GetNoConfigPositions("noconfig noconfig")); Assert.Equal(new[] { 0, 15 }, ResetCommand.GetNoConfigPositions("noconfig error noconfig")); } [WorkItem(4755, "https://github.com/dotnet/roslyn/issues/4755")] [Fact] public void ReformatBraces() { var buffer = Window.CurrentLanguageBuffer; var snapshot = buffer.CurrentSnapshot; Assert.Equal(0, snapshot.Length); // Text before reformatting. snapshot = ApplyChanges( buffer, new TextChange(0, 0, "{ {\r\n } }")); // Text after reformatting. Assert.Equal(9, snapshot.Length); snapshot = ApplyChanges( buffer, new TextChange(1, 1, "\r\n "), new TextChange(5, 1, " "), new TextChange(7, 1, "\r\n")); // Text from language buffer. var actualText = snapshot.GetText(); Assert.Equal("{\r\n {\r\n }\r\n}", actualText); // Text including prompts. buffer = Window.TextView.TextBuffer; snapshot = buffer.CurrentSnapshot; actualText = snapshot.GetText(); Assert.Equal("> {\r\n> {\r\n> }\r\n> }", actualText); // Prompts should be read-only. var regions = buffer.GetReadOnlyExtents(new Span(0, snapshot.Length)); AssertEx.SetEqual(regions, new Span(0, 2), new Span(5, 2), new Span(14, 2), new Span(23, 2)); } [Fact] public void CopyWithinInput() { Clipboard.Clear(); Window.InsertCode("1 + 2"); Window.Operations.SelectAll(); Window.Operations.Copy(); VerifyClipboardData("1 + 2"); // Shrink the selection. var selection = Window.TextView.Selection; var span = selection.SelectedSpans[0]; selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 1, span.Length - 2), isReversed: false); Window.Operations.Copy(); VerifyClipboardData(" + "); } [Fact] public void CopyInputAndOutput() { Clipboard.Clear(); Submit( @"foreach (var o in new[] { 1, 2, 3 }) System.Console.WriteLine();", @"1 2 3 "); var caret = Window.TextView.Caret; caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); Window.Operations.SelectAll(); Window.Operations.SelectAll(); Window.Operations.Copy(); VerifyClipboardData(@"foreach (var o in new[] { 1, 2, 3 }) System.Console.WriteLine(); 1 2 3 ", @"> foreach (var o in new[] \{ 1, 2, 3 \})\par > System.Console.WriteLine();\par 1\par 2\par 3\par > "); // Shrink the selection. var selection = Window.TextView.Selection; var span = selection.SelectedSpans[0]; selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 3, span.Length - 6), isReversed: false); Window.Operations.Copy(); VerifyClipboardData(@"oreach (var o in new[] { 1, 2, 3 }) System.Console.WriteLine(); 1 2 3", @"oreach (var o in new[] \{ 1, 2, 3 \})\par > System.Console.WriteLine();\par 1\par 2\par 3"); } [Fact] public void CutWithinInput() { Clipboard.Clear(); Window.InsertCode("foreach (var o in new[] { 1, 2, 3 })"); Window.Operations.BreakLine(); Window.InsertCode("System.Console.WriteLine();"); Window.Operations.BreakLine(); var caret = Window.TextView.Caret; caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); Window.Operations.SelectAll(); // Shrink the selection. var selection = Window.TextView.Selection; var span = selection.SelectedSpans[0]; selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 3, span.Length - 6), isReversed: false); Window.Operations.Cut(); VerifyClipboardData( @"each (var o in new[] { 1, 2, 3 }) System.Console.WriteLine()", expectedRtf: null); } [Fact] public void CutInputAndOutput() { Clipboard.Clear(); Submit( @"foreach (var o in new[] { 1, 2, 3 }) System.Console.WriteLine();", @"1 2 3 "); var caret = Window.TextView.Caret; caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); Window.Operations.SelectAll(); Window.Operations.SelectAll(); Window.Operations.Cut(); VerifyClipboardData(null); } /// <summary> /// When there is no selection, copy /// should copy the current line. /// </summary> [Fact] public void CopyNoSelection() { Submit( @"s + t", @" 1 2 "); CopyNoSelectionAndVerify(0, 7, "s +\r\n", @"> s +\par "); CopyNoSelectionAndVerify(7, 11, "\r\n", @"> \par "); CopyNoSelectionAndVerify(11, 17, " t\r\n", @"> t\par "); CopyNoSelectionAndVerify(17, 21, " 1\r\n", @" 1\par "); CopyNoSelectionAndVerify(21, 23, "\r\n", @"\par "); CopyNoSelectionAndVerify(23, 28, "2 ", "2 > "); } private void CopyNoSelectionAndVerify(int start, int end, string expectedText, string expectedRtf) { var caret = Window.TextView.Caret; var snapshot = Window.TextView.TextBuffer.CurrentSnapshot; for (int i = start; i < end; i++) { Clipboard.Clear(); caret.MoveTo(new SnapshotPoint(snapshot, i)); Window.Operations.Copy(); VerifyClipboardData(expectedText, expectedRtf); } } [Fact] public void CancelMultiLineInput() { ApplyChanges( Window.CurrentLanguageBuffer, new TextChange(0, 0, "{\r\n {\r\n }\r\n}")); // Text including prompts. var buffer = Window.TextView.TextBuffer; var snapshot = buffer.CurrentSnapshot; Assert.Equal("> {\r\n> {\r\n> }\r\n> }", snapshot.GetText()); Task.Run(() => Window.Operations.Cancel()).PumpingWait(); // Text after cancel. snapshot = buffer.CurrentSnapshot; Assert.Equal("> ", snapshot.GetText()); } private void Submit(string submission, string output) { Task.Run(() => Window.SubmitAsync(new[] { submission })).PumpingWait(); // TestInteractiveEngine.ExecuteCodeAsync() simply returns // success rather than executing the submission, so add the // expected output to the output buffer. var buffer = Window.OutputBuffer; using (var edit = buffer.CreateEdit()) { edit.Replace(buffer.CurrentSnapshot.Length, 0, output); edit.Apply(); } } private static void VerifyClipboardData(string expectedText) { VerifyClipboardData(expectedText, expectedText); } private static void VerifyClipboardData(string expectedText, string expectedRtf) { var data = Clipboard.GetDataObject(); Assert.Equal(expectedText, data.GetData(DataFormats.StringFormat)); Assert.Equal(expectedText, data.GetData(DataFormats.Text)); Assert.Equal(expectedText, data.GetData(DataFormats.UnicodeText)); var actualRtf = (string)data.GetData(DataFormats.Rtf); if (expectedRtf == null) { Assert.Null(actualRtf); } else { Assert.True(actualRtf.StartsWith(@"{\rtf")); Assert.True(actualRtf.EndsWith(expectedRtf + "}")); } } private struct TextChange { internal readonly int Start; internal readonly int Length; internal readonly string Text; internal TextChange(int start, int length, string text) { Start = start; Length = length; Text = text; } } private static ITextSnapshot ApplyChanges(ITextBuffer buffer, params TextChange[] changes) { using (var edit = buffer.CreateEdit()) { foreach (var change in changes) { edit.Replace(change.Start, change.Length, change.Text); } return edit.Apply(); } } } internal static class OperationsExtensions { internal static void Copy(this IInteractiveWindowOperations operations) { ((IInteractiveWindowOperations2)operations).Copy(); } } }